Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.59
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.59! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.58 2014/12/21 19:56:46 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1172.2.36 raeburn 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 100: use LONCAPA::Lond;
1.1117 foxr 101:
1.1090 raeburn 102: use File::Copy;
1.676 albertel 103:
1.195 www 104: my $readit;
1.550 foxr 105: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 106:
1.619 albertel 107: require Exporter;
108:
109: our @ISA = qw (Exporter);
110: our @EXPORT = qw(%env);
111:
1.1172.2.9 raeburn 112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 113: {
114: my $logid;
1.1172.2.9 raeburn 115: sub write_log {
116: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if ($context eq 'course') {
118: if (($cnum eq '') || ($cdom eq '')) {
119: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
120: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
121: }
1.957 raeburn 122: }
1.1172.2.13 raeburn 123: $logid ++;
1.957 raeburn 124: my $now = time();
125: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9 raeburn 126: my $logentry = {
127: $id => {
128: 'exe_uname' => $env{'user.name'},
129: 'exe_udom' => $env{'user.domain'},
130: 'exe_time' => $now,
131: 'exe_ip' => $ENV{'REMOTE_ADDR'},
132: 'delflag' => $delflag,
133: 'logentry' => $storehash,
134: 'uname' => $uname,
135: 'udom' => $udom,
136: }
137: };
138: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 139: }
140: }
1.1 albertel 141:
1.163 harris41 142: sub logtouch {
143: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 144: unless (-e "$execdir/logs/lonnet.log") {
145: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 146: close $fh;
147: }
148: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
149: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
150: }
151:
1.1 albertel 152: sub logthis {
153: my $message=shift;
154: my $execdir=$perlvar{'lonDaemons'};
155: my $now=time;
156: my $local=localtime($now);
1.448 albertel 157: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 158: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
159: print $fh $logstring;
1.448 albertel 160: close($fh);
161: }
1.1 albertel 162: return 1;
163: }
164:
165: sub logperm {
166: my $message=shift;
167: my $execdir=$perlvar{'lonDaemons'};
168: my $now=time;
169: my $local=localtime($now);
1.448 albertel 170: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
171: print $fh "$now:$message:$local\n";
172: close($fh);
173: }
1.1 albertel 174: return 1;
175: }
176:
1.850 albertel 177: sub create_connection {
1.853 albertel 178: my ($hostname,$lonid) = @_;
1.851 albertel 179: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 180: Type => SOCK_STREAM,
181: Timeout => 10);
182: return 0 if (!$client);
1.890 albertel 183: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 184: my $result = <$client>;
185: chomp($result);
186: return 1 if ($result eq 'done');
187: return 0;
188: }
189:
1.983 raeburn 190: sub get_server_timezone {
191: my ($cnum,$cdom) = @_;
192: my $home=&homeserver($cnum,$cdom);
193: if ($home ne 'no_host') {
194: my $cachetime = 24*3600;
195: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
196: if (defined($cached)) {
197: return $timezone;
198: } else {
199: my $timezone = &reply('servertimezone',$home);
200: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
201: }
202: }
203: }
1.850 albertel 204:
1.1106 raeburn 205: sub get_server_distarch {
206: my ($lonhost,$ignore_cache) = @_;
207: if (defined($lonhost)) {
208: if (!defined(&hostname($lonhost))) {
209: return;
210: }
211: my $cachetime = 12*3600;
212: if (!$ignore_cache) {
213: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
214: if (defined($cached)) {
215: return $distarch;
216: }
217: }
218: my $rep = &reply('serverdistarch',$lonhost);
219: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
220: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
221: $rep eq '') {
222: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
223: }
224: }
225: return;
226: }
227:
1.993 raeburn 228: sub get_server_loncaparev {
1.1073 raeburn 229: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 230: if (defined($lonhost)) {
231: if (!defined(&hostname($lonhost))) {
232: undef($lonhost);
233: }
234: }
235: if (!defined($lonhost)) {
236: if (defined(&domain($dom,'primary'))) {
237: $lonhost=&domain($dom,'primary');
238: if ($lonhost eq 'no_host') {
239: undef($lonhost);
240: }
241: }
242: }
243: if (defined($lonhost)) {
1.1073 raeburn 244: my $cachetime = 12*3600;
245: if (!$ignore_cache) {
246: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
247: if (defined($cached)) {
248: return $loncaparev;
249: }
250: }
251: my ($answer,$loncaparev);
252: my @ids=¤t_machine_ids();
253: if (grep(/^\Q$lonhost\E$/,@ids)) {
254: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 255: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 256: $loncaparev = $1;
257: }
258: } else {
259: $answer = &reply('serverloncaparev',$lonhost);
260: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
261: if ($caller eq 'loncron') {
262: my $ua=new LWP::UserAgent;
1.1082 raeburn 263: $ua->timeout(4);
1.1073 raeburn 264: my $protocol = $protocol{$lonhost};
265: $protocol = 'http' if ($protocol ne 'https');
266: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
267: my $request=new HTTP::Request('GET',$url);
268: my $response=$ua->request($request);
269: unless ($response->is_error()) {
270: my $content = $response->content;
1.1081 raeburn 271: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 272: $loncaparev = $1;
273: }
274: }
275: } else {
276: $loncaparev = $loncaparevs{$lonhost};
277: }
1.1081 raeburn 278: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 279: $loncaparev = $1;
280: }
1.993 raeburn 281: }
1.1073 raeburn 282: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 283: }
284: }
285:
1.1074 raeburn 286: sub get_server_homeID {
287: my ($hostname,$ignore_cache,$caller) = @_;
288: unless ($ignore_cache) {
289: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
290: if (defined($cached)) {
291: return $serverhomeID;
292: }
293: }
294: my $cachetime = 12*3600;
295: my $serverhomeID;
296: if ($caller eq 'loncron') {
297: my @machine_ids = &machine_ids($hostname);
298: foreach my $id (@machine_ids) {
299: my $response = &reply('serverhomeID',$id);
300: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
301: $serverhomeID = $response;
302: last;
303: }
304: }
305: if ($serverhomeID eq '') {
306: $serverhomeID = $machine_ids[-1];
307: }
308: } else {
309: $serverhomeID = $serverhomeIDs{$hostname};
310: }
311: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
312: }
313:
1.1121 raeburn 314: sub get_remote_globals {
315: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 316: my ($result,%returnhash,%whatneeded);
317: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 318: foreach my $what (sort(keys(%{$whathash}))) {
319: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 320: my ($response,$cached);
1.1121 raeburn 321: unless ($ignore_cache) {
1.1125 raeburn 322: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 323: }
324: if (defined($cached)) {
1.1125 raeburn 325: $returnhash{$what} = $response;
1.1121 raeburn 326: } else {
1.1125 raeburn 327: $whatneeded{$what} = 1;
1.1121 raeburn 328: }
329: }
1.1125 raeburn 330: if (keys(%whatneeded) == 0) {
331: $result = 'ok';
332: } else {
1.1121 raeburn 333: my $requested = &freeze_escape(\%whatneeded);
334: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 335: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
336: ($rep eq 'unknown_cmd')) {
337: $result = $rep;
338: } else {
339: $result = 'ok';
1.1121 raeburn 340: my @pairs=split(/\&/,$rep);
1.1125 raeburn 341: foreach my $item (@pairs) {
342: my ($key,$value)=split(/=/,$item,2);
343: my $what = &unescape($key);
344: my $hashid = $lonhost.'-'.$what;
345: $returnhash{$what}=&thaw_unescape($value);
346: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 347: }
348: }
349: }
350: }
1.1125 raeburn 351: return ($result,\%returnhash);
1.1121 raeburn 352: }
353:
1.1124 raeburn 354: sub remote_devalidate_cache {
1.1172.2.35 raeburn 355: my ($lonhost,$cachekeys) = @_;
356: my $items;
357: return unless (ref($cachekeys) eq 'ARRAY');
358: my $cachestr = join('&',@{$cachekeys});
359: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 360: }
361:
1.1 albertel 362: # -------------------------------------------------- Non-critical communication
363: sub subreply {
364: my ($cmd,$server)=@_;
1.838 albertel 365: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 366: #
367: # With loncnew process trimming, there's a timing hole between lonc server
368: # process exit and the master server picking up the listen on the AF_UNIX
369: # socket. In that time interval, a lock file will exist:
370:
371: my $lockfile=$peerfile.".lock";
372: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
373: sleep(1);
374: }
375: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 376: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 377: #
1.550 foxr 378: # We'll give the connection a few tries before abandoning it. If
379: # connection is not possible, we'll con_lost back to the client.
380: #
381: my $client;
382: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
383: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
384: Type => SOCK_STREAM,
385: Timeout => 10);
1.869 albertel 386: if ($client) {
1.550 foxr 387: last; # Connected!
1.850 albertel 388: } else {
1.853 albertel 389: &create_connection(&hostname($server),$server);
1.550 foxr 390: }
1.850 albertel 391: sleep(1); # Try again later if failed connection.
1.550 foxr 392: }
393: my $answer;
394: if ($client) {
1.704 albertel 395: print $client "sethost:$server:$cmd\n";
1.550 foxr 396: $answer=<$client>;
397: if (!$answer) { $answer="con_lost"; }
398: chomp($answer);
399: } else {
400: $answer = 'con_lost'; # Failed connection.
401: }
1.1 albertel 402: return $answer;
403: }
404:
405: sub reply {
406: my ($cmd,$server)=@_;
1.838 albertel 407: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 408: my $answer=subreply($cmd,$server);
1.65 www 409: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 410: &logthis("<font color=\"blue\">WARNING:".
1.12 www 411: " $cmd to $server returned $answer</font>");
412: }
1.1 albertel 413: return $answer;
414: }
415:
416: # ----------------------------------------------------------- Send USR1 to lonc
417:
418: sub reconlonc {
1.891 albertel 419: my ($lonid) = @_;
420: my $hostname = &hostname($lonid);
421: if ($lonid) {
422: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
423: if ($hostname && -e $peerfile) {
424: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
425: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
426: Type => SOCK_STREAM,
427: Timeout => 10);
428: if ($client) {
429: print $client ("reset_retries\n");
430: my $answer=<$client>;
431: #reset just this one.
432: }
433: }
434: return;
435: }
436:
1.836 www 437: &logthis("Trying to reconnect lonc");
1.1 albertel 438: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 439: if (open(my $fh,"<$loncfile")) {
1.1 albertel 440: my $loncpid=<$fh>;
441: chomp($loncpid);
442: if (kill 0 => $loncpid) {
443: &logthis("lonc at pid $loncpid responding, sending USR1");
444: kill USR1 => $loncpid;
445: sleep 1;
1.836 www 446: } else {
1.12 www 447: &logthis(
1.672 albertel 448: "<font color=\"blue\">WARNING:".
1.12 www 449: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 450: }
451: } else {
1.836 www 452: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 453: }
454: }
455:
456: # ------------------------------------------------------ Critical communication
1.12 www 457:
1.1 albertel 458: sub critical {
459: my ($cmd,$server)=@_;
1.838 albertel 460: unless (&hostname($server)) {
1.672 albertel 461: &logthis("<font color=\"blue\">WARNING:".
1.89 www 462: " Critical message to unknown server ($server)</font>");
463: return 'no_such_host';
464: }
1.1 albertel 465: my $answer=reply($cmd,$server);
466: if ($answer eq 'con_lost') {
467: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 468: my $answer=reply($cmd,$server);
1.1 albertel 469: if ($answer eq 'con_lost') {
470: my $now=time;
471: my $middlename=$cmd;
1.5 www 472: $middlename=substr($middlename,0,16);
1.1 albertel 473: $middlename=~s/\W//g;
474: my $dfilename=
1.305 www 475: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
476: $dumpcount++;
1.1 albertel 477: {
1.448 albertel 478: my $dfh;
479: if (open($dfh,">$dfilename")) {
480: print $dfh "$cmd\n";
481: close($dfh);
482: }
1.1 albertel 483: }
484: sleep 2;
485: my $wcmd='';
486: {
1.448 albertel 487: my $dfh;
488: if (open($dfh,"<$dfilename")) {
489: $wcmd=<$dfh>;
490: close($dfh);
491: }
1.1 albertel 492: }
493: chomp($wcmd);
1.7 www 494: if ($wcmd eq $cmd) {
1.672 albertel 495: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 496: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 497: &logperm("D:$server:$cmd");
498: return 'con_delayed';
499: } else {
1.672 albertel 500: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 501: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 502: &logperm("F:$server:$cmd");
503: return 'con_failed';
504: }
505: }
506: }
507: return $answer;
1.405 albertel 508: }
509:
1.755 albertel 510: # ------------------------------------------- check if return value is an error
511:
512: sub error {
513: my ($result) = @_;
1.756 albertel 514: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 515: if ($2 == 2) { return undef; }
516: return $1;
517: }
518: return undef;
519: }
520:
1.783 albertel 521: sub convert_and_load_session_env {
522: my ($lonidsdir,$handle)=@_;
523: my @profile;
524: {
1.917 albertel 525: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
526: if (!$opened) {
1.915 albertel 527: return 0;
528: }
1.783 albertel 529: flock($idf,LOCK_SH);
530: @profile=<$idf>;
531: close($idf);
532: }
533: my %temp_env;
534: foreach my $line (@profile) {
1.786 albertel 535: if ($line !~ m/=/) {
536: return 0;
537: }
1.783 albertel 538: chomp($line);
539: my ($envname,$envvalue)=split(/=/,$line,2);
540: $temp_env{&unescape($envname)} = &unescape($envvalue);
541: }
542: unlink("$lonidsdir/$handle.id");
543: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
544: 0640)) {
545: %disk_env = %temp_env;
546: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
547: untie(%disk_env);
548: }
1.786 albertel 549: return 1;
1.783 albertel 550: }
551:
1.374 www 552: # ------------------------------------------- Transfer profile into environment
1.780 albertel 553: my $env_loaded;
554: sub transfer_profile_to_env {
1.788 albertel 555: my ($lonidsdir,$handle,$force_transfer) = @_;
556: if (!$force_transfer && $env_loaded) { return; }
1.374 www 557:
1.720 albertel 558: if (!defined($lonidsdir)) {
559: $lonidsdir = $perlvar{'lonIDsDir'};
560: }
561: if (!defined($handle)) {
562: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
563: }
564:
1.786 albertel 565: my $convert;
566: {
1.917 albertel 567: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
568: if (!$opened) {
1.915 albertel 569: return;
570: }
1.786 albertel 571: flock($idf,LOCK_SH);
572: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
573: &GDBM_READER(),0640)) {
574: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
575: untie(%disk_env);
576: } else {
577: $convert = 1;
578: }
579: }
580: if ($convert) {
581: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
582: &logthis("Failed to load session, or convert session.");
583: }
1.374 www 584: }
1.783 albertel 585:
1.786 albertel 586: my %remove;
1.783 albertel 587: while ( my $envname = each(%env) ) {
1.433 matthew 588: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
589: if ($time < time-300) {
1.783 albertel 590: $remove{$key}++;
1.433 matthew 591: }
592: }
593: }
1.783 albertel 594:
1.619 albertel 595: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 596: $env_loaded=1;
1.783 albertel 597: foreach my $expired_key (keys(%remove)) {
1.433 matthew 598: &delenv($expired_key);
1.374 www 599: }
1.1 albertel 600: }
601:
1.916 albertel 602: # ---------------------------------------------------- Check for valid session
603: sub check_for_valid_session {
1.1172.2.36 raeburn 604: my ($r,$name,$userhashref) = @_;
1.916 albertel 605: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 606: if ($name eq '') {
607: $name = 'lonID';
608: }
609: my $lonid=$cookies{$name};
1.916 albertel 610: return undef if (!$lonid);
611:
612: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 613: my $lonidsdir;
614: if ($name eq 'lonDAV') {
615: $lonidsdir=$r->dir_config('lonDAVsessDir');
616: } else {
617: $lonidsdir=$r->dir_config('lonIDsDir');
618: }
1.916 albertel 619: return undef if (!-e "$lonidsdir/$handle.id");
620:
1.917 albertel 621: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
622: return undef if (!$opened);
1.916 albertel 623:
624: flock($idf,LOCK_SH);
625: my %disk_env;
626: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
627: &GDBM_READER(),0640)) {
628: return undef;
629: }
630:
631: if (!defined($disk_env{'user.name'})
632: || !defined($disk_env{'user.domain'})) {
633: return undef;
634: }
1.1172.2.18 raeburn 635:
1.1172.2.36 raeburn 636: if (ref($userhashref) eq 'HASH') {
637: $userhashref->{'name'} = $disk_env{'user.name'};
638: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 639: }
640:
1.916 albertel 641: return $handle;
642: }
643:
1.830 albertel 644: sub timed_flock {
645: my ($file,$lock_type) = @_;
646: my $failed=0;
647: eval {
648: local $SIG{__DIE__}='DEFAULT';
649: local $SIG{ALRM}=sub {
650: $failed=1;
651: die("failed lock");
652: };
653: alarm(13);
654: flock($file,$lock_type);
655: alarm(0);
656: };
657: if ($failed) {
658: return undef;
659: } else {
660: return 1;
661: }
662: }
663:
1.5 www 664: # ---------------------------------------------------------- Append Environment
665:
666: sub appenv {
1.949 raeburn 667: my ($newenv,$roles) = @_;
668: if (ref($newenv) eq 'HASH') {
669: foreach my $key (keys(%{$newenv})) {
670: my $refused = 0;
671: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
672: $refused = 1;
673: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 674: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 675: if (grep(/^\Q$role\E$/,@{$roles})) {
676: $refused = 0;
677: }
678: }
679: }
680: if ($refused) {
681: &logthis("<font color=\"blue\">WARNING: ".
682: "Attempt to modify environment ".$key." to ".$newenv->{$key}
683: .'</font>');
684: delete($newenv->{$key});
685: } else {
686: $env{$key}=$newenv->{$key};
687: }
688: }
689: my $opened = open(my $env_file,'+<',$env{'user.environment'});
690: if ($opened
691: && &timed_flock($env_file,LOCK_EX)
692: &&
693: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
694: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
695: while (my ($key,$value) = each(%{$newenv})) {
696: $disk_env{$key} = $value;
697: }
698: untie(%disk_env);
1.35 www 699: }
1.191 harris41 700: }
1.56 www 701: return 'ok';
702: }
703: # ----------------------------------------------------- Delete from Environment
704:
705: sub delenv {
1.1104 raeburn 706: my ($delthis,$regexp,$roles) = @_;
707: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
708: my $refused = 1;
709: if (ref($roles) eq 'ARRAY') {
710: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
711: if (grep(/^\Q$role\E$/,@{$roles})) {
712: $refused = 0;
713: }
714: }
715: if ($refused) {
716: &logthis("<font color=\"blue\">WARNING: ".
717: "Attempt to delete from environment ".$delthis);
718: return 'error';
719: }
1.56 www 720: }
1.917 albertel 721: my $opened = open(my $env_file,'+<',$env{'user.environment'});
722: if ($opened
1.915 albertel 723: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 724: &&
725: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
726: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 727: foreach my $key (keys(%disk_env)) {
1.987 raeburn 728: if ($regexp) {
729: if ($key=~/^$delthis/) {
730: delete($env{$key});
731: delete($disk_env{$key});
732: }
733: } else {
734: if ($key=~/^\Q$delthis\E/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: }
1.448 albertel 739: }
1.783 albertel 740: untie(%disk_env);
1.5 www 741: }
742: return 'ok';
1.369 albertel 743: }
744:
1.790 albertel 745: sub get_env_multiple {
746: my ($name) = @_;
747: my @values;
748: if (defined($env{$name})) {
749: # exists is it an array
750: if (ref($env{$name})) {
751: @values=@{ $env{$name} };
752: } else {
753: $values[0]=$env{$name};
754: }
755: }
756: return(@values);
757: }
758:
1.958 www 759: # ------------------------------------------------------------------- Locking
760:
761: sub set_lock {
762: my ($text)=@_;
763: $locknum++;
764: my $id=$$.'-'.$locknum;
765: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
766: 'session.lock.'.$id => $text});
767: return $id;
768: }
769:
770: sub get_locks {
771: my $num=0;
772: my %texts=();
773: foreach my $lock (split(/\,/,$env{'session.locks'})) {
774: if ($lock=~/\w/) {
775: $num++;
776: $texts{$lock}=$env{'session.lock.'.$lock};
777: }
778: }
779: return ($num,%texts);
780: }
781:
782: sub remove_lock {
783: my ($id)=@_;
784: my $newlocks='';
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if (($lock=~/\w/) && ($lock ne $id)) {
787: $newlocks.=','.$lock;
788: }
789: }
790: &appenv({'session.locks' => $newlocks});
791: &delenv('session.lock.'.$id);
792: }
793:
794: sub remove_all_locks {
795: my $activelocks=$env{'session.locks'};
796: foreach my $lock (split(/\,/,$env{'session.locks'})) {
797: if ($lock=~/\w/) {
798: &remove_lock($lock);
799: }
800: }
801: }
802:
803:
1.369 albertel 804: # ------------------------------------------ Find out current server userload
805: sub userload {
806: my $numusers=0;
807: {
808: opendir(LONIDS,$perlvar{'lonIDsDir'});
809: my $filename;
810: my $curtime=time;
811: while ($filename=readdir(LONIDS)) {
1.925 albertel 812: next if ($filename eq '.' || $filename eq '..');
813: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 814: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 815: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 816: }
817: closedir(LONIDS);
818: }
819: my $userloadpercent=0;
820: my $maxuserload=$perlvar{'lonUserLoadLim'};
821: if ($maxuserload) {
1.371 albertel 822: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 823: }
1.372 albertel 824: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 825: return $userloadpercent;
1.283 www 826: }
827:
1.1 albertel 828: # ------------------------------ Find server with least workload from spare.tab
1.11 www 829:
1.1 albertel 830: sub spareserver {
1.1083 raeburn 831: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 832: my $spare_server;
1.370 albertel 833: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 834: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
835: : $userloadpercent;
1.1083 raeburn 836: my ($uint_dom,$remotesessions);
837: if (($udom ne '') && (&domain($udom) ne '')) {
838: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
839: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
840: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
841: $remotesessions = $udomdefaults{'remotesessions'};
842: }
1.1123 raeburn 843: my $spareshash = &this_host_spares($udom);
844: if (ref($spareshash) eq 'HASH') {
845: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
846: foreach my $try_server (@{ $spareshash->{'primary'} }) {
847: if ($uint_dom) {
848: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
849: $try_server));
850: }
851: ($spare_server, $lowest_load) =
852: &compare_server_load($try_server, $spare_server, $lowest_load);
853: }
1.1083 raeburn 854: }
1.784 albertel 855:
1.1123 raeburn 856: my $found_server = ($spare_server ne '' && $lowest_load < 100);
857:
858: if (!$found_server) {
859: if (ref($spareshash->{'default'}) eq 'ARRAY') {
860: foreach my $try_server (@{ $spareshash->{'default'} }) {
861: if ($uint_dom) {
862: next unless (&spare_can_host($udom,$uint_dom,
863: $remotesessions,$try_server));
864: }
865: ($spare_server, $lowest_load) =
866: &compare_server_load($try_server, $spare_server, $lowest_load);
867: }
868: }
869: }
1.784 albertel 870: }
871:
872: if (!$want_server_name) {
1.968 raeburn 873: my $protocol = 'http';
874: if ($protocol{$spare_server} eq 'https') {
875: $protocol = $protocol{$spare_server};
876: }
1.1001 raeburn 877: if (defined($spare_server)) {
878: my $hostname = &hostname($spare_server);
1.1083 raeburn 879: if (defined($hostname)) {
1.1001 raeburn 880: $spare_server = $protocol.'://'.$hostname;
881: }
882: }
1.784 albertel 883: }
884: return $spare_server;
885: }
886:
887: sub compare_server_load {
1.1172.2.41 raeburn 888: my ($try_server, $spare_server, $lowest_load, $required) = @_;
889:
890: if ($required) {
891: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
892: my $remoterev = &get_server_loncaparev(undef,$try_server);
893: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
894: if (($major eq '' && $minor eq '') ||
895: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
896: return ($spare_server,$lowest_load);
897: }
898: }
1.784 albertel 899:
900: my $loadans = &reply('load', $try_server);
901: my $userloadans = &reply('userload',$try_server);
902:
903: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 904: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 905: }
906:
907: my $load;
908: if ($loadans =~ /\d/) {
909: if ($userloadans =~ /\d/) {
910: #both are numbers, pick the bigger one
911: $load = ($loadans > $userloadans) ? $loadans
912: : $userloadans;
1.411 albertel 913: } else {
1.784 albertel 914: $load = $loadans;
1.411 albertel 915: }
1.784 albertel 916: } else {
917: $load = $userloadans;
918: }
919:
920: if (($load =~ /\d/) && ($load < $lowest_load)) {
921: $spare_server = $try_server;
922: $lowest_load = $load;
1.370 albertel 923: }
1.784 albertel 924: return ($spare_server,$lowest_load);
1.202 matthew 925: }
1.914 albertel 926:
927: # --------------------------- ask offload servers if user already has a session
928: sub find_existing_session {
929: my ($udom,$uname) = @_;
1.1123 raeburn 930: my $spareshash = &this_host_spares($udom);
931: if (ref($spareshash) eq 'HASH') {
932: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
933: foreach my $try_server (@{ $spareshash->{'primary'} }) {
934: return $try_server if (&has_user_session($try_server, $udom, $uname));
935: }
936: }
937: if (ref($spareshash->{'default'}) eq 'ARRAY') {
938: foreach my $try_server (@{ $spareshash->{'default'} }) {
939: return $try_server if (&has_user_session($try_server, $udom, $uname));
940: }
941: }
1.914 albertel 942: }
943: return;
944: }
945:
946: # -------------------------------- ask if server already has a session for user
947: sub has_user_session {
948: my ($lonid,$udom,$uname) = @_;
949: my $result = &reply(join(':','userhassession',
950: map {&escape($_)} ($udom,$uname)),$lonid);
951: return 1 if ($result eq 'ok');
952:
953: return 0;
954: }
955:
1.1076 raeburn 956: # --------- determine least loaded server in a user's domain which allows login
957:
958: sub choose_server {
1.1172.2.47 raeburn 959: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 960: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 961: my %servers = &get_servers($udom);
1.1076 raeburn 962: my $lowest_load = 30000;
1.1172.2.47 raeburn 963: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
964: if ($skiploadbal) {
965: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
966: unless (defined($cached)) {
967: my $cachetime = 60*60*24;
968: my %domconfig =
969: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
970: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
971: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
972: $cachetime);
973: }
974: }
975: }
1.1076 raeburn 976: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 977: my $loginvia;
1.1172.2.47 raeburn 978: if ($skiploadbal) {
979: if (ref($balancers) eq 'HASH') {
980: next if (exists($balancers->{$lonhost}));
981: }
982: }
1.1115 raeburn 983: if ($checkloginvia) {
984: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 985: if ($loginvia) {
986: my ($server,$path) = split(/:/,$loginvia);
987: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 988: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 989: if ($login_host eq $server) {
990: $portal_path = $path;
1.1151 raeburn 991: $isredirect = 1;
1.1116 raeburn 992: }
993: } else {
994: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 995: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 996: if ($login_host eq $lonhost) {
997: $portal_path = '';
1.1151 raeburn 998: $isredirect = '';
1.1116 raeburn 999: }
1000: }
1001: } else {
1.1076 raeburn 1002: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1003: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1004: }
1005: }
1006: if ($login_host ne '') {
1.1116 raeburn 1007: $hostname = &hostname($login_host);
1.1076 raeburn 1008: }
1.1151 raeburn 1009: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1010: }
1011:
1.202 matthew 1012: # --------------------------------------------- Try to change a user's password
1013:
1014: sub changepass {
1.799 raeburn 1015: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1016: $currentpass = &escape($currentpass);
1017: $newpass = &escape($newpass);
1.1030 raeburn 1018: my $lonhost = $perlvar{'lonHostID'};
1019: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1020: $server);
1021: if (! $answer) {
1022: &logthis("No reply on password change request to $server ".
1023: "by $uname in domain $udom.");
1024: } elsif ($answer =~ "^ok") {
1025: &logthis("$uname in $udom successfully changed their password ".
1026: "on $server.");
1027: } elsif ($answer =~ "^pwchange_failure") {
1028: &logthis("$uname in $udom was unable to change their password ".
1029: "on $server. The action was blocked by either lcpasswd ".
1030: "or pwchange");
1031: } elsif ($answer =~ "^non_authorized") {
1032: &logthis("$uname in $udom did not get their password correct when ".
1033: "attempting to change it on $server.");
1034: } elsif ($answer =~ "^auth_mode_error") {
1035: &logthis("$uname in $udom attempted to change their password despite ".
1036: "not being locally or internally authenticated on $server.");
1037: } elsif ($answer =~ "^unknown_user") {
1038: &logthis("$uname in $udom attempted to change their password ".
1039: "on $server but were unable to because $server is not ".
1040: "their home server.");
1041: } elsif ($answer =~ "^refused") {
1042: &logthis("$server refused to change $uname in $udom password because ".
1043: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1044: } elsif ($answer =~ "invalid_client") {
1045: &logthis("$server refused to change $uname in $udom password because ".
1046: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1047: }
1048: return $answer;
1.1 albertel 1049: }
1050:
1.169 harris41 1051: # ----------------------- Try to determine user's current authentication scheme
1052:
1053: sub queryauthenticate {
1054: my ($uname,$udom)=@_;
1.456 albertel 1055: my $uhome=&homeserver($uname,$udom);
1056: if (!$uhome) {
1057: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1058: return 'no_host';
1059: }
1060: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1061: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1062: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1063: }
1.456 albertel 1064: return $answer;
1.169 harris41 1065: }
1066:
1.1 albertel 1067: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1068:
1.1 albertel 1069: sub authenticate {
1.1073 raeburn 1070: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1071: $upass=&escape($upass);
1072: $uname= &LONCAPA::clean_username($uname);
1.836 www 1073: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1074: my $newhome;
1.836 www 1075: if ((!$uhome) || ($uhome eq 'no_host')) {
1076: # Maybe the machine was offline and only re-appeared again recently?
1077: &reconlonc();
1078: # One more
1.952 raeburn 1079: $uhome=&homeserver($uname,$udom,1);
1080: if (($uhome eq 'no_host') && $checkdefauth) {
1081: if (defined(&domain($udom,'primary'))) {
1082: $newhome=&domain($udom,'primary');
1083: }
1084: if ($newhome ne '') {
1085: $uhome = $newhome;
1086: }
1087: }
1.836 www 1088: if ((!$uhome) || ($uhome eq 'no_host')) {
1089: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1090: return 'no_host';
1091: }
1.1 albertel 1092: }
1.1073 raeburn 1093: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1094: if ($answer eq 'authorized') {
1.952 raeburn 1095: if ($newhome) {
1096: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1097: return 'no_account_on_host';
1098: } else {
1099: &logthis("User $uname at $udom authorized by $uhome");
1100: return $uhome;
1101: }
1.471 albertel 1102: }
1103: if ($answer eq 'non_authorized') {
1104: &logthis("User $uname at $udom rejected by $uhome");
1105: return 'no_host';
1.9 www 1106: }
1.471 albertel 1107: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1108: return 'no_host';
1109: }
1110:
1.1073 raeburn 1111: sub can_host_session {
1.1074 raeburn 1112: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1113: my $canhost = 1;
1.1074 raeburn 1114: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1115: if (ref($remotesessions) eq 'HASH') {
1116: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1117: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1118: $canhost = 0;
1119: } else {
1120: $canhost = 1;
1121: }
1122: }
1123: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1124: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1125: $canhost = 1;
1126: } else {
1127: $canhost = 0;
1128: }
1129: }
1130: if ($canhost) {
1131: if ($remotesessions->{'version'} ne '') {
1132: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1133: if ($reqmajor ne '' && $reqminor ne '') {
1134: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1135: my $major = $1;
1136: my $minor = $2;
1137: if (($major < $reqmajor ) ||
1138: (($major == $reqmajor) && ($minor < $reqminor))) {
1139: $canhost = 0;
1140: }
1141: } else {
1142: $canhost = 0;
1143: }
1144: }
1145: }
1146: }
1147: }
1148: if ($canhost) {
1149: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1150: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1151: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1152: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1153: if (($uint_dom ne '') &&
1154: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1155: $canhost = 0;
1156: } else {
1157: $canhost = 1;
1158: }
1159: }
1160: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1161: if (($uint_dom ne '') &&
1162: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1163: $canhost = 1;
1164: } else {
1165: $canhost = 0;
1166: }
1167: }
1168: }
1169: }
1170: return $canhost;
1171: }
1172:
1.1083 raeburn 1173: sub spare_can_host {
1174: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1175: my $canhost=1;
1176: my @intdoms;
1177: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1178: if (ref($internet_names) eq 'ARRAY') {
1179: @intdoms = @{$internet_names};
1180: }
1181: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1182: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1183: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1184: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1185: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1186: $canhost = &can_host_session($udom,$try_server,$remoterev,
1187: $remotesessions,
1188: $defdomdefaults{'hostedsessions'});
1189: }
1190: return $canhost;
1191: }
1192:
1.1123 raeburn 1193: sub this_host_spares {
1194: my ($dom) = @_;
1.1126 raeburn 1195: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1196: my @hosts = ¤t_machine_ids();
1197: foreach my $lonhost (@hosts) {
1198: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1199: $dom_in_use = $dom;
1200: $lonhost_in_use = $lonhost;
1.1123 raeburn 1201: last;
1202: }
1203: }
1.1126 raeburn 1204: if ($dom_in_use ne '') {
1205: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1206: }
1207: if (ref($result) ne 'HASH') {
1208: $lonhost_in_use = $perlvar{'lonHostID'};
1209: $dom_in_use = &host_domain($lonhost_in_use);
1210: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1211: if (ref($result) ne 'HASH') {
1212: $result = \%spareid;
1213: }
1214: }
1215: return $result;
1216: }
1217:
1218: sub spares_for_offload {
1219: my ($dom_in_use,$lonhost_in_use) = @_;
1220: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1221: if (defined($cached)) {
1222: return $result;
1223: } else {
1.1126 raeburn 1224: my $cachetime = 60*60*24;
1225: my %domconfig =
1226: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1227: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1228: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1229: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1230: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1231: }
1232: }
1233: }
1234: }
1.1126 raeburn 1235: return;
1.1123 raeburn 1236: }
1237:
1.1129 raeburn 1238: sub get_lonbalancer_config {
1239: my ($servers) = @_;
1240: my ($currbalancer,$currtargets);
1241: if (ref($servers) eq 'HASH') {
1242: foreach my $server (keys(%{$servers})) {
1243: my %what = (
1244: spareid => 1,
1245: perlvar => 1,
1246: );
1247: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1248: if ($result eq 'ok') {
1249: if (ref($returnhash) eq 'HASH') {
1250: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1251: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1252: $currbalancer = $server;
1253: $currtargets = {};
1254: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1255: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1256: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1257: }
1258: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1259: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1260: }
1261: }
1262: last;
1263: }
1264: }
1265: }
1266: }
1267: }
1268: }
1269: return ($currbalancer,$currtargets);
1270: }
1271:
1272: sub check_loadbalancing {
1273: my ($uname,$udom) = @_;
1.1172.2.12 raeburn 1274: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1275: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1276: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1277: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1278: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1279: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1280: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1281: my $serverhomedom = &host_domain($lonhost);
1282:
1283: my $cachetime = 60*60*24;
1284:
1285: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1286: $dom_in_use = $udom;
1287: $homeintdom = 1;
1288: } else {
1289: $dom_in_use = $serverhomedom;
1290: }
1291: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1292: unless (defined($cached)) {
1293: my %domconfig =
1294: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1295: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1296: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1297: }
1298: }
1299: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1300: ($is_balancer,$currtargets,$currrules) =
1301: &check_balancer_result($result,@hosts);
1.1129 raeburn 1302: if ($is_balancer) {
1303: if (ref($currrules) eq 'HASH') {
1304: if ($homeintdom) {
1305: if ($uname ne '') {
1306: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1307: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1308: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1309: $rule_in_effect = $currrules->{'_LC_author'};
1310: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1311: $rule_in_effect = $currrules->{'_LC_adv'}
1312: }
1313: }
1314: if ($rule_in_effect eq '') {
1315: my %userenv = &userenvironment($udom,$uname,'inststatus');
1316: if ($userenv{'inststatus'} ne '') {
1317: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1318: my ($othertitle,$usertypes,$types) =
1319: &Apache::loncommon::sorted_inst_types($udom);
1320: if (ref($types) eq 'ARRAY') {
1321: foreach my $type (@{$types}) {
1322: if (grep(/^\Q$type\E$/,@statuses)) {
1323: if (exists($currrules->{$type})) {
1324: $rule_in_effect = $currrules->{$type};
1325: }
1326: }
1327: }
1328: }
1329: } else {
1330: if (exists($currrules->{'default'})) {
1331: $rule_in_effect = $currrules->{'default'};
1332: }
1333: }
1334: }
1335: } else {
1336: if (exists($currrules->{'default'})) {
1337: $rule_in_effect = $currrules->{'default'};
1338: }
1339: }
1340: } else {
1341: if ($currrules->{'_LC_external'} ne '') {
1342: $rule_in_effect = $currrules->{'_LC_external'};
1343: }
1344: }
1345: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1346: $uname,$udom);
1347: }
1348: }
1349: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1350: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1351: unless (defined($cached)) {
1352: my %domconfig =
1353: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1354: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1355: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1356: }
1357: }
1358: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1359: ($is_balancer,$currtargets,$currrules) =
1360: &check_balancer_result($result,@hosts);
1361: if ($is_balancer) {
1.1129 raeburn 1362: if (ref($currrules) eq 'HASH') {
1363: if ($currrules->{'_LC_internetdom'} ne '') {
1364: $rule_in_effect = $currrules->{'_LC_internetdom'};
1365: }
1366: }
1367: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1368: $uname,$udom);
1369: }
1370: } else {
1371: if ($perlvar{'lonBalancer'} eq 'yes') {
1372: $is_balancer = 1;
1373: $offloadto = &this_host_spares($dom_in_use);
1374: }
1375: }
1376: } else {
1377: if ($perlvar{'lonBalancer'} eq 'yes') {
1378: $is_balancer = 1;
1379: $offloadto = &this_host_spares($dom_in_use);
1380: }
1381: }
1.1172.2.5 raeburn 1382: if ($is_balancer) {
1383: my $lowest_load = 30000;
1384: if (ref($offloadto) eq 'HASH') {
1385: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1386: foreach my $try_server (@{$offloadto->{'primary'}}) {
1387: ($otherserver,$lowest_load) =
1388: &compare_server_load($try_server,$otherserver,$lowest_load);
1389: }
1.1129 raeburn 1390: }
1.1172.2.5 raeburn 1391: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1392:
1.1172.2.5 raeburn 1393: if (!$found_server) {
1394: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1395: foreach my $try_server (@{$offloadto->{'default'}}) {
1396: ($otherserver,$lowest_load) =
1397: &compare_server_load($try_server,$otherserver,$lowest_load);
1398: }
1399: }
1400: }
1401: } elsif (ref($offloadto) eq 'ARRAY') {
1402: if (@{$offloadto} == 1) {
1403: $otherserver = $offloadto->[0];
1404: } elsif (@{$offloadto} > 1) {
1405: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1406: ($otherserver,$lowest_load) =
1407: &compare_server_load($try_server,$otherserver,$lowest_load);
1408: }
1409: }
1410: }
1.1172.2.5 raeburn 1411: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1412: $is_balancer = 0;
1413: if ($uname ne '' && $udom ne '') {
1414: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1415:
1416: &appenv({'user.loadbalexempt' => $lonhost,
1417: 'user.loadbalcheck.time' => time});
1418: }
1.1129 raeburn 1419: }
1420: }
1421: }
1422: return ($is_balancer,$otherserver);
1423: }
1424:
1.1172.2.12 raeburn 1425: sub check_balancer_result {
1426: my ($result,@hosts) = @_;
1427: my ($is_balancer,$currtargets,$currrules);
1428: if (ref($result) eq 'HASH') {
1429: if ($result->{'lonhost'} ne '') {
1430: my $currbalancer = $result->{'lonhost'};
1431: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1432: $is_balancer = 1;
1433: $currtargets = $result->{'targets'};
1434: $currrules = $result->{'rules'};
1435: }
1436: } else {
1437: foreach my $key (keys(%{$result})) {
1438: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1439: (ref($result->{$key}) eq 'HASH')) {
1440: $is_balancer = 1;
1441: $currrules = $result->{$key}{'rules'};
1442: $currtargets = $result->{$key}{'targets'};
1443: last;
1444: }
1445: }
1446: }
1447: }
1448: return ($is_balancer,$currtargets,$currrules);
1449: }
1450:
1.1129 raeburn 1451: sub get_loadbalancer_targets {
1452: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1453: my $offloadto;
1.1172.2.4 raeburn 1454: if ($rule_in_effect eq 'none') {
1455: return [$perlvar{'lonHostID'}];
1456: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1457: $offloadto = $currtargets;
1458: } else {
1459: if ($rule_in_effect eq 'homeserver') {
1460: my $homeserver = &homeserver($uname,$udom);
1461: if ($homeserver ne 'no_host') {
1462: $offloadto = [$homeserver];
1463: }
1464: } elsif ($rule_in_effect eq 'externalbalancer') {
1465: my %domconfig =
1466: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1467: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1468: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1469: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1470: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1471: }
1472: }
1473: } else {
1.1172.2.7 raeburn 1474: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1475: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1476: if (&hostname($remotebalancer) ne '') {
1477: $offloadto = [$remotebalancer];
1478: }
1479: }
1480: } elsif (&hostname($rule_in_effect) ne '') {
1481: $offloadto = [$rule_in_effect];
1482: }
1483: }
1484: return $offloadto;
1485: }
1486:
1.1127 raeburn 1487: sub internet_dom_servers {
1488: my ($dom) = @_;
1489: my (%uniqservers,%servers);
1490: my $primaryserver = &hostname(&domain($dom,'primary'));
1491: my @machinedoms = &machine_domains($primaryserver);
1492: foreach my $mdom (@machinedoms) {
1493: my %currservers = %servers;
1494: my %server = &get_servers($mdom);
1495: %servers = (%currservers,%server);
1496: }
1497: my %by_hostname;
1498: foreach my $id (keys(%servers)) {
1499: push(@{$by_hostname{$servers{$id}}},$id);
1500: }
1501: foreach my $hostname (sort(keys(%by_hostname))) {
1502: if (@{$by_hostname{$hostname}} > 1) {
1503: my $match = 0;
1504: foreach my $id (@{$by_hostname{$hostname}}) {
1505: if (&host_domain($id) eq $dom) {
1506: $uniqservers{$id} = $hostname;
1507: $match = 1;
1508: }
1509: }
1510: unless ($match) {
1511: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1512: }
1513: } else {
1514: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1515: }
1516: }
1517: return %uniqservers;
1518: }
1519:
1.1 albertel 1520: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1521:
1.599 albertel 1522: my %homecache;
1.1 albertel 1523: sub homeserver {
1.230 stredwic 1524: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1525: my $index="$uname:$udom";
1.426 albertel 1526:
1.599 albertel 1527: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1528:
1529: my %servers = &get_servers($udom,'library');
1530: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1531: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1532: exists($badServerCache{$tryserver}));
1.841 albertel 1533:
1534: my $answer=reply("home:$udom:$uname",$tryserver);
1535: if ($answer eq 'found') {
1536: delete($badServerCache{$tryserver});
1537: return $homecache{$index}=$tryserver;
1538: } elsif ($answer eq 'no_host') {
1539: $badServerCache{$tryserver}=1;
1540: }
1.1 albertel 1541: }
1542: return 'no_host';
1.70 www 1543: }
1544:
1545: # ------------------------------------- Find the usernames behind a list of IDs
1546:
1547: sub idget {
1548: my ($udom,@ids)=@_;
1549: my %returnhash=();
1550:
1.841 albertel 1551: my %servers = &get_servers($udom,'library');
1552: foreach my $tryserver (keys(%servers)) {
1553: my $idlist=join('&',@ids);
1554: $idlist=~tr/A-Z/a-z/;
1555: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1556: my @answer=();
1557: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1558: @answer=split(/\&/,$reply);
1559: } ;
1560: my $i;
1561: for ($i=0;$i<=$#ids;$i++) {
1562: if ($answer[$i]) {
1563: $returnhash{$ids[$i]}=$answer[$i];
1564: }
1565: }
1566: }
1.70 www 1567: return %returnhash;
1568: }
1569:
1570: # ------------------------------------- Find the IDs behind a list of usernames
1571:
1572: sub idrget {
1573: my ($udom,@unames)=@_;
1574: my %returnhash=();
1.800 albertel 1575: foreach my $uname (@unames) {
1576: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1577: }
1.70 www 1578: return %returnhash;
1579: }
1580:
1581: # ------------------------------- Store away a list of names and associated IDs
1582:
1583: sub idput {
1584: my ($udom,%ids)=@_;
1585: my %servers=();
1.800 albertel 1586: foreach my $uname (keys(%ids)) {
1587: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1588: my $uhom=&homeserver($uname,$udom);
1.70 www 1589: if ($uhom ne 'no_host') {
1.800 albertel 1590: my $id=&escape($ids{$uname});
1.70 www 1591: $id=~tr/A-Z/a-z/;
1.800 albertel 1592: my $esc_unam=&escape($uname);
1.70 www 1593: if ($servers{$uhom}) {
1.800 albertel 1594: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1595: } else {
1.800 albertel 1596: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1597: }
1598: }
1.191 harris41 1599: }
1.800 albertel 1600: foreach my $server (keys(%servers)) {
1601: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1602: }
1.344 www 1603: }
1604:
1.1172.2.30 raeburn 1605: # ---------------------------------------- Delete unwanted IDs from ids.db file
1606:
1607: sub iddel {
1608: my ($udom,$idshashref,$uhome)=@_;
1609: my %result=();
1610: unless (ref($idshashref) eq 'HASH') {
1611: return %result;
1612: }
1613: my %servers=();
1614: while (my ($id,$uname) = each(%{$idshashref})) {
1615: my $uhom;
1616: if ($uhome) {
1617: $uhom = $uhome;
1618: } else {
1619: $uhom=&homeserver($uname,$udom);
1620: }
1621: if ($uhom ne 'no_host') {
1622: if ($servers{$uhom}) {
1623: $servers{$uhom}.='&'.&escape($id);
1624: } else {
1625: $servers{$uhom}=&escape($id);
1626: }
1627: }
1628: }
1629: foreach my $server (keys(%servers)) {
1630: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1631: }
1632: return %result;
1633: }
1634:
1.1023 raeburn 1635: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1636: sub dump_dom {
1.1165 droeschl 1637: my ($namespace, $udom, $regexp) = @_;
1638:
1639: $udom ||= $env{'user.domain'};
1640:
1641: return () unless $udom;
1642:
1643: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1644: }
1645:
1.1023 raeburn 1646: # ------------------------------------------ get items from domain db files
1.806 raeburn 1647:
1648: sub get_dom {
1.860 raeburn 1649: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1650: return if ($udom eq 'public');
1.806 raeburn 1651: my $items='';
1652: foreach my $item (@$storearr) {
1653: $items.=&escape($item).'&';
1654: }
1655: $items=~s/\&$//;
1.860 raeburn 1656: if (!$udom) {
1657: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1658: return if ($udom eq 'public');
1.860 raeburn 1659: if (defined(&domain($udom,'primary'))) {
1660: $uhome=&domain($udom,'primary');
1661: } else {
1.874 albertel 1662: undef($uhome);
1.860 raeburn 1663: }
1664: } else {
1665: if (!$uhome) {
1666: if (defined(&domain($udom,'primary'))) {
1667: $uhome=&domain($udom,'primary');
1668: }
1669: }
1670: }
1671: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1672: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1673: my %returnhash;
1.875 albertel 1674: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1675: return %returnhash;
1676: }
1.806 raeburn 1677: my @pairs=split(/\&/,$rep);
1678: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1679: return @pairs;
1680: }
1681: my $i=0;
1682: foreach my $item (@$storearr) {
1683: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1684: $i++;
1685: }
1686: return %returnhash;
1687: } else {
1.880 banghart 1688: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1689: }
1690: }
1691:
1692: # -------------------------------------------- put items in domain db files
1693:
1694: sub put_dom {
1.860 raeburn 1695: my ($namespace,$storehash,$udom,$uhome)=@_;
1696: if (!$udom) {
1697: $udom=$env{'user.domain'};
1698: if (defined(&domain($udom,'primary'))) {
1699: $uhome=&domain($udom,'primary');
1700: } else {
1.874 albertel 1701: undef($uhome);
1.860 raeburn 1702: }
1703: } else {
1704: if (!$uhome) {
1705: if (defined(&domain($udom,'primary'))) {
1706: $uhome=&domain($udom,'primary');
1707: }
1708: }
1709: }
1710: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1711: my $items='';
1712: foreach my $item (keys(%$storehash)) {
1713: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1714: }
1715: $items=~s/\&$//;
1716: return &reply("putdom:$udom:$namespace:$items",$uhome);
1717: } else {
1.860 raeburn 1718: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1719: }
1720: }
1721:
1.1023 raeburn 1722: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1723: sub newput_dom {
1.1023 raeburn 1724: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1725: my $result;
1726: if (!$udom) {
1727: $udom=$env{'user.domain'};
1728: }
1.1023 raeburn 1729: if ($udom) {
1730: my $uname = &get_domainconfiguser($udom);
1731: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1732: }
1733: return $result;
1734: }
1735:
1.1023 raeburn 1736: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1737: sub del_dom {
1.1023 raeburn 1738: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1739: if (ref($storearr) eq 'ARRAY') {
1740: if (!$udom) {
1741: $udom=$env{'user.domain'};
1742: }
1.1023 raeburn 1743: if ($udom) {
1744: my $uname = &get_domainconfiguser($udom);
1745: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1746: }
1747: }
1748: }
1749:
1.1023 raeburn 1750: # ----------------------------------construct domainconfig user for a domain
1751: sub get_domainconfiguser {
1752: my ($udom) = @_;
1753: return $udom.'-domainconfig';
1754: }
1755:
1.837 raeburn 1756: sub retrieve_inst_usertypes {
1757: my ($udom) = @_;
1758: my (%returnhash,@order);
1.989 raeburn 1759: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1760: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1761: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1762: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1763: } else {
1764: if (defined(&domain($udom,'primary'))) {
1765: my $uhome=&domain($udom,'primary');
1766: my $rep=&reply("inst_usertypes:$udom",$uhome);
1767: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1768: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1769: return (\%returnhash,\@order);
1770: }
1771: my ($hashitems,$orderitems) = split(/:/,$rep);
1772: my @pairs=split(/\&/,$hashitems);
1773: foreach my $item (@pairs) {
1774: my ($key,$value)=split(/=/,$item,2);
1775: $key = &unescape($key);
1776: next if ($key =~ /^error: 2 /);
1777: $returnhash{$key}=&thaw_unescape($value);
1778: }
1779: my @esc_order = split(/\&/,$orderitems);
1780: foreach my $item (@esc_order) {
1781: push(@order,&unescape($item));
1782: }
1783: } else {
1.1172.2.44 raeburn 1784: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1785: }
1.1172.2.44 raeburn 1786: return (\%returnhash,\@order);
1.837 raeburn 1787: }
1788: }
1789:
1.868 raeburn 1790: sub is_domainimage {
1791: my ($url) = @_;
1792: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1793: if (&domain($1) ne '') {
1794: return '1';
1795: }
1796: }
1797: return;
1798: }
1799:
1.899 raeburn 1800: sub inst_directory_query {
1801: my ($srch) = @_;
1802: my $udom = $srch->{'srchdomain'};
1803: my %results;
1804: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1805: my $outcome;
1.899 raeburn 1806: if ($homeserver ne '') {
1.904 albertel 1807: my $queryid=&reply("querysend:instdirsearch:".
1808: &escape($srch->{'srchby'}).':'.
1809: &escape($srch->{'srchterm'}).':'.
1810: &escape($srch->{'srchtype'}),$homeserver);
1811: my $host=&hostname($homeserver);
1812: if ($queryid !~/^\Q$host\E\_/) {
1813: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1814: return;
1815: }
1816: my $response = &get_query_reply($queryid);
1817: my $maxtries = 5;
1818: my $tries = 1;
1819: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1820: $response = &get_query_reply($queryid);
1821: $tries ++;
1822: }
1823:
1824: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1825: if ($response eq 'unavailable') {
1826: $outcome = $response;
1827: } else {
1828: $outcome = 'ok';
1829: my @matches = split(/\n/,$response);
1830: foreach my $match (@matches) {
1831: my ($key,$value) = split(/=/,$match);
1832: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1833: }
1.899 raeburn 1834: }
1835: }
1836: }
1.909 raeburn 1837: return ($outcome,%results);
1.899 raeburn 1838: }
1839:
1840: sub usersearch {
1841: my ($srch) = @_;
1842: my $dom = $srch->{'srchdomain'};
1843: my %results;
1844: my %libserv = &all_library();
1845: my $query = 'usersearch';
1846: foreach my $tryserver (keys(%libserv)) {
1847: if (&host_domain($tryserver) eq $dom) {
1848: my $host=&hostname($tryserver);
1849: my $queryid=
1.911 raeburn 1850: &reply("querysend:".&escape($query).':'.
1851: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1852: &escape($srch->{'srchtype'}).':'.
1853: &escape($srch->{'srchterm'}),$tryserver);
1854: if ($queryid !~/^\Q$host\E\_/) {
1855: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1856: next;
1.899 raeburn 1857: }
1858: my $reply = &get_query_reply($queryid);
1859: my $maxtries = 1;
1860: my $tries = 1;
1861: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1862: $reply = &get_query_reply($queryid);
1863: $tries ++;
1864: }
1865: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1866: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1867: } else {
1.911 raeburn 1868: my @matches;
1869: if ($reply =~ /\n/) {
1870: @matches = split(/\n/,$reply);
1871: } else {
1872: @matches = split(/\&/,$reply);
1873: }
1.899 raeburn 1874: foreach my $match (@matches) {
1875: my ($uname,$udom,%userhash);
1.911 raeburn 1876: foreach my $entry (split(/:/,$match)) {
1877: my ($key,$value) =
1878: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1879: $userhash{$key} = $value;
1880: if ($key eq 'username') {
1881: $uname = $value;
1882: } elsif ($key eq 'domain') {
1883: $udom = $value;
1.911 raeburn 1884: }
1.899 raeburn 1885: }
1886: $results{$uname.':'.$udom} = \%userhash;
1887: }
1888: }
1889: }
1890: }
1891: return %results;
1892: }
1893:
1.912 raeburn 1894: sub get_instuser {
1895: my ($udom,$uname,$id) = @_;
1896: my $homeserver = &domain($udom,'primary');
1897: my ($outcome,%results);
1898: if ($homeserver ne '') {
1899: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1900: &escape($id).':'.&escape($udom),$homeserver);
1901: my $host=&hostname($homeserver);
1902: if ($queryid !~/^\Q$host\E\_/) {
1903: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1904: return;
1905: }
1906: my $response = &get_query_reply($queryid);
1907: my $maxtries = 5;
1908: my $tries = 1;
1909: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1910: $response = &get_query_reply($queryid);
1911: $tries ++;
1912: }
1913: if (!&error($response) && $response ne 'refused') {
1914: if ($response eq 'unavailable') {
1915: $outcome = $response;
1916: } else {
1917: $outcome = 'ok';
1918: my @matches = split(/\n/,$response);
1919: foreach my $match (@matches) {
1920: my ($key,$value) = split(/=/,$match);
1921: $results{&unescape($key)} = &thaw_unescape($value);
1922: }
1923: }
1924: }
1925: }
1926: my %userinfo;
1927: if (ref($results{$uname}) eq 'HASH') {
1928: %userinfo = %{$results{$uname}};
1929: }
1930: return ($outcome,%userinfo);
1931: }
1932:
1933: sub inst_rulecheck {
1.923 raeburn 1934: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1935: my %returnhash;
1936: if ($udom ne '') {
1937: if (ref($rules) eq 'ARRAY') {
1938: @{$rules} = map {&escape($_);} (@{$rules});
1939: my $rulestr = join(':',@{$rules});
1940: my $homeserver=&domain($udom,'primary');
1941: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1942: my $response;
1943: if ($item eq 'username') {
1944: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1945: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1946: $homeserver));
1.923 raeburn 1947: } elsif ($item eq 'id') {
1948: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1949: ':'.&escape($id).':'.$rulestr,
1950: $homeserver));
1.945 raeburn 1951: } elsif ($item eq 'selfcreate') {
1952: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1953: &escape($udom).':'.&escape($uname).
1954: ':'.$rulestr,$homeserver));
1.923 raeburn 1955: }
1.912 raeburn 1956: if ($response ne 'refused') {
1957: my @pairs=split(/\&/,$response);
1958: foreach my $item (@pairs) {
1959: my ($key,$value)=split(/=/,$item,2);
1960: $key = &unescape($key);
1961: next if ($key =~ /^error: 2 /);
1962: $returnhash{$key}=&thaw_unescape($value);
1963: }
1964: }
1965: }
1966: }
1967: }
1968: return %returnhash;
1969: }
1970:
1971: sub inst_userrules {
1.923 raeburn 1972: my ($udom,$check) = @_;
1.912 raeburn 1973: my (%ruleshash,@ruleorder);
1974: if ($udom ne '') {
1975: my $homeserver=&domain($udom,'primary');
1976: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1977: my $response;
1978: if ($check eq 'id') {
1979: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1980: $homeserver);
1.943 raeburn 1981: } elsif ($check eq 'email') {
1982: $response=&reply('instemailrules:'.&escape($udom),
1983: $homeserver);
1.923 raeburn 1984: } else {
1985: $response=&reply('instuserrules:'.&escape($udom),
1986: $homeserver);
1987: }
1.912 raeburn 1988: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1989: ($response ne 'unknown_cmd') &&
1.912 raeburn 1990: ($response ne 'no_such_host')) {
1991: my ($hashitems,$orderitems) = split(/:/,$response);
1992: my @pairs=split(/\&/,$hashitems);
1993: foreach my $item (@pairs) {
1994: my ($key,$value)=split(/=/,$item,2);
1995: $key = &unescape($key);
1996: next if ($key =~ /^error: 2 /);
1997: $ruleshash{$key}=&thaw_unescape($value);
1998: }
1999: my @esc_order = split(/\&/,$orderitems);
2000: foreach my $item (@esc_order) {
2001: push(@ruleorder,&unescape($item));
2002: }
2003: }
2004: }
2005: }
2006: return (\%ruleshash,\@ruleorder);
2007: }
2008:
1.976 raeburn 2009: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2010:
2011: sub get_domain_defaults {
1.1172.2.35 raeburn 2012: my ($domain,$ignore_cache) = @_;
2013: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2014: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2015: unless ($ignore_cache) {
2016: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2017: if (defined($cached)) {
2018: if (ref($result) eq 'HASH') {
2019: return %{$result};
2020: }
1.943 raeburn 2021: }
2022: }
2023: my %domdefaults;
2024: my %domconfig =
1.989 raeburn 2025: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2026: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2027: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2028: 'requestauthor','selfenrollment',
2029: 'coursecategories'],$domain);
1.1172.2.41 raeburn 2030: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2031: if (ref($domconfig{'defaults'}) eq 'HASH') {
2032: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2033: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2034: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2035: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2036: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2037: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2038: } else {
2039: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2040: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2041: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2042: }
1.976 raeburn 2043: if (ref($domconfig{'quotas'}) eq 'HASH') {
2044: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2045: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2046: } else {
2047: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2048: }
1.1172.2.6 raeburn 2049: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2050: foreach my $item (@usertools) {
2051: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2052: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2053: }
2054: }
1.1172.2.29 raeburn 2055: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2056: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2057: }
1.976 raeburn 2058: }
1.985 raeburn 2059: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2060: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2061: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2062: }
2063: }
1.1172.2.9 raeburn 2064: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2065: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2066: }
1.989 raeburn 2067: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2068: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2069: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2070: }
2071: }
1.1047 raeburn 2072: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.41 raeburn 2073: foreach my $type (@coursetypes) {
2074: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2075: unless ($type eq 'community') {
2076: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2077: }
2078: }
2079: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2080: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2081: }
1.1172.2.30 raeburn 2082: }
1.1047 raeburn 2083: }
1.1073 raeburn 2084: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2085: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2086: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2087: }
2088: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2089: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2090: }
2091: }
1.1172.2.41 raeburn 2092: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2093: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2094: my @settings = ('types','registered','enroll_dates','access_dates','section',
2095: 'approval','limit');
2096: foreach my $type (@coursetypes) {
2097: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2098: my @mgrdc = ();
2099: foreach my $item (@settings) {
2100: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2101: push(@mgrdc,$item);
2102: }
2103: }
2104: if (@mgrdc) {
2105: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2106: }
2107: }
2108: }
2109: }
2110: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2111: foreach my $type (@coursetypes) {
2112: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2113: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2114: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2115: }
2116: }
2117: }
2118: }
2119: }
1.1172.2.46 raeburn 2120: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2121: $domdefaults{'catauth'} = 'std';
2122: $domdefaults{'catunauth'} = 'std';
2123: if ($domconfig{'coursecategories'}{'auth'}) {
2124: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2125: }
2126: if ($domconfig{'coursecategories'}{'unauth'}) {
2127: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2128: }
2129: }
1.1172.2.23 raeburn 2130: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2131: return %domdefaults;
2132: }
2133:
1.344 www 2134: # --------------------------------------------------- Assign a key to a student
2135:
2136: sub assign_access_key {
1.364 www 2137: #
2138: # a valid key looks like uname:udom#comments
2139: # comments are being appended
2140: #
1.498 www 2141: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2142: $kdom=
1.620 albertel 2143: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2144: $knum=
1.620 albertel 2145: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2146: $cdom=
1.620 albertel 2147: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2148: $cnum=
1.620 albertel 2149: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2150: $udom=$env{'user.name'} unless (defined($udom));
2151: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2152: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2153: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2154: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2155: # assigned to this person
2156: # - this should not happen,
1.345 www 2157: # unless something went wrong
2158: # the first time around
2159: # ready to assign
1.364 www 2160: $logentry=$1.'; '.$logentry;
1.496 www 2161: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2162: $kdom,$knum) eq 'ok') {
1.345 www 2163: # key now belongs to user
1.346 www 2164: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2165: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2166: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2167: return 'ok';
2168: } else {
2169: return
2170: 'error: Count not permanently assign key, will need to be re-entered later.';
2171: }
2172: } else {
2173: return 'error: Could not assign key, try again later.';
2174: }
1.364 www 2175: } elsif (!$existing{$ckey}) {
1.345 www 2176: # the key does not exist
2177: return 'error: The key does not exist';
2178: } else {
2179: # the key is somebody else's
2180: return 'error: The key is already in use';
2181: }
1.344 www 2182: }
2183:
1.364 www 2184: # ------------------------------------------ put an additional comment on a key
2185:
2186: sub comment_access_key {
2187: #
2188: # a valid key looks like uname:udom#comments
2189: # comments are being appended
2190: #
2191: my ($ckey,$cdom,$cnum,$logentry)=@_;
2192: $cdom=
1.620 albertel 2193: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2194: $cnum=
1.620 albertel 2195: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2196: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2197: if ($existing{$ckey}) {
2198: $existing{$ckey}.='; '.$logentry;
2199: # ready to assign
1.367 www 2200: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2201: $cdom,$cnum) eq 'ok') {
2202: return 'ok';
2203: } else {
2204: return 'error: Count not store comment.';
2205: }
2206: } else {
2207: # the key does not exist
2208: return 'error: The key does not exist';
2209: }
2210: }
2211:
1.344 www 2212: # ------------------------------------------------------ Generate a set of keys
2213:
2214: sub generate_access_keys {
1.364 www 2215: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2216: $cdom=
1.620 albertel 2217: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2218: $cnum=
1.620 albertel 2219: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2220: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2221: unless (($cdom) && ($cnum)) { return 0; }
2222: if ($number>10000) { return 0; }
2223: sleep(2); # make sure don't get same seed twice
2224: srand(time()^($$+($$<<15))); # from "Programming Perl"
2225: my $total=0;
2226: for (my $i=1;$i<=$number;$i++) {
2227: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2228: sprintf("%lx",int(100000*rand)).'-'.
2229: sprintf("%lx",int(100000*rand));
2230: $newkey=~s/1/g/g; # folks mix up 1 and l
2231: $newkey=~s/0/h/g; # and also 0 and O
2232: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2233: if ($existing{$newkey}) {
2234: $i--;
2235: } else {
1.364 www 2236: if (&put('accesskeys',
2237: { $newkey => '# generated '.localtime().
1.620 albertel 2238: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2239: '; '.$logentry },
2240: $cdom,$cnum) eq 'ok') {
1.344 www 2241: $total++;
2242: }
2243: }
2244: }
1.620 albertel 2245: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2246: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2247: return $total;
2248: }
2249:
2250: # ------------------------------------------------------- Validate an accesskey
2251:
2252: sub validate_access_key {
2253: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2254: $cdom=
1.620 albertel 2255: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2256: $cnum=
1.620 albertel 2257: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2258: $udom=$env{'user.domain'} unless (defined($udom));
2259: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2260: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2261: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2262: }
2263:
2264: # ------------------------------------- Find the section of student in a course
1.652 albertel 2265: sub devalidate_getsection_cache {
2266: my ($udom,$unam,$courseid)=@_;
2267: my $hashid="$udom:$unam:$courseid";
2268: &devalidate_cache_new('getsection',$hashid);
2269: }
1.298 matthew 2270:
1.815 albertel 2271: sub courseid_to_courseurl {
2272: my ($courseid) = @_;
2273: #already url style courseid
2274: return $courseid if ($courseid =~ m{^/});
2275:
2276: if (exists($env{'course.'.$courseid.'.num'})) {
2277: my $cnum = $env{'course.'.$courseid.'.num'};
2278: my $cdom = $env{'course.'.$courseid.'.domain'};
2279: return "/$cdom/$cnum";
2280: }
2281:
2282: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2283: if (exists($courseinfo{'num'})) {
2284: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2285: }
2286:
2287: return undef;
2288: }
2289:
1.298 matthew 2290: sub getsection {
2291: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2292: my $cachetime=1800;
1.551 albertel 2293:
2294: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2295: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2296: if (defined($cached)) { return $result; }
2297:
1.298 matthew 2298: my %Pending;
2299: my %Expired;
2300: #
2301: # Each role can either have not started yet (pending), be active,
2302: # or have expired.
2303: #
2304: # If there is an active role, we are done.
2305: #
2306: # If there is more than one role which has not started yet,
2307: # choose the one which will start sooner
2308: # If there is one role which has not started yet, return it.
2309: #
2310: # If there is more than one expired role, choose the one which ended last.
2311: # If there is a role which has expired, return it.
2312: #
1.815 albertel 2313: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2314: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2315: foreach my $key (keys(%roleshash)) {
1.479 albertel 2316: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2317: my $section=$1;
2318: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2319: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2320: my $now=time;
1.548 albertel 2321: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2322: $Expired{$end}=$section;
2323: next;
2324: }
1.548 albertel 2325: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2326: $Pending{$start}=$section;
2327: next;
2328: }
1.599 albertel 2329: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2330: }
2331: #
2332: # Presumedly there will be few matching roles from the above
2333: # loop and the sorting time will be negligible.
2334: if (scalar(keys(%Pending))) {
2335: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2336: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2337: }
2338: if (scalar(keys(%Expired))) {
2339: my @sorted = sort {$a <=> $b} keys(%Expired);
2340: my $time = pop(@sorted);
1.599 albertel 2341: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2342: }
1.599 albertel 2343: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2344: }
1.70 www 2345:
1.599 albertel 2346: sub save_cache {
2347: &purge_remembered();
1.722 albertel 2348: #&Apache::loncommon::validate_page();
1.620 albertel 2349: undef(%env);
1.780 albertel 2350: undef($env_loaded);
1.599 albertel 2351: }
1.452 albertel 2352:
1.599 albertel 2353: my $to_remember=-1;
2354: my %remembered;
2355: my %accessed;
2356: my $kicks=0;
2357: my $hits=0;
1.849 albertel 2358: sub make_key {
2359: my ($name,$id) = @_;
1.872 albertel 2360: if (length($id) > 65
2361: && length(&escape($id)) > 200) {
2362: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2363: }
1.849 albertel 2364: return &escape($name.':'.$id);
2365: }
2366:
1.599 albertel 2367: sub devalidate_cache_new {
2368: my ($name,$id,$debug) = @_;
2369: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2370: $id=&make_key($name,$id);
1.599 albertel 2371: $memcache->delete($id);
2372: delete($remembered{$id});
2373: delete($accessed{$id});
2374: }
2375:
2376: sub is_cached_new {
2377: my ($name,$id,$debug) = @_;
1.849 albertel 2378: $id=&make_key($name,$id);
1.599 albertel 2379: if (exists($remembered{$id})) {
1.1133 foxr 2380: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2381: $accessed{$id}=[&gettimeofday()];
2382: $hits++;
2383: return ($remembered{$id},1);
2384: }
2385: my $value = $memcache->get($id);
2386: if (!(defined($value))) {
2387: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2388: return (undef,undef);
1.416 albertel 2389: }
1.599 albertel 2390: if ($value eq '__undef__') {
2391: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2392: $value=undef;
2393: }
2394: &make_room($id,$value,$debug);
2395: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2396: return ($value,1);
2397: }
2398:
2399: sub do_cache_new {
2400: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2401: $id=&make_key($name,$id);
1.599 albertel 2402: my $setvalue=$value;
2403: if (!defined($setvalue)) {
2404: $setvalue='__undef__';
2405: }
1.623 albertel 2406: if (!defined($time) ) {
2407: $time=600;
2408: }
1.599 albertel 2409: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2410: my $result = $memcache->set($id,$setvalue,$time);
2411: if (! $result) {
1.872 albertel 2412: &logthis("caching of id -> $id failed");
1.910 albertel 2413: $memcache->disconnect_all();
1.872 albertel 2414: }
1.600 albertel 2415: # need to make a copy of $value
1.919 albertel 2416: &make_room($id,$value,$debug);
1.599 albertel 2417: return $value;
2418: }
2419:
2420: sub make_room {
2421: my ($id,$value,$debug)=@_;
1.919 albertel 2422:
2423: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2424: : $value;
1.599 albertel 2425: if ($to_remember<0) { return; }
2426: $accessed{$id}=[&gettimeofday()];
2427: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2428: my $to_kick;
2429: my $max_time=0;
2430: foreach my $other (keys(%accessed)) {
2431: if (&tv_interval($accessed{$other}) > $max_time) {
2432: $to_kick=$other;
2433: $max_time=&tv_interval($accessed{$other});
2434: }
2435: }
2436: delete($remembered{$to_kick});
2437: delete($accessed{$to_kick});
2438: $kicks++;
2439: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2440: return;
2441: }
2442:
1.599 albertel 2443: sub purge_remembered {
1.604 albertel 2444: #&logthis("Tossing ".scalar(keys(%remembered)));
2445: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2446: undef(%remembered);
2447: undef(%accessed);
1.428 albertel 2448: }
1.70 www 2449: # ------------------------------------- Read an entry from a user's environment
2450:
2451: sub userenvironment {
2452: my ($udom,$unam,@what)=@_;
1.976 raeburn 2453: my $items;
2454: foreach my $item (@what) {
2455: $items.=&escape($item).'&';
2456: }
2457: $items=~s/\&$//;
1.70 www 2458: my %returnhash=();
1.1009 raeburn 2459: my $uhome = &homeserver($unam,$udom);
2460: unless ($uhome eq 'no_host') {
2461: my @answer=split(/\&/,
2462: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2463: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2464: return %returnhash;
2465: }
1.1009 raeburn 2466: my $i;
2467: for ($i=0;$i<=$#what;$i++) {
2468: $returnhash{$what[$i]}=&unescape($answer[$i]);
2469: }
1.70 www 2470: }
2471: return %returnhash;
1.1 albertel 2472: }
2473:
1.617 albertel 2474: # ---------------------------------------------------------- Get a studentphoto
2475: sub studentphoto {
2476: my ($udom,$unam,$ext) = @_;
2477: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2478: if (defined($env{'request.course.id'})) {
1.708 raeburn 2479: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2480: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2481: return(&retrievestudentphoto($udom,$unam,$ext));
2482: } else {
2483: my ($result,$perm_reqd)=
1.707 albertel 2484: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2485: if ($result eq 'ok') {
2486: if (!($perm_reqd eq 'yes')) {
2487: return(&retrievestudentphoto($udom,$unam,$ext));
2488: }
2489: }
2490: }
2491: }
2492: } else {
2493: my ($result,$perm_reqd) =
1.707 albertel 2494: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2495: if ($result eq 'ok') {
2496: if (!($perm_reqd eq 'yes')) {
2497: return(&retrievestudentphoto($udom,$unam,$ext));
2498: }
2499: }
2500: }
2501: return '/adm/lonKaputt/lonlogo_broken.gif';
2502: }
2503:
2504: sub retrievestudentphoto {
2505: my ($udom,$unam,$ext,$type) = @_;
2506: my $home=&Apache::lonnet::homeserver($unam,$udom);
2507: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2508: if ($ret eq 'ok') {
2509: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2510: if ($type eq 'thumbnail') {
2511: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2512: }
2513: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2514: return $tokenurl;
2515: } else {
2516: if ($type eq 'thumbnail') {
2517: return '/adm/lonKaputt/genericstudent_tn.gif';
2518: } else {
2519: return '/adm/lonKaputt/lonlogo_broken.gif';
2520: }
1.617 albertel 2521: }
2522: }
2523:
1.263 www 2524: # -------------------------------------------------------------------- New chat
2525:
2526: sub chatsend {
1.724 raeburn 2527: my ($newentry,$anon,$group)=@_;
1.620 albertel 2528: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2529: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2530: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2531: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2532: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2533: &escape($newentry)).':'.$group,$chome);
1.292 www 2534: }
2535:
2536: # ------------------------------------------ Find current version of a resource
2537:
2538: sub getversion {
2539: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2540: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2541: return ¤tversion(&filelocation('',$fname));
2542: }
2543:
2544: sub currentversion {
2545: my $fname=shift;
2546: my $author=$fname;
2547: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2548: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2549: my $home=&homeserver($uname,$udom);
1.292 www 2550: if ($home eq 'no_host') {
2551: return -1;
2552: }
1.1112 www 2553: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2554: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2555: return -1;
2556: }
1.1112 www 2557: return $answer;
1.263 www 2558: }
2559:
1.1111 www 2560: #
2561: # Return special version number of resource if set by override, empty otherwise
2562: #
2563: sub usedversion {
2564: my $fname=shift;
2565: unless ($fname) { $fname=$env{'request.uri'}; }
2566: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2567: if ($urlversion) { return $urlversion; }
2568: return '';
2569: }
2570:
1.1 albertel 2571: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2572:
1.1 albertel 2573: sub subscribe {
2574: my $fname=shift;
1.761 raeburn 2575: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2576: $fname=~s/[\n\r]//g;
1.1 albertel 2577: my $author=$fname;
2578: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2579: my ($udom,$uname)=split(/\//,$author);
2580: my $home=homeserver($uname,$udom);
1.335 albertel 2581: if ($home eq 'no_host') {
2582: return 'not_found';
1.1 albertel 2583: }
2584: my $answer=reply("sub:$fname",$home);
1.64 www 2585: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2586: $answer.=' by '.$home;
2587: }
1.1 albertel 2588: return $answer;
2589: }
2590:
1.8 www 2591: # -------------------------------------------------------------- Replicate file
2592:
2593: sub repcopy {
2594: my $filename=shift;
1.23 www 2595: $filename=~s/\/+/\//g;
1.1142 raeburn 2596: my $londocroot = $perlvar{'lonDocRoot'};
2597: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2598: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2599: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2600: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2601: return &repcopy_userfile($filename);
2602: }
1.532 albertel 2603: $filename=~s/[\n\r]//g;
1.8 www 2604: my $transname="$filename.in.transfer";
1.828 www 2605: # FIXME: this should flock
1.607 raeburn 2606: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2607: my $remoteurl=subscribe($filename);
1.64 www 2608: if ($remoteurl =~ /^con_lost by/) {
2609: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2610: return 'unavailable';
1.8 www 2611: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2612: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2613: return 'not_found';
1.64 www 2614: } elsif ($remoteurl =~ /^rejected by/) {
2615: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2616: return 'forbidden';
1.20 www 2617: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2618: return 'ok';
1.8 www 2619: } else {
1.290 www 2620: my $author=$filename;
2621: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2622: my ($udom,$uname)=split(/\//,$author);
2623: my $home=homeserver($uname,$udom);
2624: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2625: my @parts=split(/\//,$filename);
2626: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2627: if ($path ne "$londocroot/res") {
1.8 www 2628: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2629: return 'bad_request';
1.8 www 2630: }
2631: my $count;
2632: for ($count=5;$count<$#parts;$count++) {
2633: $path.="/$parts[$count]";
2634: if ((-e $path)!=1) {
2635: mkdir($path,0777);
2636: }
2637: }
2638: my $ua=new LWP::UserAgent;
2639: my $request=new HTTP::Request('GET',"$remoteurl");
2640: my $response=$ua->request($request,$transname);
2641: if ($response->is_error()) {
2642: unlink($transname);
2643: my $message=$response->status_line;
1.672 albertel 2644: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2645: ." LWP get: $message: $filename</font>");
1.607 raeburn 2646: return 'unavailable';
1.8 www 2647: } else {
1.16 www 2648: if ($remoteurl!~/\.meta$/) {
2649: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2650: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2651: if ($mresponse->is_error()) {
2652: unlink($filename.'.meta');
2653: &logthis(
1.672 albertel 2654: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2655: }
2656: }
1.8 www 2657: rename($transname,$filename);
1.607 raeburn 2658: return 'ok';
1.8 www 2659: }
1.290 www 2660: }
1.8 www 2661: }
1.330 www 2662: }
2663:
2664: # ------------------------------------------------ Get server side include body
2665: sub ssi_body {
1.381 albertel 2666: my ($filelink,%form)=@_;
1.606 matthew 2667: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2668: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2669: }
1.953 www 2670: my $output='';
2671: my $response;
1.980 raeburn 2672: if ($filelink=~/^https?\:/) {
1.954 raeburn 2673: ($output,$response)=&externalssi($filelink);
1.953 www 2674: } else {
1.1004 droeschl 2675: $filelink .= $filelink=~/\?/ ? '&' : '?';
2676: $filelink .= 'inhibitmenu=yes';
1.953 www 2677: ($output,$response)=&ssi($filelink,%form);
2678: }
1.778 albertel 2679: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2680: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2681: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2682: if (wantarray) {
2683: return ($output, $response);
2684: } else {
2685: return $output;
2686: }
1.8 www 2687: }
2688:
1.15 www 2689: # --------------------------------------------------------- Server Side Include
2690:
1.782 albertel 2691: sub absolute_url {
2692: my ($host_name) = @_;
2693: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2694: if ($host_name eq '') {
2695: $host_name = $ENV{'SERVER_NAME'};
2696: }
2697: return $protocol.$host_name;
2698: }
2699:
1.942 foxr 2700: #
2701: # Server side include.
2702: # Parameters:
2703: # fn Possibly encrypted resource name/id.
2704: # form Hash that describes how the rendering should be done
2705: # and other things.
1.944 foxr 2706: # Returns:
1.950 raeburn 2707: # Scalar context: The content of the response.
2708: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2709: #
1.15 www 2710: sub ssi {
2711:
1.944 foxr 2712: my ($fn,%form)=@_;
1.15 www 2713: my $ua=new LWP::UserAgent;
1.23 www 2714: my $request;
1.711 albertel 2715:
2716: $form{'no_update_last_known'}=1;
1.895 albertel 2717: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2718: if (%form) {
1.782 albertel 2719: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 2720: $request->content(join('&',map {
2721: my $name = escape($_);
2722: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2723: ? join("&$name=", map {escape($_) } @{$form{$_}})
2724: : &escape($form{$_}) );
2725: } keys(%form)));
1.23 www 2726: } else {
1.782 albertel 2727: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2728: }
2729:
1.15 www 2730: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2731: my $response= $ua->request($request);
1.944 foxr 2732: if (wantarray) {
1.1172.2.3 raeburn 2733: return ($response->content, $response);
1.944 foxr 2734: } else {
1.1172.2.3 raeburn 2735: return $response->content;
1.942 foxr 2736: }
1.324 www 2737: }
2738:
2739: sub externalssi {
2740: my ($url)=@_;
2741: my $ua=new LWP::UserAgent;
2742: my $request=new HTTP::Request('GET',$url);
2743: my $response=$ua->request($request);
1.954 raeburn 2744: if (wantarray) {
2745: return ($response->content, $response);
2746: } else {
2747: return $response->content;
2748: }
1.15 www 2749: }
1.254 www 2750:
1.492 albertel 2751: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2752:
2753: sub allowuploaded {
2754: my ($srcurl,$url)=@_;
2755: $url=&clutter(&declutter($url));
2756: my $dir=$url;
2757: $dir=~s/\/[^\/]+$//;
2758: my %httpref=();
2759: my $httpurl=&hreflocation('',$url);
2760: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2761: &Apache::lonnet::appenv(\%httpref);
1.254 www 2762: }
1.477 raeburn 2763:
1.1172.2.13 raeburn 2764: #
2765: # Determine if the current user should be able to edit a particular resource,
2766: # when viewing in course context.
2767: # (a) When viewing resource used to determine if "Edit" item is included in
2768: # Functions.
2769: # (b) When displaying folder contents in course editor, used to determine if
2770: # "Edit" link will be displayed alongside resource.
2771: #
2772: # input: six args -- filename (decluttered), course number, course domain,
2773: # url, symb (if registered) and group (if this is a group
2774: # item -- e.g., bulletin board, group page etc.).
2775: # output: array of five scalars --
2776: # $cfile -- url for file editing if editable on current server
2777: # $home -- homeserver of resource (i.e., for author if published,
2778: # or course if uploaded.).
2779: # $switchserver -- 1 if server switch will be needed.
2780: # $forceedit -- 1 if icon/link should be to go to edit mode
2781: # $forceview -- 1 if icon/link should be to go to view mode
2782: #
2783:
2784: sub can_edit_resource {
2785: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2786: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2787: #
2788: # For aboutme pages user can only edit his/her own.
2789: #
2790: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2791: my ($sdom,$sname) = ($1,$2);
2792: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2793: $home = $env{'user.home'};
2794: $cfile = $resurl;
2795: if ($env{'form.forceedit'}) {
2796: $forceview = 1;
2797: } else {
2798: $forceedit = 1;
2799: }
2800: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2801: } else {
2802: return;
2803: }
2804: }
2805:
2806: if ($env{'request.course.id'}) {
2807: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2808: if ($group ne '') {
2809: # if this is a group homepage or group bulletin board, check group privs
2810: my $allowed = 0;
2811: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2812: if ((&allowed('mdg',$env{'request.course.id'}.
2813: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2814: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2815: $allowed = 1;
2816: }
2817: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2818: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2819: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2820: $allowed = 1;
2821: }
2822: }
2823: if ($allowed) {
2824: $home=&homeserver($cnum,$cdom);
2825: if ($env{'form.forceedit'}) {
2826: $forceview = 1;
2827: } else {
2828: $forceedit = 1;
2829: }
2830: $cfile = $resurl;
2831: } else {
2832: return;
2833: }
2834: } else {
1.1172.2.15 raeburn 2835: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2836: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2837: return;
2838: }
2839: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2840: #
2841: # No edit allowed where CC has switched to student role.
2842: #
2843: return;
2844: }
2845: }
2846: }
2847:
2848: if ($file ne '') {
2849: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2850: if (&is_course_upload($file,$cnum,$cdom)) {
2851: $uploaded = 1;
2852: $incourse = 1;
2853: if ($file =~/\.(htm|html|css|js|txt)$/) {
2854: $cfile = &hreflocation('',$file);
2855: if ($env{'form.forceedit'}) {
2856: $forceview = 1;
2857: } else {
2858: $forceedit = 1;
2859: }
2860: }
2861: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2862: $incourse = 1;
2863: if ($env{'form.forceedit'}) {
2864: $forceview = 1;
2865: } else {
2866: $forceedit = 1;
2867: }
2868: $cfile = $resurl;
2869: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2870: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2871: $incourse = 1;
2872: if ($env{'form.forceedit'}) {
2873: $forceview = 1;
2874: } else {
2875: $forceedit = 1;
2876: }
2877: $cfile = $resurl;
2878: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2879: $incourse = 1;
2880: $cfile = $resurl.'/smpedit';
2881: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2882: $incourse = 1;
2883: if ($env{'form.forceedit'}) {
2884: $forceview = 1;
2885: } else {
2886: $forceedit = 1;
2887: }
2888: $cfile = $resurl;
1.1172.2.15 raeburn 2889: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2890: $incourse = 1;
2891: if ($env{'form.forceedit'}) {
2892: $forceview = 1;
2893: } else {
2894: $forceedit = 1;
2895: }
2896: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2897: }
2898: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2899: my $template = '/res/lib/templates/simpleproblem.problem';
2900: if (&is_on_map($template)) {
2901: $incourse = 1;
2902: $forceview = 1;
2903: $cfile = $template;
2904: }
2905: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2906: $incourse = 1;
2907: if ($env{'form.forceedit'}) {
2908: $forceview = 1;
2909: } else {
2910: $forceedit = 1;
2911: }
2912: $cfile = $resurl;
2913: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2914: $incourse = 1;
2915: $forceview = 1;
2916: if ($symb) {
2917: my ($map,$id,$res)=&decode_symb($symb);
2918: $env{'request.symb'} = $symb;
2919: $cfile = &clutter($res);
2920: } else {
2921: $cfile = $env{'form.suppurl'};
2922: $cfile =~ s{^http://}{};
2923: $cfile = '/adm/wrapper/ext/'.$cfile;
2924: }
1.1172.2.31 raeburn 2925: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2926: if ($env{'form.forceedit'}) {
2927: $forceview = 1;
2928: } else {
2929: $forceedit = 1;
2930: }
2931: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2932: }
2933: }
2934: if ($uploaded || $incourse) {
2935: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 2936: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 2937: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2938: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2939: # Check that the user has permission to edit this resource
2940: my $setpriv = 1;
2941: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2942: if (defined($cfudom)) {
2943: $home=&homeserver($cfuname,$cfudom);
2944: $cfile=$file;
2945: }
2946: }
2947: if (($cfile ne '') && (!$incourse || $uploaded) &&
2948: (($home ne '') && ($home ne 'no_host'))) {
2949: my @ids=¤t_machine_ids();
2950: unless (grep(/^\Q$home\E$/,@ids)) {
2951: $switchserver=1;
2952: }
2953: }
2954: }
2955: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2956: }
2957:
2958: sub is_course_upload {
2959: my ($file,$cnum,$cdom) = @_;
2960: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2961: $uploadpath =~ s{^\/}{};
2962: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2963: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2964: return 1;
2965: }
2966: return;
2967: }
2968:
2969: sub in_course {
2970: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2971: if ($hideprivileged) {
2972: my $skipuser;
1.1172.2.23 raeburn 2973: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2974: my @possdoms = ($cdom);
2975: if ($coursehash{'checkforpriv'}) {
2976: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2977: }
2978: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 2979: $skipuser = 1;
2980: if ($coursehash{'nothideprivileged'}) {
2981: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2982: my $user;
2983: if ($item =~ /:/) {
2984: $user = $item;
2985: } else {
2986: $user = join(':',split(/[\@]/,$item));
2987: }
2988: if ($user eq $uname.':'.$udom) {
2989: undef($skipuser);
2990: last;
2991: }
2992: }
2993: }
2994: if ($skipuser) {
2995: return 0;
2996: }
2997: }
2998: }
2999: $type ||= 'any';
3000: if (!defined($cdom) || !defined($cnum)) {
3001: my $cid = $env{'request.course.id'};
3002: $cdom = $env{'course.'.$cid.'.domain'};
3003: $cnum = $env{'course.'.$cid.'.num'};
3004: }
3005: my $typesref;
3006: if (($type eq 'any') || ($type eq 'all')) {
3007: $typesref = ['active','previous','future'];
3008: } elsif ($type eq 'previous' || $type eq 'future') {
3009: $typesref = [$type];
3010: }
3011: my %roles = &get_my_roles($uname,$udom,'userroles',
3012: $typesref,undef,[$cdom]);
3013: my ($tmp) = keys(%roles);
3014: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3015: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3016: if (@course_roles > 0) {
3017: return 1;
3018: }
3019: return 0;
3020: }
3021:
1.478 albertel 3022: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3023: # input: action, courseID, current domain, intended
1.637 raeburn 3024: # path to file, source of file, instruction to parse file for objects,
3025: # ref to hash for embedded objects,
3026: # ref to hash for codebase of java objects.
1.1095 raeburn 3027: # reference to scalar to accommodate mime type determined
3028: # from File::MMagic if $parser = parse.
1.637 raeburn 3029: #
1.485 raeburn 3030: # output: url to file (if action was uploaddoc),
3031: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3032: #
1.478 albertel 3033: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3034: # course.
1.477 raeburn 3035: #
1.478 albertel 3036: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3037: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3038: # course's home server.
1.477 raeburn 3039: #
1.478 albertel 3040: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3041: # be copied from $source (current location) to
3042: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3043: # and will then be copied to
3044: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3045: # course's home server.
1.485 raeburn 3046: #
1.481 raeburn 3047: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3048: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3049: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3050: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3051: # in course's home server.
1.637 raeburn 3052: #
1.477 raeburn 3053:
3054: sub process_coursefile {
1.1095 raeburn 3055: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3056: $mimetype)=@_;
1.477 raeburn 3057: my $fetchresult;
1.638 albertel 3058: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3059: if ($action eq 'propagate') {
1.638 albertel 3060: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3061: $home);
1.481 raeburn 3062: } else {
1.477 raeburn 3063: my $fpath = '';
3064: my $fname = $file;
1.478 albertel 3065: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3066: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3067: my $filepath = &build_filepath($fpath);
1.481 raeburn 3068: if ($action eq 'copy') {
3069: if ($source eq '') {
3070: $fetchresult = 'no source file';
3071: return $fetchresult;
3072: } else {
3073: my $destination = $filepath.'/'.$fname;
3074: rename($source,$destination);
3075: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3076: $home);
1.481 raeburn 3077: }
3078: } elsif ($action eq 'uploaddoc') {
3079: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3080: print $fh $env{'form.'.$source};
1.481 raeburn 3081: close($fh);
1.637 raeburn 3082: if ($parser eq 'parse') {
1.1024 raeburn 3083: my $mm = new File::MMagic;
1.1095 raeburn 3084: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3085: if ($type eq 'text/html') {
1.1024 raeburn 3086: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3087: unless ($parse_result eq 'ok') {
3088: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3089: }
1.637 raeburn 3090: }
1.1095 raeburn 3091: if (ref($mimetype)) {
3092: $$mimetype = $type;
3093: }
1.637 raeburn 3094: }
1.477 raeburn 3095: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3096: $home);
1.481 raeburn 3097: if ($fetchresult eq 'ok') {
3098: return '/uploaded/'.$fpath.'/'.$fname;
3099: } else {
3100: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3101: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3102: return '/adm/notfound.html';
3103: }
1.477 raeburn 3104: }
3105: }
1.485 raeburn 3106: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3107: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3108: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3109: }
3110: return $fetchresult;
3111: }
3112:
1.637 raeburn 3113: sub build_filepath {
3114: my ($fpath) = @_;
3115: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3116: unless ($fpath eq '') {
3117: my @parts=split('/',$fpath);
3118: foreach my $part (@parts) {
3119: $filepath.= '/'.$part;
3120: if ((-e $filepath)!=1) {
3121: mkdir($filepath,0777);
3122: }
3123: }
3124: }
3125: return $filepath;
3126: }
3127:
3128: sub store_edited_file {
1.638 albertel 3129: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3130: my $file = $primary_url;
3131: $file =~ s#^/uploaded/$docudom/$docuname/##;
3132: my $fpath = '';
3133: my $fname = $file;
3134: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3135: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3136: my $filepath = &build_filepath($fpath);
3137: open(my $fh,'>'.$filepath.'/'.$fname);
3138: print $fh $content;
3139: close($fh);
1.638 albertel 3140: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3141: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3142: $home);
1.637 raeburn 3143: if ($$fetchresult eq 'ok') {
3144: return '/uploaded/'.$fpath.'/'.$fname;
3145: } else {
1.638 albertel 3146: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3147: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3148: return '/adm/notfound.html';
3149: }
3150: }
3151:
1.531 albertel 3152: sub clean_filename {
1.831 albertel 3153: my ($fname,$args)=@_;
1.315 www 3154: # Replace Windows backslashes by forward slashes
1.257 www 3155: $fname=~s/\\/\//g;
1.831 albertel 3156: if (!$args->{'keep_path'}) {
3157: # Get rid of everything but the actual filename
3158: $fname=~s/^.*\/([^\/]+)$/$1/;
3159: }
1.315 www 3160: # Replace spaces by underscores
3161: $fname=~s/\s+/\_/g;
3162: # Replace all other weird characters by nothing
1.831 albertel 3163: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3164: # Replace all .\d. sequences with _\d. so they no longer look like version
3165: # numbers
3166: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3167: return $fname;
3168: }
1.1051 raeburn 3169: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3170: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3171: # image with the same aspect ratio as the original, but with dimensions which do
3172: # not exceed $resizewidth and $resizeheight.
3173:
1.984 neumanie 3174: sub resizeImage {
1.1051 raeburn 3175: my ($img_path,$resizewidth,$resizeheight) = @_;
3176: my $ima = Image::Magick->new;
3177: my $resized;
3178: if (-e $img_path) {
3179: $ima->Read($img_path);
3180: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3181: my $width = $ima->Get('width');
3182: my $height = $ima->Get('height');
3183: if ($width > $resizewidth) {
3184: my $factor = $width/$resizewidth;
3185: my $newheight = $height/$factor;
3186: $ima->Scale(width=>$resizewidth,height=>$newheight);
3187: $resized = 1;
3188: }
3189: }
3190: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3191: my $width = $ima->Get('width');
3192: my $height = $ima->Get('height');
3193: if ($height > $resizeheight) {
3194: my $factor = $height/$resizeheight;
3195: my $newwidth = $width/$factor;
3196: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3197: $resized = 1;
3198: }
3199: }
3200: if ($resized) {
3201: $ima->Write($img_path);
3202: }
3203: }
3204: return;
1.977 amueller 3205: }
3206:
1.608 albertel 3207: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3208: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3209: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3210: # $context - possible values: coursedoc, existingfile, overwrite,
3211: # canceloverwrite, or ''.
3212: # if 'coursedoc': upload to the current course
3213: # if 'existingfile': write file to tmp/overwrites directory
3214: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3215: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3216: # $subdir - directory in userfile to store the file into
1.858 raeburn 3217: # $parser - instruction to parse file for objects ($parser = parse)
3218: # $allfiles - reference to hash for embedded objects
3219: # $codebase - reference to hash for codebase of java objects
3220: # $desuname - username for permanent storage of uploaded file
3221: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3222: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3223: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3224: # $resizewidth - width (pixels) to which to resize uploaded image
3225: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3226: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3227: # from File::MMagic.
1.858 raeburn 3228: #
1.686 albertel 3229: # output: url of file in userspace, or error: <message>
3230: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3231:
1.531 albertel 3232: sub userfileupload {
1.1090 raeburn 3233: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3234: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3235: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3236: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3237: $fname=&clean_filename($fname);
1.1090 raeburn 3238: # See if there is anything left
1.257 www 3239: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3240: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3241: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3242: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3243: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3244: my $now = time;
1.1090 raeburn 3245: my $filepath;
1.1095 raeburn 3246: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3247: $filepath = 'tmp/helprequests/'.$now;
3248: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3249: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3250: '_'.$env{'user.domain'}.'/pending';
3251: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3252: my ($docuname,$docudom);
3253: if ($destudom) {
3254: $docudom = $destudom;
3255: } else {
3256: $docudom = $env{'user.domain'};
3257: }
3258: if ($destuname) {
3259: $docuname = $destuname;
3260: } else {
3261: $docuname = $env{'user.name'};
3262: }
3263: if (exists($env{'form.group'})) {
3264: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3265: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3266: }
3267: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3268: if ($context eq 'canceloverwrite') {
3269: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3270: if (-e $tempfile) {
3271: my @info = stat($tempfile);
3272: if ($info[9] eq $env{'form.timestamp'}) {
3273: unlink($tempfile);
3274: }
3275: }
3276: return;
1.523 raeburn 3277: }
3278: }
1.1090 raeburn 3279: # Create the directory if not present
1.741 raeburn 3280: my @parts=split(/\//,$filepath);
3281: my $fullpath = $perlvar{'lonDaemons'};
3282: for (my $i=0;$i<@parts;$i++) {
3283: $fullpath .= '/'.$parts[$i];
3284: if ((-e $fullpath)!=1) {
3285: mkdir($fullpath,0777);
3286: }
3287: }
3288: open(my $fh,'>'.$fullpath.'/'.$fname);
3289: print $fh $env{'form.'.$formname};
3290: close($fh);
1.1090 raeburn 3291: if ($context eq 'existingfile') {
3292: my @info = stat($fullpath.'/'.$fname);
3293: return ($fullpath.'/'.$fname,$info[9]);
3294: } else {
3295: return $fullpath.'/'.$fname;
3296: }
1.523 raeburn 3297: }
1.995 raeburn 3298: if ($subdir eq 'scantron') {
3299: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3300: } else {
1.995 raeburn 3301: $fname="$subdir/$fname";
3302: }
1.1090 raeburn 3303: if ($context eq 'coursedoc') {
1.638 albertel 3304: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3305: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3306: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3307: return &finishuserfileupload($docuname,$docudom,
3308: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3309: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3310: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3311: } else {
1.1172.2.21 raeburn 3312: if ($env{'form.folder'}) {
3313: $fname=$env{'form.folder'}.'/'.$fname;
3314: }
1.638 albertel 3315: return &process_coursefile('uploaddoc',$docuname,$docudom,
3316: $fname,$formname,$parser,
1.1095 raeburn 3317: $allfiles,$codebase,$mimetype);
1.481 raeburn 3318: }
1.719 banghart 3319: } elsif (defined($destuname)) {
3320: my $docuname=$destuname;
3321: my $docudom=$destudom;
1.860 raeburn 3322: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3323: $parser,$allfiles,$codebase,
1.1051 raeburn 3324: $thumbwidth,$thumbheight,
1.1095 raeburn 3325: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3326: } else {
1.638 albertel 3327: my $docuname=$env{'user.name'};
3328: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3329: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3330: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3331: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3332: }
1.860 raeburn 3333: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3334: $parser,$allfiles,$codebase,
1.1051 raeburn 3335: $thumbwidth,$thumbheight,
1.1095 raeburn 3336: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3337: }
1.271 www 3338: }
3339:
3340: sub finishuserfileupload {
1.860 raeburn 3341: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3342: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3343: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3344: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3345:
1.860 raeburn 3346: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3347: $file=$fname;
3348: if ($fname=~m|/|) {
3349: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3350: $path.=$fnamepath.'/';
3351: }
1.259 www 3352: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3353: my $count;
3354: for ($count=4;$count<=$#parts;$count++) {
3355: $filepath.="/$parts[$count]";
3356: if ((-e $filepath)!=1) {
3357: mkdir($filepath,0777);
3358: }
3359: }
1.984 neumanie 3360:
1.258 www 3361: # Save the file
3362: {
1.701 albertel 3363: if (!open(FH,'>'.$filepath.'/'.$file)) {
3364: &logthis('Failed to create '.$filepath.'/'.$file);
3365: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3366: return '/adm/notfound.html';
3367: }
1.1090 raeburn 3368: if ($context eq 'overwrite') {
1.1117 foxr 3369: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3370: my $target = $filepath.'/'.$file;
3371: if (-e $source) {
3372: my @info = stat($source);
3373: if ($info[9] eq $env{'form.timestamp'}) {
3374: unless (&File::Copy::move($source,$target)) {
3375: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3376: return "Moving from $source failed";
3377: }
3378: } else {
3379: return "Temporary file: $source had unexpected date/time for last modification";
3380: }
3381: } else {
3382: return "Temporary file: $source missing";
3383: }
3384: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3385: &logthis('Failed to write to '.$filepath.'/'.$file);
3386: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3387: return '/adm/notfound.html';
3388: }
1.570 albertel 3389: close(FH);
1.1051 raeburn 3390: if ($resizewidth && $resizeheight) {
3391: my $mm = new File::MMagic;
3392: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3393: if ($mime_type =~ m{^image/}) {
3394: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3395: }
1.977 amueller 3396: }
1.258 www 3397: }
1.1152 raeburn 3398: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3399: if (ref($mimetype)) {
3400: if ($$mimetype eq '') {
3401: my $mm = new File::MMagic;
3402: my $type = $mm->checktype_filename($filepath.'/'.$file);
3403: $$mimetype = $type;
3404: }
3405: }
3406: }
1.637 raeburn 3407: if ($parser eq 'parse') {
1.1152 raeburn 3408: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3409: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3410: $allfiles,$codebase);
3411: unless ($parse_result eq 'ok') {
3412: &logthis('Failed to parse '.$filepath.$file.
3413: ' for embedded media: '.$parse_result);
3414: }
1.637 raeburn 3415: }
3416: }
1.860 raeburn 3417: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3418: my $input = $filepath.'/'.$file;
3419: my $output = $filepath.'/'.'tn-'.$file;
3420: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3421: system("convert -sample $thumbsize $input $output");
3422: if (-e $filepath.'/'.'tn-'.$file) {
3423: $fetchthumb = 1;
3424: }
3425: }
1.858 raeburn 3426:
1.259 www 3427: # Notify homeserver to grep it
3428: #
1.984 neumanie 3429: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3430: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3431: if ($fetchresult eq 'ok') {
1.860 raeburn 3432: if ($fetchthumb) {
3433: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3434: if ($thumbresult ne 'ok') {
3435: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3436: $docuhome.': '.$thumbresult);
3437: }
3438: }
1.259 www 3439: #
1.258 www 3440: # Return the URL to it
1.494 albertel 3441: return '/uploaded/'.$path.$file;
1.263 www 3442: } else {
1.494 albertel 3443: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3444: ': '.$fetchresult);
1.263 www 3445: return '/adm/notfound.html';
1.858 raeburn 3446: }
1.493 albertel 3447: }
3448:
1.637 raeburn 3449: sub extract_embedded_items {
1.961 raeburn 3450: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3451: my @state = ();
1.1164 raeburn 3452: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3453: my %javafiles = (
3454: codebase => '',
3455: code => '',
3456: archive => ''
3457: );
3458: my %mediafiles = (
3459: src => '',
3460: movie => '',
3461: );
1.648 raeburn 3462: my $p;
3463: if ($content) {
3464: $p = HTML::LCParser->new($content);
3465: } else {
1.961 raeburn 3466: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3467: }
1.641 albertel 3468: while (my $t=$p->get_token()) {
1.640 albertel 3469: if ($t->[0] eq 'S') {
3470: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3471: push(@state, $tagname);
1.648 raeburn 3472: if (lc($tagname) eq 'allow') {
3473: &add_filetype($allfiles,$attr->{'src'},'src');
3474: }
1.640 albertel 3475: if (lc($tagname) eq 'img') {
3476: &add_filetype($allfiles,$attr->{'src'},'src');
3477: }
1.886 albertel 3478: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3479: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3480: &add_filetype($allfiles,$attr->{'href'},'href');
3481: }
1.886 albertel 3482: }
1.645 raeburn 3483: if (lc($tagname) eq 'script') {
1.1164 raeburn 3484: my $src;
1.645 raeburn 3485: if ($attr->{'archive'} =~ /\.jar$/i) {
3486: &add_filetype($allfiles,$attr->{'archive'},'archive');
3487: } else {
1.1164 raeburn 3488: if ($attr->{'src'} ne '') {
3489: $src = $attr->{'src'};
3490: &add_filetype($allfiles,$src,'src');
3491: }
3492: }
3493: my $text = $p->get_trimmed_text();
3494: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3495: my @swfargs = split(/,/,$1);
3496: foreach my $item (@swfargs) {
3497: $item =~ s/["']//g;
3498: $item =~ s/^\s+//;
3499: $item =~ s/\s+$//;
3500: }
3501: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3502: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3503: push(@{$related{$swfargs[0]}},$swfargs[2]);
3504: } else {
3505: $related{$swfargs[0]} = [$swfargs[2]];
3506: }
3507: }
1.645 raeburn 3508: }
3509: }
3510: if (lc($tagname) eq 'link') {
3511: if (lc($attr->{'rel'}) eq 'stylesheet') {
3512: &add_filetype($allfiles,$attr->{'href'},'href');
3513: }
3514: }
1.640 albertel 3515: if (lc($tagname) eq 'object' ||
3516: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3517: foreach my $item (keys(%javafiles)) {
3518: $javafiles{$item} = '';
3519: }
1.1164 raeburn 3520: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3521: $lastids{lc($tagname)} = $attr->{'id'};
3522: }
1.640 albertel 3523: }
3524: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3525: my $name = lc($attr->{'name'});
3526: foreach my $item (keys(%javafiles)) {
3527: if ($name eq $item) {
3528: $javafiles{$item} = $attr->{'value'};
3529: last;
3530: }
3531: }
1.1164 raeburn 3532: my $pathfrom;
1.640 albertel 3533: foreach my $item (keys(%mediafiles)) {
3534: if ($name eq $item) {
1.1164 raeburn 3535: $pathfrom = $attr->{'value'};
3536: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3537: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3538: last;
3539: }
3540: }
1.1164 raeburn 3541: if ($name eq 'flashvars') {
3542: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3543: }
3544: if ($pathfrom ne '') {
3545: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3546: $pathfrom);
3547: }
1.640 albertel 3548: }
3549: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3550: foreach my $item (keys(%javafiles)) {
3551: if ($attr->{$item}) {
3552: $javafiles{$item} = $attr->{$item};
3553: last;
3554: }
3555: }
3556: foreach my $item (keys(%mediafiles)) {
3557: if ($attr->{$item}) {
3558: &add_filetype($allfiles,$attr->{$item},$item);
3559: last;
3560: }
3561: }
1.1164 raeburn 3562: if (lc($tagname) eq 'embed') {
3563: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3564: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3565: $attr->{'src'});
3566: }
3567: }
1.640 albertel 3568: }
1.1172.2.35 raeburn 3569: if (lc($tagname) eq 'iframe') {
3570: my $src = $attr->{'src'} ;
3571: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3572: &add_filetype($allfiles,$src,'src');
3573: } elsif ($src =~ m{^/}) {
3574: if ($env{'request.course.id'}) {
3575: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3576: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3577: my $url = &hreflocation('',$fullpath);
3578: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3579: my $relpath = $1;
3580: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3581: &add_filetype($allfiles,$1,'src');
3582: }
3583: }
3584: }
3585: }
3586: }
1.1164 raeburn 3587: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3588: pop(@state);
1.1164 raeburn 3589: }
1.640 albertel 3590: } elsif ($t->[0] eq 'E') {
3591: my ($tagname) = ($t->[1]);
3592: if ($javafiles{'codebase'} ne '') {
3593: $javafiles{'codebase'} .= '/';
3594: }
3595: if (lc($tagname) eq 'applet' ||
3596: lc($tagname) eq 'object' ||
3597: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3598: ) {
3599: foreach my $item (keys(%javafiles)) {
3600: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3601: my $file=$javafiles{'codebase'}.$javafiles{$item};
3602: &add_filetype($allfiles,$file,$item);
3603: }
3604: }
3605: }
3606: pop @state;
3607: }
3608: }
1.1164 raeburn 3609: foreach my $id (sort(keys(%flashvars))) {
3610: if ($shockwave{$id} ne '') {
3611: my @pairs = split(/\&/,$flashvars{$id});
3612: foreach my $pair (@pairs) {
3613: my ($key,$value) = split(/\=/,$pair);
3614: if ($key eq 'thumb') {
3615: &add_filetype($allfiles,$value,$key);
3616: } elsif ($key eq 'content') {
3617: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3618: my ($ext) = ($value =~ /\.([^.]+)$/);
3619: if ($ext ne '') {
3620: &add_filetype($allfiles,$path.$value,$ext);
3621: }
3622: }
3623: }
3624: }
3625: }
1.637 raeburn 3626: return 'ok';
3627: }
3628:
1.639 albertel 3629: sub add_filetype {
3630: my ($allfiles,$file,$type)=@_;
3631: if (exists($allfiles->{$file})) {
3632: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3633: push(@{$allfiles->{$file}}, &escape($type));
3634: }
3635: } else {
3636: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3637: }
3638: }
3639:
1.1164 raeburn 3640: sub embedded_dependency {
3641: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3642: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3643: if (($identifier ne '') &&
3644: (ref($related->{$identifier}) eq 'ARRAY') &&
3645: ($pathfrom ne '')) {
3646: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3647: foreach my $dep (@{$related->{$identifier}}) {
3648: &add_filetype($allfiles,$path.$dep,'object');
3649: }
3650: }
3651: }
3652: return;
3653: }
3654:
1.493 albertel 3655: sub removeuploadedurl {
1.984 neumanie 3656: my ($url)=@_;
3657: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3658: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3659: }
3660:
3661: sub removeuserfile {
3662: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3663: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3664: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3665: if ($result eq 'ok') {
1.798 raeburn 3666: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3667: my $metafile = $fname.'.meta';
3668: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3669: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3670: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3671: my $sqlresult =
1.823 albertel 3672: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3673: 'portfolio_metadata',$group,
3674: 'delete');
1.798 raeburn 3675: }
3676: }
3677: return $result;
1.257 www 3678: }
1.15 www 3679:
1.530 albertel 3680: sub mkdiruserfile {
3681: my ($docuname,$docudom,$dir)=@_;
3682: my $home=&homeserver($docuname,$docudom);
3683: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3684: }
3685:
1.531 albertel 3686: sub renameuserfile {
3687: my ($docuname,$docudom,$old,$new)=@_;
3688: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3689: my $result = &reply("renameuserfile:$docudom:$docuname:".
3690: &escape("$old").':'.&escape("$new"),$home);
3691: if ($result eq 'ok') {
3692: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3693: my $oldmeta = $old.'.meta';
3694: my $newmeta = $new.'.meta';
3695: my $metaresult =
3696: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3697: my $url = "/uploaded/$docudom/$docuname/$old";
3698: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3699: my $sqlresult =
1.823 albertel 3700: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3701: 'portfolio_metadata',$group,
3702: 'delete');
1.798 raeburn 3703: }
3704: }
3705: return $result;
1.531 albertel 3706: }
3707:
1.14 www 3708: # ------------------------------------------------------------------------- Log
3709:
3710: sub log {
3711: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3712: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3713: }
3714:
3715: # ------------------------------------------------------------------ Course Log
1.352 www 3716: #
3717: # This routine flushes several buffers of non-mission-critical nature
3718: #
1.157 www 3719:
3720: sub flushcourselogs {
1.352 www 3721: &logthis('Flushing log buffers');
3722: #
3723: # course logs
3724: # This is a log of all transactions in a course, which can be used
3725: # for data mining purposes
3726: #
3727: # It also collects the courseid database, which lists last transaction
3728: # times and course titles for all courseids
3729: #
3730: my %courseidbuffer=();
1.921 raeburn 3731: foreach my $crsid (keys(%courselogs)) {
1.352 www 3732: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3733: &escape($courselogs{$crsid}),
3734: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3735: delete $courselogs{$crsid};
3736: } else {
3737: &logthis('Failed to flush log buffer for '.$crsid);
3738: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3739: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3740: " exceeded maximum size, deleting.</font>");
3741: delete $courselogs{$crsid};
3742: }
1.352 www 3743: }
1.920 raeburn 3744: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3745: 'description' => $coursedescrbuf{$crsid},
3746: 'inst_code' => $courseinstcodebuf{$crsid},
3747: 'type' => $coursetypebuf{$crsid},
3748: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3749: };
1.191 harris41 3750: }
1.352 www 3751: #
3752: # Write course id database (reverse lookup) to homeserver of courses
3753: # Is used in pickcourse
3754: #
1.840 albertel 3755: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3756: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3757: $courseidbuffer{$crs_home},
3758: $crs_home,'timeonly');
1.352 www 3759: }
3760: #
3761: # File accesses
3762: # Writes to the dynamic metadata of resources to get hit counts, etc.
3763: #
1.449 matthew 3764: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3765: if ($entry =~ /___count$/) {
3766: my ($dom,$name);
1.807 albertel 3767: ($dom,$name,undef)=
1.811 albertel 3768: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3769: if (! defined($dom) || $dom eq '' ||
3770: ! defined($name) || $name eq '') {
1.620 albertel 3771: my $cid = $env{'request.course.id'};
3772: $dom = $env{'request.'.$cid.'.domain'};
3773: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3774: }
1.450 matthew 3775: my $value = $accesshash{$entry};
3776: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3777: my %temphash=($url => $value);
1.449 matthew 3778: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3779: if ($result eq 'ok') {
3780: delete $accesshash{$entry};
3781: }
3782: } else {
1.811 albertel 3783: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3784: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3785: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3786: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3787: delete $accesshash{$entry};
3788: }
1.185 www 3789: }
1.191 harris41 3790: }
1.352 www 3791: #
3792: # Roles
3793: # Reverse lookup of user roles for course faculty/staff and co-authorship
3794: #
1.800 albertel 3795: foreach my $entry (keys(%userrolehash)) {
1.351 www 3796: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3797: split(/\:/,$entry);
3798: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3799: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3800: $rudom,$runame) eq 'ok') {
3801: delete $userrolehash{$entry};
3802: }
3803: }
1.662 raeburn 3804: #
3805: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3806: #
3807: my %domrolebuffer = ();
1.1000 raeburn 3808: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3809: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3810: if ($domrolebuffer{$rudom}) {
3811: $domrolebuffer{$rudom}.='&'.&escape($entry).
3812: '='.&escape($domainrolehash{$entry});
3813: } else {
3814: $domrolebuffer{$rudom}.=&escape($entry).
3815: '='.&escape($domainrolehash{$entry});
3816: }
3817: delete $domainrolehash{$entry};
3818: }
3819: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3820: my %servers = &get_servers($dom,'library');
3821: foreach my $tryserver (keys(%servers)) {
3822: unless (&reply('domroleput:'.$dom.':'.
3823: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3824: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3825: }
1.662 raeburn 3826: }
3827: }
1.186 www 3828: $dumpcount++;
1.157 www 3829: }
3830:
3831: sub courselog {
3832: my $what=shift;
1.158 www 3833: $what=time.':'.$what;
1.620 albertel 3834: unless ($env{'request.course.id'}) { return ''; }
3835: $coursedombuf{$env{'request.course.id'}}=
3836: $env{'course.'.$env{'request.course.id'}.'.domain'};
3837: $coursenumbuf{$env{'request.course.id'}}=
3838: $env{'course.'.$env{'request.course.id'}.'.num'};
3839: $coursehombuf{$env{'request.course.id'}}=
3840: $env{'course.'.$env{'request.course.id'}.'.home'};
3841: $coursedescrbuf{$env{'request.course.id'}}=
3842: $env{'course.'.$env{'request.course.id'}.'.description'};
3843: $courseinstcodebuf{$env{'request.course.id'}}=
3844: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3845: $courseownerbuf{$env{'request.course.id'}}=
3846: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3847: $coursetypebuf{$env{'request.course.id'}}=
3848: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3849: if (defined $courselogs{$env{'request.course.id'}}) {
3850: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3851: } else {
1.620 albertel 3852: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3853: }
1.620 albertel 3854: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3855: &flushcourselogs();
3856: }
1.158 www 3857: }
3858:
3859: sub courseacclog {
3860: my $fnsymb=shift;
1.620 albertel 3861: unless ($env{'request.course.id'}) { return ''; }
3862: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3863: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3864: $what.=':POST';
1.583 matthew 3865: # FIXME: Probably ought to escape things....
1.800 albertel 3866: foreach my $key (keys(%env)) {
3867: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3868: my $formitem = $1;
3869: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3870: $what.=':'.$formitem.'='.$env{$key};
3871: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3872: $what.=':'.$formitem.'='.$env{$key};
3873: }
1.158 www 3874: }
1.191 harris41 3875: }
1.583 matthew 3876: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3877: # FIXME: We should not be depending on a form parameter that someone
3878: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3879: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3880: $what.= ':POST';
3881: # FIXME: Probably ought to escape things....
3882: foreach my $element ('courseexp','crsfulltext','crsrelated',
3883: 'crsdiscuss') {
1.620 albertel 3884: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3885: }
3886: }
1.158 www 3887: }
3888: &courselog($what);
1.149 www 3889: }
3890:
1.185 www 3891: sub countacc {
3892: my $url=&declutter(shift);
1.458 matthew 3893: return if (! defined($url) || $url eq '');
1.620 albertel 3894: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3895: #
3896: # Mark that this url was used in this course
3897: #
1.620 albertel 3898: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3899: #
3900: # Increase the access count for this resource in this child process
3901: #
1.281 www 3902: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3903: $accesshash{$key}++;
1.185 www 3904: }
1.349 www 3905:
1.361 www 3906: sub linklog {
3907: my ($from,$to)=@_;
3908: $from=&declutter($from);
3909: $to=&declutter($to);
3910: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3911: $accesshash{$to.'___'.$from.'___goto'}=1;
3912: }
1.1160 www 3913:
3914: sub statslog {
3915: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3916: if ($users<2) { return; }
3917: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3918: 'course' => $env{'request.course.id'},
3919: 'sections' => '"all"',
3920: 'num_students' => $users,
3921: 'part' => $part,
3922: 'symb' => $symb,
3923: 'mean_tries' => $av_attempts,
3924: 'deg_of_diff' => $degdiff});
3925: foreach my $key (keys(%dynstore)) {
3926: $accesshash{$key}=$dynstore{$key};
3927: }
3928: }
1.361 www 3929:
1.349 www 3930: sub userrolelog {
3931: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3932: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3933: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3934: $userrolehash
3935: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3936: =$tend.':'.$tstart;
1.662 raeburn 3937: }
1.1169 droeschl 3938: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3939: $userrolehash
3940: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3941: =$tend.':'.$tstart;
3942: }
1.1169 droeschl 3943: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3944: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3945: $domainrolehash
3946: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3947: = $tend.':'.$tstart;
3948: }
1.351 www 3949: }
3950:
1.957 raeburn 3951: sub courserolelog {
3952: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 3953: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3954: my $cdom = $1;
3955: my $cnum = $2;
3956: my $sec = $3;
3957: my $namespace = 'rolelog';
3958: my %storehash = (
3959: role => $trole,
3960: start => $tstart,
3961: end => $tend,
3962: selfenroll => $selfenroll,
3963: context => $context,
3964: );
3965: if ($trole eq 'gr') {
3966: $namespace = 'groupslog';
3967: $storehash{'group'} = $sec;
3968: } else {
3969: $storehash{'section'} = $sec;
3970: }
3971: &write_log('course',$namespace,\%storehash,$delflag,$username,
3972: $domain,$cnum,$cdom);
3973: if (($trole ne 'st') || ($sec ne '')) {
3974: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3975: }
3976: }
3977: return;
3978: }
3979:
1.1172.2.9 raeburn 3980: sub domainrolelog {
3981: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3982: if ($area =~ m{^/($match_domain)/$}) {
3983: my $cdom = $1;
3984: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3985: my $namespace = 'rolelog';
3986: my %storehash = (
3987: role => $trole,
3988: start => $tstart,
3989: end => $tend,
3990: context => $context,
3991: );
3992: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3993: $domain,$domconfiguser,$cdom);
3994: }
3995: return;
3996:
3997: }
3998:
3999: sub coauthorrolelog {
4000: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4001: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4002: my $audom = $1;
4003: my $auname = $2;
4004: my $namespace = 'rolelog';
4005: my %storehash = (
4006: role => $trole,
4007: start => $tstart,
4008: end => $tend,
4009: context => $context,
4010: );
4011: &write_log('author',$namespace,\%storehash,$delflag,$username,
4012: $domain,$auname,$audom);
4013: }
4014: return;
4015: }
4016:
1.351 www 4017: sub get_course_adv_roles {
1.948 raeburn 4018: my ($cid,$codes) = @_;
1.620 albertel 4019: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4020: my %coursehash=&coursedescription($cid);
1.988 raeburn 4021: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4022: my %nothide=();
1.800 albertel 4023: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4024: if ($user !~ /:/) {
4025: $nothide{join(':',split(/[\@]/,$user))}=1;
4026: } else {
4027: $nothide{$user}=1;
4028: }
1.470 www 4029: }
1.1172.2.23 raeburn 4030: my @possdoms = ($coursehash{'domain'});
4031: if ($coursehash{'checkforpriv'}) {
4032: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4033: }
1.351 www 4034: my %returnhash=();
4035: my %dumphash=
4036: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4037: my $now=time;
1.997 raeburn 4038: my %privileged;
1.1000 raeburn 4039: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4040: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4041: if (($tstart) && ($tstart<0)) { next; }
4042: if (($tend) && ($tend<$now)) { next; }
4043: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4044: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4045: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4046: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4047: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4048: if ($role eq 'cr') { next; }
1.948 raeburn 4049: if ($codes) {
4050: if ($section) { $role .= ':'.$section; }
4051: if ($returnhash{$role}) {
4052: $returnhash{$role}.=','.$username.':'.$domain;
4053: } else {
4054: $returnhash{$role}=$username.':'.$domain;
4055: }
1.351 www 4056: } else {
1.988 raeburn 4057: my $key=&plaintext($role,$crstype);
1.973 bisitz 4058: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4059: if ($returnhash{$key}) {
4060: $returnhash{$key}.=','.$username.':'.$domain;
4061: } else {
4062: $returnhash{$key}=$username.':'.$domain;
4063: }
1.351 www 4064: }
1.948 raeburn 4065: }
1.400 www 4066: return %returnhash;
4067: }
4068:
4069: sub get_my_roles {
1.937 raeburn 4070: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4071: unless (defined($uname)) { $uname=$env{'user.name'}; }
4072: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4073: my (%dumphash,%nothide);
1.1086 raeburn 4074: if ($context eq 'userroles') {
1.1166 raeburn 4075: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4076: } else {
1.1172.2.23 raeburn 4077: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4078: if ($hidepriv) {
4079: my %coursehash=&coursedescription($udom.'_'.$uname);
4080: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4081: if ($user !~ /:/) {
4082: $nothide{join(':',split(/[\@]/,$user))} = 1;
4083: } else {
4084: $nothide{$user} = 1;
4085: }
4086: }
4087: }
1.858 raeburn 4088: }
1.400 www 4089: my %returnhash=();
4090: my $now=time;
1.999 raeburn 4091: my %privileged;
1.800 albertel 4092: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4093: my ($role,$tend,$tstart);
4094: if ($context eq 'userroles') {
1.1149 raeburn 4095: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4096: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4097: } else {
4098: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4099: }
1.400 www 4100: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4101: my $status = 'active';
1.939 raeburn 4102: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4103: $status = 'previous';
4104: }
4105: if (($tstart) && ($now<$tstart)) {
4106: $status = 'future';
4107: }
4108: if (ref($types) eq 'ARRAY') {
4109: if (!grep(/^\Q$status\E$/,@{$types})) {
4110: next;
4111: }
4112: } else {
4113: if ($status ne 'active') {
4114: next;
4115: }
4116: }
1.867 raeburn 4117: my ($rolecode,$username,$domain,$section,$area);
4118: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4119: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4120: (undef,$domain,$username,$section) = split(/\//,$area);
4121: } else {
4122: ($role,$username,$domain,$section) = split(/\:/,$entry);
4123: }
1.832 raeburn 4124: if (ref($roledoms) eq 'ARRAY') {
4125: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4126: next;
4127: }
4128: }
4129: if (ref($roles) eq 'ARRAY') {
4130: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4131: if ($role =~ /^cr\//) {
4132: if (!grep(/^cr$/,@{$roles})) {
4133: next;
4134: }
1.1104 raeburn 4135: } elsif ($role =~ /^gr\//) {
4136: if (!grep(/^gr$/,@{$roles})) {
4137: next;
4138: }
1.922 raeburn 4139: } else {
4140: next;
4141: }
1.832 raeburn 4142: }
1.867 raeburn 4143: }
1.937 raeburn 4144: if ($hidepriv) {
1.1172.2.23 raeburn 4145: my @privroles = ('dc','su');
1.999 raeburn 4146: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4147: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4148: } else {
1.1172.2.23 raeburn 4149: my $possdoms = [$domain];
4150: if (ref($roledoms) eq 'ARRAY') {
4151: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4152: }
1.1172.2.23 raeburn 4153: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4154: if (!$nothide{$username.':'.$domain}) {
4155: next;
4156: }
4157: }
1.937 raeburn 4158: }
4159: }
1.933 raeburn 4160: if ($withsec) {
4161: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4162: $tstart.':'.$tend;
4163: } else {
4164: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4165: }
1.832 raeburn 4166: }
1.373 www 4167: return %returnhash;
1.399 www 4168: }
4169:
4170: # ----------------------------------------------------- Frontpage Announcements
4171: #
4172: #
4173:
4174: sub postannounce {
4175: my ($server,$text)=@_;
1.844 albertel 4176: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4177: unless ($text=~/\w/) { $text=''; }
4178: return &reply('setannounce:'.&escape($text),$server);
4179: }
4180:
4181: sub getannounce {
1.448 albertel 4182:
4183: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4184: my $announcement='';
1.800 albertel 4185: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4186: close($fh);
1.399 www 4187: if ($announcement=~/\w/) {
4188: return
4189: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4190: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4191: } else {
4192: return '';
4193: }
4194: } else {
4195: return '';
4196: }
1.351 www 4197: }
1.353 www 4198:
4199: # ---------------------------------------------------------- Course ID routines
4200: # Deal with domain's nohist_courseid.db files
4201: #
4202:
4203: sub courseidput {
1.921 raeburn 4204: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4205: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4206: my $outcome;
4207: if ($caller eq 'timeonly') {
4208: my $cids = '';
4209: foreach my $item (keys(%$storehash)) {
4210: $cids.=&escape($item).'&';
4211: }
4212: $cids=~s/\&$//;
4213: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4214: $coursehome);
4215: } else {
4216: my $items = '';
4217: foreach my $item (keys(%$storehash)) {
4218: $items.= &escape($item).'='.
4219: &freeze_escape($$storehash{$item}).'&';
4220: }
4221: $items=~s/\&$//;
4222: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4223: $coursehome);
1.918 raeburn 4224: }
4225: if ($outcome eq 'unknown_cmd') {
4226: my $what;
4227: foreach my $cid (keys(%$storehash)) {
4228: $what .= &escape($cid).'=';
1.921 raeburn 4229: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4230: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4231: }
4232: $what =~ s/\:$/&/;
4233: }
4234: $what =~ s/\&$//;
4235: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4236: } else {
4237: return $outcome;
4238: }
1.353 www 4239: }
4240:
4241: sub courseiddump {
1.921 raeburn 4242: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4243: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4244: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4245: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4246: $hasuniquecode)=@_;
1.918 raeburn 4247: my $as_hash = 1;
4248: my %returnhash;
4249: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4250: my %libserv = &all_library();
4251: foreach my $tryserver (keys(%libserv)) {
4252: if ( ( $hostidflag == 1
4253: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4254: || (!defined($hostidflag)) ) {
4255:
1.918 raeburn 4256: if (($domfilter eq '') ||
4257: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4258: my $rep;
4259: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4260: $rep = &LONCAPA::Lond::dump_course_id_handler(
4261: join(":", (&host_domain($tryserver), $sincefilter,
4262: &escape($descfilter), &escape($instcodefilter),
4263: &escape($ownerfilter), &escape($coursefilter),
4264: &escape($typefilter), &escape($regexp_ok),
4265: $as_hash, &escape($selfenrollonly),
4266: &escape($catfilter), $showhidden, $caller,
4267: &escape($cloner), &escape($cc_clone), $cloneonly,
4268: &escape($createdbefore), &escape($createdafter),
1.1172.2.38 raeburn 4269: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1172.2.22 raeburn 4270: } else {
4271: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4272: $sincefilter.':'.&escape($descfilter).':'.
4273: &escape($instcodefilter).':'.&escape($ownerfilter).
4274: ':'.&escape($coursefilter).':'.&escape($typefilter).
4275: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4276: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4277: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4278: &escape($cc_clone).':'.$cloneonly.':'.
4279: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.38 raeburn 4280: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1172.2.22 raeburn 4281: $tryserver);
4282: }
4283:
1.918 raeburn 4284: my @pairs=split(/\&/,$rep);
4285: foreach my $item (@pairs) {
4286: my ($key,$value)=split(/\=/,$item,2);
4287: $key = &unescape($key);
4288: next if ($key =~ /^error: 2 /);
4289: my $result = &thaw_unescape($value);
4290: if (ref($result) eq 'HASH') {
4291: $returnhash{$key}=$result;
4292: } else {
1.921 raeburn 4293: my @responses = split(/:/,$value);
4294: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4295: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4296: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4297: }
1.1008 raeburn 4298: }
1.353 www 4299: }
4300: }
4301: }
4302: }
4303: return %returnhash;
4304: }
4305:
1.1055 raeburn 4306: sub courselastaccess {
4307: my ($cdom,$cnum,$hostidref) = @_;
4308: my %returnhash;
4309: if ($cdom && $cnum) {
4310: my $chome = &homeserver($cnum,$cdom);
4311: if ($chome ne 'no_host') {
4312: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4313: &extract_lastaccess(\%returnhash,$rep);
4314: }
4315: } else {
4316: if (!$cdom) { $cdom=''; }
4317: my %libserv = &all_library();
4318: foreach my $tryserver (keys(%libserv)) {
4319: if (ref($hostidref) eq 'ARRAY') {
4320: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4321: }
4322: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4323: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4324: &extract_lastaccess(\%returnhash,$rep);
4325: }
4326: }
4327: }
4328: return %returnhash;
4329: }
4330:
4331: sub extract_lastaccess {
4332: my ($returnhash,$rep) = @_;
4333: if (ref($returnhash) eq 'HASH') {
4334: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4335: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4336: $rep eq '') {
4337: my @pairs=split(/\&/,$rep);
4338: foreach my $item (@pairs) {
4339: my ($key,$value)=split(/\=/,$item,2);
4340: $key = &unescape($key);
4341: next if ($key =~ /^error: 2 /);
4342: $returnhash->{$key} = &thaw_unescape($value);
4343: }
4344: }
4345: }
4346: return;
4347: }
4348:
1.658 raeburn 4349: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4350:
4351: sub dcmailput {
1.685 raeburn 4352: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4353: my $status = &Apache::lonnet::critical(
1.740 www 4354: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4355: &escape($message),$server);
1.662 raeburn 4356: return $status;
4357: }
4358:
1.658 raeburn 4359: sub dcmaildump {
4360: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4361: my %returnhash=();
1.846 albertel 4362:
4363: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4364: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4365: &escape($enddate).':';
4366: my @esc_senders=map { &escape($_)} @$senders;
4367: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4368: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4369: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4370: if (($key) && ($value)) {
4371: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4372: }
4373: }
4374: }
4375: return %returnhash;
4376: }
1.662 raeburn 4377: # ---------------------------------------------------------- Domain roles
4378:
4379: sub get_domain_roles {
4380: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4381: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4382: $startdate = '.';
4383: }
1.1018 raeburn 4384: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4385: $enddate = '.';
4386: }
1.922 raeburn 4387: my $rolelist;
4388: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4389: $rolelist = join('&',@{$roles});
1.922 raeburn 4390: }
1.662 raeburn 4391: my %personnel = ();
1.841 albertel 4392:
4393: my %servers = &get_servers($dom,'library');
4394: foreach my $tryserver (keys(%servers)) {
4395: %{$personnel{$tryserver}}=();
4396: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4397: &escape($startdate).':'.
4398: &escape($enddate).':'.
4399: &escape($rolelist), $tryserver))) {
4400: my ($key,$value) = split(/\=/,$line,2);
4401: if (($key) && ($value)) {
4402: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4403: }
4404: }
1.662 raeburn 4405: }
4406: return %personnel;
4407: }
1.658 raeburn 4408:
1.1057 www 4409: # ----------------------------------------------------------- Interval timing
1.149 www 4410:
1.1153 www 4411: {
4412: # Caches needed for speedup of navmaps
4413: # We don't want to cache this for very long at all (5 seconds at most)
4414: #
4415: # The user for whom we cache
4416: my $cachedkey='';
4417: # The cached times for this user
4418: my %cachedtimes=();
4419: # When this was last done
4420: my $cachedtime=();
4421:
4422: sub load_all_first_access {
1.1154 raeburn 4423: my ($uname,$udom)=@_;
1.1156 www 4424: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4425: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4426: return;
4427: }
4428: $cachedtime=time;
4429: $cachedkey=$uname.':'.$udom;
4430: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4431: }
4432:
1.504 albertel 4433: sub get_first_access {
1.1162 raeburn 4434: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4435: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4436: if ($argsymb) { $symb=$argsymb; }
4437: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4438: if ($argmap) { $map = $argmap; }
1.926 albertel 4439: if ($type eq 'course') {
4440: $res='course';
4441: } elsif ($type eq 'map') {
1.588 albertel 4442: $res=&symbread($map);
4443: } else {
4444: $res=$symb;
4445: }
1.1153 www 4446: &load_all_first_access($uname,$udom);
4447: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4448: }
4449:
4450: sub set_first_access {
1.1162 raeburn 4451: my ($type,$interval)=@_;
1.790 albertel 4452: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4453: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4454: if ($type eq 'course') {
4455: $res='course';
4456: } elsif ($type eq 'map') {
1.588 albertel 4457: $res=&symbread($map);
4458: } else {
4459: $res=$symb;
4460: }
1.1153 www 4461: $cachedkey='';
1.1162 raeburn 4462: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4463: if (!$firstaccess) {
1.1162 raeburn 4464: my $start = time;
4465: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4466: $udom,$uname);
4467: if ($putres eq 'ok') {
4468: &put('timerinterval',{"$courseid\0$res"=>$interval},
4469: $udom,$uname);
4470: &appenv(
4471: {
4472: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4473: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4474: }
4475: );
4476: }
4477: return $putres;
1.505 albertel 4478: }
4479: return 'already_set';
1.504 albertel 4480: }
1.1153 www 4481: }
1.1172.2.32 raeburn 4482:
4483: sub checkout {
4484: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4485: my $now=time;
4486: my $lonhost=$perlvar{'lonHostID'};
4487: my $infostr=&escape(
4488: 'CHECKOUTTOKEN&'.
4489: $tuname.'&'.
4490: $tudom.'&'.
4491: $tcrsid.'&'.
4492: $symb.'&'.
4493: $now.'&'.$ENV{'REMOTE_ADDR'});
4494: my $token=&reply('tmpput:'.$infostr,$lonhost);
4495: if ($token=~/^error\:/) {
4496: &logthis("<font color=\"blue\">WARNING: ".
4497: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4498: "</font>");
4499: return '';
4500: }
4501:
4502: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4503: $token=~tr/a-z/A-Z/;
4504:
4505: my %infohash=('resource.0.outtoken' => $token,
4506: 'resource.0.checkouttime' => $now,
4507: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4508:
4509: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4510: return '';
4511: } else {
4512: &logthis("<font color=\"blue\">WARNING: ".
4513: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4514: "</font>");
4515: }
4516:
4517: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4518: &escape('Checkout '.$infostr.' - '.
4519: $token)) ne 'ok') {
4520: return '';
4521: } else {
4522: &logthis("<font color=\"blue\">WARNING: ".
4523: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4524: "</font>");
4525: }
4526: return $token;
4527: }
4528:
4529: # ------------------------------------------------------------ Check in an item
4530:
4531: sub checkin {
4532: my $token=shift;
4533: my $now=time;
4534: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4535: $lonhost=~tr/A-Z/a-z/;
4536: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4537: $dtoken=~s/\W/\_/g;
4538: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4539: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4540:
4541: unless (($tuname) && ($tudom)) {
4542: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4543: return '';
4544: }
4545:
4546: unless (&allowed('mgr',$tcrsid)) {
4547: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4548: $env{'user.name'}.' - '.$env{'user.domain'});
4549: return '';
4550: }
4551:
4552: my %infohash=('resource.0.intoken' => $token,
4553: 'resource.0.checkintime' => $now,
4554: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4555:
4556: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4557: return '';
4558: }
4559:
4560: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4561: &escape('Checkin - '.$token)) ne 'ok') {
4562: return '';
4563: }
4564:
4565: return ($symb,$tuname,$tudom,$tcrsid);
4566: }
4567:
1.110 www 4568: # --------------------------------------------- Set Expire Date for Spreadsheet
4569:
4570: sub expirespread {
4571: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4572: my $cid=$env{'request.course.id'};
1.110 www 4573: if ($cid) {
4574: my $now=time;
4575: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4576: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4577: $env{'course.'.$cid.'.num'}.
1.110 www 4578: ':nohist_expirationdates:'.
4579: &escape($key).'='.$now,
1.620 albertel 4580: $env{'course.'.$cid.'.home'})
1.110 www 4581: }
4582: return 'ok';
1.14 www 4583: }
4584:
1.109 www 4585: # ----------------------------------------------------- Devalidate Spreadsheets
4586:
4587: sub devalidate {
1.325 www 4588: my ($symb,$uname,$udom)=@_;
1.620 albertel 4589: my $cid=$env{'request.course.id'};
1.109 www 4590: if ($cid) {
1.391 matthew 4591: # delete the stored spreadsheets for
4592: # - the student level sheet of this user in course's homespace
4593: # - the assessment level sheet for this resource
4594: # for this user in user's homespace
1.553 albertel 4595: # - current conditional state info
1.325 www 4596: my $key=$uname.':'.$udom.':';
1.109 www 4597: my $status=
1.299 matthew 4598: &del('nohist_calculatedsheets',
1.391 matthew 4599: [$key.'studentcalc:'],
1.620 albertel 4600: $env{'course.'.$cid.'.domain'},
4601: $env{'course.'.$cid.'.num'})
1.133 albertel 4602: .' '.
4603: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4604: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4605: unless ($status eq 'ok ok') {
4606: &logthis('Could not devalidate spreadsheet '.
1.325 www 4607: $uname.' at '.$udom.' for '.
1.109 www 4608: $symb.': '.$status);
1.133 albertel 4609: }
1.553 albertel 4610: &delenv('user.state.'.$cid);
1.109 www 4611: }
4612: }
4613:
1.265 albertel 4614: sub get_scalar {
4615: my ($string,$end) = @_;
4616: my $value;
4617: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4618: $value = $1;
4619: } elsif ($$string =~ s/^([^&]*?)&//) {
4620: $value = $1;
4621: }
4622: return &unescape($value);
4623: }
4624:
4625: sub array2str {
4626: my (@array) = @_;
4627: my $result=&arrayref2str(\@array);
4628: $result=~s/^__ARRAY_REF__//;
4629: $result=~s/__END_ARRAY_REF__$//;
4630: return $result;
4631: }
4632:
1.204 albertel 4633: sub arrayref2str {
4634: my ($arrayref) = @_;
1.265 albertel 4635: my $result='__ARRAY_REF__';
1.204 albertel 4636: foreach my $elem (@$arrayref) {
1.265 albertel 4637: if(ref($elem) eq 'ARRAY') {
4638: $result.=&arrayref2str($elem).'&';
4639: } elsif(ref($elem) eq 'HASH') {
4640: $result.=&hashref2str($elem).'&';
4641: } elsif(ref($elem)) {
4642: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4643: } else {
4644: $result.=&escape($elem).'&';
4645: }
4646: }
4647: $result=~s/\&$//;
1.265 albertel 4648: $result .= '__END_ARRAY_REF__';
1.204 albertel 4649: return $result;
4650: }
4651:
1.168 albertel 4652: sub hash2str {
1.204 albertel 4653: my (%hash) = @_;
4654: my $result=&hashref2str(\%hash);
1.265 albertel 4655: $result=~s/^__HASH_REF__//;
4656: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4657: return $result;
4658: }
4659:
4660: sub hashref2str {
4661: my ($hashref)=@_;
1.265 albertel 4662: my $result='__HASH_REF__';
1.800 albertel 4663: foreach my $key (sort(keys(%$hashref))) {
4664: if (ref($key) eq 'ARRAY') {
4665: $result.=&arrayref2str($key).'=';
4666: } elsif (ref($key) eq 'HASH') {
4667: $result.=&hashref2str($key).'=';
4668: } elsif (ref($key)) {
1.265 albertel 4669: $result.='=';
1.800 albertel 4670: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4671: } else {
1.1132 raeburn 4672: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4673: }
4674:
1.800 albertel 4675: if(ref($hashref->{$key}) eq 'ARRAY') {
4676: $result.=&arrayref2str($hashref->{$key}).'&';
4677: } elsif(ref($hashref->{$key}) eq 'HASH') {
4678: $result.=&hashref2str($hashref->{$key}).'&';
4679: } elsif(ref($hashref->{$key})) {
1.265 albertel 4680: $result.='&';
1.800 albertel 4681: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4682: } else {
1.800 albertel 4683: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4684: }
4685: }
1.168 albertel 4686: $result=~s/\&$//;
1.265 albertel 4687: $result .= '__END_HASH_REF__';
1.168 albertel 4688: return $result;
4689: }
4690:
4691: sub str2hash {
1.265 albertel 4692: my ($string)=@_;
4693: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4694: return %$hash;
4695: }
4696:
4697: sub str2hashref {
1.168 albertel 4698: my ($string) = @_;
1.265 albertel 4699:
4700: my %hash;
4701:
4702: if($string !~ /^__HASH_REF__/) {
4703: if (! ($string eq '' || !defined($string))) {
4704: $hash{'error'}='Not hash reference';
4705: }
4706: return (\%hash, $string);
4707: }
4708:
4709: $string =~ s/^__HASH_REF__//;
4710:
4711: while($string !~ /^__END_HASH_REF__/) {
4712: #key
4713: my $key='';
4714: if($string =~ /^__HASH_REF__/) {
4715: ($key, $string)=&str2hashref($string);
4716: if(defined($key->{'error'})) {
4717: $hash{'error'}='Bad data';
4718: return (\%hash, $string);
4719: }
4720: } elsif($string =~ /^__ARRAY_REF__/) {
4721: ($key, $string)=&str2arrayref($string);
4722: if($key->[0] eq 'Array reference error') {
4723: $hash{'error'}='Bad data';
4724: return (\%hash, $string);
4725: }
4726: } else {
4727: $string =~ s/^(.*?)=//;
1.267 albertel 4728: $key=&unescape($1);
1.265 albertel 4729: }
4730: $string =~ s/^=//;
4731:
4732: #value
4733: my $value='';
4734: if($string =~ /^__HASH_REF__/) {
4735: ($value, $string)=&str2hashref($string);
4736: if(defined($value->{'error'})) {
4737: $hash{'error'}='Bad data';
4738: return (\%hash, $string);
4739: }
4740: } elsif($string =~ /^__ARRAY_REF__/) {
4741: ($value, $string)=&str2arrayref($string);
4742: if($value->[0] eq 'Array reference error') {
4743: $hash{'error'}='Bad data';
4744: return (\%hash, $string);
4745: }
4746: } else {
4747: $value=&get_scalar(\$string,'__END_HASH_REF__');
4748: }
4749: $string =~ s/^&//;
4750:
4751: $hash{$key}=$value;
1.204 albertel 4752: }
1.265 albertel 4753:
4754: $string =~ s/^__END_HASH_REF__//;
4755:
4756: return (\%hash, $string);
1.204 albertel 4757: }
4758:
4759: sub str2array {
1.265 albertel 4760: my ($string)=@_;
4761: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4762: return @$array;
4763: }
4764:
4765: sub str2arrayref {
1.204 albertel 4766: my ($string) = @_;
1.265 albertel 4767: my @array;
4768:
4769: if($string !~ /^__ARRAY_REF__/) {
4770: if (! ($string eq '' || !defined($string))) {
4771: $array[0]='Array reference error';
4772: }
4773: return (\@array, $string);
4774: }
4775:
4776: $string =~ s/^__ARRAY_REF__//;
4777:
4778: while($string !~ /^__END_ARRAY_REF__/) {
4779: my $value='';
4780: if($string =~ /^__HASH_REF__/) {
4781: ($value, $string)=&str2hashref($string);
4782: if(defined($value->{'error'})) {
4783: $array[0] ='Array reference error';
4784: return (\@array, $string);
4785: }
4786: } elsif($string =~ /^__ARRAY_REF__/) {
4787: ($value, $string)=&str2arrayref($string);
4788: if($value->[0] eq 'Array reference error') {
4789: $array[0] ='Array reference error';
4790: return (\@array, $string);
4791: }
4792: } else {
4793: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4794: }
4795: $string =~ s/^&//;
4796:
4797: push(@array, $value);
1.191 harris41 4798: }
1.265 albertel 4799:
4800: $string =~ s/^__END_ARRAY_REF__//;
4801:
4802: return (\@array, $string);
1.168 albertel 4803: }
4804:
1.167 albertel 4805: # -------------------------------------------------------------------Temp Store
4806:
1.168 albertel 4807: sub tmpreset {
4808: my ($symb,$namespace,$domain,$stuname) = @_;
4809: if (!$symb) {
4810: $symb=&symbread();
1.620 albertel 4811: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4812: }
4813: $symb=escape($symb);
4814:
1.620 albertel 4815: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4816: $namespace=~s/\//\_/g;
4817: $namespace=~s/\W//g;
4818:
1.620 albertel 4819: if (!$domain) { $domain=$env{'user.domain'}; }
4820: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4821: if ($domain eq 'public' && $stuname eq 'public') {
4822: $stuname=$ENV{'REMOTE_ADDR'};
4823: }
1.1117 foxr 4824: my $path=LONCAPA::tempdir();
1.168 albertel 4825: my %hash;
4826: if (tie(%hash,'GDBM_File',
4827: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4828: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4829: foreach my $key (keys(%hash)) {
1.180 albertel 4830: if ($key=~ /:$symb/) {
1.168 albertel 4831: delete($hash{$key});
4832: }
4833: }
4834: }
4835: }
4836:
1.167 albertel 4837: sub tmpstore {
1.168 albertel 4838: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4839:
4840: if (!$symb) {
4841: $symb=&symbread();
1.620 albertel 4842: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4843: }
4844: $symb=escape($symb);
4845:
4846: if (!$namespace) {
4847: # I don't think we would ever want to store this for a course.
4848: # it seems this will only be used if we don't have a course.
1.620 albertel 4849: #$namespace=$env{'request.course.id'};
1.168 albertel 4850: #if (!$namespace) {
1.620 albertel 4851: $namespace=$env{'request.state'};
1.168 albertel 4852: #}
4853: }
4854: $namespace=~s/\//\_/g;
4855: $namespace=~s/\W//g;
1.620 albertel 4856: if (!$domain) { $domain=$env{'user.domain'}; }
4857: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4858: if ($domain eq 'public' && $stuname eq 'public') {
4859: $stuname=$ENV{'REMOTE_ADDR'};
4860: }
1.168 albertel 4861: my $now=time;
4862: my %hash;
1.1117 foxr 4863: my $path=LONCAPA::tempdir();
1.168 albertel 4864: if (tie(%hash,'GDBM_File',
4865: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4866: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4867: $hash{"version:$symb"}++;
4868: my $version=$hash{"version:$symb"};
4869: my $allkeys='';
4870: foreach my $key (keys(%$storehash)) {
4871: $allkeys.=$key.':';
1.591 albertel 4872: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4873: }
4874: $hash{"$version:$symb:timestamp"}=$now;
4875: $allkeys.='timestamp';
4876: $hash{"$version:keys:$symb"}=$allkeys;
4877: if (untie(%hash)) {
4878: return 'ok';
4879: } else {
4880: return "error:$!";
4881: }
4882: } else {
4883: return "error:$!";
4884: }
4885: }
1.167 albertel 4886:
1.168 albertel 4887: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4888:
1.168 albertel 4889: sub tmprestore {
4890: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4891:
1.168 albertel 4892: if (!$symb) {
4893: $symb=&symbread();
1.620 albertel 4894: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4895: }
4896: $symb=escape($symb);
4897:
1.620 albertel 4898: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4899:
1.620 albertel 4900: if (!$domain) { $domain=$env{'user.domain'}; }
4901: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4902: if ($domain eq 'public' && $stuname eq 'public') {
4903: $stuname=$ENV{'REMOTE_ADDR'};
4904: }
1.168 albertel 4905: my %returnhash;
4906: $namespace=~s/\//\_/g;
4907: $namespace=~s/\W//g;
4908: my %hash;
1.1117 foxr 4909: my $path=LONCAPA::tempdir();
1.168 albertel 4910: if (tie(%hash,'GDBM_File',
4911: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4912: &GDBM_READER(),0640)) {
1.168 albertel 4913: my $version=$hash{"version:$symb"};
4914: $returnhash{'version'}=$version;
4915: my $scope;
4916: for ($scope=1;$scope<=$version;$scope++) {
4917: my $vkeys=$hash{"$scope:keys:$symb"};
4918: my @keys=split(/:/,$vkeys);
4919: my $key;
4920: $returnhash{"$scope:keys"}=$vkeys;
4921: foreach $key (@keys) {
1.591 albertel 4922: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4923: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4924: }
4925: }
1.168 albertel 4926: if (!(untie(%hash))) {
4927: return "error:$!";
4928: }
4929: } else {
4930: return "error:$!";
4931: }
4932: return %returnhash;
1.167 albertel 4933: }
4934:
1.9 www 4935: # ----------------------------------------------------------------------- Store
4936:
4937: sub store {
1.124 www 4938: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4939: my $home='';
4940:
1.168 albertel 4941: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4942:
1.213 www 4943: $symb=&symbclean($symb);
1.122 albertel 4944: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4945:
1.620 albertel 4946: if (!$domain) { $domain=$env{'user.domain'}; }
4947: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4948:
4949: &devalidate($symb,$stuname,$domain);
1.109 www 4950:
4951: $symb=escape($symb);
1.187 www 4952: if (!$namespace) {
1.620 albertel 4953: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4954: return '';
4955: }
4956: }
1.620 albertel 4957: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4958:
4959: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4960: $$storehash{'host'}=$perlvar{'lonHostID'};
4961:
1.12 www 4962: my $namevalue='';
1.800 albertel 4963: foreach my $key (keys(%$storehash)) {
4964: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4965: }
1.12 www 4966: $namevalue=~s/\&$//;
1.187 www 4967: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4968: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4969: }
4970:
1.47 www 4971: # -------------------------------------------------------------- Critical Store
4972:
4973: sub cstore {
1.124 www 4974: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4975: my $home='';
4976:
1.168 albertel 4977: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4978:
1.213 www 4979: $symb=&symbclean($symb);
1.122 albertel 4980: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4981:
1.620 albertel 4982: if (!$domain) { $domain=$env{'user.domain'}; }
4983: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4984:
4985: &devalidate($symb,$stuname,$domain);
1.109 www 4986:
4987: $symb=escape($symb);
1.187 www 4988: if (!$namespace) {
1.620 albertel 4989: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4990: return '';
4991: }
4992: }
1.620 albertel 4993: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4994:
4995: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4996: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4997:
1.47 www 4998: my $namevalue='';
1.800 albertel 4999: foreach my $key (keys(%$storehash)) {
5000: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5001: }
1.47 www 5002: $namevalue=~s/\&$//;
1.187 www 5003: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5004: return critical
5005: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 5006: }
5007:
1.9 www 5008: # --------------------------------------------------------------------- Restore
5009:
5010: sub restore {
1.124 www 5011: my ($symb,$namespace,$domain,$stuname) = @_;
5012: my $home='';
5013:
1.168 albertel 5014: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5015:
1.122 albertel 5016: if (!$symb) {
1.1172.2.26 raeburn 5017: return if ($namespace eq 'courserequests');
5018: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5019: } else {
1.1172.2.26 raeburn 5020: unless ($namespace eq 'courserequests') {
5021: $symb=&escape(&symbclean($symb));
5022: }
1.122 albertel 5023: }
1.188 www 5024: if (!$namespace) {
1.620 albertel 5025: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5026: return '';
5027: }
5028: }
1.620 albertel 5029: if (!$domain) { $domain=$env{'user.domain'}; }
5030: if (!$stuname) { $stuname=$env{'user.name'}; }
5031: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5032: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5033:
1.12 www 5034: my %returnhash=();
1.800 albertel 5035: foreach my $line (split(/\&/,$answer)) {
5036: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5037: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5038: }
1.75 www 5039: my $version;
5040: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5041: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5042: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5043: }
1.75 www 5044: }
1.13 www 5045: return %returnhash;
1.34 www 5046: }
5047:
5048: # ---------------------------------------------------------- Course Description
1.1118 foxr 5049: #
5050: #
1.34 www 5051:
5052: sub coursedescription {
1.731 albertel 5053: my ($courseid,$args)=@_;
1.34 www 5054: $courseid=~s/^\///;
1.49 www 5055: $courseid=~s/\_/\//g;
1.34 www 5056: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5057: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5058: my $normalid=$cdomain.'_'.$cnum;
5059: # need to always cache even if we get errors otherwise we keep
5060: # trying and trying and trying to get the course description.
5061: my %envhash=();
5062: my %returnhash=();
1.731 albertel 5063:
5064: my $expiretime=600;
5065: if ($env{'request.course.id'} eq $normalid) {
5066: $expiretime=120;
5067: }
5068:
5069: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5070: if (!$args->{'freshen_cache'}
5071: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5072: foreach my $key (keys(%env)) {
5073: next if ($key !~ /^\Q$prefix\E(.*)/);
5074: my ($setting) = $1;
5075: $returnhash{$setting} = $env{$key};
5076: }
5077: return %returnhash;
5078: }
5079:
1.1118 foxr 5080: # get the data again
5081:
1.731 albertel 5082: if (!$args->{'one_time'}) {
5083: $envhash{'course.'.$normalid.'.last_cache'}=time;
5084: }
1.811 albertel 5085:
1.34 www 5086: if ($chome ne 'no_host') {
1.302 albertel 5087: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5088: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5089: my $username = $env{'user.name'}; # Defult username
5090: if(defined $args->{'user'}) {
5091: $username = $args->{'user'};
5092: }
1.129 albertel 5093: $returnhash{'home'}= $chome;
5094: $returnhash{'domain'} = $cdomain;
5095: $returnhash{'num'} = $cnum;
1.741 raeburn 5096: if (!defined($returnhash{'type'})) {
5097: $returnhash{'type'} = 'Course';
5098: }
1.130 albertel 5099: while (my ($name,$value) = each %returnhash) {
1.53 www 5100: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5101: }
1.270 www 5102: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5103: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5104: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5105: $envhash{'course.'.$normalid.'.home'}=$chome;
5106: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5107: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5108: }
5109: }
1.731 albertel 5110: if (!$args->{'one_time'}) {
1.949 raeburn 5111: &appenv(\%envhash);
1.731 albertel 5112: }
1.302 albertel 5113: return %returnhash;
1.461 www 5114: }
5115:
1.1080 raeburn 5116: sub update_released_required {
5117: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5118: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5119: $cid = $env{'request.course.id'};
5120: $cdom = $env{'course.'.$cid.'.domain'};
5121: $cnum = $env{'course.'.$cid.'.num'};
5122: $chome = $env{'course.'.$cid.'.home'};
5123: }
5124: if ($needsrelease) {
5125: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5126: my $needsupdate;
5127: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5128: $needsupdate = 1;
5129: } else {
5130: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5131: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5132: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5133: $needsupdate = 1;
5134: }
5135: }
5136: if ($needsupdate) {
5137: my %needshash = (
5138: 'internal.releaserequired' => $needsrelease,
5139: );
5140: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5141: if ($putresult eq 'ok') {
5142: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5143: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5144: if (ref($crsinfo{$cid}) eq 'HASH') {
5145: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5146: &courseidput($cdom,\%crsinfo,$chome,'notime');
5147: }
5148: }
5149: }
5150: }
5151: return;
5152: }
5153:
1.461 www 5154: # -------------------------------------------------See if a user is privileged
5155:
5156: sub privileged {
1.1172.2.23 raeburn 5157: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5158: my $now = time;
1.1172.2.23 raeburn 5159: my $roles;
5160: if (ref($possroles) eq 'ARRAY') {
5161: $roles = $possroles;
5162: } else {
5163: $roles = ['dc','su'];
5164: }
5165: if (ref($possdomains) eq 'ARRAY') {
5166: my %privileged = &privileged_by_domain($possdomains,$roles);
5167: foreach my $dom (@{$possdomains}) {
5168: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5169: (ref($privileged{$dom}) eq 'HASH')) {
5170: foreach my $role (@{$roles}) {
5171: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5172: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5173: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5174: return 1 unless (($end && $end < $now) ||
5175: ($start && $start > $now));
5176: }
5177: }
5178: }
5179: }
5180: }
5181: } else {
5182: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5183: my $now = time;
1.1170 droeschl 5184:
1.1172.2.58 raeburn 5185: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5186: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5187: if (grep(/^\Q$trole\E$/,@{$roles})) {
5188: return 1 unless ($tend && $tend < $now)
5189: or ($tstart && $tstart > $now);
1.1170 droeschl 5190: }
1.1172.2.23 raeburn 5191: }
5192: }
1.461 www 5193: return 0;
1.9 www 5194: }
1.1 albertel 5195:
1.1172.2.23 raeburn 5196: sub privileged_by_domain {
5197: my ($domains,$roles) = @_;
5198: my %privileged = ();
5199: my $cachetime = 60*60*24;
5200: my $now = time;
5201: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5202: return %privileged;
5203: }
5204: foreach my $dom (@{$domains}) {
5205: next if (ref($privileged{$dom}) eq 'HASH');
5206: my $needroles;
5207: foreach my $role (@{$roles}) {
5208: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5209: if (defined($cached)) {
5210: if (ref($result) eq 'HASH') {
5211: $privileged{$dom}{$role} = $result;
5212: }
5213: } else {
5214: $needroles = 1;
5215: }
5216: }
5217: if ($needroles) {
5218: my %dompersonnel = &get_domain_roles($dom,$roles);
5219: $privileged{$dom} = {};
5220: foreach my $server (keys(%dompersonnel)) {
5221: if (ref($dompersonnel{$server}) eq 'HASH') {
5222: foreach my $item (keys(%{$dompersonnel{$server}})) {
5223: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5224: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5225: next if ($end && $end < $now);
5226: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5227: $dompersonnel{$server}{$item};
5228: }
5229: }
5230: }
5231: if (ref($privileged{$dom}) eq 'HASH') {
5232: foreach my $role (@{$roles}) {
5233: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5234: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5235: } else {
5236: my %hash = ();
5237: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5238: }
5239: }
5240: }
5241: }
5242: }
5243: return %privileged;
5244: }
5245:
1.103 harris41 5246: # -------------------------------------------------------- Get user privileges
1.11 www 5247:
5248: sub rolesinit {
1.1169 droeschl 5249: my ($domain, $username) = @_;
5250: my %userroles = ('user.login.time' => time);
5251: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5252:
5253: # firstaccess and timerinterval are related to timed maps/resources.
5254: # also, blocking can be triggered by an activating timer
5255: # it's saved in the user's %env.
5256: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5257: my %timerinterval = &dump('timerinterval', $domain, $username);
5258: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5259: %timerintchk, %timerintenv);
5260:
1.1162 raeburn 5261: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5262: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5263: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5264: }
1.1169 droeschl 5265:
1.1162 raeburn 5266: foreach my $key (keys(%timerinterval)) {
5267: my ($cid,$rest) = split(/\0/,$key);
5268: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5269: }
1.1169 droeschl 5270:
1.11 www 5271: my %allroles=();
1.1162 raeburn 5272: my %allgroups=();
1.11 www 5273:
1.1172.2.58 raeburn 5274: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5275: my $role = $rolesdump{$area};
5276: $area =~ s/\_\w\w$//;
5277:
5278: my ($trole, $tend, $tstart, $group_privs);
5279:
5280: if ($role =~ /^cr/) {
5281: # Custom role, defined by a user
5282: # e.g., user.role.cr/msu/smith/mynewrole
5283: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5284: $trole = $1;
5285: ($tend, $tstart) = split('_', $2);
5286: } else {
5287: $trole = $role;
5288: }
5289: } elsif ($role =~ m|^gr/|) {
5290: # Role of member in a group, defined within a course/community
5291: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5292: ($trole, $tend, $tstart) = split(/_/, $role);
5293: next if $tstart eq '-1';
5294: ($trole, $group_privs) = split(/\//, $trole);
5295: $group_privs = &unescape($group_privs);
5296: } else {
5297: # Just a normal role, defined in roles.tab
5298: ($trole, $tend, $tstart) = split(/_/,$role);
5299: }
5300:
5301: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5302: $username);
5303: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5304:
5305: # role expired or not available yet?
5306: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5307: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5308:
5309: next if $area eq '' or $trole eq '';
5310:
5311: my $spec = "$trole.$area";
5312: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5313:
5314: if ($trole =~ /^cr\//) {
5315: # Custom role, defined by a user
5316: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5317: } elsif ($trole eq 'gr') {
5318: # Role of a member in a group, defined within a course/community
5319: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5320: next;
5321: } else {
5322: # Normal role, defined in roles.tab
5323: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5324: }
5325:
5326: my $cid = $tdomain.'_'.$trest;
5327: unless ($firstaccchk{$cid}) {
5328: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5329: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5330: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5331: $coursetimerstarts{$cid}{$item};
5332: }
5333: }
5334: $firstaccchk{$cid} = 1;
5335: }
5336: unless ($timerintchk{$cid}) {
5337: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5338: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5339: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5340: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5341: }
1.12 www 5342: }
1.1169 droeschl 5343: $timerintchk{$cid} = 1;
1.191 harris41 5344: }
1.11 www 5345: }
1.1169 droeschl 5346:
5347: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5348: \%allroles, \%allgroups);
5349: $env{'user.adv'} = $userroles{'user.adv'};
5350:
1.1162 raeburn 5351: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5352: }
5353:
1.567 raeburn 5354: sub set_arearole {
1.1172.2.19 raeburn 5355: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5356: unless ($nolog) {
1.567 raeburn 5357: # log the associated role with the area
1.1172.2.19 raeburn 5358: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5359: }
1.743 albertel 5360: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5361: }
5362:
5363: sub custom_roleprivs {
5364: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5365: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5366: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5367: if (&hostname($homsvr) ne '') {
1.567 raeburn 5368: my ($rdummy,$roledef)=
5369: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5370: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5371: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5372: if (defined($syspriv)) {
1.1043 raeburn 5373: if ($trest =~ /^$match_community$/) {
5374: $syspriv =~ s/bre\&S//;
5375: }
1.567 raeburn 5376: $$allroles{'cm./'}.=':'.$syspriv;
5377: $$allroles{$spec.'./'}.=':'.$syspriv;
5378: }
5379: if ($tdomain ne '') {
5380: if (defined($dompriv)) {
5381: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5382: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5383: }
5384: if (($trest ne '') && (defined($coursepriv))) {
5385: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5386: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5387: }
5388: }
5389: }
5390: }
5391: }
5392:
1.678 raeburn 5393: sub group_roleprivs {
5394: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5395: my $access = 1;
5396: my $now = time;
5397: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5398: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5399: if ($access) {
1.811 albertel 5400: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5401: $$allgroups{$course}{$group} .=':'.$group_privs;
5402: }
5403: }
1.567 raeburn 5404:
5405: sub standard_roleprivs {
5406: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5407: if (defined($pr{$trole.':s'})) {
5408: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5409: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5410: }
5411: if ($tdomain ne '') {
5412: if (defined($pr{$trole.':d'})) {
5413: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5414: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5415: }
5416: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5417: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5418: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5419: }
5420: }
5421: }
5422:
5423: sub set_userprivs {
1.1064 raeburn 5424: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5425: my $author=0;
5426: my $adv=0;
1.678 raeburn 5427: my %grouproles = ();
5428: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5429: my @groupkeys;
1.1000 raeburn 5430: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5431: push(@groupkeys,$role);
5432: }
5433: if (ref($groups_roles) eq 'HASH') {
5434: foreach my $key (keys(%{$groups_roles})) {
5435: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5436: push(@groupkeys,$key);
5437: }
5438: }
5439: }
5440: if (@groupkeys > 0) {
5441: foreach my $role (@groupkeys) {
5442: my ($trole,$area,$sec,$extendedarea);
5443: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5444: $trole = $1;
5445: $area = $2;
5446: $sec = $3;
5447: $extendedarea = $area.$sec;
5448: if (exists($$allgroups{$area})) {
5449: foreach my $group (keys(%{$$allgroups{$area}})) {
5450: my $spec = $trole.'.'.$extendedarea;
5451: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5452: $$allgroups{$area}{$group};
1.1064 raeburn 5453: }
1.678 raeburn 5454: }
5455: }
5456: }
5457: }
5458: }
1.800 albertel 5459: foreach my $group (keys(%grouproles)) {
5460: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5461: }
1.800 albertel 5462: foreach my $role (keys(%{$allroles})) {
5463: my %thesepriv;
1.941 raeburn 5464: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5465: foreach my $item (split(/:/,$$allroles{$role})) {
5466: if ($item ne '') {
5467: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5468: if ($restrictions eq '') {
5469: $thesepriv{$privilege}='F';
5470: } elsif ($thesepriv{$privilege} ne 'F') {
5471: $thesepriv{$privilege}.=$restrictions;
5472: }
5473: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5474: }
5475: }
5476: my $thesestr='';
1.1104 raeburn 5477: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5478: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5479: }
5480: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5481: }
5482: return ($author,$adv);
5483: }
5484:
1.994 raeburn 5485: sub role_status {
1.1104 raeburn 5486: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5487: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5488: my ($one,$two) = split(m{\./},$rolekey,2);
5489: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5490: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5491: $$where = '/'.$two;
1.994 raeburn 5492: $$trolecode=$$role.'.'.$$where;
5493: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5494: $$tstatus='is';
1.1104 raeburn 5495: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5496: $$tstatus='future';
1.1034 raeburn 5497: if ($$tstart<$now) {
5498: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5499: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5500: my (%allroles,%allgroups,$group_privs,
5501: %groups_roles,@rolecodes);
1.1002 raeburn 5502: my %userroles = (
5503: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5504: );
1.1064 raeburn 5505: @rolecodes = ('cm');
1.1002 raeburn 5506: my $spec=$$role.'.'.$$where;
5507: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5508: if ($$role =~ /^cr\//) {
5509: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5510: push(@rolecodes,'cr');
1.1002 raeburn 5511: } elsif ($$role eq 'gr') {
1.1064 raeburn 5512: push(@rolecodes,$$role);
1.1002 raeburn 5513: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5514: $env{'user.name'});
1.1064 raeburn 5515: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5516: (undef,my $group_privs) = split(/\//,$trole);
5517: $group_privs = &unescape($group_privs);
5518: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5519: 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 5520: &get_groups_roles($tdomain,$trest,
5521: \%course_roles,\@rolecodes,
5522: \%groups_roles);
1.1002 raeburn 5523: } else {
1.1064 raeburn 5524: push(@rolecodes,$$role);
1.1002 raeburn 5525: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5526: }
1.1064 raeburn 5527: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5528: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5529: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5530: }
5531: }
1.1034 raeburn 5532: $$tstatus = 'is';
1.1002 raeburn 5533: }
1.994 raeburn 5534: }
5535: if ($$tend) {
1.1104 raeburn 5536: if ($$tend<$update) {
1.994 raeburn 5537: $$tstatus='expired';
5538: } elsif ($$tend<$now) {
5539: $$tstatus='will_not';
5540: }
5541: }
5542: }
5543: }
5544: }
5545:
1.1104 raeburn 5546: sub get_groups_roles {
5547: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5548: return unless((ref($cdom_courseroles) eq 'HASH') &&
5549: (ref($rolecodes) eq 'ARRAY') &&
5550: (ref($groups_roles) eq 'HASH'));
5551: if (keys(%{$cdom_courseroles}) > 0) {
5552: my ($cnum) = ($rest =~ /^($match_courseid)/);
5553: if ($cdom ne '' && $cnum ne '') {
5554: foreach my $key (keys(%{$cdom_courseroles})) {
5555: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5556: my $crsrole = $1;
5557: my $crssec = $2;
5558: if ($crsrole =~ /^cr/) {
5559: unless (grep(/^cr$/,@{$rolecodes})) {
5560: push(@{$rolecodes},'cr');
5561: }
5562: } else {
5563: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5564: push(@{$rolecodes},$crsrole);
5565: }
5566: }
5567: my $rolekey = "$crsrole./$cdom/$cnum";
5568: if ($crssec ne '') {
5569: $rolekey .= "/$crssec";
5570: }
5571: $rolekey .= './';
5572: $groups_roles->{$rolekey} = $rolecodes;
5573: }
5574: }
5575: }
5576: }
5577: return;
5578: }
5579:
5580: sub delete_env_groupprivs {
5581: my ($where,$courseroles,$possroles) = @_;
5582: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5583: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5584: unless (ref($courseroles->{$udom}) eq 'HASH') {
5585: %{$courseroles->{$udom}} =
5586: &get_my_roles('','','userroles',['active'],
5587: $possroles,[$udom],1);
5588: }
5589: if (ref($courseroles->{$udom}) eq 'HASH') {
5590: foreach my $item (keys(%{$courseroles->{$udom}})) {
5591: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5592: my $area = '/'.$cdom.'/'.$cnum;
5593: my $privkey = "user.priv.$crsrole.$area";
5594: if ($crssec ne '') {
5595: $privkey .= '/'.$crssec;
5596: }
5597: $privkey .= ".$area/$group";
5598: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5599: }
5600: }
5601: return;
5602: }
5603:
1.994 raeburn 5604: sub check_adhoc_privs {
1.1104 raeburn 5605: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5606: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5607: my $setprivs;
1.994 raeburn 5608: if ($env{$cckey}) {
5609: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5610: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5611: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5612: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5613: $setprivs = 1;
1.994 raeburn 5614: }
5615: } else {
1.1088 raeburn 5616: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5617: $setprivs = 1;
1.994 raeburn 5618: }
1.1172.2.9 raeburn 5619: return $setprivs;
1.994 raeburn 5620: }
5621:
5622: sub set_adhoc_privileges {
5623: # role can be cc or ca
1.1088 raeburn 5624: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5625: my $area = '/'.$dcdom.'/'.$pickedcourse;
5626: my $spec = $role.'.'.$area;
5627: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5628: $env{'user.name'},1);
1.994 raeburn 5629: my %ccrole = ();
5630: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5631: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5632: &appenv(\%userroles,[$role,'cm']);
5633: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5634: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5635: &appenv( {'request.role' => $spec,
5636: 'request.role.domain' => $dcdom,
5637: 'request.course.sec' => ''
5638: }
5639: );
5640: my $tadv=0;
5641: if (&allowed('adv') eq 'F') { $tadv=1; }
5642: &appenv({'request.role.adv' => $tadv});
5643: }
1.994 raeburn 5644: }
5645:
1.12 www 5646: # --------------------------------------------------------------- get interface
5647:
5648: sub get {
1.131 albertel 5649: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5650: my $items='';
1.800 albertel 5651: foreach my $item (@$storearr) {
5652: $items.=&escape($item).'&';
1.191 harris41 5653: }
1.12 www 5654: $items=~s/\&$//;
1.620 albertel 5655: if (!$udomain) { $udomain=$env{'user.domain'}; }
5656: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5657: my $uhome=&homeserver($uname,$udomain);
5658:
1.133 albertel 5659: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5660: my @pairs=split(/\&/,$rep);
1.273 albertel 5661: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5662: return @pairs;
5663: }
1.15 www 5664: my %returnhash=();
1.42 www 5665: my $i=0;
1.800 albertel 5666: foreach my $item (@$storearr) {
5667: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5668: $i++;
1.191 harris41 5669: }
1.15 www 5670: return %returnhash;
1.27 www 5671: }
5672:
5673: # --------------------------------------------------------------- del interface
5674:
5675: sub del {
1.133 albertel 5676: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5677: my $items='';
1.800 albertel 5678: foreach my $item (@$storearr) {
5679: $items.=&escape($item).'&';
1.191 harris41 5680: }
1.984 neumanie 5681:
1.27 www 5682: $items=~s/\&$//;
1.620 albertel 5683: if (!$udomain) { $udomain=$env{'user.domain'}; }
5684: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5685: my $uhome=&homeserver($uname,$udomain);
5686: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5687: }
5688:
5689: # -------------------------------------------------------------- dump interface
5690:
1.1172.2.22 raeburn 5691: sub unserialize {
5692: my ($rep, $escapedkeys) = @_;
5693:
5694: return {} if $rep =~ /^error/;
5695:
5696: my %returnhash=();
5697: foreach my $item (split(/\&/,$rep)) {
5698: my ($key, $value) = split(/=/, $item, 2);
5699: $key = unescape($key) unless $escapedkeys;
5700: next if $key =~ /^error: 2 /;
5701: $returnhash{$key} = &thaw_unescape($value);
5702: }
5703: return \%returnhash;
5704: }
5705:
5706: # see Lond::dump_with_regexp
5707: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5708: sub dump {
1.1172.2.22 raeburn 5709: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5710: if (!$udomain) { $udomain=$env{'user.domain'}; }
5711: if (!$uname) { $uname=$env{'user.name'}; }
5712: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5713:
1.1172.2.55 raeburn 5714: if ($regexp) {
5715: $regexp=&escape($regexp);
5716: } else {
5717: $regexp='.';
5718: }
1.1172.2.22 raeburn 5719: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5720: # user is hosted on this machine
1.1172.2.55 raeburn 5721: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5722: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5723: return %{&unserialize($reply, $escapedkeys)};
5724: }
1.1166 raeburn 5725: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5726: my @pairs=split(/\&/,$rep);
5727: my %returnhash=();
1.1098 foxr 5728: if (!($rep =~ /^error/ )) {
5729: foreach my $item (@pairs) {
5730: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5731: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5732: next if ($key =~ /^error: 2 /);
5733: $returnhash{$key}=&thaw_unescape($value);
5734: }
1.755 albertel 5735: }
5736: return %returnhash;
1.407 www 5737: }
5738:
1.1098 foxr 5739:
1.717 albertel 5740: # --------------------------------------------------------- dumpstore interface
5741:
5742: sub dumpstore {
5743: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5744: # same as dump but keys must be escaped. They may contain colon separated
5745: # lists of values that may themself contain colons (e.g. symbs).
5746: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5747: }
5748:
1.407 www 5749: # -------------------------------------------------------------- keys interface
5750:
5751: sub getkeys {
5752: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5753: if (!$udomain) { $udomain=$env{'user.domain'}; }
5754: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5755: my $uhome=&homeserver($uname,$udomain);
5756: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5757: my @keyarray=();
1.800 albertel 5758: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5759: next if ($key =~ /^error: 2 /);
1.800 albertel 5760: push(@keyarray,&unescape($key));
1.407 www 5761: }
5762: return @keyarray;
1.318 matthew 5763: }
5764:
1.319 matthew 5765: # --------------------------------------------------------------- currentdump
5766: sub currentdump {
1.328 matthew 5767: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5768: $courseid = $env{'request.course.id'} if (! defined($courseid));
5769: $sdom = $env{'user.domain'} if (! defined($sdom));
5770: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5771: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 5772: my $rep;
5773:
5774: if (grep { $_ eq $uhome } current_machine_ids()) {
5775: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5776: $courseid)));
5777: } else {
5778: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5779: }
5780:
1.318 matthew 5781: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5782: #
1.318 matthew 5783: my %returnhash=();
1.319 matthew 5784: #
5785: if ($rep eq "unknown_cmd") {
5786: # an old lond will not know currentdump
5787: # Do a dump and make it look like a currentdump
1.822 albertel 5788: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5789: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5790: my %hash = @tmp;
5791: @tmp=();
1.424 matthew 5792: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5793: } else {
5794: my @pairs=split(/\&/,$rep);
1.800 albertel 5795: foreach my $pair (@pairs) {
5796: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5797: my ($symb,$param) = split(/:/,$key);
5798: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5799: &thaw_unescape($value);
1.319 matthew 5800: }
1.191 harris41 5801: }
1.12 www 5802: return %returnhash;
1.424 matthew 5803: }
5804:
5805: sub convert_dump_to_currentdump{
5806: my %hash = %{shift()};
5807: my %returnhash;
5808: # Code ripped from lond, essentially. The only difference
5809: # here is the unescaping done by lonnet::dump(). Conceivably
5810: # we might run in to problems with parameter names =~ /^v\./
5811: while (my ($key,$value) = each(%hash)) {
5812: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5813: $symb = &unescape($symb);
5814: $param = &unescape($param);
1.424 matthew 5815: next if ($v eq 'version' || $symb eq 'keys');
5816: next if (exists($returnhash{$symb}) &&
5817: exists($returnhash{$symb}->{$param}) &&
5818: $returnhash{$symb}->{'v.'.$param} > $v);
5819: $returnhash{$symb}->{$param}=$value;
5820: $returnhash{$symb}->{'v.'.$param}=$v;
5821: }
5822: #
5823: # Remove all of the keys in the hashes which keep track of
5824: # the version of the parameter.
5825: while (my ($symb,$param_hash) = each(%returnhash)) {
5826: # use a foreach because we are going to delete from the hash.
5827: foreach my $key (keys(%$param_hash)) {
5828: delete($param_hash->{$key}) if ($key =~ /^v\./);
5829: }
5830: }
5831: return \%returnhash;
1.12 www 5832: }
5833:
1.627 albertel 5834: # ------------------------------------------------------ critical inc interface
5835:
5836: sub cinc {
5837: return &inc(@_,'critical');
5838: }
5839:
1.449 matthew 5840: # --------------------------------------------------------------- inc interface
5841:
5842: sub inc {
1.627 albertel 5843: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5844: if (!$udomain) { $udomain=$env{'user.domain'}; }
5845: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5846: my $uhome=&homeserver($uname,$udomain);
5847: my $items='';
5848: if (! ref($store)) {
5849: # got a single value, so use that instead
5850: $items = &escape($store).'=&';
5851: } elsif (ref($store) eq 'SCALAR') {
5852: $items = &escape($$store).'=&';
5853: } elsif (ref($store) eq 'ARRAY') {
5854: $items = join('=&',map {&escape($_);} @{$store});
5855: } elsif (ref($store) eq 'HASH') {
5856: while (my($key,$value) = each(%{$store})) {
5857: $items.= &escape($key).'='.&escape($value).'&';
5858: }
5859: }
5860: $items=~s/\&$//;
1.627 albertel 5861: if ($critical) {
5862: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5863: } else {
5864: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5865: }
1.449 matthew 5866: }
5867:
1.12 www 5868: # --------------------------------------------------------------- put interface
5869:
5870: sub put {
1.134 albertel 5871: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5872: if (!$udomain) { $udomain=$env{'user.domain'}; }
5873: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5874: my $uhome=&homeserver($uname,$udomain);
1.12 www 5875: my $items='';
1.800 albertel 5876: foreach my $item (keys(%$storehash)) {
5877: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5878: }
1.12 www 5879: $items=~s/\&$//;
1.134 albertel 5880: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5881: }
5882:
1.631 albertel 5883: # ------------------------------------------------------------ newput interface
5884:
5885: sub newput {
5886: my ($namespace,$storehash,$udomain,$uname)=@_;
5887: if (!$udomain) { $udomain=$env{'user.domain'}; }
5888: if (!$uname) { $uname=$env{'user.name'}; }
5889: my $uhome=&homeserver($uname,$udomain);
5890: my $items='';
5891: foreach my $key (keys(%$storehash)) {
5892: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5893: }
5894: $items=~s/\&$//;
5895: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5896: }
5897:
5898: # --------------------------------------------------------- putstore interface
5899:
1.524 raeburn 5900: sub putstore {
1.1172.2.59! raeburn 5901: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 5902: if (!$udomain) { $udomain=$env{'user.domain'}; }
5903: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5904: my $uhome=&homeserver($uname,$udomain);
5905: my $items='';
1.715 albertel 5906: foreach my $key (keys(%$storehash)) {
5907: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5908: }
1.715 albertel 5909: $items=~s/\&$//;
1.716 albertel 5910: my $esc_symb=&escape($symb);
5911: my $esc_v=&escape($version);
1.715 albertel 5912: my $reply =
1.716 albertel 5913: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5914: $uhome);
1.1172.2.59! raeburn 5915: if (($tolog) && ($reply eq 'ok')) {
! 5916: my $namevalue='';
! 5917: foreach my $key (keys(%{$storehash})) {
! 5918: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
! 5919: }
! 5920: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
! 5921: '&host='.&escape($perlvar{'lonHostID'}).
! 5922: '&version='.$esc_v.
! 5923: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
! 5924: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
! 5925: }
1.715 albertel 5926: if ($reply eq 'unknown_cmd') {
1.716 albertel 5927: # gfall back to way things use to be done
1.715 albertel 5928: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5929: $uname);
1.524 raeburn 5930: }
1.715 albertel 5931: return $reply;
5932: }
5933:
5934: sub old_putstore {
1.716 albertel 5935: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5936: if (!$udomain) { $udomain=$env{'user.domain'}; }
5937: if (!$uname) { $uname=$env{'user.name'}; }
5938: my $uhome=&homeserver($uname,$udomain);
5939: my %newstorehash;
1.800 albertel 5940: foreach my $item (keys(%$storehash)) {
5941: my $key = $version.':'.&escape($symb).':'.$item;
5942: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5943: }
5944: my $items='';
5945: my %allitems = ();
1.800 albertel 5946: foreach my $item (keys(%newstorehash)) {
5947: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5948: my $key = $1.':keys:'.$2;
5949: $allitems{$key} .= $3.':';
5950: }
1.800 albertel 5951: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5952: }
1.800 albertel 5953: foreach my $item (keys(%allitems)) {
5954: $allitems{$item} =~ s/\:$//;
5955: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5956: }
5957: $items=~s/\&$//;
5958: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5959: }
5960:
1.47 www 5961: # ------------------------------------------------------ critical put interface
5962:
5963: sub cput {
1.134 albertel 5964: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5965: if (!$udomain) { $udomain=$env{'user.domain'}; }
5966: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5967: my $uhome=&homeserver($uname,$udomain);
1.47 www 5968: my $items='';
1.800 albertel 5969: foreach my $item (keys(%$storehash)) {
5970: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5971: }
1.47 www 5972: $items=~s/\&$//;
1.134 albertel 5973: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5974: }
5975:
5976: # -------------------------------------------------------------- eget interface
5977:
5978: sub eget {
1.133 albertel 5979: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5980: my $items='';
1.800 albertel 5981: foreach my $item (@$storearr) {
5982: $items.=&escape($item).'&';
1.191 harris41 5983: }
1.12 www 5984: $items=~s/\&$//;
1.620 albertel 5985: if (!$udomain) { $udomain=$env{'user.domain'}; }
5986: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5987: my $uhome=&homeserver($uname,$udomain);
5988: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5989: my @pairs=split(/\&/,$rep);
5990: my %returnhash=();
1.42 www 5991: my $i=0;
1.800 albertel 5992: foreach my $item (@$storearr) {
5993: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5994: $i++;
1.191 harris41 5995: }
1.12 www 5996: return %returnhash;
5997: }
5998:
1.667 albertel 5999: # ------------------------------------------------------------ tmpput interface
6000: sub tmpput {
1.802 raeburn 6001: my ($storehash,$server,$context)=@_;
1.667 albertel 6002: my $items='';
1.800 albertel 6003: foreach my $item (keys(%$storehash)) {
6004: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6005: }
6006: $items=~s/\&$//;
1.802 raeburn 6007: if (defined($context)) {
6008: $items .= ':'.&escape($context);
6009: }
1.667 albertel 6010: return &reply("tmpput:$items",$server);
6011: }
6012:
6013: # ------------------------------------------------------------ tmpget interface
6014: sub tmpget {
1.688 albertel 6015: my ($token,$server)=@_;
6016: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6017: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6018: my %returnhash;
6019: foreach my $item (split(/\&/,$rep)) {
6020: my ($key,$value)=split(/=/,$item);
1.951 raeburn 6021: next if ($key =~ /^error: 2 /);
1.667 albertel 6022: $returnhash{&unescape($key)}=&thaw_unescape($value);
6023: }
6024: return %returnhash;
6025: }
6026:
1.1113 raeburn 6027: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6028: sub tmpdel {
6029: my ($token,$server)=@_;
6030: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6031: return &reply("tmpdel:$token",$server);
6032: }
6033:
1.1172.2.13 raeburn 6034: # ------------------------------------------------------------ get_timebased_id
6035:
6036: sub get_timebased_id {
6037: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6038: $maxtries) = @_;
6039: my ($newid,$error,$dellock);
6040: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6041: return ('','ok','invalid call to get suffix');
6042: }
6043:
6044: # set defaults for any optional args for which values were not supplied
6045: if ($who eq '') {
6046: $who = $env{'user.name'}.':'.$env{'user.domain'};
6047: }
6048: if (!$locktries) {
6049: $locktries = 3;
6050: }
6051: if (!$maxtries) {
6052: $maxtries = 10;
6053: }
6054:
6055: if (($cdom eq '') || ($cnum eq '')) {
6056: if ($env{'request.course.id'}) {
6057: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6058: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6059: }
6060: if (($cdom eq '') || ($cnum eq '')) {
6061: return ('','ok','call to get suffix not in course context');
6062: }
6063: }
6064:
6065: # construct locking item
6066: my $lockhash = {
6067: $prefix."\0".'locked_'.$keyid => $who,
6068: };
6069: my $tries = 0;
6070:
6071: # attempt to get lock on nohist_$namespace file
6072: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6073: while (($gotlock ne 'ok') && $tries <$locktries) {
6074: $tries ++;
6075: sleep 1;
6076: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6077: }
6078:
6079: # attempt to get unique identifier, based on current timestamp
6080: if ($gotlock eq 'ok') {
6081: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6082: my $id = time;
6083: $newid = $id;
1.1172.2.56 raeburn 6084: if ($idtype eq 'addcode') {
6085: $newid .= &sixnum_code();
6086: }
1.1172.2.13 raeburn 6087: my $idtries = 0;
6088: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6089: if ($idtype eq 'concat') {
6090: $newid = $id.$idtries;
1.1172.2.56 raeburn 6091: } elsif ($idtype eq 'addcode') {
6092: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6093: } else {
6094: $newid ++;
6095: }
6096: $idtries ++;
6097: }
6098: if (!exists($inuse{$prefix."\0".$newid})) {
6099: my %new_item = (
6100: $prefix."\0".$newid => $who,
6101: );
6102: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6103: $cdom,$cnum);
6104: if ($putresult ne 'ok') {
6105: undef($newid);
6106: $error = 'error saving new item: '.$putresult;
6107: }
6108: } else {
1.1172.2.56 raeburn 6109: undef($newid);
1.1172.2.13 raeburn 6110: $error = ('error: no unique suffix available for the new item ');
6111: }
6112: # remove lock
6113: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6114: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6115: } else {
6116: $error = "error: could not obtain lockfile\n";
6117: $dellock = 'ok';
1.1172.2.58 raeburn 6118: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6119: $dellock = 'nolock';
6120: }
1.1172.2.13 raeburn 6121: }
6122: return ($newid,$dellock,$error);
6123: }
6124:
1.1172.2.56 raeburn 6125: sub sixnum_code {
6126: my $code;
6127: for (0..6) {
6128: $code .= int( rand(9) );
6129: }
6130: return $code;
6131: }
6132:
1.765 albertel 6133: # -------------------------------------------------- portfolio access checking
6134:
6135: sub portfolio_access {
1.766 albertel 6136: my ($requrl) = @_;
1.765 albertel 6137: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6138: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6139: if ($result) {
6140: my %setters;
6141: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6142: my ($startblock,$endblock) =
6143: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6144: if ($startblock && $endblock) {
6145: return 'B';
6146: }
6147: } else {
6148: my ($startblock,$endblock) =
6149: &Apache::loncommon::blockcheck(\%setters,'port');
6150: if ($startblock && $endblock) {
6151: return 'B';
6152: }
6153: }
6154: }
1.765 albertel 6155: if ($result eq 'ok') {
1.766 albertel 6156: return 'F';
1.765 albertel 6157: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6158: return 'A';
1.765 albertel 6159: }
1.766 albertel 6160: return '';
1.765 albertel 6161: }
6162:
6163: sub get_portfolio_access {
1.767 albertel 6164: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6165:
6166: if (!ref($access_hash)) {
6167: my $current_perms = &get_portfile_permissions($udom,$unum);
6168: my %access_controls = &get_access_controls($current_perms,$group,
6169: $file_name);
6170: $access_hash = $access_controls{$file_name};
6171: }
6172:
1.765 albertel 6173: my ($public,$guest,@domains,@users,@courses,@groups);
6174: my $now = time;
6175: if (ref($access_hash) eq 'HASH') {
6176: foreach my $key (keys(%{$access_hash})) {
6177: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6178: if ($start > $now) {
6179: next;
6180: }
6181: if ($end && $end<$now) {
6182: next;
6183: }
6184: if ($scope eq 'public') {
6185: $public = $key;
6186: last;
6187: } elsif ($scope eq 'guest') {
6188: $guest = $key;
6189: } elsif ($scope eq 'domains') {
6190: push(@domains,$key);
6191: } elsif ($scope eq 'users') {
6192: push(@users,$key);
6193: } elsif ($scope eq 'course') {
6194: push(@courses,$key);
6195: } elsif ($scope eq 'group') {
6196: push(@groups,$key);
6197: }
6198: }
6199: if ($public) {
6200: return 'ok';
6201: }
6202: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6203: if ($guest) {
6204: return $guest;
6205: }
6206: } else {
6207: if (@domains > 0) {
6208: foreach my $domkey (@domains) {
6209: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6210: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6211: return 'ok';
6212: }
6213: }
6214: }
6215: }
6216: if (@users > 0) {
6217: foreach my $userkey (@users) {
1.865 raeburn 6218: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6219: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6220: if (ref($item) eq 'HASH') {
6221: if (($item->{'uname'} eq $env{'user.name'}) &&
6222: ($item->{'udom'} eq $env{'user.domain'})) {
6223: return 'ok';
6224: }
6225: }
6226: }
6227: }
1.765 albertel 6228: }
6229: }
6230: my %roleshash;
6231: my @courses_and_groups = @courses;
6232: push(@courses_and_groups,@groups);
6233: if (@courses_and_groups > 0) {
6234: my (%allgroups,%allroles);
6235: my ($start,$end,$role,$sec,$group);
6236: foreach my $envkey (%env) {
1.1060 raeburn 6237: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6238: my $cid = $2.'_'.$3;
6239: if ($1 eq 'gr') {
6240: $group = $4;
6241: $allgroups{$cid}{$group} = $env{$envkey};
6242: } else {
6243: if ($4 eq '') {
6244: $sec = 'none';
6245: } else {
6246: $sec = $4;
6247: }
6248: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6249: }
1.811 albertel 6250: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6251: my $cid = $2.'_'.$3;
6252: if ($4 eq '') {
6253: $sec = 'none';
6254: } else {
6255: $sec = $4;
6256: }
6257: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6258: }
6259: }
6260: if (keys(%allroles) == 0) {
6261: return;
6262: }
6263: foreach my $key (@courses_and_groups) {
6264: my %content = %{$$access_hash{$key}};
6265: my $cnum = $content{'number'};
6266: my $cdom = $content{'domain'};
6267: my $cid = $cdom.'_'.$cnum;
6268: if (!exists($allroles{$cid})) {
6269: next;
6270: }
6271: foreach my $role_id (keys(%{$content{'roles'}})) {
6272: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6273: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6274: my @status = @{$content{'roles'}{$role_id}{'access'}};
6275: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6276: foreach my $role (keys(%{$allroles{$cid}})) {
6277: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6278: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6279: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6280: if (grep/^all$/,@sections) {
6281: return 'ok';
6282: } else {
6283: if (grep/^$sec$/,@sections) {
6284: return 'ok';
6285: }
6286: }
6287: }
6288: }
6289: if (keys(%{$allgroups{$cid}}) == 0) {
6290: if (grep/^none$/,@groups) {
6291: return 'ok';
6292: }
6293: } else {
6294: if (grep/^all$/,@groups) {
6295: return 'ok';
6296: }
6297: foreach my $group (keys(%{$allgroups{$cid}})) {
6298: if (grep/^$group$/,@groups) {
6299: return 'ok';
6300: }
6301: }
6302: }
6303: }
6304: }
6305: }
6306: }
6307: }
6308: if ($guest) {
6309: return $guest;
6310: }
6311: }
6312: }
6313: return;
6314: }
6315:
6316: sub course_group_datechecker {
6317: my ($dates,$now,$status) = @_;
6318: my ($start,$end) = split(/\./,$dates);
6319: if (!$start && !$end) {
6320: return 'ok';
6321: }
6322: if (grep/^active$/,@{$status}) {
6323: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6324: return 'ok';
6325: }
6326: }
6327: if (grep/^previous$/,@{$status}) {
6328: if ($end > $now ) {
6329: return 'ok';
6330: }
6331: }
6332: if (grep/^future$/,@{$status}) {
6333: if ($start > $now) {
6334: return 'ok';
6335: }
6336: }
6337: return;
6338: }
6339:
6340: sub parse_portfolio_url {
6341: my ($url) = @_;
6342:
6343: my ($type,$udom,$unum,$group,$file_name);
6344:
1.823 albertel 6345: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6346: $type = 1;
6347: $udom = $1;
6348: $unum = $2;
6349: $file_name = $3;
1.823 albertel 6350: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6351: $type = 2;
6352: $udom = $1;
6353: $unum = $2;
6354: $group = $3;
6355: $file_name = $3.'/'.$4;
6356: }
6357: if (wantarray) {
6358: return ($type,$udom,$unum,$file_name,$group);
6359: }
6360: return $type;
6361: }
6362:
6363: sub is_portfolio_url {
6364: my ($url) = @_;
6365: return scalar(&parse_portfolio_url($url));
6366: }
6367:
1.798 raeburn 6368: sub is_portfolio_file {
6369: my ($file) = @_;
1.820 raeburn 6370: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6371: return 1;
6372: }
6373: return;
6374: }
6375:
1.976 raeburn 6376: sub usertools_access {
1.1084 raeburn 6377: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6378: my ($access,%tools);
6379: if ($context eq '') {
6380: $context = 'tools';
6381: }
6382: if ($context eq 'requestcourses') {
6383: %tools = (
6384: official => 1,
6385: unofficial => 1,
1.1006 raeburn 6386: community => 1,
1.1172.2.37 raeburn 6387: textbook => 1,
1.985 raeburn 6388: );
1.1172.2.9 raeburn 6389: } elsif ($context eq 'requestauthor') {
6390: %tools = (
6391: requestauthor => 1,
6392: );
1.985 raeburn 6393: } else {
6394: %tools = (
6395: aboutme => 1,
6396: blog => 1,
1.1172.2.6 raeburn 6397: webdav => 1,
1.985 raeburn 6398: portfolio => 1,
6399: );
6400: }
1.976 raeburn 6401: return if (!defined($tools{$tool}));
6402:
1.1172.2.35 raeburn 6403: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6404: $udom = $env{'user.domain'};
6405: $uname = $env{'user.name'};
6406: }
6407:
1.978 raeburn 6408: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6409: if ($action ne 'reload') {
1.985 raeburn 6410: if ($context eq 'requestcourses') {
6411: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6412: } elsif ($context eq 'requestauthor') {
6413: return $env{'environment.canrequest.author'};
1.985 raeburn 6414: } else {
6415: return $env{'environment.availabletools.'.$tool};
6416: }
6417: }
1.976 raeburn 6418: }
6419:
1.1172.2.9 raeburn 6420: my ($toolstatus,$inststatus,$envkey);
6421: if ($context eq 'requestauthor') {
6422: $envkey = $context;
6423: } else {
6424: $envkey = $context.'.'.$tool;
6425: }
1.976 raeburn 6426:
1.985 raeburn 6427: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6428: ($action ne 'reload')) {
1.1172.2.9 raeburn 6429: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6430: $inststatus = $env{'environment.inststatus'};
6431: } else {
1.1084 raeburn 6432: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6433: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6434: $inststatus = $userenvref->{'inststatus'};
6435: } else {
1.1172.2.9 raeburn 6436: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6437: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6438: $inststatus = $userenv{'inststatus'};
6439: }
1.976 raeburn 6440: }
6441:
6442: if ($toolstatus ne '') {
6443: if ($toolstatus) {
6444: $access = 1;
6445: } else {
6446: $access = 0;
6447: }
6448: return $access;
6449: }
6450:
1.1084 raeburn 6451: my ($is_adv,%domdef);
6452: if (ref($is_advref) eq 'HASH') {
6453: $is_adv = $is_advref->{'is_adv'};
6454: } else {
6455: $is_adv = &is_advanced_user($udom,$uname);
6456: }
6457: if (ref($domdefref) eq 'HASH') {
6458: %domdef = %{$domdefref};
6459: } else {
6460: %domdef = &get_domain_defaults($udom);
6461: }
1.976 raeburn 6462: if (ref($domdef{$tool}) eq 'HASH') {
6463: if ($is_adv) {
6464: if ($domdef{$tool}{'_LC_adv'} ne '') {
6465: if ($domdef{$tool}{'_LC_adv'}) {
6466: $access = 1;
6467: } else {
6468: $access = 0;
6469: }
6470: return $access;
6471: }
6472: }
6473: if ($inststatus ne '') {
6474: my ($hasaccess,$hasnoaccess);
6475: foreach my $affiliation (split(/:/,$inststatus)) {
6476: if ($domdef{$tool}{$affiliation} ne '') {
6477: if ($domdef{$tool}{$affiliation}) {
6478: $hasaccess = 1;
6479: } else {
6480: $hasnoaccess = 1;
6481: }
6482: }
6483: }
6484: if ($hasaccess || $hasnoaccess) {
6485: if ($hasaccess) {
6486: $access = 1;
6487: } elsif ($hasnoaccess) {
6488: $access = 0;
6489: }
6490: return $access;
6491: }
6492: } else {
6493: if ($domdef{$tool}{'default'} ne '') {
6494: if ($domdef{$tool}{'default'}) {
6495: $access = 1;
6496: } elsif ($domdef{$tool}{'default'} == 0) {
6497: $access = 0;
6498: }
6499: return $access;
6500: }
6501: }
6502: } else {
1.1172.2.6 raeburn 6503: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6504: $access = 1;
6505: } else {
6506: $access = 0;
6507: }
1.976 raeburn 6508: return $access;
6509: }
6510: }
6511:
1.1050 raeburn 6512: sub is_course_owner {
6513: my ($cdom,$cnum,$udom,$uname) = @_;
6514: if (($udom eq '') || ($uname eq '')) {
6515: $udom = $env{'user.domain'};
6516: $uname = $env{'user.name'};
6517: }
6518: unless (($udom eq '') || ($uname eq '')) {
6519: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6520: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6521: return 1;
6522: } else {
6523: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6524: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6525: return 1;
6526: }
6527: }
6528: }
6529: }
6530: return;
6531: }
6532:
1.976 raeburn 6533: sub is_advanced_user {
6534: my ($udom,$uname) = @_;
1.1085 raeburn 6535: if ($udom ne '' && $uname ne '') {
6536: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6537: if (wantarray) {
6538: return ($env{'user.adv'},$env{'user.author'});
6539: } else {
6540: return $env{'user.adv'};
6541: }
1.1085 raeburn 6542: }
6543: }
1.976 raeburn 6544: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6545: my %allroles;
1.1128 raeburn 6546: my ($is_adv,$is_author);
1.976 raeburn 6547: foreach my $role (keys(%roleshash)) {
6548: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6549: my $area = '/'.$tdomain.'/'.$trest;
6550: if ($sec ne '') {
6551: $area .= '/'.$sec;
6552: }
6553: if (($area ne '') && ($trole ne '')) {
6554: my $spec=$trole.'.'.$area;
6555: if ($trole =~ /^cr\//) {
6556: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6557: } elsif ($trole ne 'gr') {
6558: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6559: }
1.1128 raeburn 6560: if ($trole eq 'au') {
6561: $is_author = 1;
6562: }
1.976 raeburn 6563: }
6564: }
6565: foreach my $role (keys(%allroles)) {
6566: last if ($is_adv);
6567: foreach my $item (split(/:/,$allroles{$role})) {
6568: if ($item ne '') {
6569: my ($privilege,$restrictions)=split(/&/,$item);
6570: if ($privilege eq 'adv') {
6571: $is_adv = 1;
6572: last;
6573: }
6574: }
6575: }
6576: }
1.1128 raeburn 6577: if (wantarray) {
6578: return ($is_adv,$is_author);
6579: }
1.976 raeburn 6580: return $is_adv;
6581: }
1.798 raeburn 6582:
1.1035 raeburn 6583: sub check_can_request {
1.1036 raeburn 6584: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6585: my $canreq = 0;
6586: my ($types,$typename) = &Apache::loncommon::course_types();
6587: my @options = ('approval','validate','autolimit');
6588: my $optregex = join('|',@options);
6589: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6590: foreach my $type (@{$types}) {
6591: if (&usertools_access($env{'user.name'},
6592: $env{'user.domain'},
6593: $type,undef,'requestcourses')) {
6594: $canreq ++;
1.1036 raeburn 6595: if (ref($request_domains) eq 'HASH') {
6596: push(@{$request_domains->{$type}},$env{'user.domain'});
6597: }
1.1035 raeburn 6598: if ($dom eq $env{'user.domain'}) {
6599: $can_request->{$type} = 1;
6600: }
6601: }
6602: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6603: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6604: if (@curr > 0) {
1.1036 raeburn 6605: foreach my $item (@curr) {
6606: if (ref($request_domains) eq 'HASH') {
6607: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6608: if ($otherdom ne '') {
6609: if (ref($request_domains->{$type}) eq 'ARRAY') {
6610: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6611: push(@{$request_domains->{$type}},$otherdom);
6612: }
6613: } else {
6614: push(@{$request_domains->{$type}},$otherdom);
6615: }
6616: }
6617: }
6618: }
6619: unless($dom eq $env{'user.domain'}) {
6620: $canreq ++;
1.1035 raeburn 6621: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6622: $can_request->{$type} = 1;
6623: }
6624: }
6625: }
6626: }
6627: }
6628: }
6629: return $canreq;
6630: }
6631:
1.341 www 6632: # ---------------------------------------------- Custom access rule evaluation
6633:
6634: sub customaccess {
6635: my ($priv,$uri)=@_;
1.807 albertel 6636: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6637: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6638: $udom = &LONCAPA::clean_domain($udom);
6639: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6640: my $access=0;
1.800 albertel 6641: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6642: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6643: if ($type eq 'user') {
6644: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6645: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6646: if ($tdom) {
6647: if ($tdom ne $env{'user.domain'}) { next; }
6648: }
1.896 albertel 6649: if ($tuname) {
6650: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6651: }
6652: $access=($effect eq 'allow');
6653: last;
6654: }
6655: } else {
6656: if ($role) {
6657: if ($role ne $urole) { next; }
6658: }
6659: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6660: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6661: if ($tdom) {
6662: if ($tdom ne $udom) { next; }
6663: }
6664: if ($tcrs) {
6665: if ($tcrs ne $ucrs) { next; }
6666: }
6667: if ($tsec) {
6668: if ($tsec ne $usec) { next; }
6669: }
6670: $access=($effect eq 'allow');
6671: last;
6672: }
6673: if ($realm eq '' && $role eq '') {
6674: $access=($effect eq 'allow');
6675: }
1.402 bowersj2 6676: }
1.341 www 6677: }
6678: return $access;
6679: }
6680:
1.103 harris41 6681: # ------------------------------------------------- Check for a user privilege
1.12 www 6682:
6683: sub allowed {
1.810 raeburn 6684: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6685: my $ver_orguri=$uri;
1.439 www 6686: $uri=&deversion($uri);
1.152 www 6687: my $orguri=$uri;
1.52 www 6688: $uri=&declutter($uri);
1.809 raeburn 6689:
1.810 raeburn 6690: if ($priv eq 'evb') {
6691: # Evade communication block restrictions for specified role in a course
6692: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6693: return $1;
6694: } else {
6695: return;
6696: }
6697: }
6698:
1.620 albertel 6699: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6700: # Free bre access to adm and meta resources
1.775 albertel 6701: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6702: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6703: && ($priv eq 'bre')) {
1.14 www 6704: return 'F';
1.159 www 6705: }
6706:
1.545 banghart 6707: # Free bre access to user's own portfolio contents
1.714 raeburn 6708: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6709: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6710: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6711: my %setters;
6712: my ($startblock,$endblock) =
6713: &Apache::loncommon::blockcheck(\%setters,'port');
6714: if ($startblock && $endblock) {
6715: return 'B';
6716: } else {
6717: return 'F';
6718: }
1.545 banghart 6719: }
6720:
1.762 raeburn 6721: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6722: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6723: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6724: if (exists($env{'request.course.id'})) {
6725: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6726: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6727: if (($domain eq $cdom) && ($name eq $cnum)) {
6728: my $courseprivid=$env{'request.course.id'};
6729: $courseprivid=~s/\_/\//;
6730: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6731: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6732: return $1;
1.762 raeburn 6733: } else {
6734: if ($env{'request.course.sec'}) {
6735: $courseprivid.='/'.$env{'request.course.sec'};
6736: }
6737: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6738: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6739: return $2;
6740: }
1.714 raeburn 6741: }
6742: }
6743: }
6744: }
6745:
1.159 www 6746: # Free bre to public access
6747:
6748: if ($priv eq 'bre') {
1.238 www 6749: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6750: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6751: return 'F';
6752: }
1.238 www 6753: if ($copyright eq 'priv') {
6754: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6755: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6756: return '';
6757: }
6758: }
6759: if ($copyright eq 'domain') {
6760: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6761: unless (($env{'user.domain'} eq $1) ||
6762: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6763: return '';
6764: }
1.262 matthew 6765: }
1.620 albertel 6766: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6767: # Library role, so allow browsing of resources in this domain.
6768: return 'F';
1.238 www 6769: }
1.341 www 6770: if ($copyright eq 'custom') {
6771: unless (&customaccess($priv,$uri)) { return ''; }
6772: }
1.14 www 6773: }
1.264 matthew 6774: # Domain coordinator is trying to create a course
1.620 albertel 6775: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6776: # uri is the requested domain in this case.
6777: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6778: # a role of dc for the domain in question.
1.620 albertel 6779: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6780: }
1.29 www 6781:
1.52 www 6782: my $thisallowed='';
6783: my $statecond=0;
6784: my $courseprivid='';
6785:
1.1039 raeburn 6786: my $ownaccess;
1.1043 raeburn 6787: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6788: if (($priv eq 'bro') && ($env{'user.author'})) {
6789: if ($uri eq '') {
6790: $ownaccess = 1;
6791: } else {
6792: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6793: my $udom = $env{'user.domain'};
6794: my $uname = $env{'user.name'};
6795: if ($uri =~ m{^\Q$udom\E/?$}) {
6796: $ownaccess = 1;
1.1040 raeburn 6797: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6798: unless ($uri =~ m{\.\./}) {
6799: $ownaccess = 1;
6800: }
6801: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6802: my $now = time;
6803: if ($uri =~ m{^([^/]+)/?$}) {
6804: my $adom = $1;
6805: foreach my $key (keys(%env)) {
1.1042 raeburn 6806: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6807: my ($start,$end) = split('.',$env{$key});
6808: if (($now >= $start) && (!$end || $end < $now)) {
6809: $ownaccess = 1;
6810: last;
6811: }
6812: }
6813: }
6814: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6815: my $adom = $1;
6816: my $aname = $2;
1.1042 raeburn 6817: foreach my $role ('ca','aa') {
6818: if ($env{"user.role.$role./$adom/$aname"}) {
6819: my ($start,$end) =
6820: split('.',$env{"user.role.$role./$adom/$aname"});
6821: if (($now >= $start) && (!$end || $end < $now)) {
6822: $ownaccess = 1;
6823: last;
6824: }
1.1039 raeburn 6825: }
6826: }
6827: }
6828: }
6829: }
6830: }
6831: }
6832:
1.52 www 6833: # Course
6834:
1.620 albertel 6835: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6836: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6837: $thisallowed.=$1;
6838: }
1.52 www 6839: }
1.29 www 6840:
1.52 www 6841: # Domain
6842:
1.620 albertel 6843: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6844: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6845: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6846: $thisallowed.=$1;
6847: }
1.12 www 6848: }
1.52 www 6849:
1.1141 raeburn 6850: # User who is not author or co-author might still be able to edit
6851: # resource of an author in the domain (e.g., if Domain Coordinator).
6852: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6853: (&allowed('mdc',$env{'request.course.id'}))) {
6854: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6855: $thisallowed.=$1;
6856: }
6857: }
6858:
1.52 www 6859: # Course: uri itself is a course
1.66 www 6860: my $courseuri=$uri;
6861: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6862: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6863:
1.620 albertel 6864: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6865: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6866: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6867: $thisallowed.=$1;
6868: }
1.12 www 6869: }
1.29 www 6870:
1.665 albertel 6871: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6872: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6873: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6874: $thisallowed='';
1.671 raeburn 6875: my ($match)=&is_on_map($uri);
6876: if ($match) {
6877: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6878: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6879: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6880: if (@blockers > 0) {
6881: $thisallowed = 'B';
6882: } else {
6883: $thisallowed.=$1;
6884: }
1.671 raeburn 6885: }
6886: } else {
1.705 albertel 6887: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6888: if ($refuri) {
6889: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6890: $thisallowed='F';
1.671 raeburn 6891: } else {
6892: $refuri=&declutter($refuri);
6893: my ($match) = &is_on_map($refuri);
6894: if ($match) {
1.1162 raeburn 6895: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6896: if (@blockers > 0) {
6897: $thisallowed = 'B';
6898: } else {
6899: $thisallowed='F';
6900: }
1.671 raeburn 6901: }
1.669 raeburn 6902: }
1.671 raeburn 6903: }
6904: }
1.314 www 6905: }
1.492 albertel 6906:
1.766 albertel 6907: if ($priv eq 'bre'
6908: && $thisallowed ne 'F'
6909: && $thisallowed ne '2'
6910: && &is_portfolio_url($uri)) {
6911: $thisallowed = &portfolio_access($uri);
6912: }
6913:
1.52 www 6914: # Full access at system, domain or course-wide level? Exit.
1.29 www 6915: if ($thisallowed=~/F/) {
6916: return 'F';
6917: }
6918:
1.52 www 6919: # If this is generating or modifying users, exit with special codes
1.29 www 6920:
1.643 www 6921: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6922: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6923: my ($audom,$auname)=split('/',$uri);
1.643 www 6924: # no author name given, so this just checks on the general right to make a co-author in this domain
6925: unless ($auname) { return $thisallowed; }
6926: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6927: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6928: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6929: ($audom ne $env{'request.role.domain'}))) { return ''; }
6930: }
1.52 www 6931: return $thisallowed;
6932: }
6933: #
1.103 harris41 6934: # Gathered so far: system, domain and course wide privileges
1.52 www 6935: #
6936: # Course: See if uri or referer is an individual resource that is part of
6937: # the course
6938:
1.620 albertel 6939: if ($env{'request.course.id'}) {
1.232 www 6940:
1.620 albertel 6941: $courseprivid=$env{'request.course.id'};
6942: if ($env{'request.course.sec'}) {
6943: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6944: }
6945: $courseprivid=~s/\_/\//;
6946: my $checkreferer=1;
1.232 www 6947: my ($match,$cond)=&is_on_map($uri);
6948: if ($match) {
6949: $statecond=$cond;
1.620 albertel 6950: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6951: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6952: my $value = $1;
6953: if ($priv eq 'bre') {
6954: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6955: if (@blockers > 0) {
6956: $thisallowed = 'B';
6957: } else {
6958: $thisallowed.=$value;
6959: }
6960: } else {
6961: $thisallowed.=$value;
6962: }
1.52 www 6963: $checkreferer=0;
6964: }
1.29 www 6965: }
1.83 www 6966:
1.148 www 6967: if ($checkreferer) {
1.620 albertel 6968: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6969: unless ($refuri) {
1.800 albertel 6970: foreach my $key (keys(%env)) {
6971: if ($key=~/^httpref\..*\*/) {
6972: my $pattern=$key;
1.156 www 6973: $pattern=~s/^httpref\.\/res\///;
1.148 www 6974: $pattern=~s/\*/\[\^\/\]\+/g;
6975: $pattern=~s/\//\\\//g;
1.152 www 6976: if ($orguri=~/$pattern/) {
1.800 albertel 6977: $refuri=$env{$key};
1.148 www 6978: }
6979: }
1.191 harris41 6980: }
1.148 www 6981: }
1.232 www 6982:
1.148 www 6983: if ($refuri) {
1.152 www 6984: $refuri=&declutter($refuri);
1.232 www 6985: my ($match,$cond)=&is_on_map($refuri);
6986: if ($match) {
6987: my $refstatecond=$cond;
1.620 albertel 6988: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6989: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6990: my $value = $1;
6991: if ($priv eq 'bre') {
6992: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6993: if (@blockers > 0) {
6994: $thisallowed = 'B';
6995: } else {
6996: $thisallowed.=$value;
6997: }
6998: } else {
6999: $thisallowed.=$value;
7000: }
1.53 www 7001: $uri=$refuri;
7002: $statecond=$refstatecond;
1.52 www 7003: }
7004: }
1.148 www 7005: }
1.29 www 7006: }
1.52 www 7007: }
1.29 www 7008:
1.52 www 7009: #
1.103 harris41 7010: # Gathered now: all privileges that could apply, and condition number
1.52 www 7011: #
7012: #
7013: # Full or no access?
7014: #
1.29 www 7015:
1.52 www 7016: if ($thisallowed=~/F/) {
7017: return 'F';
7018: }
1.29 www 7019:
1.52 www 7020: unless ($thisallowed) {
7021: return '';
7022: }
1.29 www 7023:
1.52 www 7024: # Restrictions exist, deal with them
7025: #
7026: # C:according to course preferences
7027: # R:according to resource settings
7028: # L:unless locked
7029: # X:according to user session state
7030: #
7031:
7032: # Possibly locked functionality, check all courses
1.54 www 7033: # Locks might take effect only after 10 minutes cache expiration for other
7034: # courses, and 2 minutes for current course
1.52 www 7035:
7036: my $envkey;
7037: if ($thisallowed=~/L/) {
1.1000 raeburn 7038: foreach $envkey (keys(%env)) {
1.54 www 7039: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7040: my $courseid=$2;
7041: my $roleid=$1.'.'.$2;
1.92 www 7042: $courseid=~s/^\///;
1.54 www 7043: my $expiretime=600;
1.620 albertel 7044: if ($env{'request.role'} eq $roleid) {
1.54 www 7045: $expiretime=120;
7046: }
7047: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7048: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7049: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7050: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7051: }
1.620 albertel 7052: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7053: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7054: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7055: &log($env{'user.domain'},$env{'user.name'},
7056: $env{'user.home'},
1.57 www 7057: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7058: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7059: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7060: return '';
7061: }
7062: }
1.620 albertel 7063: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7064: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7065: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7066: &log($env{'user.domain'},$env{'user.name'},
7067: $env{'user.home'},
1.57 www 7068: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7069: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7070: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7071: return '';
7072: }
7073: }
7074: }
1.29 www 7075: }
1.52 www 7076: }
7077:
7078: #
7079: # Rest of the restrictions depend on selected course
7080: #
7081:
1.620 albertel 7082: unless ($env{'request.course.id'}) {
1.766 albertel 7083: if ($thisallowed eq 'A') {
7084: return 'A';
1.814 raeburn 7085: } elsif ($thisallowed eq 'B') {
7086: return 'B';
1.766 albertel 7087: } else {
7088: return '1';
7089: }
1.52 www 7090: }
1.29 www 7091:
1.52 www 7092: #
7093: # Now user is definitely in a course
7094: #
1.53 www 7095:
7096:
7097: # Course preferences
7098:
7099: if ($thisallowed=~/C/) {
1.620 albertel 7100: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7101: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7102: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7103: =~/\Q$rolecode\E/) {
1.1103 raeburn 7104: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7105: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7106: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7107: $env{'request.course.id'});
7108: }
1.237 www 7109: return '';
7110: }
7111:
1.620 albertel 7112: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7113: =~/\Q$unamedom\E/) {
1.1103 raeburn 7114: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7115: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7116: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7117: $env{'request.course.id'});
7118: }
1.54 www 7119: return '';
7120: }
1.53 www 7121: }
7122:
7123: # Resource preferences
7124:
7125: if ($thisallowed=~/R/) {
1.620 albertel 7126: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7127: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7128: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7129: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7130: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7131: }
7132: return '';
1.54 www 7133: }
1.53 www 7134: }
1.30 www 7135:
1.246 www 7136: # Restricted by state or randomout?
1.30 www 7137:
1.52 www 7138: if ($thisallowed=~/X/) {
1.620 albertel 7139: if ($env{'acc.randomout'}) {
1.579 albertel 7140: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7141: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7142: return '';
7143: }
1.247 www 7144: }
7145: if (&condval($statecond)) {
1.52 www 7146: return '2';
7147: } else {
7148: return '';
7149: }
7150: }
1.30 www 7151:
1.766 albertel 7152: if ($thisallowed eq 'A') {
7153: return 'A';
1.814 raeburn 7154: } elsif ($thisallowed eq 'B') {
7155: return 'B';
1.766 albertel 7156: }
1.52 www 7157: return 'F';
1.232 www 7158: }
1.1162 raeburn 7159:
1.1172.2.13 raeburn 7160: # ------------------------------------------- Check construction space access
7161:
7162: sub constructaccess {
7163: my ($url,$setpriv)=@_;
7164:
7165: # We do not allow editing of previous versions of files
7166: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7167:
7168: # Get username and domain from URL
7169: my ($ownername,$ownerdomain,$ownerhome);
7170:
7171: ($ownerdomain,$ownername) =
7172: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7173:
7174: # The URL does not really point to any authorspace, forget it
7175: unless (($ownername) && ($ownerdomain)) { return ''; }
7176:
7177: # Now we need to see if the user has access to the authorspace of
7178: # $ownername at $ownerdomain
7179:
7180: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7181: # Real author for this?
7182: $ownerhome = $env{'user.home'};
7183: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7184: return ($ownername,$ownerdomain,$ownerhome);
7185: }
7186: } else {
7187: # Co-author for this?
7188: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7189: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7190: $ownerhome = &homeserver($ownername,$ownerdomain);
7191: return ($ownername,$ownerdomain,$ownerhome);
7192: }
7193: }
7194:
7195: # We don't have any access right now. If we are not possibly going to do anything about this,
7196: # we might as well leave
7197: unless ($setpriv) { return ''; }
7198:
7199: # Backdoor access?
7200: my $allowed=&allowed('eco',$ownerdomain);
7201: # Nope
7202: unless ($allowed) { return ''; }
7203: # Looks like we may have access, but could be locked by the owner of the construction space
7204: if ($allowed eq 'U') {
7205: my %blocked=&get('environment',['domcoord.author'],
7206: $ownerdomain,$ownername);
7207: # Is blocked by owner
7208: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7209: }
7210: if (($allowed eq 'F') || ($allowed eq 'U')) {
7211: # Grant temporary access
7212: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7213: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7214: if (!$update) { $update = $then; }
7215: my $refresh=$env{'user.refresh.time'};
7216: if (!$refresh) { $refresh = $update; }
7217: my $now = time;
7218: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7219: $now,'ca','constructaccess');
7220: $ownerhome = &homeserver($ownername,$ownerdomain);
7221: return($ownername,$ownerdomain,$ownerhome);
7222: }
7223: # No business here
7224: return '';
7225: }
7226:
1.1162 raeburn 7227: sub get_comm_blocks {
7228: my ($cdom,$cnum) = @_;
7229: if ($cdom eq '' || $cnum eq '') {
7230: return unless ($env{'request.course.id'});
7231: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7232: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7233: }
7234: my %commblocks;
7235: my $hashid=$cdom.'_'.$cnum;
7236: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7237: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7238: %commblocks = %{$blocksref};
7239: } else {
7240: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7241: my $cachetime = 600;
7242: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7243: }
7244: return %commblocks;
7245: }
7246:
7247: sub has_comm_blocking {
7248: my ($priv,$symb,$uri,$blocks) = @_;
7249: return unless ($env{'request.course.id'});
7250: return unless ($priv eq 'bre');
7251: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7252: my %commblocks;
7253: if (ref($blocks) eq 'HASH') {
7254: %commblocks = %{$blocks};
7255: } else {
7256: %commblocks = &get_comm_blocks();
7257: }
7258: return unless (keys(%commblocks) > 0);
7259: if (!$symb) { $symb=&symbread($uri,1); }
7260: my ($map,$resid,undef)=&decode_symb($symb);
7261: my %tocheck = (
7262: maps => $map,
7263: resources => $symb,
7264: );
7265: my @blockers;
7266: my $now = time;
1.1163 raeburn 7267: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7268: foreach my $block (keys(%commblocks)) {
7269: if ($block =~ /^(\d+)____(\d+)$/) {
7270: my ($start,$end) = ($1,$2);
7271: if ($start <= $now && $end >= $now) {
7272: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7273: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7274: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7275: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7276: unless (grep(/^\Q$block\E$/,@blockers)) {
7277: push(@blockers,$block);
7278: }
7279: }
7280: }
7281: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7282: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7283: unless (grep(/^\Q$block\E$/,@blockers)) {
7284: push(@blockers,$block);
7285: }
7286: }
7287: }
7288: }
7289: }
7290: }
7291: } elsif ($block =~ /^firstaccess____(.+)$/) {
7292: my $item = $1;
1.1163 raeburn 7293: my @to_test;
1.1162 raeburn 7294: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7295: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7296: my $check_interval;
7297: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7298: my @interval;
7299: my $type = 'map';
7300: if ($item eq 'course') {
7301: $type = 'course';
7302: @interval=&EXT("resource.0.interval");
7303: } else {
7304: if ($item =~ /___\d+___/) {
7305: $type = 'resource';
7306: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7307: if (ref($navmap)) {
7308: my $res = $navmap->getBySymb($item);
7309: push(@to_test,$res);
7310: }
1.1162 raeburn 7311: } else {
7312: my $mapsymb = &symbread($item,1);
7313: if ($mapsymb) {
7314: if (ref($navmap)) {
7315: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7316: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7317: foreach my $res (@to_test) {
1.1162 raeburn 7318: my $symb = $res->symb();
7319: next if ($symb eq $mapsymb);
7320: if ($symb ne '') {
7321: @interval=&EXT("resource.0.interval",$symb);
7322: last;
7323: }
7324: }
7325: }
7326: }
7327: }
7328: }
7329: if ($interval[0] =~ /\d+/) {
7330: my $first_access;
7331: if ($type eq 'resource') {
7332: $first_access=&get_first_access($interval[1],$item);
7333: } elsif ($type eq 'map') {
7334: $first_access=&get_first_access($interval[1],undef,$item);
7335: } else {
7336: $first_access=&get_first_access($interval[1]);
7337: }
7338: if ($first_access) {
7339: my $timesup = $first_access+$interval[0];
7340: if ($timesup > $now) {
1.1163 raeburn 7341: foreach my $res (@to_test) {
7342: if ($res->is_problem()) {
7343: if ($res->completable()) {
7344: unless (grep(/^\Q$block\E$/,@blockers)) {
7345: push(@blockers,$block);
7346: }
7347: last;
7348: }
7349: }
1.1162 raeburn 7350: }
7351: }
7352: }
7353: }
7354: }
7355: }
7356: }
7357: }
7358: }
7359: return @blockers;
7360: }
7361:
7362: sub check_docs_block {
7363: my ($docsblock,$tocheck) =@_;
7364: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7365: return;
7366: }
7367: if (ref($docsblock->{'maps'}) eq 'HASH') {
7368: if ($tocheck->{'maps'}) {
7369: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7370: return 1;
7371: }
7372: }
7373: }
7374: if (ref($docsblock->{'resources'}) eq 'HASH') {
7375: if ($tocheck->{'resources'}) {
7376: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7377: return 1;
7378: }
7379: }
7380: }
7381: return;
7382: }
7383:
1.1133 foxr 7384: #
7385: # Removes the versino from a URI and
7386: # splits it in to its filename and path to the filename.
7387: # Seems like File::Basename could have done this more clearly.
7388: # Parameters:
7389: # $uri - input URI
7390: # Returns:
7391: # Two element list consisting of
7392: # $pathname - the URI up to and excluding the trailing /
7393: # $filename - The part of the URI following the last /
7394: # NOTE:
7395: # Another realization of this is simply:
7396: # use File::Basename;
7397: # ...
7398: # $uri = shift;
7399: # $filename = basename($uri);
7400: # $path = dirname($uri);
7401: # return ($filename, $path);
7402: #
7403: # The implementation below is probably faster however.
7404: #
1.710 albertel 7405: sub split_uri_for_cond {
7406: my $uri=&deversion(&declutter(shift));
7407: my @uriparts=split(/\//,$uri);
7408: my $filename=pop(@uriparts);
7409: my $pathname=join('/',@uriparts);
7410: return ($pathname,$filename);
7411: }
1.232 www 7412: # --------------------------------------------------- Is a resource on the map?
7413:
7414: sub is_on_map {
1.710 albertel 7415: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7416: #Trying to find the conditional for the file
1.620 albertel 7417: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7418: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7419: if ($match) {
1.289 bowersj2 7420: return (1,$1);
7421: } else {
1.434 www 7422: return (0,0);
1.289 bowersj2 7423: }
1.12 www 7424: }
7425:
1.427 www 7426: # --------------------------------------------------------- Get symb from alias
7427:
7428: sub get_symb_from_alias {
7429: my $symb=shift;
7430: my ($map,$resid,$url)=&decode_symb($symb);
7431: # Already is a symb
7432: if ($url) { return $symb; }
7433: # Must be an alias
7434: my $aliassymb='';
7435: my %bighash;
1.620 albertel 7436: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7437: &GDBM_READER(),0640)) {
7438: my $rid=$bighash{'mapalias_'.$symb};
7439: if ($rid) {
7440: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7441: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7442: $resid,$bighash{'src_'.$rid});
1.427 www 7443: }
7444: untie %bighash;
7445: }
7446: return $aliassymb;
7447: }
7448:
1.12 www 7449: # ----------------------------------------------------------------- Define Role
7450:
7451: sub definerole {
7452: if (allowed('mcr','/')) {
7453: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7454: foreach my $role (split(':',$sysrole)) {
7455: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7456: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7457: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7458: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7459: return "refused:s:$crole&$cqual";
7460: }
7461: }
1.191 harris41 7462: }
1.800 albertel 7463: foreach my $role (split(':',$domrole)) {
7464: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7465: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7466: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7467: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7468: return "refused:d:$crole&$cqual";
7469: }
7470: }
1.191 harris41 7471: }
1.800 albertel 7472: foreach my $role (split(':',$courole)) {
7473: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7474: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7475: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7476: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7477: return "refused:c:$crole&$cqual";
7478: }
7479: }
1.191 harris41 7480: }
1.620 albertel 7481: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7482: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7483: "rolesdef_$rolename=".
7484: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7485: return reply($command,$env{'user.home'});
1.12 www 7486: } else {
7487: return 'refused';
7488: }
1.105 harris41 7489: }
7490:
7491: # ---------------- Make a metadata query against the network of library servers
7492:
7493: sub metadata_query {
1.1172.2.33 raeburn 7494: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7495: my %rhash;
1.845 albertel 7496: my %libserv = &all_library();
1.244 matthew 7497: my @server_list = (defined($server_array) ? @$server_array
7498: : keys(%libserv) );
7499: for my $server (@server_list) {
1.1172.2.33 raeburn 7500: my $domains = '';
7501: if (ref($domains_hash) eq 'HASH') {
7502: $domains = $domains_hash->{$server};
7503: }
1.118 harris41 7504: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7505: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7506: $rhash{$server}=$reply;
7507: }
7508: else {
7509: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7510: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7511: $server);
7512: $rhash{$server}=$reply;
7513: }
1.112 harris41 7514: }
1.118 harris41 7515: return \%rhash;
1.240 www 7516: }
7517:
7518: # ----------------------------------------- Send log queries and wait for reply
7519:
7520: sub log_query {
7521: my ($uname,$udom,$query,%filters)=@_;
7522: my $uhome=&homeserver($uname,$udom);
7523: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7524: my $uhost=&hostname($uhome);
1.800 albertel 7525: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7526: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7527: $uhome);
1.479 albertel 7528: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7529: return get_query_reply($queryid);
7530: }
7531:
1.818 raeburn 7532: # -------------------------- Update MySQL table for portfolio file
7533:
7534: sub update_portfolio_table {
1.821 raeburn 7535: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7536: if ($group ne '') {
7537: $file_name =~s /^\Q$group\E//;
7538: }
1.818 raeburn 7539: my $homeserver = &homeserver($uname,$udom);
7540: my $queryid=
1.821 raeburn 7541: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7542: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7543: my $reply = &get_query_reply($queryid);
7544: return $reply;
7545: }
7546:
1.899 raeburn 7547: # -------------------------- Update MySQL allusers table
7548:
7549: sub update_allusers_table {
7550: my ($uname,$udom,$names) = @_;
7551: my $homeserver = &homeserver($uname,$udom);
7552: my $queryid=
7553: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7554: 'lastname='.&escape($names->{'lastname'}).'%%'.
7555: 'firstname='.&escape($names->{'firstname'}).'%%'.
7556: 'middlename='.&escape($names->{'middlename'}).'%%'.
7557: 'generation='.&escape($names->{'generation'}).'%%'.
7558: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7559: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7560: return;
1.899 raeburn 7561: }
7562:
1.508 raeburn 7563: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7564:
7565: sub fetch_enrollment_query {
1.511 raeburn 7566: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7567: my $homeserver;
1.547 raeburn 7568: my $maxtries = 1;
1.508 raeburn 7569: if ($context eq 'automated') {
7570: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7571: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7572: } else {
7573: $homeserver = &homeserver($cnum,$dom);
7574: }
1.838 albertel 7575: my $host=&hostname($homeserver);
1.506 raeburn 7576: my $cmd = '';
1.1000 raeburn 7577: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7578: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7579: }
7580: $cmd =~ s/%%$//;
7581: $cmd = &escape($cmd);
7582: my $query = 'fetchenrollment';
1.620 albertel 7583: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7584: unless ($queryid=~/^\Q$host\E\_/) {
7585: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7586: return 'error: '.$queryid;
7587: }
1.506 raeburn 7588: my $reply = &get_query_reply($queryid);
1.547 raeburn 7589: my $tries = 1;
7590: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7591: $reply = &get_query_reply($queryid);
7592: $tries ++;
7593: }
1.526 raeburn 7594: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7595: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7596: } else {
1.901 albertel 7597: my @responses = split(/:/,$reply);
1.515 raeburn 7598: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7599: foreach my $line (@responses) {
7600: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7601: $$replyref{$key} = $value;
7602: }
7603: } else {
1.1117 foxr 7604: my $pathname = LONCAPA::tempdir();
1.800 albertel 7605: foreach my $line (@responses) {
7606: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7607: $$replyref{$key} = $value;
7608: if ($value > 0) {
1.800 albertel 7609: foreach my $item (@{$$affiliatesref{$key}}) {
7610: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7611: my $destname = $pathname.'/'.$filename;
7612: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7613: if ($xml_classlist =~ /^error/) {
7614: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7615: } else {
1.506 raeburn 7616: if ( open(FILE,">$destname") ) {
7617: print FILE &unescape($xml_classlist);
7618: close(FILE);
1.526 raeburn 7619: } else {
7620: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7621: }
7622: }
7623: }
7624: }
7625: }
7626: }
7627: return 'ok';
7628: }
7629: return 'error';
7630: }
7631:
1.242 www 7632: sub get_query_reply {
7633: my $queryid=shift;
1.1117 foxr 7634: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7635: my $reply='';
7636: for (1..100) {
7637: sleep 2;
7638: if (-e $replyfile.'.end') {
1.448 albertel 7639: if (open(my $fh,$replyfile)) {
1.904 albertel 7640: $reply = join('',<$fh>);
7641: close($fh);
1.240 www 7642: } else { return 'error: reply_file_error'; }
1.242 www 7643: return &unescape($reply);
7644: }
1.240 www 7645: }
1.242 www 7646: return 'timeout:'.$queryid;
1.240 www 7647: }
7648:
7649: sub courselog_query {
1.241 www 7650: #
7651: # possible filters:
7652: # url: url or symb
7653: # username
7654: # domain
7655: # action: view, submit, grade
7656: # start: timestamp
7657: # end: timestamp
7658: #
1.240 www 7659: my (%filters)=@_;
1.620 albertel 7660: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7661: if ($filters{'url'}) {
7662: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7663: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7664: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7665: }
1.620 albertel 7666: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7667: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7668: return &log_query($cname,$cdom,'courselog',%filters);
7669: }
7670:
7671: sub userlog_query {
1.858 raeburn 7672: #
7673: # possible filters:
7674: # action: log check role
7675: # start: timestamp
7676: # end: timestamp
7677: #
1.240 www 7678: my ($uname,$udom,%filters)=@_;
7679: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7680: }
7681:
1.506 raeburn 7682: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7683:
7684: sub auto_run {
1.508 raeburn 7685: my ($cnum,$cdom) = @_;
1.876 raeburn 7686: my $response = 0;
7687: my $settings;
7688: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7689: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7690: $settings = $domconfig{'autoenroll'};
7691: if ($settings->{'run'} eq '1') {
7692: $response = 1;
7693: }
7694: } else {
1.934 raeburn 7695: my $homeserver;
7696: if (&is_course($cdom,$cnum)) {
7697: $homeserver = &homeserver($cnum,$cdom);
7698: } else {
7699: $homeserver = &domain($cdom,'primary');
7700: }
7701: if ($homeserver ne 'no_host') {
7702: $response = &reply('autorun:'.$cdom,$homeserver);
7703: }
1.876 raeburn 7704: }
1.506 raeburn 7705: return $response;
7706: }
1.776 albertel 7707:
1.506 raeburn 7708: sub auto_get_sections {
1.508 raeburn 7709: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7710: my $homeserver;
7711: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7712: $homeserver = &homeserver($cnum,$cdom);
7713: }
7714: if (!defined($homeserver)) {
7715: if ($cdom =~ /^$match_domain$/) {
7716: $homeserver = &domain($cdom,'primary');
7717: }
7718: }
7719: my @secs;
7720: if (defined($homeserver)) {
7721: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7722: unless ($response eq 'refused') {
7723: @secs = split(/:/,$response);
7724: }
1.506 raeburn 7725: }
7726: return @secs;
7727: }
1.776 albertel 7728:
1.506 raeburn 7729: sub auto_new_course {
1.1099 raeburn 7730: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7731: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7732: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7733: return $response;
7734: }
1.776 albertel 7735:
1.506 raeburn 7736: sub auto_validate_courseID {
1.508 raeburn 7737: my ($cnum,$cdom,$inst_course_id) = @_;
7738: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7739: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7740: return $response;
7741: }
1.776 albertel 7742:
1.1007 raeburn 7743: sub auto_validate_instcode {
1.1020 raeburn 7744: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7745: my ($homeserver,$response);
7746: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7747: $homeserver = &homeserver($cnum,$cdom);
7748: }
7749: if (!defined($homeserver)) {
7750: if ($cdom =~ /^$match_domain$/) {
7751: $homeserver = &domain($cdom,'primary');
7752: }
7753: }
1.1065 raeburn 7754: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7755: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7756: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7757: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7758: }
7759:
1.506 raeburn 7760: sub auto_create_password {
1.873 raeburn 7761: my ($cnum,$cdom,$authparam,$udom) = @_;
7762: my ($homeserver,$response);
1.506 raeburn 7763: my $create_passwd = 0;
7764: my $authchk = '';
1.873 raeburn 7765: if ($udom =~ /^$match_domain$/) {
7766: $homeserver = &domain($udom,'primary');
7767: }
7768: if ($homeserver eq '') {
7769: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7770: $homeserver = &homeserver($cnum,$cdom);
7771: }
7772: }
7773: if ($homeserver eq '') {
7774: $authchk = 'nodomain';
1.506 raeburn 7775: } else {
1.873 raeburn 7776: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7777: if ($response eq 'refused') {
7778: $authchk = 'refused';
7779: } else {
1.901 albertel 7780: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7781: }
1.506 raeburn 7782: }
7783: return ($authparam,$create_passwd,$authchk);
7784: }
7785:
1.706 raeburn 7786: sub auto_photo_permission {
7787: my ($cnum,$cdom,$students) = @_;
7788: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7789: my ($outcome,$perm_reqd,$conditions) =
7790: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7791: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7792: return (undef,undef);
7793: }
1.706 raeburn 7794: return ($outcome,$perm_reqd,$conditions);
7795: }
7796:
7797: sub auto_checkphotos {
7798: my ($uname,$udom,$pid) = @_;
7799: my $homeserver = &homeserver($uname,$udom);
7800: my ($result,$resulttype);
7801: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7802: &escape($uname).':'.&escape($pid),
7803: $homeserver));
1.709 albertel 7804: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7805: return (undef,undef);
7806: }
1.706 raeburn 7807: if ($outcome) {
7808: ($result,$resulttype) = split(/:/,$outcome);
7809: }
7810: return ($result,$resulttype);
7811: }
7812:
7813: sub auto_photochoice {
7814: my ($cnum,$cdom) = @_;
7815: my $homeserver = &homeserver($cnum,$cdom);
7816: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7817: &escape($cdom),
7818: $homeserver)));
1.709 albertel 7819: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7820: return (undef,undef);
7821: }
1.706 raeburn 7822: return ($update,$comment);
7823: }
7824:
7825: sub auto_photoupdate {
7826: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7827: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7828: my $host=&hostname($homeserver);
1.706 raeburn 7829: my $cmd = '';
7830: my $maxtries = 1;
1.800 albertel 7831: foreach my $affiliate (keys(%{$affiliatesref})) {
7832: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7833: }
7834: $cmd =~ s/%%$//;
7835: $cmd = &escape($cmd);
7836: my $query = 'institutionalphotos';
7837: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7838: unless ($queryid=~/^\Q$host\E\_/) {
7839: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7840: return 'error: '.$queryid;
7841: }
7842: my $reply = &get_query_reply($queryid);
7843: my $tries = 1;
7844: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7845: $reply = &get_query_reply($queryid);
7846: $tries ++;
7847: }
7848: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7849: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7850: } else {
7851: my @responses = split(/:/,$reply);
7852: my $outcome = shift(@responses);
7853: foreach my $item (@responses) {
7854: my ($key,$value) = split(/=/,$item);
7855: $$photo{$key} = $value;
7856: }
7857: return $outcome;
7858: }
7859: return 'error';
7860: }
7861:
1.521 raeburn 7862: sub auto_instcode_format {
1.793 albertel 7863: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7864: $cat_order) = @_;
1.521 raeburn 7865: my $courses = '';
1.772 raeburn 7866: my @homeservers;
1.521 raeburn 7867: if ($caller eq 'global') {
1.841 albertel 7868: my %servers = &get_servers($codedom,'library');
7869: foreach my $tryserver (keys(%servers)) {
7870: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7871: push(@homeservers,$tryserver);
7872: }
1.584 raeburn 7873: }
1.1022 raeburn 7874: } elsif ($caller eq 'requests') {
7875: if ($codedom =~ /^$match_domain$/) {
7876: my $chome = &domain($codedom,'primary');
7877: unless ($chome eq 'no_host') {
7878: push(@homeservers,$chome);
7879: }
7880: }
1.521 raeburn 7881: } else {
1.772 raeburn 7882: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7883: }
1.793 albertel 7884: foreach my $code (keys(%{$instcodes})) {
7885: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7886: }
7887: chop($courses);
1.772 raeburn 7888: my $ok_response = 0;
7889: my $response;
7890: while (@homeservers > 0 && $ok_response == 0) {
7891: my $server = shift(@homeservers);
7892: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7893: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7894: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7895: split(/:/,$response);
1.772 raeburn 7896: %{$codes} = (%{$codes},&str2hash($codes_str));
7897: push(@{$codetitles},&str2array($codetitles_str));
7898: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7899: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7900: $ok_response = 1;
7901: }
7902: }
7903: if ($ok_response) {
1.521 raeburn 7904: return 'ok';
1.772 raeburn 7905: } else {
7906: return $response;
1.521 raeburn 7907: }
7908: }
7909:
1.792 raeburn 7910: sub auto_instcode_defaults {
7911: my ($domain,$returnhash,$code_order) = @_;
7912: my @homeservers;
1.841 albertel 7913:
7914: my %servers = &get_servers($domain,'library');
7915: foreach my $tryserver (keys(%servers)) {
7916: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7917: push(@homeservers,$tryserver);
7918: }
1.792 raeburn 7919: }
1.841 albertel 7920:
1.792 raeburn 7921: my $response;
1.841 albertel 7922: foreach my $server (@homeservers) {
1.792 raeburn 7923: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7924: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7925:
7926: foreach my $pair (split(/\&/,$response)) {
7927: my ($name,$value)=split(/\=/,$pair);
7928: if ($name eq 'code_order') {
7929: @{$code_order} = split(/\&/,&unescape($value));
7930: } else {
7931: $returnhash->{&unescape($name)}=&unescape($value);
7932: }
7933: }
7934: return 'ok';
1.792 raeburn 7935: }
1.841 albertel 7936:
7937: return $response;
1.1003 raeburn 7938: }
7939:
7940: sub auto_possible_instcodes {
1.1007 raeburn 7941: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7942: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7943: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7944: return;
7945: }
1.1003 raeburn 7946: my (@homeservers,$uhome);
7947: if (defined(&domain($domain,'primary'))) {
7948: $uhome=&domain($domain,'primary');
7949: push(@homeservers,&domain($domain,'primary'));
7950: } else {
7951: my %servers = &get_servers($domain,'library');
7952: foreach my $tryserver (keys(%servers)) {
7953: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7954: push(@homeservers,$tryserver);
7955: }
7956: }
7957: }
7958: my $response;
7959: foreach my $server (@homeservers) {
7960: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7961: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7962: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7963: split(':',$response);
7964: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7965: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7966: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7967: my ($name,$value)=split('=',$item);
7968: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7969: }
7970: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7971: my ($name,$value)=split('=',$item);
7972: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7973: }
7974: return 'ok';
7975: }
7976: return $response;
7977: }
1.792 raeburn 7978:
1.1010 raeburn 7979: sub auto_courserequest_checks {
7980: my ($dom) = @_;
1.1020 raeburn 7981: my ($homeserver,%validations);
7982: if ($dom =~ /^$match_domain$/) {
7983: $homeserver = &domain($dom,'primary');
7984: }
7985: unless ($homeserver eq 'no_host') {
7986: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7987: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7988: my @items = split(/&/,$response);
7989: foreach my $item (@items) {
7990: my ($key,$value) = split('=',$item);
7991: $validations{&unescape($key)} = &thaw_unescape($value);
7992: }
7993: }
7994: }
1.1010 raeburn 7995: return %validations;
7996: }
7997:
1.1020 raeburn 7998: sub auto_courserequest_validation {
1.1172.2.43 raeburn 7999: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8000: my ($homeserver,$response);
8001: if ($dom =~ /^$match_domain$/) {
8002: $homeserver = &domain($dom,'primary');
8003: }
1.1172.2.43 raeburn 8004: unless ($homeserver eq 'no_host') {
8005: my $customdata;
8006: if (ref($custominfo) eq 'HASH') {
8007: $customdata = &freeze_escape($custominfo);
8008: }
1.1020 raeburn 8009: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8010: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8011: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8012: $customdata,$homeserver));
1.1020 raeburn 8013: }
8014: return $response;
8015: }
8016:
1.777 albertel 8017: sub auto_validate_class_sec {
1.918 raeburn 8018: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8019: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8020: my $ownerlist;
8021: if (ref($owners) eq 'ARRAY') {
8022: $ownerlist = join(',',@{$owners});
8023: } else {
8024: $ownerlist = $owners;
8025: }
1.773 raeburn 8026: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8027: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8028: return $response;
8029: }
8030:
1.1172.2.38 raeburn 8031: sub auto_crsreq_update {
8032: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8033: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8034: my ($homeserver,%crsreqresponse);
8035: if ($cdom =~ /^$match_domain$/) {
8036: $homeserver = &domain($cdom,'primary');
8037: }
8038: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8039: my $info;
8040: if (ref($inbound) eq 'HASH') {
8041: $info = &freeze_escape($inbound);
8042: }
8043: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8044: ':'.&escape($action).':'.&escape($ownername).':'.
8045: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8046: &escape($title).':'.&escape($code).':'.
8047: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8048: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8049: my @items = split(/&/,$response);
8050: foreach my $item (@items) {
8051: my ($key,$value) = split('=',$item);
8052: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8053: }
8054: }
8055: }
8056: return \%crsreqresponse;
8057: }
8058:
1.679 raeburn 8059: # ------------------------------------------------------- Course Group routines
8060:
8061: sub get_coursegroups {
1.809 raeburn 8062: my ($cdom,$cnum,$group,$namespace) = @_;
8063: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8064: }
8065:
1.679 raeburn 8066: sub modify_coursegroup {
8067: my ($cdom,$cnum,$groupsettings) = @_;
8068: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8069: }
8070:
1.809 raeburn 8071: sub toggle_coursegroup_status {
8072: my ($cdom,$cnum,$group,$action) = @_;
8073: my ($from_namespace,$to_namespace);
8074: if ($action eq 'delete') {
8075: $from_namespace = 'coursegroups';
8076: $to_namespace = 'deleted_groups';
8077: } else {
8078: $from_namespace = 'deleted_groups';
8079: $to_namespace = 'coursegroups';
8080: }
8081: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8082: if (my $tmp = &error(%curr_group)) {
8083: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8084: return ('read error',$tmp);
8085: } else {
8086: my %savedsettings = %curr_group;
1.809 raeburn 8087: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8088: my $deloutcome;
8089: if ($result eq 'ok') {
1.809 raeburn 8090: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8091: } else {
8092: return ('write error',$result);
8093: }
8094: if ($deloutcome eq 'ok') {
8095: return 'ok';
8096: } else {
8097: return ('delete error',$deloutcome);
8098: }
8099: }
8100: }
8101:
1.679 raeburn 8102: sub modify_group_roles {
1.957 raeburn 8103: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8104: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8105: my $role = 'gr/'.&escape($userprivs);
8106: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8107: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8108: if ($result eq 'ok') {
8109: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8110: }
1.679 raeburn 8111: return $result;
8112: }
8113:
8114: sub modify_coursegroup_membership {
8115: my ($cdom,$cnum,$membership) = @_;
8116: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8117: return $result;
8118: }
8119:
1.682 raeburn 8120: sub get_active_groups {
8121: my ($udom,$uname,$cdom,$cnum) = @_;
8122: my $now = time;
8123: my %groups = ();
8124: foreach my $key (keys(%env)) {
1.811 albertel 8125: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8126: my ($start,$end) = split(/\./,$env{$key});
8127: if (($end!=0) && ($end<$now)) { next; }
8128: if (($start!=0) && ($start>$now)) { next; }
8129: if ($1 eq $cdom && $2 eq $cnum) {
8130: $groups{$3} = $env{$key} ;
8131: }
8132: }
8133: }
8134: return %groups;
8135: }
8136:
1.683 raeburn 8137: sub get_group_membership {
8138: my ($cdom,$cnum,$group) = @_;
8139: return(&dump('groupmembership',$cdom,$cnum,$group));
8140: }
8141:
8142: sub get_users_groups {
8143: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8144: my @usersgroups;
1.683 raeburn 8145: my $cachetime=1800;
8146:
8147: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8148: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8149: if (defined($cached)) {
1.734 albertel 8150: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8151: } else {
8152: $grouplist = '';
1.816 raeburn 8153: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8154: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8155: my $access_end = $env{'course.'.$courseid.
8156: '.default_enrollment_end_date'};
8157: my $now = time;
8158: foreach my $key (keys(%roleshash)) {
8159: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8160: my $group = $1;
8161: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8162: my $start = $2;
8163: my $end = $1;
8164: if ($start == -1) { next; } # deleted from group
8165: if (($start!=0) && ($start>$now)) { next; }
8166: if (($end!=0) && ($end<$now)) {
8167: if ($access_end && $access_end < $now) {
8168: if ($access_end - $end < 86400) {
8169: push(@usersgroups,$group);
1.733 raeburn 8170: }
8171: }
1.817 raeburn 8172: next;
1.733 raeburn 8173: }
1.817 raeburn 8174: push(@usersgroups,$group);
1.683 raeburn 8175: }
8176: }
8177: }
1.817 raeburn 8178: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8179: $grouplist = join(':',@usersgroups);
8180: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8181: }
1.733 raeburn 8182: return @usersgroups;
1.683 raeburn 8183: }
8184:
8185: sub devalidate_getgroups_cache {
8186: my ($udom,$uname,$cdom,$cnum)=@_;
8187: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8188:
1.683 raeburn 8189: my $hashid="$udom:$uname:$courseid";
8190: &devalidate_cache_new('getgroups',$hashid);
8191: }
8192:
1.12 www 8193: # ------------------------------------------------------------------ Plain Text
8194:
8195: sub plaintext {
1.988 raeburn 8196: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8197: if ($short =~ m{^cr/}) {
1.758 albertel 8198: return (split('/',$short))[-1];
8199: }
1.742 raeburn 8200: if (!defined($cid)) {
8201: $cid = $env{'request.course.id'};
8202: }
8203: my %rolenames = (
1.1008 raeburn 8204: Course => 'std',
8205: Community => 'alt1',
1.742 raeburn 8206: );
1.1037 raeburn 8207: if ($cid ne '') {
8208: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8209: unless ($forcedefault) {
8210: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8211: &Apache::lonlocal::mt_escape(\$roletext);
8212: return &Apache::lonlocal::mt($roletext);
8213: }
8214: }
8215: }
8216: if ((defined($type)) && (defined($rolenames{$type})) &&
8217: (defined($rolenames{$type})) &&
8218: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8219: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8220: } elsif ($cid ne '') {
8221: my $crstype = $env{'course.'.$cid.'.type'};
8222: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8223: (defined($prp{$short}{$rolenames{$crstype}}))) {
8224: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8225: }
1.742 raeburn 8226: }
1.1037 raeburn 8227: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8228: }
8229:
8230: # ----------------------------------------------------------------- Assign Role
8231:
8232: sub assignrole {
1.957 raeburn 8233: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8234: $context)=@_;
1.21 www 8235: my $mrole;
8236: if ($role =~ /^cr\//) {
1.393 www 8237: my $cwosec=$url;
1.811 albertel 8238: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8239: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8240: my $refused = 1;
8241: if ($context eq 'requestcourses') {
8242: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8243: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8244: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8245: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8246: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8247: if ($crsenv{'internal.courseowner'} eq
8248: $env{'user.name'}.':'.$env{'user.domain'}) {
8249: $refused = '';
8250: }
8251: }
8252: }
8253: }
8254: }
8255: if ($refused) {
8256: &logthis('Refused custom assignrole: '.
8257: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8258: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8259: return 'refused';
8260: }
1.104 www 8261: }
1.21 www 8262: $mrole='cr';
1.678 raeburn 8263: } elsif ($role =~ /^gr\//) {
8264: my $cwogrp=$url;
1.811 albertel 8265: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8266: unless (&allowed('mdg',$cwogrp)) {
8267: &logthis('Refused group assignrole: '.
8268: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8269: $env{'user.name'}.' at '.$env{'user.domain'});
8270: return 'refused';
8271: }
8272: $mrole='gr';
1.21 www 8273: } else {
1.82 www 8274: my $cwosec=$url;
1.811 albertel 8275: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8276: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8277: my $refused;
8278: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8279: if (!(&allowed('c'.$role,$url))) {
8280: $refused = 1;
8281: }
8282: } else {
8283: $refused = 1;
8284: }
1.947 raeburn 8285: if ($refused) {
1.1045 raeburn 8286: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8287: if (!$selfenroll && $context eq 'course') {
8288: my %crsenv;
8289: if ($role eq 'cc' || $role eq 'co') {
8290: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8291: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8292: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8293: if ($crsenv{'internal.courseowner'} eq
8294: $env{'user.name'}.':'.$env{'user.domain'}) {
8295: $refused = '';
8296: }
8297: }
8298: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8299: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8300: if ($crsenv{'internal.courseowner'} eq
8301: $env{'user.name'}.':'.$env{'user.domain'}) {
8302: $refused = '';
8303: }
8304: }
8305: }
8306: }
8307: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8308: $refused = '';
1.1017 raeburn 8309: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8310: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8311: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8312: my $wrongcc;
8313: if ($cnum =~ /^$match_community$/) {
8314: $wrongcc = 1 if ($role eq 'cc');
8315: } else {
8316: $wrongcc = 1 if ($role eq 'co');
8317: }
8318: unless ($wrongcc) {
8319: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8320: if ($crsenv{'internal.courseowner'} eq
8321: $env{'user.name'}.':'.$env{'user.domain'}) {
8322: $refused = '';
8323: }
1.1017 raeburn 8324: }
8325: }
1.1172.2.9 raeburn 8326: } elsif ($context eq 'requestauthor') {
8327: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8328: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8329: if ($env{'environment.requestauthor'} eq 'automatic') {
8330: $refused = '';
8331: } else {
8332: my %domdefaults = &get_domain_defaults($udom);
8333: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8334: my $checkbystatus;
8335: if ($env{'user.adv'}) {
8336: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8337: if ($disposition eq 'automatic') {
8338: $refused = '';
8339: } elsif ($disposition eq '') {
8340: $checkbystatus = 1;
8341: }
8342: } else {
8343: $checkbystatus = 1;
8344: }
8345: if ($checkbystatus) {
8346: if ($env{'environment.inststatus'}) {
8347: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8348: foreach my $type (@inststatuses) {
8349: if (($type ne '') &&
8350: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8351: $refused = '';
8352: }
8353: }
8354: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8355: $refused = '';
8356: }
8357: }
8358: }
8359: }
8360: }
1.1017 raeburn 8361: }
8362: if ($refused) {
1.947 raeburn 8363: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8364: ' '.$role.' '.$end.' '.$start.' by '.
8365: $env{'user.name'}.' at '.$env{'user.domain'});
8366: return 'refused';
8367: }
1.932 raeburn 8368: }
1.1131 raeburn 8369: } elsif ($role eq 'au') {
8370: if ($url ne '/'.$udom.'/') {
8371: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8372: ' to assign author role for '.$uname.':'.$udom.
8373: ' in domain: '.$url.' refused (wrong domain).');
8374: return 'refused';
8375: }
1.104 www 8376: }
1.21 www 8377: $mrole=$role;
8378: }
1.620 albertel 8379: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8380: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8381: if ($end) { $command.='_'.$end; }
1.21 www 8382: if ($start) {
8383: if ($end) {
1.81 www 8384: $command.='_'.$start;
1.21 www 8385: } else {
1.81 www 8386: $command.='_0_'.$start;
1.21 www 8387: }
8388: }
1.739 raeburn 8389: my $origstart = $start;
8390: my $origend = $end;
1.957 raeburn 8391: my $delflag;
1.357 www 8392: # actually delete
8393: if ($deleteflag) {
1.373 www 8394: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8395: # modify command to delete the role
1.620 albertel 8396: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8397: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8398: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8399: # set start and finish to negative values for userrolelog
8400: $start=-1;
8401: $end=-1;
1.957 raeburn 8402: $delflag = 1;
1.357 www 8403: }
8404: }
8405: # send command
1.349 www 8406: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8407: # log new user role if status is ok
1.349 www 8408: if ($answer eq 'ok') {
1.663 raeburn 8409: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8410: if (($role eq 'cc') || ($role eq 'in') ||
8411: ($role eq 'ep') || ($role eq 'ad') ||
8412: ($role eq 'ta') || ($role eq 'st') ||
8413: ($role=~/^cr/) || ($role eq 'gr') ||
8414: ($role eq 'co')) {
1.1172.2.13 raeburn 8415: # for course roles, perform group memberships changes triggered by role change.
8416: unless ($role =~ /^gr/) {
8417: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8418: $origstart,$selfenroll,$context);
8419: }
1.1172.2.9 raeburn 8420: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8421: $selfenroll,$context);
8422: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8423: ($role eq 'au') || ($role eq 'dc')) {
8424: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8425: $context);
8426: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8427: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8428: $context);
8429: }
1.1053 raeburn 8430: if ($role eq 'cc') {
8431: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8432: }
1.349 www 8433: }
8434: return $answer;
1.169 harris41 8435: }
8436:
1.1053 raeburn 8437: sub autoupdate_coowners {
8438: my ($url,$end,$start,$uname,$udom) = @_;
8439: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8440: if (($cdom ne '') && ($cnum ne '')) {
8441: my $now = time;
8442: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8443: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8444: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8445: my $instcode = $coursehash{'internal.coursecode'};
8446: if ($instcode ne '') {
1.1056 raeburn 8447: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8448: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8449: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8450: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8451: if ($result eq 'valid') {
8452: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8453: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8454: push(@newcoowners,$coowner);
8455: }
8456: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8457: push(@newcoowners,$uname.':'.$udom);
8458: }
8459: @newcoowners = sort(@newcoowners);
8460: } else {
8461: push(@newcoowners,$uname.':'.$udom);
8462: }
8463: } else {
8464: if ($coursehash{'internal.co-owners'}) {
8465: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8466: unless ($coowner eq $uname.':'.$udom) {
8467: push(@newcoowners,$coowner);
8468: }
8469: }
8470: unless (@newcoowners > 0) {
8471: $delcoowners = 1;
8472: $coowners = '';
8473: }
8474: }
8475: }
8476: if (@newcoowners || $delcoowners) {
8477: &store_coowners($cdom,$cnum,$coursehash{'home'},
8478: $delcoowners,@newcoowners);
8479: }
8480: }
8481: }
8482: }
8483: }
8484: }
8485: }
8486:
8487: sub store_coowners {
8488: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8489: my $cid = $cdom.'_'.$cnum;
8490: my ($coowners,$delresult,$putresult);
8491: if (@newcoowners) {
8492: $coowners = join(',',@newcoowners);
8493: my %coownershash = (
8494: 'internal.co-owners' => $coowners,
8495: );
8496: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8497: if ($putresult eq 'ok') {
8498: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8499: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8500: }
8501: }
8502: }
8503: if ($delcoowners) {
8504: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8505: if ($delresult eq 'ok') {
8506: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8507: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8508: }
8509: }
8510: }
8511: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8512: my %crsinfo =
8513: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8514: if (ref($crsinfo{$cid}) eq 'HASH') {
8515: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8516: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8517: }
8518: }
8519: }
8520:
1.169 harris41 8521: # -------------------------------------------------- Modify user authentication
1.197 www 8522: # Overrides without validation
8523:
1.169 harris41 8524: sub modifyuserauth {
8525: my ($udom,$uname,$umode,$upass)=@_;
8526: my $uhome=&homeserver($uname,$udom);
1.197 www 8527: unless (&allowed('mau',$udom)) { return 'refused'; }
8528: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8529: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8530: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8531: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8532: &escape($upass),$uhome);
1.620 albertel 8533: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8534: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8535: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8536: &log($udom,,$uname,$uhome,
1.620 albertel 8537: 'Authentication changed by '.$env{'user.domain'}.', '.
8538: $env{'user.name'}.', '.$umode.
1.197 www 8539: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8540: unless ($reply eq 'ok') {
1.197 www 8541: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8542: return 'error: '.$reply;
8543: }
1.170 harris41 8544: return 'ok';
1.80 www 8545: }
8546:
1.81 www 8547: # --------------------------------------------------------------- Modify a user
1.80 www 8548:
1.81 www 8549: sub modifyuser {
1.206 matthew 8550: my ($udom, $uname, $uid,
8551: $umode, $upass, $first,
8552: $middle, $last, $gene,
1.1058 raeburn 8553: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8554: $udom= &LONCAPA::clean_domain($udom);
8555: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8556: my $showcandelete = 'none';
8557: if (ref($candelete) eq 'ARRAY') {
8558: if (@{$candelete} > 0) {
8559: $showcandelete = join(', ',@{$candelete});
8560: }
8561: }
1.81 www 8562: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8563: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8564: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8565: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8566: ' desiredhome not specified').
1.620 albertel 8567: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8568: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8569: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8570: my $newuser;
8571: if ($uhome eq 'no_host') {
8572: $newuser = 1;
8573: }
1.80 www 8574: # ----------------------------------------------------------------- Create User
1.406 albertel 8575: if (($uhome eq 'no_host') &&
8576: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8577: my $unhome='';
1.844 albertel 8578: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8579: $unhome = $desiredhome;
1.620 albertel 8580: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8581: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8582: } else { # load balancing routine for determining $unhome
1.81 www 8583: my $loadm=10000000;
1.841 albertel 8584: my %servers = &get_servers($udom,'library');
8585: foreach my $tryserver (keys(%servers)) {
8586: my $answer=reply('load',$tryserver);
8587: if (($answer=~/\d+/) && ($answer<$loadm)) {
8588: $loadm=$answer;
8589: $unhome=$tryserver;
8590: }
1.80 www 8591: }
8592: }
8593: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8594: return 'error: unable to find a home server for '.$uname.
8595: ' in domain '.$udom;
1.80 www 8596: }
8597: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8598: &escape($upass),$unhome);
8599: unless ($reply eq 'ok') {
8600: return 'error: '.$reply;
8601: }
1.230 stredwic 8602: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8603: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8604: return 'error: unable verify users home machine.';
1.80 www 8605: }
1.209 matthew 8606: } # End of creation of new user
1.80 www 8607: # ---------------------------------------------------------------------- Add ID
8608: if ($uid) {
8609: $uid=~tr/A-Z/a-z/;
8610: my %uidhash=&idrget($udom,$uname);
1.196 www 8611: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8612: && (!$forceid)) {
1.80 www 8613: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8614: return 'error: user id "'.$uid.'" does not match '.
8615: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8616: }
8617: } else {
8618: &idput($udom,($uname => $uid));
8619: }
8620: }
8621: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8622: my @tmp=&get('environment',
1.899 raeburn 8623: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8624: 'permanentemail','inststatus'],
1.134 albertel 8625: $udom,$uname);
1.1075 raeburn 8626: my (%names,%oldnames);
1.313 matthew 8627: if ($tmp[0] =~ m/^error:.*/) {
8628: %names=();
8629: } else {
8630: %names = @tmp;
1.1075 raeburn 8631: %oldnames = %names;
1.313 matthew 8632: }
1.388 www 8633: #
1.1058 raeburn 8634: # If name, email and/or uid are blank (e.g., because an uploaded file
8635: # of users did not contain them), do not overwrite existing values
8636: # unless field is in $candelete array ref.
8637: #
8638:
8639: my @fields = ('firstname','middlename','lastname','generation',
8640: 'permanentemail','id');
8641: my %newvalues;
8642: if (ref($candelete) eq 'ARRAY') {
8643: foreach my $field (@fields) {
8644: if (grep(/^\Q$field\E$/,@{$candelete})) {
8645: if ($field eq 'firstname') {
8646: $names{$field} = $first;
8647: } elsif ($field eq 'middlename') {
8648: $names{$field} = $middle;
8649: } elsif ($field eq 'lastname') {
8650: $names{$field} = $last;
8651: } elsif ($field eq 'generation') {
8652: $names{$field} = $gene;
8653: } elsif ($field eq 'permanentemail') {
8654: $names{$field} = $email;
8655: } elsif ($field eq 'id') {
8656: $names{$field} = $uid;
8657: }
8658: }
8659: }
8660: }
1.388 www 8661: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8662: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8663: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8664: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8665: if ($email) {
8666: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8667: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8668: }
1.899 raeburn 8669: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8670: if (defined($inststatus)) {
8671: $names{'inststatus'} = '';
8672: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8673: if (ref($usertypes) eq 'HASH') {
8674: my @okstatuses;
8675: foreach my $item (split(/:/,$inststatus)) {
8676: if (defined($usertypes->{$item})) {
8677: push(@okstatuses,$item);
8678: }
8679: }
8680: if (@okstatuses) {
8681: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8682: }
8683: }
8684: }
1.1075 raeburn 8685: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8686: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8687: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8688: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8689: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8690: } else {
8691: $logmsg .= ' during self creation';
8692: }
1.1075 raeburn 8693: my $changed;
8694: if ($newuser) {
8695: $changed = 1;
8696: } else {
8697: foreach my $field (@fields) {
8698: if ($names{$field} ne $oldnames{$field}) {
8699: $changed = 1;
8700: last;
8701: }
8702: }
8703: }
8704: unless ($changed) {
8705: $logmsg = 'No changes in user information needed for: '.$logmsg;
8706: &logthis($logmsg);
8707: return 'ok';
8708: }
8709: my $reply = &put('environment', \%names, $udom,$uname);
8710: if ($reply ne 'ok') {
8711: return 'error: '.$reply;
8712: }
1.1087 raeburn 8713: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8714: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8715: }
1.1075 raeburn 8716: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8717: &devalidate_cache_new('namescache',$uname.':'.$udom);
8718: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8719: &logthis($logmsg);
1.134 albertel 8720: return 'ok';
1.80 www 8721: }
8722:
1.81 www 8723: # -------------------------------------------------------------- Modify student
1.80 www 8724:
1.81 www 8725: sub modifystudent {
8726: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8727: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19 raeburn 8728: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8729: if (!$cid) {
1.620 albertel 8730: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8731: return 'not_in_class';
8732: }
1.80 www 8733: }
8734: # --------------------------------------------------------------- Make the user
1.81 www 8735: my $reply=&modifyuser
1.209 matthew 8736: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8737: $desiredhome,$email,$inststatus);
1.80 www 8738: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8739: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 8740: # student's environment
1.297 matthew 8741: $uid = undef if (!$forceid);
1.455 albertel 8742: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 8743: $gene,$usec,$end,$start,$type,$locktype,
8744: $cid,$selfenroll,$context,$credits);
1.297 matthew 8745: return $reply;
8746: }
8747:
8748: sub modify_student_enrollment {
1.1172.2.23 raeburn 8749: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8750: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8751: my ($cdom,$cnum,$chome);
8752: if (!$cid) {
1.620 albertel 8753: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8754: return 'not_in_class';
8755: }
1.620 albertel 8756: $cdom=$env{'course.'.$cid.'.domain'};
8757: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8758: } else {
8759: ($cdom,$cnum)=split(/_/,$cid);
8760: }
1.620 albertel 8761: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8762: if (!$chome) {
1.457 raeburn 8763: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8764: }
1.455 albertel 8765: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8766: # Make sure the user exists
1.81 www 8767: my $uhome=&homeserver($uname,$udom);
8768: if (($uhome eq '') || ($uhome eq 'no_host')) {
8769: return 'error: no such user';
8770: }
1.297 matthew 8771: # Get student data if we were not given enough information
8772: if (!defined($first) || $first eq '' ||
8773: !defined($last) || $last eq '' ||
8774: !defined($uid) || $uid eq '' ||
8775: !defined($middle) || $middle eq '' ||
8776: !defined($gene) || $gene eq '') {
1.294 matthew 8777: # They did not supply us with enough data to enroll the student, so
8778: # we need to pick up more information.
1.297 matthew 8779: my %tmp = &get('environment',
1.294 matthew 8780: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8781: ,$udom,$uname);
8782:
1.800 albertel 8783: #foreach my $key (keys(%tmp)) {
8784: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8785: #}
1.294 matthew 8786: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8787: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8788: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8789: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8790: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8791: }
1.556 albertel 8792: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8793: my $user = "$uname:$udom";
8794: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8795: my $reply=cput('classlist',
1.1148 raeburn 8796: {$user =>
1.1172.2.19 raeburn 8797: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8798: $cdom,$cnum);
1.1148 raeburn 8799: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8800: &devalidate_getsection_cache($udom,$uname,$cid);
8801: } else {
1.81 www 8802: return 'error: '.$reply;
8803: }
1.297 matthew 8804: # Add student role to user
1.83 www 8805: my $uurl='/'.$cid;
1.81 www 8806: $uurl=~s/\_/\//g;
8807: if ($usec) {
8808: $uurl.='/'.$usec;
8809: }
1.1148 raeburn 8810: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8811: $selfenroll,$context);
8812: if ($result ne 'ok') {
8813: if ($old_entry{$user} ne '') {
8814: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8815: } else {
8816: $reply = &del('classlist',[$user],$cdom,$cnum);
8817: }
8818: }
8819: return $result;
1.21 www 8820: }
8821:
1.556 albertel 8822: sub format_name {
8823: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8824: my $name;
8825: if ($first ne 'lastname') {
8826: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8827: } else {
8828: if ($lastname=~/\S/) {
8829: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8830: $name=~s/\s+,/,/;
8831: } else {
8832: $name.= $firstname.' '.$middlename.' '.$generation;
8833: }
8834: }
8835: $name=~s/^\s+//;
8836: $name=~s/\s+$//;
8837: $name=~s/\s+/ /g;
8838: return $name;
8839: }
8840:
1.84 www 8841: # ------------------------------------------------- Write to course preferences
8842:
8843: sub writecoursepref {
8844: my ($courseid,%prefs)=@_;
8845: $courseid=~s/^\///;
8846: $courseid=~s/\_/\//g;
8847: my ($cdomain,$cnum)=split(/\//,$courseid);
8848: my $chome=homeserver($cnum,$cdomain);
8849: if (($chome eq '') || ($chome eq 'no_host')) {
8850: return 'error: no such course';
8851: }
8852: my $cstring='';
1.800 albertel 8853: foreach my $pref (keys(%prefs)) {
8854: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8855: }
1.84 www 8856: $cstring=~s/\&$//;
8857: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8858: }
8859:
8860: # ---------------------------------------------------------- Make/modify course
8861:
8862: sub createcourse {
1.741 raeburn 8863: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8864: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8865: $url=&declutter($url);
8866: my $cid='';
1.1028 raeburn 8867: if ($context eq 'requestcourses') {
8868: my $can_create = 0;
8869: my ($ownername,$ownerdom) = split(':',$course_owner);
8870: if ($udom eq $ownerdom) {
8871: if (&usertools_access($ownername,$ownerdom,$category,undef,
8872: $context)) {
8873: $can_create = 1;
8874: }
8875: } else {
8876: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8877: $category);
8878: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8879: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8880: if (@curr > 0) {
8881: my @options = qw(approval validate autolimit);
8882: my $optregex = join('|',@options);
8883: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8884: $can_create = 1;
8885: }
8886: }
8887: }
8888: }
8889: if ($can_create) {
8890: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8891: unless (&allowed('ccc',$udom)) {
8892: return 'refused';
8893: }
1.1017 raeburn 8894: }
8895: } else {
8896: return 'refused';
8897: }
1.1028 raeburn 8898: } elsif (!&allowed('ccc',$udom)) {
8899: return 'refused';
1.84 www 8900: }
1.1011 raeburn 8901: # --------------------------------------------------------------- Get Unique ID
8902: my $uname;
8903: if ($cnum =~ /^$match_courseid$/) {
8904: my $chome=&homeserver($cnum,$udom,'true');
8905: if (($chome eq '') || ($chome eq 'no_host')) {
8906: $uname = $cnum;
8907: } else {
1.1038 raeburn 8908: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8909: }
8910: } else {
1.1038 raeburn 8911: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8912: }
8913: return $uname if ($uname =~ /^error/);
8914: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8915: if (!defined($course_server)) {
8916: if (defined(&domain($udom,'primary'))) {
8917: $course_server = &domain($udom,'primary');
8918: } else {
8919: $course_server = $env{'user.home'};
8920: }
8921: }
8922: my %host_servers =
8923: &Apache::lonnet::get_servers($udom,'library');
8924: unless ($host_servers{$course_server}) {
8925: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8926: }
1.84 www 8927: # ------------------------------------------------------------- Make the course
8928: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8929: $course_server);
1.84 www 8930: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8931: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8932: if (($uhome eq '') || ($uhome eq 'no_host')) {
8933: return 'error: no such course';
8934: }
1.271 www 8935: # ----------------------------------------------------------------- Course made
1.516 raeburn 8936: # log existence
1.1029 raeburn 8937: my $now = time;
1.918 raeburn 8938: my $newcourse = {
8939: $udom.'_'.$uname => {
1.921 raeburn 8940: description => $description,
8941: inst_code => $inst_code,
8942: owner => $course_owner,
8943: type => $crstype,
1.1029 raeburn 8944: creator => $env{'user.name'}.':'.
8945: $env{'user.domain'},
8946: created => $now,
8947: context => $context,
1.918 raeburn 8948: },
8949: };
1.921 raeburn 8950: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8951: # set toplevel url
1.271 www 8952: my $topurl=$url;
8953: unless ($nonstandard) {
8954: # ------------------------------------------ For standard courses, make top url
8955: my $mapurl=&clutter($url);
1.278 www 8956: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8957: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8958: <map>
8959: <resource id="1" type="start"></resource>
8960: <resource id="2" src="$mapurl"></resource>
8961: <resource id="3" type="finish"></resource>
8962: <link index="1" from="1" to="2"></link>
8963: <link index="2" from="2" to="3"></link>
8964: </map>
8965: ENDINITMAP
8966: $topurl=&declutter(
1.638 albertel 8967: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8968: );
8969: }
8970: # ----------------------------------------------------------- Write preferences
1.84 www 8971: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8972: ('description' => $description,
8973: 'url' => $topurl,
8974: 'internal.creator' => $env{'user.name'}.':'.
8975: $env{'user.domain'},
8976: 'internal.created' => $now,
8977: 'internal.creationcontext' => $context)
8978: );
1.84 www 8979: return '/'.$udom.'/'.$uname;
8980: }
8981:
1.1011 raeburn 8982: # ------------------------------------------------------------------- Create ID
8983: sub generate_coursenum {
1.1038 raeburn 8984: my ($udom,$crstype) = @_;
1.1011 raeburn 8985: my $domdesc = &domain($udom);
8986: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8987: my $first;
8988: if ($crstype eq 'Community') {
8989: $first = '0';
8990: } else {
8991: $first = int(1+rand(9));
8992: }
8993: my $uname=$first.
1.1011 raeburn 8994: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8995: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8996: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8997: # ----------------------------------------------- Make sure that does not exist
8998: my $uhome=&homeserver($uname,$udom,'true');
8999: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9000: if ($crstype eq 'Community') {
9001: $first = '0';
9002: } else {
9003: $first = int(1+rand(9));
9004: }
9005: $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: $uhome=&homeserver($uname,$udom,'true');
9010: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9011: return 'error: unable to generate unique course-ID';
9012: }
9013: }
9014: return $uname;
9015: }
9016:
1.813 albertel 9017: sub is_course {
1.1167 droeschl 9018: my ($cdom, $cnum) = scalar(@_) == 1 ?
9019: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9020:
9021: return unless $cdom and $cnum;
9022:
9023: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9024: '.');
9025:
1.1172.2.23 raeburn 9026: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9027: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9028: }
9029:
1.1015 raeburn 9030: sub store_userdata {
9031: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9032: my $result;
1.1016 raeburn 9033: if ($datakey ne '') {
1.1013 raeburn 9034: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9035: if ($udom eq '' || $uname eq '') {
9036: $udom = $env{'user.domain'};
9037: $uname = $env{'user.name'};
9038: }
9039: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9040: if (($uhome eq '') || ($uhome eq 'no_host')) {
9041: $result = 'error: no_host';
9042: } else {
9043: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9044: $storehash->{'host'} = $perlvar{'lonHostID'};
9045:
9046: my $namevalue='';
9047: foreach my $key (keys(%{$storehash})) {
9048: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9049: }
9050: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9051: unless ($namespace eq 'courserequests') {
9052: $datakey = &escape($datakey);
9053: }
1.1105 raeburn 9054: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9055: $namevalue,$uhome);
1.1013 raeburn 9056: }
9057: } else {
9058: $result = 'error: data to store was not a hash reference';
9059: }
9060: } else {
9061: $result= 'error: invalid requestkey';
9062: }
9063: return $result;
9064: }
9065:
1.21 www 9066: # ---------------------------------------------------------- Assign Custom Role
9067:
9068: sub assigncustomrole {
1.957 raeburn 9069: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9070: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9071: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9072: }
9073:
9074: # ----------------------------------------------------------------- Revoke Role
9075:
9076: sub revokerole {
1.957 raeburn 9077: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9078: my $now=time;
1.965 raeburn 9079: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9080: }
9081:
9082: # ---------------------------------------------------------- Revoke Custom Role
9083:
9084: sub revokecustomrole {
1.957 raeburn 9085: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9086: my $now=time;
1.357 www 9087: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9088: $deleteflag,$selfenroll,$context);
1.17 www 9089: }
9090:
1.533 banghart 9091: # ------------------------------------------------------------ Disk usage
1.535 albertel 9092: sub diskusage {
1.955 raeburn 9093: my ($udom,$uname,$directorypath,$getpropath)=@_;
9094: $directorypath =~ s/\/$//;
9095: my $listing=&reply('du2:'.&escape($directorypath).':'
9096: .&escape($getpropath).':'.&escape($uname).':'
9097: .&escape($udom),homeserver($uname,$udom));
9098: if ($listing eq 'unknown_cmd') {
9099: if ($getpropath) {
9100: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9101: }
9102: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9103: }
1.514 albertel 9104: return $listing;
1.512 banghart 9105: }
9106:
1.566 banghart 9107: sub is_locked {
1.1096 raeburn 9108: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9109: my @check;
9110: my $is_locked;
1.1093 raeburn 9111: push (@check,$file_name);
1.613 albertel 9112: my %locked = &get('file_permissions',\@check,
1.620 albertel 9113: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9114: my ($tmp)=keys(%locked);
9115: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9116:
1.566 banghart 9117: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9118: $is_locked = 'false';
9119: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9120: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9121: $is_locked = 'true';
1.1096 raeburn 9122: if (ref($which) eq 'ARRAY') {
9123: push(@{$which},$entry);
9124: } else {
9125: last;
9126: }
1.745 raeburn 9127: }
9128: }
1.566 banghart 9129: } else {
9130: $is_locked = 'false';
9131: }
1.1093 raeburn 9132: return $is_locked;
1.566 banghart 9133: }
9134:
1.759 albertel 9135: sub declutter_portfile {
9136: my ($file) = @_;
1.833 albertel 9137: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9138: return $file;
9139: }
9140:
1.559 banghart 9141: # ------------------------------------------------------------- Mark as Read Only
9142:
9143: sub mark_as_readonly {
9144: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9145: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9146: my ($tmp)=keys(%current_permissions);
9147: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9148: foreach my $file (@{$files}) {
1.759 albertel 9149: $file = &declutter_portfile($file);
1.561 banghart 9150: push(@{$current_permissions{$file}},$what);
1.559 banghart 9151: }
1.613 albertel 9152: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9153: return;
9154: }
9155:
1.572 banghart 9156: # ------------------------------------------------------------Save Selected Files
9157:
9158: sub save_selected_files {
9159: my ($user, $path, @files) = @_;
9160: my $filename = $user."savedfiles";
1.573 banghart 9161: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9162: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9163: foreach my $file (@files) {
1.620 albertel 9164: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9165: }
9166: foreach my $file (@other_files) {
1.574 banghart 9167: print (OUT $file."\n");
1.572 banghart 9168: }
1.574 banghart 9169: close (OUT);
1.572 banghart 9170: return 'ok';
9171: }
9172:
1.574 banghart 9173: sub clear_selected_files {
9174: my ($user) = @_;
9175: my $filename = $user."savedfiles";
1.1117 foxr 9176: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9177: print (OUT undef);
9178: close (OUT);
9179: return ("ok");
9180: }
9181:
1.572 banghart 9182: sub files_in_path {
9183: my ($user, $path) = @_;
9184: my $filename = $user."savedfiles";
9185: my %return_files;
1.1117 foxr 9186: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9187: while (my $line_in = <IN>) {
1.574 banghart 9188: chomp ($line_in);
9189: my @paths_and_file = split (m!/!, $line_in);
9190: my $file_part = pop (@paths_and_file);
9191: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9192: $path_part.='/';
9193: my $path_and_file = $path_part.$file_part;
9194: if ($path_part eq $path) {
9195: $return_files{$file_part}= 'selected';
9196: }
9197: }
1.574 banghart 9198: close (IN);
9199: return (\%return_files);
1.572 banghart 9200: }
9201:
9202: # called in portfolio select mode, to show files selected NOT in current directory
9203: sub files_not_in_path {
9204: my ($user, $path) = @_;
9205: my $filename = $user."savedfiles";
9206: my @return_files;
9207: my $path_part;
1.1117 foxr 9208: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9209: while (my $line = <IN>) {
1.572 banghart 9210: #ok, I know it's clunky, but I want it to work
1.800 albertel 9211: my @paths_and_file = split(m|/|, $line);
9212: my $file_part = pop(@paths_and_file);
9213: chomp($file_part);
9214: my $path_part = join('/', @paths_and_file);
1.572 banghart 9215: $path_part .= '/';
9216: my $path_and_file = $path_part.$file_part;
9217: if ($path_part ne $path) {
1.800 albertel 9218: push(@return_files, ($path_and_file));
1.572 banghart 9219: }
9220: }
1.800 albertel 9221: close(OUT);
1.574 banghart 9222: return (@return_files);
1.572 banghart 9223: }
9224:
1.745 raeburn 9225: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9226:
1.745 raeburn 9227: sub get_portfile_permissions {
9228: my ($domain,$user) = @_;
1.613 albertel 9229: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9230: my ($tmp)=keys(%current_permissions);
9231: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9232: return \%current_permissions;
9233: }
9234:
9235: #---------------------------------------------Get portfolio file access controls
9236:
1.749 raeburn 9237: sub get_access_controls {
1.745 raeburn 9238: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9239: my %access;
9240: my $real_file = $file;
9241: $file =~ s/\.meta$//;
1.745 raeburn 9242: if (defined($file)) {
1.749 raeburn 9243: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9244: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9245: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9246: }
9247: }
1.745 raeburn 9248: } else {
1.749 raeburn 9249: foreach my $key (keys(%{$current_permissions})) {
9250: if ($key =~ /\0accesscontrol$/) {
9251: if (defined($group)) {
9252: if ($key !~ m-^\Q$group\E/-) {
9253: next;
9254: }
9255: }
9256: my ($fullpath) = split(/\0/,$key);
9257: if (ref($$current_permissions{$key}) eq 'HASH') {
9258: foreach my $control (keys(%{$$current_permissions{$key}})) {
9259: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9260: }
9261: }
9262: }
9263: }
9264: }
9265: return %access;
9266: }
9267:
9268: sub modify_access_controls {
9269: my ($file_name,$changes,$domain,$user)=@_;
9270: my ($outcome,$deloutcome);
9271: my %store_permissions;
9272: my %new_values;
9273: my %new_control;
9274: my %translation;
9275: my @deletions = ();
9276: my $now = time;
9277: if (exists($$changes{'activate'})) {
9278: if (ref($$changes{'activate'}) eq 'HASH') {
9279: my @newitems = sort(keys(%{$$changes{'activate'}}));
9280: my $numnew = scalar(@newitems);
9281: for (my $i=0; $i<$numnew; $i++) {
9282: my $newkey = $newitems[$i];
9283: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9284: if ($newkey =~ /^\d+:/) {
9285: $newkey =~ s/^(\d+)/$newid/;
9286: $translation{$1} = $newid;
9287: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9288: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9289: $translation{$1} = $newid;
9290: }
1.749 raeburn 9291: $new_values{$file_name."\0".$newkey} =
9292: $$changes{'activate'}{$newitems[$i]};
9293: $new_control{$newkey} = $now;
9294: }
9295: }
9296: }
9297: my %todelete;
9298: my %changed_items;
9299: foreach my $action ('delete','update') {
9300: if (exists($$changes{$action})) {
9301: if (ref($$changes{$action}) eq 'HASH') {
9302: foreach my $key (keys(%{$$changes{$action}})) {
9303: my ($itemnum) = ($key =~ /^([^:]+):/);
9304: if ($action eq 'delete') {
9305: $todelete{$itemnum} = 1;
9306: } else {
9307: $changed_items{$itemnum} = $key;
9308: }
9309: }
1.745 raeburn 9310: }
9311: }
1.749 raeburn 9312: }
9313: # get lock on access controls for file.
9314: my $lockhash = {
9315: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9316: ':'.$env{'user.domain'},
9317: };
9318: my $tries = 0;
9319: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9320:
9321: while (($gotlock ne 'ok') && $tries <3) {
9322: $tries ++;
9323: sleep 1;
9324: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9325: }
9326: if ($gotlock eq 'ok') {
9327: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9328: my ($tmp)=keys(%curr_permissions);
9329: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9330: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9331: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9332: if (ref($curr_controls) eq 'HASH') {
9333: foreach my $control_item (keys(%{$curr_controls})) {
9334: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9335: if (defined($todelete{$itemnum})) {
9336: push(@deletions,$file_name."\0".$control_item);
9337: } else {
9338: if (defined($changed_items{$itemnum})) {
9339: $new_control{$changed_items{$itemnum}} = $now;
9340: push(@deletions,$file_name."\0".$control_item);
9341: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9342: } else {
9343: $new_control{$control_item} = $$curr_controls{$control_item};
9344: }
9345: }
1.745 raeburn 9346: }
9347: }
9348: }
1.970 raeburn 9349: my ($group);
9350: if (&is_course($domain,$user)) {
9351: ($group,my $file) = split(/\//,$file_name,2);
9352: }
1.749 raeburn 9353: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9354: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9355: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9356: # remove lock
9357: my @del_lock = ($file_name."\0".'locked_access_records');
9358: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9359: my $sqlresult =
1.970 raeburn 9360: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9361: $group);
1.749 raeburn 9362: } else {
9363: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9364: }
1.749 raeburn 9365: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9366: }
9367:
1.827 raeburn 9368: sub make_public_indefinitely {
9369: my ($requrl) = @_;
9370: my $now = time;
9371: my $action = 'activate';
9372: my $aclnum = 0;
9373: if (&is_portfolio_url($requrl)) {
9374: my (undef,$udom,$unum,$file_name,$group) =
9375: &parse_portfolio_url($requrl);
9376: my $current_perms = &get_portfile_permissions($udom,$unum);
9377: my %access_controls = &get_access_controls($current_perms,
9378: $group,$file_name);
9379: foreach my $key (keys(%{$access_controls{$file_name}})) {
9380: my ($num,$scope,$end,$start) =
9381: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9382: if ($scope eq 'public') {
9383: if ($start <= $now && $end == 0) {
9384: $action = 'none';
9385: } else {
9386: $action = 'update';
9387: $aclnum = $num;
9388: }
9389: last;
9390: }
9391: }
9392: if ($action eq 'none') {
9393: return 'ok';
9394: } else {
9395: my %changes;
9396: my $newend = 0;
9397: my $newstart = $now;
9398: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9399: $changes{$action}{$newkey} = {
9400: type => 'public',
9401: time => {
9402: start => $newstart,
9403: end => $newend,
9404: },
9405: };
9406: my ($outcome,$deloutcome,$new_values,$translation) =
9407: &modify_access_controls($file_name,\%changes,$udom,$unum);
9408: return $outcome;
9409: }
9410: } else {
9411: return 'invalid';
9412: }
9413: }
9414:
1.745 raeburn 9415: #------------------------------------------------------Get Marked as Read Only
9416:
9417: sub get_marked_as_readonly {
9418: my ($domain,$user,$what,$group) = @_;
9419: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9420: my @readonly_files;
1.629 banghart 9421: my $cmp1=$what;
9422: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9423: while (my ($file_name,$value) = each(%{$current_permissions})) {
9424: if (defined($group)) {
9425: if ($file_name !~ m-^\Q$group\E/-) {
9426: next;
9427: }
9428: }
1.561 banghart 9429: if (ref($value) eq "ARRAY"){
9430: foreach my $stored_what (@{$value}) {
1.629 banghart 9431: my $cmp2=$stored_what;
1.759 albertel 9432: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9433: $cmp2=join('',@{$stored_what});
1.745 raeburn 9434: }
1.629 banghart 9435: if ($cmp1 eq $cmp2) {
1.561 banghart 9436: push(@readonly_files, $file_name);
1.745 raeburn 9437: last;
1.563 banghart 9438: } elsif (!defined($what)) {
9439: push(@readonly_files, $file_name);
1.745 raeburn 9440: last;
1.561 banghart 9441: }
9442: }
1.745 raeburn 9443: }
1.561 banghart 9444: }
9445: return @readonly_files;
9446: }
1.577 banghart 9447: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9448:
1.577 banghart 9449: sub get_marked_as_readonly_hash {
1.745 raeburn 9450: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9451: my %readonly_files;
1.745 raeburn 9452: while (my ($file_name,$value) = each(%{$current_permissions})) {
9453: if (defined($group)) {
9454: if ($file_name !~ m-^\Q$group\E/-) {
9455: next;
9456: }
9457: }
1.577 banghart 9458: if (ref($value) eq "ARRAY"){
9459: foreach my $stored_what (@{$value}) {
1.745 raeburn 9460: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9461: foreach my $lock_descriptor(@{$stored_what}) {
9462: if ($lock_descriptor eq 'graded') {
9463: $readonly_files{$file_name} = 'graded';
9464: } elsif ($lock_descriptor eq 'handback') {
9465: $readonly_files{$file_name} = 'handback';
9466: } else {
9467: if (!exists($readonly_files{$file_name})) {
9468: $readonly_files{$file_name} = 'locked';
9469: }
9470: }
1.745 raeburn 9471: }
1.750 banghart 9472: }
1.577 banghart 9473: }
9474: }
9475: }
9476: return %readonly_files;
9477: }
1.559 banghart 9478: # ------------------------------------------------------------ Unmark as Read Only
9479:
9480: sub unmark_as_readonly {
1.629 banghart 9481: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9482: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9483: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9484: $file_name = &declutter_portfile($file_name);
1.634 albertel 9485: my $symb_crs = $what;
9486: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9487: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9488: my ($tmp)=keys(%current_permissions);
9489: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9490: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9491: foreach my $file (@readonly_files) {
1.759 albertel 9492: my $clean_file = &declutter_portfile($file);
9493: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9494: my $current_locks = $current_permissions{$file};
1.563 banghart 9495: my @new_locks;
9496: my @del_keys;
9497: if (ref($current_locks) eq "ARRAY"){
9498: foreach my $locker (@{$current_locks}) {
1.632 albertel 9499: my $compare=$locker;
1.749 raeburn 9500: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9501: $compare=join('',@{$locker});
1.746 raeburn 9502: if ($compare ne $symb_crs) {
9503: push(@new_locks, $locker);
9504: }
1.563 banghart 9505: }
9506: }
1.650 albertel 9507: if (scalar(@new_locks) > 0) {
1.563 banghart 9508: $current_permissions{$file} = \@new_locks;
9509: } else {
9510: push(@del_keys, $file);
1.613 albertel 9511: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9512: delete($current_permissions{$file});
1.563 banghart 9513: }
9514: }
1.561 banghart 9515: }
1.613 albertel 9516: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9517: return;
9518: }
1.512 banghart 9519:
1.17 www 9520: # ------------------------------------------------------------ Directory lister
9521:
9522: sub dirlist {
1.955 raeburn 9523: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9524: $uri=~s/^\///;
9525: $uri=~s/\/$//;
1.253 stredwic 9526: my ($udom, $uname);
1.955 raeburn 9527: if ($getuserdir) {
1.253 stredwic 9528: $udom = $userdomain;
9529: $uname = $username;
1.955 raeburn 9530: } else {
9531: (undef,$udom,$uname)=split(/\//,$uri);
9532: if(defined($userdomain)) {
9533: $udom = $userdomain;
9534: }
9535: if(defined($username)) {
9536: $uname = $username;
9537: }
1.253 stredwic 9538: }
1.955 raeburn 9539: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9540:
1.955 raeburn 9541: $dirRoot = $perlvar{'lonDocRoot'};
9542: if (defined($getpropath)) {
9543: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9544: $dirRoot =~ s/\/$//;
1.955 raeburn 9545: } elsif (defined($getuserdir)) {
9546: my $subdir=$uname.'__';
9547: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9548: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9549: ."/$udom/$subdir/$uname";
9550: } elsif (defined($alternateRoot)) {
9551: $dirRoot = $alternateRoot;
1.751 banghart 9552: }
1.253 stredwic 9553:
9554: if($udom) {
9555: if($uname) {
1.1135 raeburn 9556: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9557: if ($uhome eq 'no_host') {
9558: return ([],'no_host');
9559: }
1.955 raeburn 9560: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9561: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9562: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9563: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9564: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9565: } else {
9566: @listing_results = map { &unescape($_); } split(/:/,$listing);
9567: }
1.605 matthew 9568: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9569: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9570: @listing_results = split(/:/,$listing);
9571: } else {
9572: @listing_results = map { &unescape($_); } split(/:/,$listing);
9573: }
1.1135 raeburn 9574: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9575: ($listing eq 'rejected') || ($listing eq 'refused') ||
9576: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9577: return ([],$listing);
9578: } else {
9579: return (\@listing_results);
1.1135 raeburn 9580: }
1.955 raeburn 9581: } elsif(!$alternateRoot) {
1.1136 raeburn 9582: my (%allusers,%listerror);
1.841 albertel 9583: my %servers = &get_servers($udom,'library');
1.955 raeburn 9584: foreach my $tryserver (keys(%servers)) {
9585: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9586: &escape($udom),$tryserver);
9587: if ($listing eq 'unknown_cmd') {
9588: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9589: $udom, $tryserver);
9590: } else {
9591: @listing_results = map { &unescape($_); } split(/:/,$listing);
9592: }
1.841 albertel 9593: if ($listing eq 'unknown_cmd') {
9594: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9595: $udom, $tryserver);
9596: @listing_results = split(/:/,$listing);
9597: } else {
9598: @listing_results =
9599: map { &unescape($_); } split(/:/,$listing);
9600: }
1.1136 raeburn 9601: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9602: ($listing eq 'rejected') || ($listing eq 'refused') ||
9603: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9604: $listerror{$tryserver} = $listing;
9605: } else {
1.841 albertel 9606: foreach my $line (@listing_results) {
9607: my ($entry) = split(/&/,$line,2);
9608: $allusers{$entry} = 1;
9609: }
9610: }
1.253 stredwic 9611: }
1.1136 raeburn 9612: my @alluserslist=();
1.800 albertel 9613: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9614: push(@alluserslist,$user.'&user');
1.253 stredwic 9615: }
1.1136 raeburn 9616: return (\@alluserslist);
1.253 stredwic 9617: } else {
1.1136 raeburn 9618: return ([],'missing username');
1.253 stredwic 9619: }
1.955 raeburn 9620: } elsif(!defined($getpropath)) {
1.1136 raeburn 9621: my $path = $perlvar{'lonDocRoot'}.'/res/';
9622: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9623: return (\@all_domains);
1.955 raeburn 9624: } else {
1.1136 raeburn 9625: return ([],'missing domain');
1.275 stredwic 9626: }
9627: }
9628:
9629: # --------------------------------------------- GetFileTimestamp
9630: # This function utilizes dirlist and returns the date stamp for
9631: # when it was last modified. It will also return an error of -1
9632: # if an error occurs
9633:
9634: sub GetFileTimestamp {
1.955 raeburn 9635: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9636: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9637: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9638: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9639: undef,$getuserdir);
9640: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9641: return -1;
9642: }
9643: if (ref($fileref) eq 'ARRAY') {
9644: my @stats = split('&',$fileref->[0]);
1.375 matthew 9645: # @stats contains first the filename, then the stat output
9646: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9647: } else {
9648: return -1;
1.253 stredwic 9649: }
1.26 www 9650: }
9651:
1.712 albertel 9652: sub stat_file {
9653: my ($uri) = @_;
1.787 albertel 9654: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9655:
1.955 raeburn 9656: my ($udom,$uname,$file);
1.712 albertel 9657: if ($uri =~ m-^/(uploaded|editupload)/-) {
9658: ($udom,$uname,$file) =
1.811 albertel 9659: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9660: $file = 'userfiles/'.$file;
9661: }
9662: if ($uri =~ m-^/res/-) {
9663: ($udom,$uname) =
1.807 albertel 9664: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9665: $file = $uri;
9666: }
9667:
9668: if (!$udom || !$uname || !$file) {
9669: # unable to handle the uri
9670: return ();
9671: }
1.956 raeburn 9672: my $getpropath;
9673: if ($file =~ /^userfiles\//) {
9674: $getpropath = 1;
9675: }
1.1136 raeburn 9676: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9677: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9678: return ();
9679: } else {
9680: if (ref($listref) eq 'ARRAY') {
9681: my @stats = split('&',$listref->[0]);
9682: shift(@stats); #filename is first
9683: return @stats;
9684: }
1.712 albertel 9685: }
9686: return ();
9687: }
9688:
1.26 www 9689: # -------------------------------------------------------- Value of a Condition
9690:
1.713 albertel 9691: # gets the value of a specific preevaluated condition
9692: # stored in the string $env{user.state.<cid>}
9693: # or looks up a condition reference in the bighash and if if hasn't
9694: # already been evaluated recurses into docondval to get the value of
9695: # the condition, then memoizing it to
9696: # $env{user.state.<cid>.<condition>}
1.40 www 9697: sub directcondval {
9698: my $number=shift;
1.620 albertel 9699: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9700: &Apache::lonuserstate::evalstate();
9701: }
1.713 albertel 9702: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9703: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9704: } elsif ($number =~ /^_/) {
9705: my $sub_condition;
9706: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9707: &GDBM_READER(),0640)) {
9708: $sub_condition=$bighash{'conditions'.$number};
9709: untie(%bighash);
9710: }
9711: my $value = &docondval($sub_condition);
1.949 raeburn 9712: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9713: return $value;
9714: }
1.620 albertel 9715: if ($env{'user.state.'.$env{'request.course.id'}}) {
9716: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9717: } else {
9718: return 2;
9719: }
9720: }
9721:
1.713 albertel 9722: # get the collection of conditions for this resource
1.26 www 9723: sub condval {
9724: my $condidx=shift;
1.54 www 9725: my $allpathcond='';
1.713 albertel 9726: foreach my $cond (split(/\|/,$condidx)) {
9727: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9728: $allpathcond.=
9729: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9730: }
1.191 harris41 9731: }
1.54 www 9732: $allpathcond=~s/\|$//;
1.713 albertel 9733: return &docondval($allpathcond);
9734: }
9735:
9736: #evaluates an expression of conditions
9737: sub docondval {
9738: my ($allpathcond) = @_;
9739: my $result=0;
9740: if ($env{'request.course.id'}
9741: && defined($allpathcond)) {
9742: my $operand='|';
9743: my @stack;
9744: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9745: if ($chunk eq '(') {
9746: push @stack,($operand,$result);
9747: } elsif ($chunk eq ')') {
9748: my $before=pop @stack;
9749: if (pop @stack eq '&') {
9750: $result=$result>$before?$before:$result;
9751: } else {
9752: $result=$result>$before?$result:$before;
9753: }
9754: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9755: $operand=$chunk;
9756: } else {
9757: my $new=directcondval($chunk);
9758: if ($operand eq '&') {
9759: $result=$result>$new?$new:$result;
9760: } else {
9761: $result=$result>$new?$result:$new;
9762: }
9763: }
9764: }
1.26 www 9765: }
9766: return $result;
1.421 albertel 9767: }
9768:
9769: # ---------------------------------------------------- Devalidate courseresdata
9770:
9771: sub devalidatecourseresdata {
9772: my ($coursenum,$coursedomain)=@_;
9773: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9774: &devalidate_cache_new('courseres',$hashid);
1.28 www 9775: }
9776:
1.763 www 9777:
1.200 www 9778: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9779: #
9780: # Parameters:
9781: # $coursenum - Number of the course.
9782: # $coursedomain - Domain at which the course was created.
9783: # Returns:
9784: # A hash of the course parameters along (I think) with timestamps
9785: # and version info.
1.877 foxr 9786:
1.624 albertel 9787: sub get_courseresdata {
9788: my ($coursenum,$coursedomain)=@_;
1.200 www 9789: my $coursehom=&homeserver($coursenum,$coursedomain);
9790: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9791: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9792: my %dumpreply;
1.417 albertel 9793: unless (defined($cached)) {
1.624 albertel 9794: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9795: $result=\%dumpreply;
1.251 albertel 9796: my ($tmp) = keys(%dumpreply);
9797: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9798: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9799: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9800: return $tmp;
1.416 albertel 9801: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9802: $result=undef;
1.599 albertel 9803: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9804: }
9805: }
1.624 albertel 9806: return $result;
9807: }
9808:
1.633 albertel 9809: sub devalidateuserresdata {
9810: my ($uname,$udom)=@_;
9811: my $hashid="$udom:$uname";
9812: &devalidate_cache_new('userres',$hashid);
9813: }
9814:
1.624 albertel 9815: sub get_userresdata {
9816: my ($uname,$udom)=@_;
9817: #most student don\'t have any data set, check if there is some data
9818: if (&EXT_cache_status($udom,$uname)) { return undef; }
9819:
9820: my $hashid="$udom:$uname";
9821: my ($result,$cached)=&is_cached_new('userres',$hashid);
9822: if (!defined($cached)) {
9823: my %resourcedata=&dump('resourcedata',$udom,$uname);
9824: $result=\%resourcedata;
9825: &do_cache_new('userres',$hashid,$result,600);
9826: }
9827: my ($tmp)=keys(%$result);
9828: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9829: return $result;
9830: }
9831: #error 2 occurs when the .db doesn't exist
9832: if ($tmp!~/error: 2 /) {
1.672 albertel 9833: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9834: " Trying to get resource data for ".
9835: $uname." at ".$udom.": ".
9836: $tmp."</font>");
9837: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9838: #&EXT_cache_set($udom,$uname);
9839: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9840: undef($tmp); # not really an error so don't send it back
1.624 albertel 9841: }
9842: return $tmp;
9843: }
1.879 foxr 9844: #----------------------------------------------- resdata - return resource data
9845: # Purpose:
9846: # Return resource data for either users or for a course.
9847: # Parameters:
9848: # $name - Course/user name.
9849: # $domain - Name of the domain the user/course is registered on.
9850: # $type - Type of thing $name is (must be 'course' or 'user'
9851: # @which - Array of names of resources desired.
9852: # Returns:
9853: # The value of the first reasource in @which that is found in the
9854: # resource hash.
9855: # Exceptional Conditions:
9856: # If the $type passed in is not valid (not the string 'course' or
9857: # 'user', an undefined reference is returned.
9858: # If none of the resources are found, an undef is returned
1.624 albertel 9859: sub resdata {
9860: my ($name,$domain,$type,@which)=@_;
9861: my $result;
9862: if ($type eq 'course') {
9863: $result=&get_courseresdata($name,$domain);
9864: } elsif ($type eq 'user') {
9865: $result=&get_userresdata($name,$domain);
9866: }
9867: if (!ref($result)) { return $result; }
1.251 albertel 9868: foreach my $item (@which) {
1.927 albertel 9869: if (defined($result->{$item->[0]})) {
9870: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9871: }
1.250 albertel 9872: }
1.291 albertel 9873: return undef;
1.200 www 9874: }
9875:
1.1172.2.31 raeburn 9876: sub get_numsuppfiles {
9877: my ($cnum,$cdom,$ignorecache)=@_;
9878: my $hashid=$cnum.':'.$cdom;
9879: my ($suppcount,$cached);
9880: unless ($ignorecache) {
9881: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9882: }
9883: unless (defined($cached)) {
9884: my $chome=&homeserver($cnum,$cdom);
9885: unless ($chome eq 'no_host') {
9886: ($suppcount,my $errors) = (0,0);
9887: my $suppmap = 'supplemental.sequence';
9888: ($suppcount,$errors) =
9889: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9890: }
9891: &do_cache_new('suppcount',$hashid,$suppcount,600);
9892: }
9893: return $suppcount;
9894: }
9895:
1.379 matthew 9896: #
9897: # EXT resource caching routines
9898: #
9899:
9900: sub clear_EXT_cache_status {
1.383 albertel 9901: &delenv('cache.EXT.');
1.379 matthew 9902: }
9903:
9904: sub EXT_cache_status {
9905: my ($target_domain,$target_user) = @_;
1.383 albertel 9906: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9907: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9908: # We know already the user has no data
9909: return 1;
9910: } else {
9911: return 0;
9912: }
9913: }
9914:
9915: sub EXT_cache_set {
9916: my ($target_domain,$target_user) = @_;
1.383 albertel 9917: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9918: #&appenv({$cachename => time});
1.379 matthew 9919: }
9920:
1.28 www 9921: # --------------------------------------------------------- Value of a Variable
1.58 www 9922: sub EXT {
1.715 albertel 9923:
1.1172.2.28 raeburn 9924: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9925: unless ($varname) { return ''; }
1.218 albertel 9926: #get real user name/domain, courseid and symb
9927: my $courseid;
1.359 albertel 9928: my $publicuser;
1.427 www 9929: if ($symbparm) {
9930: $symbparm=&get_symb_from_alias($symbparm);
9931: }
1.218 albertel 9932: if (!($uname && $udom)) {
1.790 albertel 9933: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9934: if (!$symbparm) { $symbparm=$cursymb; }
9935: } else {
1.620 albertel 9936: $courseid=$env{'request.course.id'};
1.218 albertel 9937: }
1.48 www 9938: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9939: my $rest;
1.320 albertel 9940: if (defined($therest[0])) {
1.48 www 9941: $rest=join('.',@therest);
9942: } else {
9943: $rest='';
9944: }
1.320 albertel 9945:
1.57 www 9946: my $qualifierrest=$qualifier;
9947: if ($rest) { $qualifierrest.='.'.$rest; }
9948: my $spacequalifierrest=$space;
9949: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9950: if ($realm eq 'user') {
1.48 www 9951: # --------------------------------------------------------------- user.resource
9952: if ($space eq 'resource') {
1.651 albertel 9953: if ( (defined($Apache::lonhomework::parsing_a_problem)
9954: || defined($Apache::lonhomework::parsing_a_task))
9955: &&
1.744 albertel 9956: ($symbparm eq &symbread()) ) {
9957: # if we are in the middle of processing the resource the
9958: # get the value we are planning on committing
9959: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9960: return $Apache::lonhomework::results{$qualifierrest};
9961: } else {
9962: return $Apache::lonhomework::history{$qualifierrest};
9963: }
1.335 albertel 9964: } else {
1.359 albertel 9965: my %restored;
1.620 albertel 9966: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9967: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9968: } else {
9969: %restored=&restore($symbparm,$courseid,$udom,$uname);
9970: }
1.335 albertel 9971: return $restored{$qualifierrest};
9972: }
1.48 www 9973: # ----------------------------------------------------------------- user.access
9974: } elsif ($space eq 'access') {
1.218 albertel 9975: # FIXME - not supporting calls for a specific user
1.48 www 9976: return &allowed($qualifier,$rest);
9977: # ------------------------------------------ user.preferences, user.environment
9978: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9979: if (($uname eq $env{'user.name'}) &&
9980: ($udom eq $env{'user.domain'})) {
9981: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9982: } else {
1.359 albertel 9983: my %returnhash;
9984: if (!$publicuser) {
9985: %returnhash=&userenvironment($udom,$uname,
9986: $qualifierrest);
9987: }
1.218 albertel 9988: return $returnhash{$qualifierrest};
9989: }
1.48 www 9990: # ----------------------------------------------------------------- user.course
9991: } elsif ($space eq 'course') {
1.218 albertel 9992: # FIXME - not supporting calls for a specific user
1.620 albertel 9993: return $env{join('.',('request.course',$qualifier))};
1.48 www 9994: # ------------------------------------------------------------------- user.role
9995: } elsif ($space eq 'role') {
1.218 albertel 9996: # FIXME - not supporting calls for a specific user
1.620 albertel 9997: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9998: if ($qualifier eq 'value') {
9999: return $role;
10000: } elsif ($qualifier eq 'extent') {
10001: return $where;
10002: }
10003: # ----------------------------------------------------------------- user.domain
10004: } elsif ($space eq 'domain') {
1.218 albertel 10005: return $udom;
1.48 www 10006: # ------------------------------------------------------------------- user.name
10007: } elsif ($space eq 'name') {
1.218 albertel 10008: return $uname;
1.48 www 10009: # ---------------------------------------------------- Any other user namespace
1.29 www 10010: } else {
1.359 albertel 10011: my %reply;
10012: if (!$publicuser) {
10013: %reply=&get($space,[$qualifierrest],$udom,$uname);
10014: }
10015: return $reply{$qualifierrest};
1.48 www 10016: }
1.236 www 10017: } elsif ($realm eq 'query') {
10018: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10019: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10020: [$spacequalifierrest]);
1.620 albertel 10021: return $env{'form.'.$spacequalifierrest};
1.236 www 10022: } elsif ($realm eq 'request') {
1.48 www 10023: # ------------------------------------------------------------- request.browser
10024: if ($space eq 'browser') {
1.1145 bisitz 10025: return $env{'browser.'.$qualifier};
1.57 www 10026: # ------------------------------------------------------------ request.filename
10027: } else {
1.620 albertel 10028: return $env{'request.'.$spacequalifierrest};
1.29 www 10029: }
1.28 www 10030: } elsif ($realm eq 'course') {
1.48 www 10031: # ---------------------------------------------------------- course.description
1.620 albertel 10032: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10033: } elsif ($realm eq 'resource') {
1.165 www 10034:
1.620 albertel 10035: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10036: if (!$symbparm) { $symbparm=&symbread(); }
10037: }
1.693 albertel 10038:
1.1172.2.30 raeburn 10039: if ($qualifier eq '') {
10040: if ($space eq 'title') {
10041: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10042: return &gettitle($symbparm);
10043: }
1.693 albertel 10044:
1.1172.2.30 raeburn 10045: if ($space eq 'map') {
10046: my ($map) = &decode_symb($symbparm);
10047: return &symbread($map);
10048: }
10049: if ($space eq 'maptitle') {
10050: my ($map) = &decode_symb($symbparm);
10051: return &gettitle($map);
10052: }
10053: if ($space eq 'filename') {
10054: if ($symbparm) {
10055: return &clutter((&decode_symb($symbparm))[2]);
10056: }
10057: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10058: }
1.1172.2.30 raeburn 10059:
10060: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10061: if ($space eq 'visibleparts') {
10062: my $navmap = Apache::lonnavmaps::navmap->new();
10063: my $item;
10064: if (ref($navmap)) {
10065: my $res = $navmap->getBySymb($symbparm);
10066: my $parts = $res->parts();
10067: if (ref($parts) eq 'ARRAY') {
10068: $item = join(',',@{$parts});
10069: }
10070: undef($navmap);
10071: }
10072: return $item;
10073: }
10074: }
10075: }
1.693 albertel 10076:
10077: my ($section, $group, @groups);
1.593 albertel 10078: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10079: if (($courseid eq '') && ($cid)) {
10080: $courseid = $cid;
10081: }
10082: if (($symbparm && $courseid) &&
10083: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10084:
1.218 albertel 10085: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10086:
1.60 www 10087: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10088: my $symbp=$symbparm;
1.735 albertel 10089: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10090:
10091: my $symbparm=$symbp.'.'.$spacequalifierrest;
10092: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10093:
1.620 albertel 10094: if (($env{'user.name'} eq $uname) &&
10095: ($env{'user.domain'} eq $udom)) {
10096: $section=$env{'request.course.sec'};
1.733 raeburn 10097: @groups = split(/:/,$env{'request.course.groups'});
10098: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10099: } else {
1.539 albertel 10100: if (! defined($usection)) {
1.551 albertel 10101: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10102: } else {
10103: $section = $usection;
10104: }
1.733 raeburn 10105: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10106: }
10107:
10108: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10109: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10110: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10111:
1.593 albertel 10112: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10113: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10114: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10115:
1.60 www 10116: # ----------------------------------------------------------- first, check user
1.624 albertel 10117:
10118: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10119: ([$courselevelr,'resource'],
10120: [$courselevelm,'map' ],
10121: [$courselevel, 'course' ]));
1.931 albertel 10122: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10123:
1.594 albertel 10124: # ------------------------------------------------ second, check some of course
1.684 raeburn 10125: my $coursereply;
1.691 raeburn 10126: if (@groups > 0) {
10127: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10128: $mapparm,$spacequalifierrest);
1.927 albertel 10129: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10130: }
1.96 www 10131:
1.684 raeburn 10132: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10133: $env{'course.'.$courseid.'.domain'},
10134: 'course',
10135: ([$seclevelr, 'resource'],
10136: [$seclevelm, 'map' ],
10137: [$seclevel, 'course' ],
10138: [$courselevelr,'resource']));
10139: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10140:
1.60 www 10141: # ------------------------------------------------------ third, check map parms
1.218 albertel 10142: my %parmhash=();
10143: my $thisparm='';
10144: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10145: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10146: &GDBM_READER(),0640)) {
1.218 albertel 10147: $thisparm=$parmhash{$symbparm};
10148: untie(%parmhash);
10149: }
1.927 albertel 10150: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10151: }
1.594 albertel 10152: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10153:
1.218 albertel 10154: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10155: my $filename;
10156: if (!$symbparm) { $symbparm=&symbread(); }
10157: if ($symbparm) {
1.409 www 10158: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10159: } else {
1.620 albertel 10160: $filename=$env{'request.filename'};
1.282 albertel 10161: }
10162: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10163: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10164: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10165: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10166:
1.927 albertel 10167: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10168: if ($symbparm && defined($courseid) &&
1.620 albertel 10169: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10170: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10171: $env{'course.'.$courseid.'.domain'},
10172: 'course',
1.927 albertel 10173: ([$courselevelm,'map' ],
10174: [$courselevel, 'course']));
10175: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10176: }
1.145 www 10177: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10178: unless ($space eq '0') {
1.336 albertel 10179: my @parts=split(/_/,$space);
10180: my $id=pop(@parts);
10181: my $part=join('_',@parts);
10182: if ($part eq '') { $part='0'; }
1.927 albertel 10183: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10184: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10185: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10186: }
1.395 albertel 10187: if ($recurse) { return undef; }
10188: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10189: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10190: # ---------------------------------------------------- Any other user namespace
10191: } elsif ($realm eq 'environment') {
10192: # ----------------------------------------------------------------- environment
1.620 albertel 10193: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10194: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10195: } else {
1.770 albertel 10196: if ($uname eq 'anonymous' && $udom eq '') {
10197: return '';
10198: }
1.219 albertel 10199: my %returnhash=&userenvironment($udom,$uname,
10200: $spacequalifierrest);
10201: return $returnhash{$spacequalifierrest};
10202: }
1.28 www 10203: } elsif ($realm eq 'system') {
1.48 www 10204: # ----------------------------------------------------------------- system.time
10205: if ($space eq 'time') {
10206: return time;
10207: }
1.696 albertel 10208: } elsif ($realm eq 'server') {
10209: # ----------------------------------------------------------------- system.time
10210: if ($space eq 'name') {
10211: return $ENV{'SERVER_NAME'};
10212: }
1.28 www 10213: }
1.48 www 10214: return '';
1.61 www 10215: }
10216:
1.927 albertel 10217: sub get_reply {
10218: my ($reply_value) = @_;
1.940 raeburn 10219: if (ref($reply_value) eq 'ARRAY') {
10220: if (wantarray) {
10221: return @$reply_value;
10222: }
10223: return $reply_value->[0];
10224: } else {
10225: return $reply_value;
1.927 albertel 10226: }
10227: }
10228:
1.691 raeburn 10229: sub check_group_parms {
10230: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10231: my @groupitems = ();
10232: my $resultitem;
1.927 albertel 10233: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10234: foreach my $group (@{$groups}) {
10235: foreach my $level (@levels) {
1.927 albertel 10236: my $item = $courseid.'.['.$group.'].'.$level->[0];
10237: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10238: }
10239: }
10240: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10241: $env{'course.'.$courseid.'.domain'},
10242: 'course',@groupitems);
10243: return $coursereply;
10244: }
10245:
10246: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10247: my ($courseid,@groups) = @_;
10248: @groups = sort(@groups);
1.691 raeburn 10249: return @groups;
10250: }
10251:
1.395 albertel 10252: sub packages_tab_default {
10253: my ($uri,$varname)=@_;
10254: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10255:
10256: my (@extension,@specifics,$do_default);
10257: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10258: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10259: if ($pack_type eq 'default') {
10260: $do_default=1;
10261: } elsif ($pack_type eq 'extension') {
10262: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10263: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10264: # only look at packages defaults for packages that this id is
1.738 albertel 10265: push(@specifics,[$package,$pack_type,$pack_part]);
10266: }
10267: }
10268: # first look for a package that matches the requested part id
10269: foreach my $package (@specifics) {
10270: my (undef,$pack_type,$pack_part)=@{$package};
10271: next if ($pack_part ne $part);
10272: if (defined($packagetab{"$pack_type&$name&default"})) {
10273: return $packagetab{"$pack_type&$name&default"};
10274: }
10275: }
10276: # look for any possible matching non extension_ package
10277: foreach my $package (@specifics) {
10278: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10279: if (defined($packagetab{"$pack_type&$name&default"})) {
10280: return $packagetab{"$pack_type&$name&default"};
10281: }
1.585 albertel 10282: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10283: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10284: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10285: }
10286: }
1.738 albertel 10287: # look for any posible extension_ match
10288: foreach my $package (@extension) {
10289: my ($package,$pack_type)=@{$package};
10290: if (defined($packagetab{"$pack_type&$name&default"})) {
10291: return $packagetab{"$pack_type&$name&default"};
10292: }
10293: if (defined($packagetab{$package."&$name&default"})) {
10294: return $packagetab{$package."&$name&default"};
10295: }
10296: }
10297: # look for a global default setting
10298: if ($do_default && defined($packagetab{"default&$name&default"})) {
10299: return $packagetab{"default&$name&default"};
10300: }
1.395 albertel 10301: return undef;
10302: }
10303:
1.334 albertel 10304: sub add_prefix_and_part {
10305: my ($prefix,$part)=@_;
10306: my $keyroot;
10307: if (defined($prefix) && $prefix !~ /^__/) {
10308: # prefix that has a part already
10309: $keyroot=$prefix;
10310: } elsif (defined($prefix)) {
10311: # prefix that is missing a part
10312: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10313: } else {
10314: # no prefix at all
10315: if (defined($part)) { $keyroot='_'.$part; }
10316: }
10317: return $keyroot;
10318: }
10319:
1.71 www 10320: # ---------------------------------------------------------------- Get metadata
10321:
1.599 albertel 10322: my %metaentry;
1.1070 www 10323: my %importedpartids;
1.71 www 10324: sub metadata {
1.176 www 10325: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10326: $uri=&declutter($uri);
1.288 albertel 10327: # if it is a non metadata possible uri return quickly
1.529 albertel 10328: if (($uri eq '') ||
10329: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10330: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10331: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10332: return undef;
10333: }
1.1172.2.49 raeburn 10334: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10335: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10336: return undef;
1.288 albertel 10337: }
1.73 www 10338: my $filename=$uri;
10339: $uri=~s/\.meta$//;
1.172 www 10340: #
10341: # Is the metadata already cached?
1.177 www 10342: # Look at timestamp of caching
1.172 www 10343: # Everything is cached by the main uri, libraries are never directly cached
10344: #
1.428 albertel 10345: if (!defined($liburi)) {
1.599 albertel 10346: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10347: if (defined($cached)) { return $result->{':'.$what}; }
10348: }
10349: {
1.1069 www 10350: # Imported parts would go here
1.1070 www 10351: my %importedids=();
10352: my @origfileimportpartids=();
1.1069 www 10353: my $importedparts=0;
1.172 www 10354: #
10355: # Is this a recursive call for a library?
10356: #
1.599 albertel 10357: # if (! exists($metacache{$uri})) {
10358: # $metacache{$uri}={};
10359: # }
1.924 albertel 10360: my $cachetime = 60*60;
1.171 www 10361: if ($liburi) {
10362: $liburi=&declutter($liburi);
10363: $filename=$liburi;
1.401 bowersj2 10364: } else {
1.599 albertel 10365: &devalidate_cache_new('meta',$uri);
10366: undef(%metaentry);
1.401 bowersj2 10367: }
1.140 www 10368: my %metathesekeys=();
1.73 www 10369: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10370: my $metastring;
1.1140 www 10371: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10372: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10373: $metastring =
1.929 albertel 10374: &Apache::lonnet::ssi_body($which,
1.924 albertel 10375: ('grade_target' => 'meta'));
10376: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10377: } elsif (($uri !~ m -^(editupload)/-) &&
10378: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10379: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10380: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10381: $metastring=&getfile($file);
1.489 albertel 10382: }
1.208 albertel 10383: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10384: my $token;
1.140 www 10385: undef %metathesekeys;
1.71 www 10386: while ($token=$parser->get_token) {
1.339 albertel 10387: if ($token->[0] eq 'S') {
10388: if (defined($token->[2]->{'package'})) {
1.172 www 10389: #
10390: # This is a package - get package info
10391: #
1.339 albertel 10392: my $package=$token->[2]->{'package'};
10393: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10394: if (defined($token->[2]->{'id'})) {
10395: $keyroot.='_'.$token->[2]->{'id'};
10396: }
1.599 albertel 10397: if ($metaentry{':packages'}) {
10398: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10399: } else {
1.599 albertel 10400: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10401: }
1.736 albertel 10402: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10403: my $part=$keyroot;
10404: $part=~s/^\_//;
1.736 albertel 10405: if ($pack_entry=~/^\Q$package\E\&/ ||
10406: $pack_entry=~/^\Q$package\E_0\&/) {
10407: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10408: # ignore package.tab specified default values
10409: # here &package_tab_default() will fetch those
10410: if ($subp eq 'default') { next; }
1.736 albertel 10411: my $value=$packagetab{$pack_entry};
1.432 albertel 10412: my $unikey;
10413: if ($pack =~ /_0$/) {
10414: $unikey='parameter_0_'.$name;
10415: $part=0;
10416: } else {
10417: $unikey='parameter'.$keyroot.'_'.$name;
10418: }
1.339 albertel 10419: if ($subp eq 'display') {
10420: $value.=' [Part: '.$part.']';
10421: }
1.599 albertel 10422: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10423: $metathesekeys{$unikey}=1;
1.599 albertel 10424: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10425: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10426: }
1.599 albertel 10427: if (defined($metaentry{':'.$unikey.'.default'})) {
10428: $metaentry{':'.$unikey}=
10429: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10430: }
1.339 albertel 10431: }
10432: }
10433: } else {
1.172 www 10434: #
10435: # This is not a package - some other kind of start tag
1.339 albertel 10436: #
10437: my $entry=$token->[1];
1.1068 www 10438: my $unikey='';
1.175 www 10439:
1.339 albertel 10440: if ($entry eq 'import') {
1.175 www 10441: #
10442: # Importing a library here
1.339 albertel 10443: #
1.1067 www 10444: my $location=$parser->get_text('/import');
10445: my $dir=$filename;
10446: $dir=~s|[^/]*$||;
10447: $location=&filelocation($dir,$location);
1.1069 www 10448:
1.1068 www 10449: my $importmode=$token->[2]->{'importmode'};
10450: if ($importmode eq 'problem') {
1.1069 www 10451: # Import as problem/response
1.1068 www 10452: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10453: } elsif ($importmode eq 'part') {
10454: # Import as part(s)
1.1069 www 10455: $importedparts=1;
10456: # We need to get the original file and the imported file to get the part order correct
10457: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10458: # Load and inspect original file
1.1070 www 10459: if ($#origfileimportpartids<0) {
10460: undef(%importedpartids);
10461: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10462: my $origfile=&getfile($origfilelocation);
10463: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10464: }
10465:
1.1069 www 10466: # Load and inspect imported file
10467: my $impfile=&getfile($location);
10468: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10469: if ($#impfilepartids>=0) {
10470: # This problem had parts
1.1070 www 10471: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10472: } else {
10473: # Importing by turning a single problem into a problem part
10474: # It gets the import-tags ID as part-ID
10475: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10476: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10477: }
1.1068 www 10478: } else {
10479: # Normal import
10480: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10481: if (defined($token->[2]->{'id'})) {
10482: $unikey.='_'.$token->[2]->{'id'};
10483: }
1.1067 www 10484: }
10485:
1.339 albertel 10486: if ($depthcount<20) {
1.736 albertel 10487: my $metadata =
10488: &metadata($uri,'keys', $location,$unikey,
10489: $depthcount+1);
10490: foreach my $meta (split(',',$metadata)) {
10491: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10492: $metathesekeys{$meta}=1;
1.339 albertel 10493: }
1.1068 www 10494:
10495: }
1.1067 www 10496: } else {
10497: #
10498: # Not importing, some other kind of non-package, non-library start tag
10499: #
10500: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10501: if (defined($token->[2]->{'id'})) {
10502: $unikey.='_'.$token->[2]->{'id'};
10503: }
1.339 albertel 10504: if (defined($token->[2]->{'name'})) {
10505: $unikey.='_'.$token->[2]->{'name'};
10506: }
10507: $metathesekeys{$unikey}=1;
1.736 albertel 10508: foreach my $param (@{$token->[3]}) {
10509: $metaentry{':'.$unikey.'.'.$param} =
10510: $token->[2]->{$param};
1.339 albertel 10511: }
10512: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10513: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10514: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10515: # only ws inside the tag, and not in default, so use default
10516: # as value
1.599 albertel 10517: $metaentry{':'.$unikey}=$default;
1.908 albertel 10518: } elsif ( $internaltext =~ /\S/ ) {
10519: # something interesting inside the tag
10520: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10521: } else {
1.908 albertel 10522: # no interesting values, don't set a default
1.339 albertel 10523: }
1.172 www 10524: # end of not-a-package not-a-library import
1.339 albertel 10525: }
1.172 www 10526: # end of not-a-package start tag
1.339 albertel 10527: }
1.172 www 10528: # the next is the end of "start tag"
1.339 albertel 10529: }
10530: }
1.483 albertel 10531: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10532: $extension = lc($extension);
10533: if ($extension eq 'htm') { $extension='html'; }
10534:
1.737 albertel 10535: foreach my $key (keys(%packagetab)) {
1.483 albertel 10536: #no specific packages #how's our extension
10537: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10538: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10539: \%metathesekeys);
10540: }
1.883 albertel 10541:
10542: if (!exists($metaentry{':packages'})
10543: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10544: foreach my $key (keys(%packagetab)) {
1.483 albertel 10545: #no specific packages well let's get default then
10546: if ($key!~/^default&/) { next; }
1.488 albertel 10547: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10548: \%metathesekeys);
10549: }
10550: }
1.338 www 10551: # are there custom rights to evaluate
1.599 albertel 10552: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10553:
1.338 www 10554: #
10555: # Importing a rights file here
1.339 albertel 10556: #
10557: unless ($depthcount) {
1.599 albertel 10558: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10559: my $dir=$filename;
10560: $dir=~s|[^/]*$||;
10561: $location=&filelocation($dir,$location);
1.736 albertel 10562: my $rights_metadata =
10563: &metadata($uri,'keys',$location,'_rights',
10564: $depthcount+1);
10565: foreach my $rights (split(',',$rights_metadata)) {
10566: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10567: $metathesekeys{$rights}=1;
1.339 albertel 10568: }
10569: }
10570: }
1.737 albertel 10571: # uniqifiy package listing
10572: my %seen;
10573: my @uniq_packages =
10574: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10575: $metaentry{':packages'} = join(',',@uniq_packages);
10576:
1.1070 www 10577: if ($importedparts) {
10578: # We had imported parts and need to rebuild partorder
10579: $metaentry{':partorder'}='';
10580: $metathesekeys{'partorder'}=1;
10581: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10582: if ($origfileimportpartids[$index] eq 'part') {
10583: # original part, part of the problem
10584: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10585: } else {
10586: # we have imported parts at this position
10587: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10588: }
10589: }
10590: $metaentry{':partorder'}=~s/^\,//;
10591: }
10592:
1.737 albertel 10593: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10594: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 10595: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10596: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10597: # this is the end of "was not already recently cached
1.71 www 10598: }
1.599 albertel 10599: return $metaentry{':'.$what};
1.261 albertel 10600: }
10601:
1.488 albertel 10602: sub metadata_create_package_def {
1.483 albertel 10603: my ($uri,$key,$package,$metathesekeys)=@_;
10604: my ($pack,$name,$subp)=split(/\&/,$key);
10605: if ($subp eq 'default') { next; }
10606:
1.599 albertel 10607: if (defined($metaentry{':packages'})) {
10608: $metaentry{':packages'}.=','.$package;
1.483 albertel 10609: } else {
1.599 albertel 10610: $metaentry{':packages'}=$package;
1.483 albertel 10611: }
10612: my $value=$packagetab{$key};
10613: my $unikey;
10614: $unikey='parameter_0_'.$name;
1.599 albertel 10615: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10616: $$metathesekeys{$unikey}=1;
1.599 albertel 10617: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10618: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10619: }
1.599 albertel 10620: if (defined($metaentry{':'.$unikey.'.default'})) {
10621: $metaentry{':'.$unikey}=
10622: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10623: }
10624: }
10625:
1.261 albertel 10626: sub metadata_generate_part0 {
10627: my ($metadata,$metacache,$uri) = @_;
10628: my %allnames;
1.737 albertel 10629: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10630: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10631: my $part=$$metacache{':'.$metakey.'.part'};
10632: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10633: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10634: $allnames{$name}=$part;
10635: }
10636: }
10637: }
10638: foreach my $name (keys(%allnames)) {
10639: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10640: my $key=":parameter_0_$name";
1.261 albertel 10641: $$metacache{"$key.part"}='0';
10642: $$metacache{"$key.name"}=$name;
1.428 albertel 10643: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10644: $allnames{$name}.'_'.$name.
10645: '.type'};
1.428 albertel 10646: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10647: '.display'};
1.644 www 10648: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10649: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10650: $$metacache{"$key.display"}=$olddis;
10651: }
1.71 www 10652: }
10653:
1.764 albertel 10654: # ------------------------------------------------------ Devalidate title cache
10655:
10656: sub devalidate_title_cache {
10657: my ($url)=@_;
10658: if (!$env{'request.course.id'}) { return; }
10659: my $symb=&symbread($url);
10660: if (!$symb) { return; }
10661: my $key=$env{'request.course.id'}."\0".$symb;
10662: &devalidate_cache_new('title',$key);
10663: }
10664:
1.1014 droeschl 10665: # ------------------------------------------------- Get the title of a course
10666:
10667: sub current_course_title {
10668: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10669: }
1.301 www 10670: # ------------------------------------------------- Get the title of a resource
10671:
10672: sub gettitle {
10673: my $urlsymb=shift;
10674: my $symb=&symbread($urlsymb);
1.534 albertel 10675: if ($symb) {
1.620 albertel 10676: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10677: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10678: if (defined($cached)) {
10679: return $result;
10680: }
1.534 albertel 10681: my ($map,$resid,$url)=&decode_symb($symb);
10682: my $title='';
1.907 albertel 10683: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10684: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10685: } else {
10686: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10687: &GDBM_READER(),0640)) {
10688: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10689: $title=$bighash{'title_'.$mapid.'.'.$resid};
10690: untie(%bighash);
10691: }
1.534 albertel 10692: }
10693: $title=~s/\&colon\;/\:/gs;
10694: if ($title) {
1.1159 www 10695: # Remember both $symb and $title for dynamic metadata
10696: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10697: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10698: # Cache this title and then return it
1.599 albertel 10699: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10700: }
10701: $urlsymb=$url;
10702: }
10703: my $title=&metadata($urlsymb,'title');
10704: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10705: return $title;
1.301 www 10706: }
1.613 albertel 10707:
1.614 albertel 10708: sub get_slot {
10709: my ($which,$cnum,$cdom)=@_;
10710: if (!$cnum || !$cdom) {
1.790 albertel 10711: (undef,my $courseid)=&whichuser();
1.620 albertel 10712: $cdom=$env{'course.'.$courseid.'.domain'};
10713: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10714: }
1.703 albertel 10715: my $key=join("\0",'slots',$cdom,$cnum,$which);
10716: my %slotinfo;
10717: if (exists($remembered{$key})) {
10718: $slotinfo{$which} = $remembered{$key};
10719: } else {
10720: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10721: &Apache::lonhomework::showhash(%slotinfo);
10722: my ($tmp)=keys(%slotinfo);
10723: if ($tmp=~/^error:/) { return (); }
10724: $remembered{$key} = $slotinfo{$which};
10725: }
1.616 albertel 10726: if (ref($slotinfo{$which}) eq 'HASH') {
10727: return %{$slotinfo{$which}};
10728: }
10729: return $slotinfo{$which};
1.614 albertel 10730: }
1.1150 raeburn 10731:
10732: sub get_reservable_slots {
10733: my ($cnum,$cdom,$uname,$udom) = @_;
10734: my $now = time;
10735: my $reservable_info;
10736: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10737: if (exists($remembered{$key})) {
10738: $reservable_info = $remembered{$key};
10739: } else {
10740: my %resv;
10741: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10742: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10743: $reservable_info = \%resv;
10744: $remembered{$key} = $reservable_info;
10745: }
10746: return $reservable_info;
10747: }
10748:
10749: sub get_course_slots {
10750: my ($cnum,$cdom) = @_;
10751: my $hashid=$cnum.':'.$cdom;
10752: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10753: if (defined($cached)) {
10754: if (ref($result) eq 'HASH') {
10755: return %{$result};
10756: }
10757: } else {
10758: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10759: my ($tmp) = keys(%slots);
10760: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 10761: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10762: return %slots;
10763: }
10764: }
10765: return;
10766: }
10767:
10768: sub devalidate_slots_cache {
10769: my ($cnum,$cdom)=@_;
10770: my $hashid=$cnum.':'.$cdom;
10771: &devalidate_cache_new('allslots',$hashid);
10772: }
10773:
1.1172.2.8 raeburn 10774: sub get_coursechange {
10775: my ($cdom,$cnum) = @_;
10776: if ($cdom eq '' || $cnum eq '') {
10777: return unless ($env{'request.course.id'});
10778: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10779: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10780: }
10781: my $hashid=$cdom.'_'.$cnum;
10782: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10783: if ((defined($cached)) && ($change ne '')) {
10784: return $change;
10785: } else {
10786: my %crshash;
10787: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10788: if ($crshash{'internal.contentchange'} eq '') {
10789: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10790: if ($change eq '') {
10791: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10792: $change = $crshash{'internal.created'};
10793: }
10794: } else {
10795: $change = $crshash{'internal.contentchange'};
10796: }
10797: my $cachetime = 600;
10798: &do_cache_new('crschange',$hashid,$change,$cachetime);
10799: }
10800: return $change;
10801: }
10802:
10803: sub devalidate_coursechange_cache {
10804: my ($cnum,$cdom)=@_;
10805: my $hashid=$cnum.':'.$cdom;
10806: &devalidate_cache_new('crschange',$hashid);
10807: }
10808:
1.31 www 10809: # ------------------------------------------------- Update symbolic store links
10810:
10811: sub symblist {
10812: my ($mapname,%newhash)=@_;
1.438 www 10813: $mapname=&deversion(&declutter($mapname));
1.31 www 10814: my %hash;
1.620 albertel 10815: if (($env{'request.course.fn'}) && (%newhash)) {
10816: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10817: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10818: foreach my $url (keys(%newhash)) {
1.711 albertel 10819: next if ($url eq 'last_known'
10820: && $env{'form.no_update_last_known'});
10821: $hash{declutter($url)}=&encode_symb($mapname,
10822: $newhash{$url}->[1],
10823: $newhash{$url}->[0]);
1.191 harris41 10824: }
1.31 www 10825: if (untie(%hash)) {
10826: return 'ok';
10827: }
10828: }
10829: }
10830: return 'error';
1.212 www 10831: }
10832:
10833: # --------------------------------------------------------------- Verify a symb
10834:
10835: sub symbverify {
1.1172.2.11 raeburn 10836: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10837: my $thisfn=$thisurl;
1.439 www 10838: $thisfn=&declutter($thisfn);
1.215 www 10839: # direct jump to resource in page or to a sequence - will construct own symbs
10840: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10841: # check URL part
1.409 www 10842: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10843:
1.431 www 10844: unless ($url eq $thisfn) { return 0; }
1.213 www 10845:
1.216 www 10846: $symb=&symbclean($symb);
1.510 www 10847: $thisurl=&deversion($thisurl);
1.439 www 10848: $thisfn=&deversion($thisfn);
1.213 www 10849:
10850: my %bighash;
10851: my $okay=0;
1.431 www 10852:
1.620 albertel 10853: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10854: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 10855: my $noclutter;
1.1032 raeburn 10856: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10857: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 10858: if ($map =~ m{^uploaded/.+\.page$}) {
10859: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10860: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10861: $noclutter = 1;
10862: }
10863: }
10864: my $ids;
10865: if ($noclutter) {
10866: $ids=$bighash{'ids_'.$thisurl};
10867: } else {
10868: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10869: }
1.1102 raeburn 10870: unless ($ids) {
1.1172.2.13 raeburn 10871: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 10872: $ids=$bighash{$idkey};
1.216 www 10873: }
10874: if ($ids) {
10875: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 10876: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10877: $symb =~ s/\?.+$//;
10878: }
1.800 albertel 10879: foreach my $id (split(/\,/,$ids)) {
10880: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10881: if (
10882: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 10883: eq $symb) {
1.1172.2.11 raeburn 10884: if (ref($encstate)) {
10885: $$encstate = $bighash{'encrypted_'.$id};
10886: }
1.1172.2.13 raeburn 10887: if (($env{'request.role.adv'}) ||
10888: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 10889: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 10890: $okay=1;
10891: last;
10892: }
10893: }
10894: }
1.216 www 10895: }
1.213 www 10896: untie(%bighash);
10897: }
10898: return $okay;
1.31 www 10899: }
10900:
1.210 www 10901: # --------------------------------------------------------------- Clean-up symb
10902:
10903: sub symbclean {
10904: my $symb=shift;
1.568 albertel 10905: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10906: # remove version from map
10907: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10908:
1.210 www 10909: # remove version from URL
10910: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10911:
1.507 www 10912: # remove wrapper
10913:
1.510 www 10914: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10915: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10916: return $symb;
1.409 www 10917: }
10918:
10919: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10920:
10921: sub encode_symb {
10922: my ($map,$resid,$url)=@_;
10923: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10924: }
1.409 www 10925:
10926: sub decode_symb {
1.568 albertel 10927: my $symb=shift;
10928: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10929: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10930: return (&fixversion($map),$resid,&fixversion($url));
10931: }
10932:
10933: sub fixversion {
10934: my $fn=shift;
1.609 banghart 10935: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10936: my %bighash;
10937: my $uri=&clutter($fn);
1.620 albertel 10938: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10939: # is this cached?
1.599 albertel 10940: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10941: if (defined($cached)) { return $result; }
10942: # unfortunately not cached, or expired
1.620 albertel 10943: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10944: &GDBM_READER(),0640)) {
10945: if ($bighash{'version_'.$uri}) {
10946: my $version=$bighash{'version_'.$uri};
1.444 www 10947: unless (($version eq 'mostrecent') ||
10948: ($version==&getversion($uri))) {
1.440 www 10949: $uri=~s/\.(\w+)$/\.$version\.$1/;
10950: }
10951: }
10952: untie %bighash;
1.413 www 10953: }
1.599 albertel 10954: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10955: }
10956:
10957: sub deversion {
10958: my $url=shift;
10959: $url=~s/\.\d+\.(\w+)$/\.$1/;
10960: return $url;
1.210 www 10961: }
10962:
1.31 www 10963: # ------------------------------------------------------ Return symb list entry
10964:
10965: sub symbread {
1.249 www 10966: my ($thisfn,$donotrecurse)=@_;
1.1172.2.54 raeburn 10967: my $cache_str='request.symbread.cached.'.$thisfn;
10968: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 10969: # no filename provided? try from environment
1.1172.2.54 raeburn 10970: unless ($thisfn) {
1.620 albertel 10971: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 10972: return $env{$cache_str}=&symbclean($env{'request.symb'});
10973: }
10974: $thisfn=$env{'request.filename'};
1.44 www 10975: }
1.569 albertel 10976: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10977: # is that filename actually a symb? Verify, clean, and return
10978: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10979: if (&symbverify($thisfn,$1)) {
1.620 albertel 10980: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10981: }
1.242 www 10982: }
1.44 www 10983: $thisfn=declutter($thisfn);
1.31 www 10984: my %hash;
1.37 www 10985: my %bighash;
10986: my $syval='';
1.620 albertel 10987: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10988: my $targetfn = $thisfn;
1.609 banghart 10989: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10990: $targetfn = 'adm/wrapper/'.$thisfn;
10991: }
1.687 albertel 10992: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10993: $targetfn=$1;
10994: }
1.620 albertel 10995: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10996: &GDBM_READER(),0640)) {
1.481 raeburn 10997: $syval=$hash{$targetfn};
1.37 www 10998: untie(%hash);
10999: }
11000: # ---------------------------------------------------------- There was an entry
11001: if ($syval) {
1.601 albertel 11002: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11003: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11004: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11005: #return $env{$cache_str}='';
1.601 albertel 11006: #}
11007: #$syval.=$1;
11008: #}
1.37 www 11009: } else {
11010: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11011: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11012: &GDBM_READER(),0640)) {
1.37 www 11013: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11014: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11015: unless ($ids) {
11016: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11017: }
11018: unless ($ids) {
11019: # alias?
11020: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11021: }
1.37 www 11022: if ($ids) {
11023: # ------------------------------------------------------------------- Has ID(s)
11024: my @possibilities=split(/\,/,$ids);
1.39 www 11025: if ($#possibilities==0) {
11026: # ----------------------------------------------- There is only one possibility
1.37 www 11027: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11028: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11029: $resid,$thisfn);
1.249 www 11030: } elsif (!$donotrecurse) {
1.39 www 11031: # ------------------------------------------ There is more than one possibility
11032: my $realpossible=0;
1.800 albertel 11033: foreach my $id (@possibilities) {
11034: my $file=$bighash{'src_'.$id};
1.39 www 11035: if (&allowed('bre',$file)) {
1.800 albertel 11036: my ($mapid,$resid)=split(/\./,$id);
1.39 www 11037: if ($bighash{'map_type_'.$mapid} ne 'page') {
11038: $realpossible++;
1.626 albertel 11039: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11040: $resid,$thisfn);
1.39 www 11041: }
11042: }
1.191 harris41 11043: }
1.39 www 11044: if ($realpossible!=1) { $syval=''; }
1.249 www 11045: } else {
11046: $syval='';
1.37 www 11047: }
11048: }
11049: untie(%bighash)
1.481 raeburn 11050: }
1.31 www 11051: }
1.62 www 11052: if ($syval) {
1.620 albertel 11053: return $env{$cache_str}=$syval;
1.62 www 11054: }
1.31 www 11055: }
1.949 raeburn 11056: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11057: return $env{$cache_str}='';
1.31 www 11058: }
11059:
11060: # ---------------------------------------------------------- Return random seed
11061:
1.32 www 11062: sub numval {
11063: my $txt=shift;
11064: $txt=~tr/A-J/0-9/;
11065: $txt=~tr/a-j/0-9/;
11066: $txt=~tr/K-T/0-9/;
11067: $txt=~tr/k-t/0-9/;
11068: $txt=~tr/U-Z/0-5/;
11069: $txt=~tr/u-z/0-5/;
11070: $txt=~s/\D//g;
1.564 albertel 11071: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11072: return int($txt);
1.368 albertel 11073: }
11074:
1.484 albertel 11075: sub numval2 {
11076: my $txt=shift;
11077: $txt=~tr/A-J/0-9/;
11078: $txt=~tr/a-j/0-9/;
11079: $txt=~tr/K-T/0-9/;
11080: $txt=~tr/k-t/0-9/;
11081: $txt=~tr/U-Z/0-5/;
11082: $txt=~tr/u-z/0-5/;
11083: $txt=~s/\D//g;
11084: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11085: my $total;
11086: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11087: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11088: return int($total);
11089: }
11090:
1.575 albertel 11091: sub numval3 {
11092: use integer;
11093: my $txt=shift;
11094: $txt=~tr/A-J/0-9/;
11095: $txt=~tr/a-j/0-9/;
11096: $txt=~tr/K-T/0-9/;
11097: $txt=~tr/k-t/0-9/;
11098: $txt=~tr/U-Z/0-5/;
11099: $txt=~tr/u-z/0-5/;
11100: $txt=~s/\D//g;
11101: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11102: my $total;
11103: foreach my $val (@txts) { $total+=$val; }
11104: if ($_64bit) { $total=(($total<<32)>>32); }
11105: return $total;
11106: }
11107:
1.675 albertel 11108: sub digest {
11109: my ($data)=@_;
11110: my $digest=&Digest::MD5::md5($data);
11111: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11112: my ($e,$f);
11113: {
11114: use integer;
11115: $e=($a+$b);
11116: $f=($c+$d);
11117: if ($_64bit) {
11118: $e=(($e<<32)>>32);
11119: $f=(($f<<32)>>32);
11120: }
11121: }
11122: if (wantarray) {
11123: return ($e,$f);
11124: } else {
11125: my $g;
11126: {
11127: use integer;
11128: $g=($e+$f);
11129: if ($_64bit) {
11130: $g=(($g<<32)>>32);
11131: }
11132: }
11133: return $g;
11134: }
11135: }
11136:
1.368 albertel 11137: sub latest_rnd_algorithm_id {
1.675 albertel 11138: return '64bit5';
1.366 albertel 11139: }
1.32 www 11140:
1.503 albertel 11141: sub get_rand_alg {
11142: my ($courseid)=@_;
1.790 albertel 11143: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11144: if ($courseid) {
1.620 albertel 11145: return $env{"course.$courseid.rndseed"};
1.503 albertel 11146: }
11147: return &latest_rnd_algorithm_id();
11148: }
11149:
1.562 albertel 11150: sub validCODE {
11151: my ($CODE)=@_;
11152: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11153: return 0;
11154: }
11155:
1.491 albertel 11156: sub getCODE {
1.620 albertel 11157: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11158: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11159: defined($Apache::lonhomework::parsing_a_task) ) &&
11160: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11161: return $Apache::lonhomework::history{'resource.CODE'};
11162: }
11163: return undef;
11164: }
1.1133 foxr 11165: #
11166: # Determines the random seed for a specific context:
11167: #
11168: # parameters:
11169: # symb - in course context the symb for the seed.
11170: # course_id - The course id of the form domain_coursenum.
11171: # domain - Domain for the user.
11172: # course - Course for the user.
11173: # cenv - environment of the course.
11174: #
11175: # NOTE:
11176: # All parameters are picked out of the environment if missing
11177: # or not defined.
11178: # If a symb cannot be determined the current time is used instead.
11179: #
11180: # For a given well defined symb, courside, domain, username,
11181: # and course environment, the seed is reproducible.
11182: #
1.31 www 11183: sub rndseed {
1.1133 foxr 11184: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11185: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11186: if (!defined($symb)) {
1.366 albertel 11187: unless ($symb=$wsymb) { return time; }
11188: }
1.1146 foxr 11189: if (!defined $courseid) {
11190: $courseid=$wcourseid;
11191: }
11192: if (!defined $domain) { $domain=$wdomain; }
11193: if (!defined $username) { $username=$wusername }
1.1133 foxr 11194:
11195: my $which;
11196: if (defined($cenv->{'rndseed'})) {
11197: $which = $cenv->{'rndseed'};
11198: } else {
11199: $which =&get_rand_alg($courseid);
11200: }
1.491 albertel 11201: if (defined(&getCODE())) {
1.675 albertel 11202: if ($which eq '64bit5') {
11203: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11204: } elsif ($which eq '64bit4') {
1.575 albertel 11205: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11206: } else {
11207: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11208: }
1.675 albertel 11209: } elsif ($which eq '64bit5') {
11210: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11211: } elsif ($which eq '64bit4') {
11212: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11213: } elsif ($which eq '64bit3') {
11214: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11215: } elsif ($which eq '64bit2') {
11216: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11217: } elsif ($which eq '64bit') {
11218: return &rndseed_64bit($symb,$courseid,$domain,$username);
11219: }
11220: return &rndseed_32bit($symb,$courseid,$domain,$username);
11221: }
11222:
11223: sub rndseed_32bit {
11224: my ($symb,$courseid,$domain,$username)=@_;
11225: {
11226: use integer;
11227: my $symbchck=unpack("%32C*",$symb) << 27;
11228: my $symbseed=numval($symb) << 22;
11229: my $namechck=unpack("%32C*",$username) << 17;
11230: my $nameseed=numval($username) << 12;
11231: my $domainseed=unpack("%32C*",$domain) << 7;
11232: my $courseseed=unpack("%32C*",$courseid);
11233: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11234: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11235: #&logthis("rndseed :$num:$symb");
1.564 albertel 11236: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11237: return $num;
11238: }
11239: }
11240:
11241: sub rndseed_64bit {
11242: my ($symb,$courseid,$domain,$username)=@_;
11243: {
11244: use integer;
11245: my $symbchck=unpack("%32S*",$symb) << 21;
11246: my $symbseed=numval($symb) << 10;
11247: my $namechck=unpack("%32S*",$username);
11248:
11249: my $nameseed=numval($username) << 21;
11250: my $domainseed=unpack("%32S*",$domain) << 10;
11251: my $courseseed=unpack("%32S*",$courseid);
11252:
11253: my $num1=$symbchck+$symbseed+$namechck;
11254: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11255: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11256: #&logthis("rndseed :$num:$symb");
1.564 albertel 11257: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11258: return "$num1,$num2";
1.155 albertel 11259: }
1.366 albertel 11260: }
11261:
1.443 albertel 11262: sub rndseed_64bit2 {
11263: my ($symb,$courseid,$domain,$username)=@_;
11264: {
11265: use integer;
11266: # strings need to be an even # of cahracters long, it it is odd the
11267: # last characters gets thrown away
11268: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11269: my $symbseed=numval($symb) << 10;
11270: my $namechck=unpack("%32S*",$username.' ');
11271:
11272: my $nameseed=numval($username) << 21;
1.501 albertel 11273: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11274: my $courseseed=unpack("%32S*",$courseid.' ');
11275:
11276: my $num1=$symbchck+$symbseed+$namechck;
11277: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11278: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11279: #&logthis("rndseed :$num:$symb");
1.803 albertel 11280: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11281: return "$num1,$num2";
11282: }
11283: }
11284:
11285: sub rndseed_64bit3 {
11286: my ($symb,$courseid,$domain,$username)=@_;
11287: {
11288: use integer;
11289: # strings need to be an even # of cahracters long, it it is odd the
11290: # last characters gets thrown away
11291: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11292: my $symbseed=numval2($symb) << 10;
11293: my $namechck=unpack("%32S*",$username.' ');
11294:
11295: my $nameseed=numval2($username) << 21;
1.443 albertel 11296: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11297: my $courseseed=unpack("%32S*",$courseid.' ');
11298:
11299: my $num1=$symbchck+$symbseed+$namechck;
11300: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11301: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11302: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11303: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11304:
1.503 albertel 11305: return "$num1:$num2";
1.443 albertel 11306: }
11307: }
11308:
1.575 albertel 11309: sub rndseed_64bit4 {
11310: my ($symb,$courseid,$domain,$username)=@_;
11311: {
11312: use integer;
11313: # strings need to be an even # of cahracters long, it it is odd the
11314: # last characters gets thrown away
11315: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11316: my $symbseed=numval3($symb) << 10;
11317: my $namechck=unpack("%32S*",$username.' ');
11318:
11319: my $nameseed=numval3($username) << 21;
11320: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11321: my $courseseed=unpack("%32S*",$courseid.' ');
11322:
11323: my $num1=$symbchck+$symbseed+$namechck;
11324: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11325: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11326: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11327: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11328:
1.575 albertel 11329: return "$num1:$num2";
11330: }
11331: }
11332:
1.675 albertel 11333: sub rndseed_64bit5 {
11334: my ($symb,$courseid,$domain,$username)=@_;
11335: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11336: return "$num1:$num2";
11337: }
11338:
1.366 albertel 11339: sub rndseed_CODE_64bit {
11340: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11341: {
1.366 albertel 11342: use integer;
1.443 albertel 11343: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11344: my $symbseed=numval2($symb);
1.491 albertel 11345: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11346: my $CODEseed=numval(&getCODE());
1.443 albertel 11347: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11348: my $num1=$symbseed+$CODEchck;
11349: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11350: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11351: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11352: if ($_64bit) { $num1=(($num1<<32)>>32); }
11353: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11354: return "$num1:$num2";
1.366 albertel 11355: }
11356: }
11357:
1.575 albertel 11358: sub rndseed_CODE_64bit4 {
11359: my ($symb,$courseid,$domain,$username)=@_;
11360: {
11361: use integer;
11362: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11363: my $symbseed=numval3($symb);
11364: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11365: my $CODEseed=numval3(&getCODE());
11366: my $courseseed=unpack("%32S*",$courseid.' ');
11367: my $num1=$symbseed+$CODEchck;
11368: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11369: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11370: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11371: if ($_64bit) { $num1=(($num1<<32)>>32); }
11372: if ($_64bit) { $num2=(($num2<<32)>>32); }
11373: return "$num1:$num2";
11374: }
11375: }
11376:
1.675 albertel 11377: sub rndseed_CODE_64bit5 {
11378: my ($symb,$courseid,$domain,$username)=@_;
11379: my $code = &getCODE();
11380: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11381: return "$num1:$num2";
11382: }
11383:
1.366 albertel 11384: sub setup_random_from_rndseed {
11385: my ($rndseed)=@_;
1.503 albertel 11386: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 11387: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11388: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11389: &Math::Random::random_set_seed_from_phrase($rndseed);
11390: } else {
11391: &Math::Random::random_set_seed($num1,$num2);
11392: }
1.366 albertel 11393: } else {
11394: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11395: }
1.36 albertel 11396: }
11397:
1.474 albertel 11398: sub latest_receipt_algorithm_id {
1.835 albertel 11399: return 'receipt3';
1.474 albertel 11400: }
11401:
1.480 www 11402: sub recunique {
11403: my $fucourseid=shift;
11404: my $unique;
1.835 albertel 11405: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11406: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11407: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11408: } else {
11409: $unique=$perlvar{'lonReceipt'};
11410: }
11411: return unpack("%32C*",$unique);
11412: }
11413:
11414: sub recprefix {
11415: my $fucourseid=shift;
11416: my $prefix;
1.835 albertel 11417: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11418: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11419: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11420: } else {
11421: $prefix=$perlvar{'lonHostID'};
11422: }
11423: return unpack("%32C*",$prefix);
11424: }
11425:
1.76 www 11426: sub ireceipt {
1.474 albertel 11427: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11428:
11429: my $return =&recprefix($fucourseid).'-';
11430:
11431: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11432: $env{'request.state'} eq 'construct') {
11433: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11434: return $return;
11435: }
11436:
1.76 www 11437: my $cuname=unpack("%32C*",$funame);
11438: my $cudom=unpack("%32C*",$fudom);
11439: my $cucourseid=unpack("%32C*",$fucourseid);
11440: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11441: my $cunique=&recunique($fucourseid);
1.474 albertel 11442: my $cpart=unpack("%32S*",$part);
1.835 albertel 11443: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11444:
1.790 albertel 11445: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11446:
11447: $return.= ($cunique%$cuname+
11448: $cunique%$cudom+
11449: $cusymb%$cuname+
11450: $cusymb%$cudom+
11451: $cucourseid%$cuname+
11452: $cucourseid%$cudom+
11453: $cpart%$cuname+
11454: $cpart%$cudom);
11455: } else {
11456: $return.= ($cunique%$cuname+
11457: $cunique%$cudom+
11458: $cusymb%$cuname+
11459: $cusymb%$cudom+
11460: $cucourseid%$cuname+
11461: $cucourseid%$cudom);
11462: }
11463: return $return;
1.76 www 11464: }
11465:
11466: sub receipt {
1.474 albertel 11467: my ($part)=@_;
1.790 albertel 11468: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11469: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11470: }
1.260 ng 11471:
1.790 albertel 11472: sub whichuser {
11473: my ($passedsymb)=@_;
11474: my ($symb,$courseid,$domain,$name,$publicuser);
11475: if (defined($env{'form.grade_symb'})) {
11476: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11477: my $allowed=&allowed('vgr',$tmp_courseid);
11478: if (!$allowed &&
11479: exists($env{'request.course.sec'}) &&
11480: $env{'request.course.sec'} !~ /^\s*$/) {
11481: $allowed=&allowed('vgr',$tmp_courseid.
11482: '/'.$env{'request.course.sec'});
11483: }
11484: if ($allowed) {
11485: ($symb)=&get_env_multiple('form.grade_symb');
11486: $courseid=$tmp_courseid;
11487: ($domain)=&get_env_multiple('form.grade_domain');
11488: ($name)=&get_env_multiple('form.grade_username');
11489: return ($symb,$courseid,$domain,$name,$publicuser);
11490: }
11491: }
11492: if (!$passedsymb) {
11493: $symb=&symbread();
11494: } else {
11495: $symb=$passedsymb;
11496: }
11497: $courseid=$env{'request.course.id'};
11498: $domain=$env{'user.domain'};
11499: $name=$env{'user.name'};
11500: if ($name eq 'public' && $domain eq 'public') {
11501: if (!defined($env{'form.username'})) {
11502: $env{'form.username'}.=time.rand(10000000);
11503: }
11504: $name.=$env{'form.username'};
11505: }
11506: return ($symb,$courseid,$domain,$name,$publicuser);
11507:
11508: }
11509:
1.36 albertel 11510: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11511: # returns either the contents of the file or
11512: # -1 if the file doesn't exist
1.481 raeburn 11513: #
11514: # if the target is a file that was uploaded via DOCS,
11515: # a check will be made to see if a current copy exists on the local server,
11516: # if it does this will be served, otherwise a copy will be retrieved from
11517: # the home server for the course and stored in /home/httpd/html/userfiles on
11518: # the local server.
1.472 albertel 11519:
1.36 albertel 11520: sub getfile {
1.538 albertel 11521: my ($file) = @_;
1.609 banghart 11522: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11523: &repcopy($file);
11524: return &readfile($file);
11525: }
11526:
11527: sub repcopy_userfile {
11528: my ($file)=@_;
1.1142 raeburn 11529: my $londocroot = $perlvar{'lonDocRoot'};
11530: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11531: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11532: my ($cdom,$cnum,$filename) =
1.811 albertel 11533: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11534: my $uri="/uploaded/$cdom/$cnum/$filename";
11535: if (-e "$file") {
1.828 www 11536: # we already have a local copy, check it out
1.538 albertel 11537: my @fileinfo = stat($file);
1.828 www 11538: my $rtncode;
11539: my $info;
1.538 albertel 11540: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11541: if ($lwpresp ne 'ok') {
1.828 www 11542: # there is no such file anymore, even though we had a local copy
1.482 albertel 11543: if ($rtncode eq '404') {
1.538 albertel 11544: unlink($file);
1.482 albertel 11545: }
11546: return -1;
11547: }
11548: if ($info < $fileinfo[9]) {
1.828 www 11549: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11550: return 'ok';
1.828 www 11551: } else {
11552: # the file is outdated, get rid of it
11553: unlink($file);
1.482 albertel 11554: }
1.828 www 11555: }
11556: # one way or the other, at this point, we don't have the file
11557: # construct the correct path for the file
11558: my @parts = ($cdom,$cnum);
11559: if ($filename =~ m|^(.+)/[^/]+$|) {
11560: push @parts, split(/\//,$1);
11561: }
11562: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11563: foreach my $part (@parts) {
11564: $path .= '/'.$part;
11565: if (!-e $path) {
11566: mkdir($path,0770);
1.482 albertel 11567: }
11568: }
1.828 www 11569: # now the path exists for sure
11570: # get a user agent
11571: my $ua=new LWP::UserAgent;
11572: my $transferfile=$file.'.in.transfer';
11573: # FIXME: this should flock
11574: if (-e $transferfile) { return 'ok'; }
11575: my $request;
11576: $uri=~s/^\///;
1.980 raeburn 11577: my $homeserver = &homeserver($cnum,$cdom);
11578: my $protocol = $protocol{$homeserver};
11579: $protocol = 'http' if ($protocol ne 'https');
11580: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11581: my $response=$ua->request($request,$transferfile);
11582: # did it work?
11583: if ($response->is_error()) {
11584: unlink($transferfile);
11585: &logthis("Userfile repcopy failed for $uri");
11586: return -1;
11587: }
11588: # worked, rename the transfer file
11589: rename($transferfile,$file);
1.607 raeburn 11590: return 'ok';
1.481 raeburn 11591: }
11592:
1.517 albertel 11593: sub tokenwrapper {
11594: my $uri=shift;
1.980 raeburn 11595: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11596: $uri=~s|^/||;
1.620 albertel 11597: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11598: my $token=$1;
1.552 albertel 11599: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11600: if ($udom && $uname && $file) {
11601: $file=~s|(\?\.*)*$||;
1.949 raeburn 11602: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11603: my $homeserver = &homeserver($uname,$udom);
11604: my $protocol = $protocol{$homeserver};
11605: $protocol = 'http' if ($protocol ne 'https');
11606: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11607: (($uri=~/\?/)?'&':'?').'token='.$token.
11608: '&tokenissued='.$perlvar{'lonHostID'};
11609: } else {
11610: return '/adm/notfound.html';
11611: }
11612: }
11613:
1.828 www 11614: # call with reqtype HEAD: get last modification time
11615: # call with reqtype GET: get the file contents
11616: # Do not call this with reqtype GET for large files! It loads everything into memory
11617: #
1.481 raeburn 11618: sub getuploaded {
11619: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11620: $uri=~s/^\///;
1.980 raeburn 11621: my $homeserver = &homeserver($cnum,$cdom);
11622: my $protocol = $protocol{$homeserver};
11623: $protocol = 'http' if ($protocol ne 'https');
11624: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11625: my $ua=new LWP::UserAgent;
11626: my $request=new HTTP::Request($reqtype,$uri);
11627: my $response=$ua->request($request);
11628: $$rtncode = $response->code;
1.482 albertel 11629: if (! $response->is_success()) {
11630: return 'failed';
11631: }
11632: if ($reqtype eq 'HEAD') {
1.486 www 11633: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11634: } elsif ($reqtype eq 'GET') {
11635: $$info = $response->content;
1.472 albertel 11636: }
1.482 albertel 11637: return 'ok';
1.36 albertel 11638: }
11639:
1.481 raeburn 11640: sub readfile {
11641: my $file = shift;
11642: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11643: my $fh;
11644: open($fh,"<$file");
11645: my $a='';
1.800 albertel 11646: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11647: return $a;
11648: }
11649:
1.36 albertel 11650: sub filelocation {
1.590 banghart 11651: my ($dir,$file) = @_;
11652: my $location;
11653: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11654:
11655: if ($file =~ m-^/adm/-) {
11656: $file=~s-^/adm/wrapper/-/-;
11657: $file=~s-^/adm/coursedocs/showdoc/-/-;
11658: }
1.882 albertel 11659:
1.1139 www 11660: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11661: $location = $file;
1.609 banghart 11662: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11663: my ($udom,$uname,$filename)=
1.811 albertel 11664: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11665: my $home=&homeserver($uname,$udom);
11666: my $is_me=0;
11667: my @ids=¤t_machine_ids();
11668: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11669: if ($is_me) {
1.1117 foxr 11670: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11671: } else {
11672: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11673: $udom.'/'.$uname.'/'.$filename;
11674: }
1.882 albertel 11675: } elsif ($file =~ m-^/adm/-) {
11676: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11677: } else {
11678: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11679: $file=~s:^/(res|priv)/:/:;
11680: my $space=$1;
1.590 banghart 11681: if ( !( $file =~ m:^/:) ) {
11682: $location = $dir. '/'.$file;
11683: } else {
1.1142 raeburn 11684: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11685: }
1.59 albertel 11686: }
1.590 banghart 11687: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11688: while ($location=~m{/\.\./}) {
11689: if ($location =~ m{/[^/]+/\.\./}) {
11690: $location=~ s{/[^/]+/\.\./}{/}g;
11691: } else {
11692: $location=~ s{/\.\./}{/}g;
11693: }
11694: } #remove dir/..
1.590 banghart 11695: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11696: return $location;
1.46 www 11697: }
1.36 albertel 11698:
1.46 www 11699: sub hreflocation {
11700: my ($dir,$file)=@_;
1.980 raeburn 11701: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11702: $file=filelocation($dir,$file);
1.700 albertel 11703: } elsif ($file=~m-^/adm/-) {
11704: $file=~s-^/adm/wrapper/-/-;
11705: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11706: }
11707: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11708: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11709: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11710: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11711: {/uploaded/$1/$2/}x;
1.46 www 11712: }
1.913 albertel 11713: if ($file=~ m{^/userfiles/}) {
11714: $file =~ s{^/userfiles/}{/uploaded/};
11715: }
1.462 albertel 11716: return $file;
1.465 albertel 11717: }
11718:
1.1139 www 11719:
11720:
11721:
11722:
1.465 albertel 11723: sub current_machine_domains {
1.853 albertel 11724: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11725: }
11726:
11727: sub machine_domains {
11728: my ($hostname) = @_;
1.465 albertel 11729: my @domains;
1.838 albertel 11730: my %hostname = &all_hostnames();
1.465 albertel 11731: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11732: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11733: if ($hostname eq $name) {
1.844 albertel 11734: push(@domains,&host_domain($id));
1.465 albertel 11735: }
11736: }
11737: return @domains;
11738: }
11739:
11740: sub current_machine_ids {
1.853 albertel 11741: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11742: }
11743:
11744: sub machine_ids {
11745: my ($hostname) = @_;
11746: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11747: my @ids;
1.888 albertel 11748: my %name_to_host = &all_names();
1.889 albertel 11749: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11750: return @{ $name_to_host{$hostname} };
11751: }
11752: return;
1.31 www 11753: }
11754:
1.824 raeburn 11755: sub additional_machine_domains {
11756: my @domains;
11757: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11758: while( my $line = <$fh>) {
11759: $line =~ s/\s//g;
11760: push(@domains,$line);
11761: }
11762: return @domains;
11763: }
11764:
11765: sub default_login_domain {
11766: my $domain = $perlvar{'lonDefDomain'};
11767: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11768: foreach my $posdom (¤t_machine_domains(),
11769: &additional_machine_domains()) {
11770: if (lc($posdom) eq lc($testdomain)) {
11771: $domain=$posdom;
11772: last;
11773: }
11774: }
11775: return $domain;
11776: }
11777:
1.31 www 11778: # ------------------------------------------------------------- Declutters URLs
11779:
11780: sub declutter {
11781: my $thisfn=shift;
1.569 albertel 11782: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 11783: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
11784: $thisfn=~s{^/home/httpd/html}{};
11785: }
1.31 www 11786: $thisfn=~s/^\///;
1.697 albertel 11787: $thisfn=~s|^adm/wrapper/||;
11788: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11789: $thisfn=~s/^res\///;
1.1172 bisitz 11790: $thisfn=~s/^priv\///;
1.1032 raeburn 11791: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11792: $thisfn=~s/\?.+$//;
11793: }
1.268 www 11794: return $thisfn;
11795: }
11796:
11797: # ------------------------------------------------------------- Clutter up URLs
11798:
11799: sub clutter {
11800: my $thisfn='/'.&declutter(shift);
1.887 albertel 11801: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11802: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11803: $thisfn='/res'.$thisfn;
11804: }
1.1031 raeburn 11805: if ($thisfn !~m|^/adm|) {
11806: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11807: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11808: } else {
11809: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11810: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11811: if ($embstyle eq 'ssi'
11812: || ($embstyle eq 'hdn')
11813: || ($embstyle eq 'rat')
11814: || ($embstyle eq 'prv')
11815: || ($embstyle eq 'ign')) {
11816: #do nothing with these
11817: } elsif (($embstyle eq 'img')
1.695 albertel 11818: || ($embstyle eq 'emb')
11819: || ($embstyle eq 'wrp')) {
11820: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11821: } elsif ($embstyle eq 'unk'
11822: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11823: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11824: } else {
1.718 www 11825: # &logthis("Got a blank emb style");
1.695 albertel 11826: }
1.694 albertel 11827: }
11828: }
1.31 www 11829: return $thisfn;
1.12 www 11830: }
11831:
1.787 albertel 11832: sub clutter_with_no_wrapper {
11833: my $uri = &clutter(shift);
11834: if ($uri =~ m-^/adm/-) {
11835: $uri =~ s-^/adm/wrapper/-/-;
11836: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11837: }
11838: return $uri;
11839: }
11840:
1.557 albertel 11841: sub freeze_escape {
11842: my ($value)=@_;
11843: if (ref($value)) {
11844: $value=&nfreeze($value);
11845: return '__FROZEN__'.&escape($value);
11846: }
11847: return &escape($value);
11848: }
11849:
1.11 www 11850:
1.557 albertel 11851: sub thaw_unescape {
11852: my ($value)=@_;
11853: if ($value =~ /^__FROZEN__/) {
11854: substr($value,0,10,undef);
11855: $value=&unescape($value);
11856: return &thaw($value);
11857: }
11858: return &unescape($value);
11859: }
11860:
1.436 albertel 11861: sub correct_line_ends {
11862: my ($result)=@_;
11863: $$result =~s/\r\n/\n/mg;
11864: $$result =~s/\r/\n/mg;
1.415 albertel 11865: }
1.1 albertel 11866: # ================================================================ Main Program
11867:
1.184 www 11868: sub goodbye {
1.204 albertel 11869: &logthis("Starting Shut down");
1.443 albertel 11870: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11871: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11872: #converted
1.599 albertel 11873: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11874: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11875: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11876: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11877: #1.1 only
1.870 albertel 11878: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11879: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11880: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11881: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11882: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11883: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11884: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11885: &flushcourselogs();
11886: &logthis("Shutting down");
11887: }
11888:
1.852 albertel 11889: sub get_dns {
1.1172.2.17 raeburn 11890: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11891: if (!$ignore_cache) {
11892: my ($content,$cached)=
11893: &Apache::lonnet::is_cached_new('dns',$url);
11894: if ($cached) {
1.1172.2.17 raeburn 11895: &$func($content,$hashref);
1.869 albertel 11896: return;
11897: }
11898: }
11899:
11900: my %alldns;
1.852 albertel 11901: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11902: foreach my $dns (<$config>) {
11903: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11904: my $line = $1;
11905: my ($host,$protocol) = split(/:/,$line);
11906: if ($protocol ne 'https') {
11907: $protocol = 'http';
11908: }
11909: $alldns{$host} = $protocol;
1.869 albertel 11910: }
11911: while (%alldns) {
1.1172.2.52 raeburn 11912: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 11913: my $ua=new LWP::UserAgent;
1.1134 raeburn 11914: $ua->timeout(30);
1.979 raeburn 11915: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11916: my $response=$ua->request($request);
1.979 raeburn 11917: delete($alldns{$dns});
1.852 albertel 11918: next if ($response->is_error());
11919: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 11920: unless ($nocache) {
1.1172.2.23 raeburn 11921: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 11922: }
11923: &$func(\@content,$hashref);
1.869 albertel 11924: return;
1.852 albertel 11925: }
11926: close($config);
1.871 albertel 11927: my $which = (split('/',$url))[3];
11928: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11929: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11930: my @content = <$config>;
1.1172.2.17 raeburn 11931: &$func(\@content,$hashref);
11932: return;
11933: }
11934:
11935: # ------------------------------------------------------Get DNS checksums file
11936: sub parse_dns_checksums_tab {
11937: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 11938: my $lonhost = $perlvar{'lonHostID'};
11939: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 11940: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 11941: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
11942: my $webconfdir = '/etc/httpd/conf';
11943: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
11944: $webconfdir = '/etc/apache2';
11945: } elsif ($distro =~ /^sles(\d+)$/) {
11946: if ($1 >= 10) {
11947: $webconfdir = '/etc/apache2';
11948: }
11949: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
11950: if ($1 >= 10.0) {
11951: $webconfdir = '/etc/apache2';
11952: }
11953: }
1.1172.2.17 raeburn 11954: my ($release,$timestamp) = split(/\-/,$loncaparev);
11955: my (%chksum,%revnum);
11956: if (ref($lines) eq 'ARRAY') {
11957: chomp(@{$lines});
1.1172.2.34 raeburn 11958: my $version = shift(@{$lines});
11959: if ($version eq $release) {
1.1172.2.17 raeburn 11960: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 11961: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 11962: if ($file =~ m{^/etc/httpd/conf}) {
11963: if ($webconfdir eq '/etc/apache2') {
11964: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
11965: }
11966: }
1.1172.2.34 raeburn 11967: $chksum{$file} = $shasum;
11968: $revnum{$file} = $version;
1.1172.2.17 raeburn 11969: }
11970: if (ref($hashref) eq 'HASH') {
11971: %{$hashref} = (
11972: sums => \%chksum,
11973: versions => \%revnum,
11974: );
11975: }
11976: }
11977: }
1.869 albertel 11978: return;
1.852 albertel 11979: }
1.1172.2.17 raeburn 11980:
11981: sub fetch_dns_checksums {
11982: my %checksums;
1.1172.2.34 raeburn 11983: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 11984: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 11985: my ($release,$timestamp) = split(/\-/,$loncaparev);
11986: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 11987: \%checksums);
11988: return \%checksums;
11989: }
11990:
1.327 albertel 11991: # ------------------------------------------------------------ Read domain file
11992: {
1.852 albertel 11993: my $loaded;
1.846 albertel 11994: my %domain;
11995:
1.852 albertel 11996: sub parse_domain_tab {
11997: my ($lines) = @_;
11998: foreach my $line (@$lines) {
11999: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12000:
1.846 albertel 12001: chomp($line);
1.852 albertel 12002: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12003: my %this_domain;
12004: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12005: 'lang_def', 'city', 'longi', 'lati',
12006: 'primary') {
12007: $this_domain{$field} = shift(@elements);
12008: }
12009: $domain{$name} = \%this_domain;
1.852 albertel 12010: }
12011: }
1.864 albertel 12012:
12013: sub reset_domain_info {
12014: undef($loaded);
12015: undef(%domain);
12016: }
12017:
1.852 albertel 12018: sub load_domain_tab {
1.869 albertel 12019: my ($ignore_cache) = @_;
12020: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 12021: my $fh;
12022: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12023: my @lines = <$fh>;
12024: &parse_domain_tab(\@lines);
1.448 albertel 12025: }
1.852 albertel 12026: close($fh);
12027: $loaded = 1;
1.327 albertel 12028: }
1.846 albertel 12029:
12030: sub domain {
1.852 albertel 12031: &load_domain_tab() if (!$loaded);
12032:
1.846 albertel 12033: my ($name,$what) = @_;
12034: return if ( !exists($domain{$name}) );
12035:
12036: if (!$what) {
12037: return $domain{$name}{'description'};
12038: }
12039: return $domain{$name}{$what};
12040: }
1.974 raeburn 12041:
12042: sub domain_info {
12043: &load_domain_tab() if (!$loaded);
12044: return %domain;
12045: }
12046:
1.327 albertel 12047: }
12048:
12049:
1.1 albertel 12050: # ------------------------------------------------------------- Read hosts file
12051: {
1.838 albertel 12052: my %hostname;
1.844 albertel 12053: my %hostdom;
1.845 albertel 12054: my %libserv;
1.852 albertel 12055: my $loaded;
1.888 albertel 12056: my %name_to_host;
1.1074 raeburn 12057: my %internetdom;
1.1107 raeburn 12058: my %LC_dns_serv;
1.852 albertel 12059:
12060: sub parse_hosts_tab {
12061: my ($file) = @_;
12062: foreach my $configline (@$file) {
12063: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12064: chomp($configline);
12065: if ($configline =~ /^\^/) {
12066: if ($configline =~ /^\^([\w.\-]+)/) {
12067: $LC_dns_serv{$1} = 1;
12068: }
12069: next;
12070: }
1.1074 raeburn 12071: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12072: $name=~s/\s//g;
12073: if ($id && $domain && $role && $name) {
12074: $hostname{$id}=$name;
1.888 albertel 12075: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12076: $hostdom{$id}=$domain;
12077: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12078: if (defined($protocol)) {
12079: if ($protocol eq 'https') {
12080: $protocol{$id} = $protocol;
12081: } else {
12082: $protocol{$id} = 'http';
12083: }
1.968 raeburn 12084: } else {
1.969 raeburn 12085: $protocol{$id} = 'http';
1.968 raeburn 12086: }
1.1074 raeburn 12087: if (defined($intdom)) {
12088: $internetdom{$id} = $intdom;
12089: }
1.852 albertel 12090: }
12091: }
12092: }
1.864 albertel 12093:
12094: sub reset_hosts_info {
1.897 albertel 12095: &purge_remembered();
1.864 albertel 12096: &reset_domain_info();
12097: &reset_hosts_ip_info();
1.892 albertel 12098: undef(%name_to_host);
1.864 albertel 12099: undef(%hostname);
12100: undef(%hostdom);
12101: undef(%libserv);
12102: undef($loaded);
12103: }
1.1 albertel 12104:
1.852 albertel 12105: sub load_hosts_tab {
1.869 albertel 12106: my ($ignore_cache) = @_;
12107: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 12108: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12109: my @config = <$config>;
12110: &parse_hosts_tab(\@config);
12111: close($config);
12112: $loaded=1;
1.1 albertel 12113: }
1.852 albertel 12114:
1.838 albertel 12115: sub hostname {
1.852 albertel 12116: &load_hosts_tab() if (!$loaded);
12117:
1.838 albertel 12118: my ($lonid) = @_;
12119: return $hostname{$lonid};
12120: }
1.845 albertel 12121:
1.838 albertel 12122: sub all_hostnames {
1.852 albertel 12123: &load_hosts_tab() if (!$loaded);
12124:
1.838 albertel 12125: return %hostname;
12126: }
1.845 albertel 12127:
1.888 albertel 12128: sub all_names {
12129: &load_hosts_tab() if (!$loaded);
12130:
12131: return %name_to_host;
12132: }
12133:
1.974 raeburn 12134: sub all_host_domain {
12135: &load_hosts_tab() if (!$loaded);
12136: return %hostdom;
12137: }
12138:
1.845 albertel 12139: sub is_library {
1.852 albertel 12140: &load_hosts_tab() if (!$loaded);
12141:
1.845 albertel 12142: return exists($libserv{$_[0]});
12143: }
12144:
12145: sub all_library {
1.852 albertel 12146: &load_hosts_tab() if (!$loaded);
12147:
1.845 albertel 12148: return %libserv;
12149: }
12150:
1.1062 droeschl 12151: sub unique_library {
12152: #2x reverse removes all hostnames that appear more than once
12153: my %unique = reverse &all_library();
12154: return reverse %unique;
12155: }
12156:
1.841 albertel 12157: sub get_servers {
1.852 albertel 12158: &load_hosts_tab() if (!$loaded);
12159:
1.841 albertel 12160: my ($domain,$type) = @_;
12161: my %possible_hosts = ($type eq 'library') ? %libserv
12162: : %hostname;
12163: my %result;
1.842 albertel 12164: if (ref($domain) eq 'ARRAY') {
12165: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12166: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12167: $result{$host} = $hostname;
12168: }
12169: }
12170: } else {
12171: while ( my ($host,$hostname) = each(%possible_hosts)) {
12172: if ($hostdom{$host} eq $domain) {
12173: $result{$host} = $hostname;
12174: }
1.841 albertel 12175: }
12176: }
12177: return %result;
12178: }
1.845 albertel 12179:
1.1062 droeschl 12180: sub get_unique_servers {
12181: my %unique = reverse &get_servers(@_);
12182: return reverse %unique;
12183: }
12184:
1.844 albertel 12185: sub host_domain {
1.852 albertel 12186: &load_hosts_tab() if (!$loaded);
12187:
1.844 albertel 12188: my ($lonid) = @_;
12189: return $hostdom{$lonid};
12190: }
12191:
1.841 albertel 12192: sub all_domains {
1.852 albertel 12193: &load_hosts_tab() if (!$loaded);
12194:
1.841 albertel 12195: my %seen;
12196: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12197: return @uniq;
12198: }
1.1074 raeburn 12199:
12200: sub internet_dom {
12201: &load_hosts_tab() if (!$loaded);
12202:
12203: my ($lonid) = @_;
12204: return $internetdom{$lonid};
12205: }
1.1107 raeburn 12206:
12207: sub is_LC_dns {
12208: &load_hosts_tab() if (!$loaded);
12209:
12210: my ($hostname) = @_;
12211: return exists($LC_dns_serv{$hostname});
12212: }
12213:
1.1 albertel 12214: }
12215:
1.847 albertel 12216: {
12217: my %iphost;
1.856 albertel 12218: my %name_to_ip;
12219: my %lonid_to_ip;
1.869 albertel 12220:
1.847 albertel 12221: sub get_hosts_from_ip {
12222: my ($ip) = @_;
12223: my %iphosts = &get_iphost();
12224: if (ref($iphosts{$ip})) {
12225: return @{$iphosts{$ip}};
12226: }
12227: return;
1.839 albertel 12228: }
1.864 albertel 12229:
12230: sub reset_hosts_ip_info {
12231: undef(%iphost);
12232: undef(%name_to_ip);
12233: undef(%lonid_to_ip);
12234: }
1.856 albertel 12235:
12236: sub get_host_ip {
12237: my ($lonid) = @_;
12238: if (exists($lonid_to_ip{$lonid})) {
12239: return $lonid_to_ip{$lonid};
12240: }
12241: my $name=&hostname($lonid);
12242: my $ip = gethostbyname($name);
12243: return if (!$ip || length($ip) ne 4);
12244: $ip=inet_ntoa($ip);
12245: $name_to_ip{$name} = $ip;
12246: $lonid_to_ip{$lonid} = $ip;
12247: return $ip;
12248: }
1.847 albertel 12249:
12250: sub get_iphost {
1.869 albertel 12251: my ($ignore_cache) = @_;
1.894 albertel 12252:
1.869 albertel 12253: if (!$ignore_cache) {
12254: if (%iphost) {
12255: return %iphost;
12256: }
12257: my ($ip_info,$cached)=
12258: &Apache::lonnet::is_cached_new('iphost','iphost');
12259: if ($cached) {
12260: %iphost = %{$ip_info->[0]};
12261: %name_to_ip = %{$ip_info->[1]};
12262: %lonid_to_ip = %{$ip_info->[2]};
12263: return %iphost;
12264: }
12265: }
1.894 albertel 12266:
12267: # get yesterday's info for fallback
12268: my %old_name_to_ip;
12269: my ($ip_info,$cached)=
12270: &Apache::lonnet::is_cached_new('iphost','iphost');
12271: if ($cached) {
12272: %old_name_to_ip = %{$ip_info->[1]};
12273: }
12274:
1.888 albertel 12275: my %name_to_host = &all_names();
12276: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12277: my $ip;
12278: if (!exists($name_to_ip{$name})) {
12279: $ip = gethostbyname($name);
12280: if (!$ip || length($ip) ne 4) {
1.894 albertel 12281: if (defined($old_name_to_ip{$name})) {
12282: $ip = $old_name_to_ip{$name};
12283: &logthis("Can't find $name defaulting to old $ip");
12284: } else {
12285: &logthis("Name $name no IP found");
12286: next;
12287: }
12288: } else {
12289: $ip=inet_ntoa($ip);
1.847 albertel 12290: }
12291: $name_to_ip{$name} = $ip;
12292: } else {
12293: $ip = $name_to_ip{$name};
1.653 albertel 12294: }
1.888 albertel 12295: foreach my $id (@{ $name_to_host{$name} }) {
12296: $lonid_to_ip{$id} = $ip;
12297: }
12298: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12299: }
1.1172.2.23 raeburn 12300: &do_cache_new('iphost','iphost',
12301: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12302: 48*60*60);
1.869 albertel 12303:
1.847 albertel 12304: return %iphost;
1.598 albertel 12305: }
12306:
1.992 raeburn 12307: #
12308: # Given a DNS returns the loncapa host name for that DNS
12309: #
12310: sub host_from_dns {
12311: my ($dns) = @_;
12312: my @hosts;
12313: my $ip;
12314:
1.993 raeburn 12315: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12316: $ip = $name_to_ip{$dns};
12317: }
12318: if (!$ip) {
12319: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12320: if (length($ip) == 4) {
12321: $ip = &IO::Socket::inet_ntoa($ip);
12322: }
12323: }
12324: if ($ip) {
12325: @hosts = get_hosts_from_ip($ip);
12326: return $hosts[0];
12327: }
12328: return undef;
1.986 foxr 12329: }
1.992 raeburn 12330:
1.1074 raeburn 12331: sub get_internet_names {
12332: my ($lonid) = @_;
12333: return if ($lonid eq '');
12334: my ($idnref,$cached)=
12335: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12336: if ($cached) {
12337: return $idnref;
12338: }
12339: my $ip = &get_host_ip($lonid);
12340: my @hosts = &get_hosts_from_ip($ip);
12341: my %iphost = &get_iphost();
12342: my (@idns,%seen);
12343: foreach my $id (@hosts) {
12344: my $dom = &host_domain($id);
12345: my $prim_id = &domain($dom,'primary');
12346: my $prim_ip = &get_host_ip($prim_id);
12347: next if ($seen{$prim_ip});
12348: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12349: foreach my $id (@{$iphost{$prim_ip}}) {
12350: my $intdom = &internet_dom($id);
12351: unless (grep(/^\Q$intdom\E$/,@idns)) {
12352: push(@idns,$intdom);
12353: }
12354: }
12355: }
12356: $seen{$prim_ip} = 1;
12357: }
1.1172.2.23 raeburn 12358: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12359: }
12360:
1.986 foxr 12361: }
12362:
1.1079 raeburn 12363: sub all_loncaparevs {
1.1172.2.39 raeburn 12364: 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 12365: }
12366:
1.1172.2.27 raeburn 12367: # ------------------------------------------------------- Read loncaparev table
12368: {
12369: sub load_loncaparevs {
12370: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12371: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12372: while (my $configline=<$config>) {
12373: chomp($configline);
12374: my ($hostid,$loncaparev)=split(/:/,$configline);
12375: $loncaparevs{$hostid}=$loncaparev;
12376: }
12377: close($config);
12378: }
12379: }
12380: }
12381: }
12382:
12383: # ----------------------------------------------------- Read serverhostID table
12384: {
12385: sub load_serverhomeIDs {
12386: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12387: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12388: while (my $configline=<$config>) {
12389: chomp($configline);
12390: my ($name,$id)=split(/:/,$configline);
12391: $serverhomeIDs{$name}=$id;
12392: }
12393: close($config);
12394: }
12395: }
12396: }
12397: }
12398:
12399:
1.862 albertel 12400: BEGIN {
12401:
12402: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12403: unless ($readit) {
12404: {
12405: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12406: %perlvar = (%perlvar,%{$configvars});
12407: }
12408:
12409:
1.1 albertel 12410: # ------------------------------------------------------ Read spare server file
12411: {
1.448 albertel 12412: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12413:
12414: while (my $configline=<$config>) {
12415: chomp($configline);
1.284 matthew 12416: if ($configline) {
1.784 albertel 12417: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12418: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12419: push(@{ $spareid{$type} }, $host);
1.1 albertel 12420: }
12421: }
1.448 albertel 12422: close($config);
1.1 albertel 12423: }
1.11 www 12424: # ------------------------------------------------------------ Read permissions
12425: {
1.448 albertel 12426: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12427:
12428: while (my $configline=<$config>) {
1.448 albertel 12429: chomp($configline);
12430: if ($configline) {
12431: my ($role,$perm)=split(/ /,$configline);
12432: if ($perm ne '') { $pr{$role}=$perm; }
12433: }
1.11 www 12434: }
1.448 albertel 12435: close($config);
1.11 www 12436: }
12437:
12438: # -------------------------------------------- Read plain texts for permissions
12439: {
1.448 albertel 12440: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12441:
12442: while (my $configline=<$config>) {
1.448 albertel 12443: chomp($configline);
12444: if ($configline) {
1.742 raeburn 12445: my ($short,@plain)=split(/:/,$configline);
12446: %{$prp{$short}} = ();
12447: if (@plain > 0) {
12448: $prp{$short}{'std'} = $plain[0];
12449: for (my $i=1; $i<@plain; $i++) {
12450: $prp{$short}{'alt'.$i} = $plain[$i];
12451: }
12452: }
1.448 albertel 12453: }
1.135 www 12454: }
1.448 albertel 12455: close($config);
1.135 www 12456: }
12457:
12458: # ---------------------------------------------------------- Read package table
12459: {
1.448 albertel 12460: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12461:
12462: while (my $configline=<$config>) {
1.483 albertel 12463: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12464: chomp($configline);
12465: my ($short,$plain)=split(/:/,$configline);
12466: my ($pack,$name)=split(/\&/,$short);
12467: if ($plain ne '') {
12468: $packagetab{$pack.'&'.$name.'&name'}=$name;
12469: $packagetab{$short}=$plain;
12470: }
1.11 www 12471: }
1.448 albertel 12472: close($config);
1.329 matthew 12473: }
12474:
1.1172.2.27 raeburn 12475: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12476:
1.1172.2.27 raeburn 12477: &load_loncaparevs();
12478:
12479: # ------------------------------------------------------- Read serverhostID table
12480:
12481: &load_serverhomeIDs();
1.1074 raeburn 12482:
1.1172.2.27 raeburn 12483: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12484: {
12485: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12486: if (-e $file) {
12487: my $parser = HTML::LCParser->new($file);
12488: while (my $token = $parser->get_token()) {
12489: if ($token->[0] eq 'S') {
12490: my $item = $token->[1];
12491: my $name = $token->[2]{'name'};
12492: my $value = $token->[2]{'value'};
12493: if ($item ne '' && $name ne '' && $value ne '') {
12494: my $release = $parser->get_text();
12495: $release =~ s/(^\s*|\s*$ )//gx;
12496: $needsrelease{$item.':'.$name.':'.$value} = $release;
12497: }
12498: }
12499: }
12500: }
1.1073 raeburn 12501: }
12502:
1.1138 raeburn 12503: # ---------------------------------------------------------- Read managers table
12504: {
12505: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12506: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12507: while (my $configline=<$config>) {
12508: chomp($configline);
12509: next if ($configline =~ /^\#/);
12510: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12511: $managerstab{$configline} = 1;
12512: }
12513: }
12514: close($config);
12515: }
12516: }
12517: }
12518:
1.329 matthew 12519: # ------------- set up temporary directory
12520: {
1.1117 foxr 12521: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12522:
1.11 www 12523: }
12524:
1.794 albertel 12525: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12526: 'compress_threshold'=> 20_000,
12527: });
1.185 www 12528:
1.281 www 12529: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12530: $dumpcount=0;
1.958 www 12531: $locknum=0;
1.22 www 12532:
1.163 harris41 12533: &logtouch();
1.672 albertel 12534: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12535: $readit=1;
1.564 albertel 12536: {
12537: use integer;
12538: my $test=(2**32)+1;
1.568 albertel 12539: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12540: &logthis(" Detected 64bit platform ($_64bit)");
12541: }
1.195 www 12542: }
1.1 albertel 12543: }
1.179 www 12544:
1.1 albertel 12545: 1;
1.191 harris41 12546: __END__
12547:
1.243 albertel 12548: =pod
12549:
1.191 harris41 12550: =head1 NAME
12551:
1.243 albertel 12552: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12553:
12554: =head1 SYNOPSIS
12555:
1.243 albertel 12556: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12557:
12558: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12559:
1.243 albertel 12560: Common parameters:
12561:
12562: =over 4
12563:
12564: =item *
12565:
12566: $uname : an internal username (if $cname expecting a course Id specifically)
12567:
12568: =item *
12569:
12570: $udom : a domain (if $cdom expecting a course's domain specifically)
12571:
12572: =item *
12573:
12574: $symb : a resource instance identifier
12575:
12576: =item *
12577:
12578: $namespace : the name of a .db file that contains the data needed or
12579: being set.
12580:
12581: =back
12582:
1.394 bowersj2 12583: =head1 OVERVIEW
1.191 harris41 12584:
1.394 bowersj2 12585: lonnet provides subroutines which interact with the
12586: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12587: about classes, users, and resources.
1.243 albertel 12588:
12589: For many of these objects you can also use this to store data about
12590: them or modify them in various ways.
1.191 harris41 12591:
1.394 bowersj2 12592: =head2 Symbs
1.191 harris41 12593:
1.394 bowersj2 12594: To identify a specific instance of a resource, LON-CAPA uses symbols
12595: or "symbs"X<symb>. These identifiers are built from the URL of the
12596: map, the resource number of the resource in the map, and the URL of
12597: the resource itself. The latter is somewhat redundant, but might help
12598: if maps change.
12599:
12600: An example is
12601:
12602: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12603:
12604: The respective map entry is
12605:
12606: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12607: title="Problem 2">
12608: </resource>
12609:
12610: Symbs are used by the random number generator, as well as to store and
12611: restore data specific to a certain instance of for example a problem.
12612:
12613: =head2 Storing And Retrieving Data
12614:
12615: X<store()>X<cstore()>X<restore()>Three of the most important functions
12616: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12617: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12618: is is the non-critical message twin of cstore. These functions are for
12619: handlers to store a perl hash to a user's permanent data space in an
12620: easy manner, and to retrieve it again on another call. It is expected
12621: that a handler would use this once at the beginning to retrieve data,
12622: and then again once at the end to send only the new data back.
12623:
12624: The data is stored in the user's data directory on the user's
12625: homeserver under the ID of the course.
12626:
12627: The hash that is returned by restore will have all of the previous
12628: value for all of the elements of the hash.
12629:
12630: Example:
12631:
12632: #creating a hash
12633: my %hash;
12634: $hash{'foo'}='bar';
12635:
12636: #storing it
12637: &Apache::lonnet::cstore(\%hash);
12638:
12639: #changing a value
12640: $hash{'foo'}='notbar';
12641:
12642: #adding a new value
12643: $hash{'bar'}='foo';
12644: &Apache::lonnet::cstore(\%hash);
12645:
12646: #retrieving the hash
12647: my %history=&Apache::lonnet::restore();
12648:
12649: #print the hash
12650: foreach my $key (sort(keys(%history))) {
12651: print("\%history{$key} = $history{$key}");
12652: }
12653:
12654: Will print out:
1.191 harris41 12655:
1.394 bowersj2 12656: %history{1:foo} = bar
12657: %history{1:keys} = foo:timestamp
12658: %history{1:timestamp} = 990455579
12659: %history{2:bar} = foo
12660: %history{2:foo} = notbar
12661: %history{2:keys} = foo:bar:timestamp
12662: %history{2:timestamp} = 990455580
12663: %history{bar} = foo
12664: %history{foo} = notbar
12665: %history{timestamp} = 990455580
12666: %history{version} = 2
12667:
12668: Note that the special hash entries C<keys>, C<version> and
12669: C<timestamp> were added to the hash. C<version> will be equal to the
12670: total number of versions of the data that have been stored. The
12671: C<timestamp> attribute will be the UNIX time the hash was
12672: stored. C<keys> is available in every historical section to list which
12673: keys were added or changed at a specific historical revision of a
12674: hash.
12675:
12676: B<Warning>: do not store the hash that restore returns directly. This
12677: will cause a mess since it will restore the historical keys as if the
12678: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12679:
1.394 bowersj2 12680: Calling convention:
1.191 harris41 12681:
1.1172.2.27 raeburn 12682: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12683: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12684:
1.394 bowersj2 12685: For more detailed information, see lonnet specific documentation.
1.191 harris41 12686:
1.394 bowersj2 12687: =head1 RETURN MESSAGES
1.191 harris41 12688:
1.394 bowersj2 12689: =over 4
1.191 harris41 12690:
1.394 bowersj2 12691: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12692:
1.394 bowersj2 12693: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12694: when the connection is brought back up
1.191 harris41 12695:
1.394 bowersj2 12696: =item * B<con_failed>: unable to contact remote host and unable to save message
12697: for later delivery
1.191 harris41 12698:
1.967 bisitz 12699: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12700:
1.394 bowersj2 12701: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12702: that was requested
1.191 harris41 12703:
1.243 albertel 12704: =back
1.191 harris41 12705:
1.243 albertel 12706: =head1 PUBLIC SUBROUTINES
1.191 harris41 12707:
1.243 albertel 12708: =head2 Session Environment Functions
1.191 harris41 12709:
1.243 albertel 12710: =over 4
1.191 harris41 12711:
1.394 bowersj2 12712: =item *
12713: X<appenv()>
1.949 raeburn 12714: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12715: the user envirnoment file, and will be restored for each access this
1.620 albertel 12716: user makes during this session, also modifies the %env for the current
1.949 raeburn 12717: process. Optional rolesarrayref - if defined contains a reference to an array
12718: of roles which are exempt from the restriction on modifying user.role entries
12719: in the user's environment.db and in %env.
1.191 harris41 12720:
12721: =item *
1.394 bowersj2 12722: X<delenv()>
1.987 raeburn 12723: B<delenv($delthis,$regexp)>: removes all items from the session
12724: environment file that begin with $delthis. If the
12725: optional second arg - $regexp - is true, $delthis is treated as a
12726: regular expression, otherwise \Q$delthis\E is used.
12727: The values are also deleted from the current processes %env.
1.191 harris41 12728:
1.795 albertel 12729: =item * get_env_multiple($name)
12730:
12731: gets $name from the %env hash, it seemlessly handles the cases where multiple
12732: values may be defined and end up as an array ref.
12733:
12734: returns an array of values
12735:
1.243 albertel 12736: =back
12737:
12738: =head2 User Information
1.191 harris41 12739:
1.243 albertel 12740: =over 4
1.191 harris41 12741:
12742: =item *
1.394 bowersj2 12743: X<queryauthenticate()>
12744: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12745: authentication scheme
12746:
12747: =item *
1.394 bowersj2 12748: X<authenticate()>
1.1073 raeburn 12749: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12750: authenticate user from domain's lib servers (first use the current
12751: one). C<$upass> should be the users password.
1.1073 raeburn 12752: $checkdefauth is optional (value is 1 if a check should be made to
12753: authenticate user using default authentication method, and allow
12754: account creation if username does not have account in the domain).
12755: $clientcancheckhost is optional (value is 1 if checking whether the
12756: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12757:
12758: =item *
1.394 bowersj2 12759: X<homeserver()>
12760: B<homeserver($uname,$udom)>: find the server which has
12761: the user's directory and files (there must be only one), this caches
12762: the answer, and also caches if there is a borken connection.
1.191 harris41 12763:
12764: =item *
1.394 bowersj2 12765: X<idget()>
12766: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12767: (IDs are a unique resource in a domain, there must be only 1 ID per
12768: username, and only 1 username per ID in a specific domain) (returns
12769: hash: id=>name,id=>name)
1.191 harris41 12770:
12771: =item *
1.394 bowersj2 12772: X<idrget()>
12773: B<idrget($udom,@unames)>: find the IDs behind a list of
12774: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12775:
12776: =item *
1.394 bowersj2 12777: X<idput()>
12778: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12779:
12780: =item *
1.394 bowersj2 12781: X<rolesinit()>
1.1169 droeschl 12782: B<rolesinit($udom,$username)>: get user privileges.
12783: returns user role, first access and timer interval hashes
1.243 albertel 12784:
12785: =item *
1.1171 droeschl 12786: X<privileged()>
12787: B<privileged($username,$domain)>: returns a true if user has a
12788: privileged and active role (i.e. su or dc), false otherwise.
12789:
12790: =item *
1.551 albertel 12791: X<getsection()>
12792: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12793: course $cname, return section name/number or '' for "not in course"
12794: and '-1' for "no section"
12795:
12796: =item *
1.394 bowersj2 12797: X<userenvironment()>
12798: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12799: passed in @what from the requested user's environment, returns a hash
12800:
1.858 raeburn 12801: =item *
12802: X<userlog_query()>
1.859 albertel 12803: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12804: activity.log file. %filters defines filters applied when parsing the
12805: log file. These can be start or end timestamps, or the type of action
12806: - log to look for Login or Logout events, check for Checkin or
12807: Checkout, role for role selection. The response is in the form
12808: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12809: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12810:
1.243 albertel 12811: =back
12812:
12813: =head2 User Roles
12814:
12815: =over 4
12816:
12817: =item *
12818:
1.810 raeburn 12819: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12820: F: full access
12821: U,I,K: authentication modes (cxx only)
12822: '': forbidden
12823: 1: user needs to choose course
12824: 2: browse allowed
1.766 albertel 12825: A: passphrase authentication needed
1.243 albertel 12826:
12827: =item *
12828:
1.1172.2.13 raeburn 12829: constructaccess($url,$setpriv) : check for access to construction space URL
12830:
12831: See if the owner domain and name in the URL match those in the
12832: expected environment. If so, return three element list
12833: ($ownername,$ownerdomain,$ownerhome).
12834:
12835: Otherwise return the null string.
12836:
12837: If second argument 'setpriv' is true, it assigns the privileges,
12838: and returns the same three element list, unless the owner has
12839: blocked "ad hoc" Domain Coordinator access to the Author Space,
12840: in which case the null string is returned.
12841:
12842: =item *
12843:
1.243 albertel 12844: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12845: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12846: and course level
12847:
12848: =item *
12849:
1.988 raeburn 12850: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12851: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12852: $type is Course (default) or Community.
1.988 raeburn 12853: If $forcedefault evaluates to true, text returned will be default
12854: text for $type. Otherwise, if this is a course, the text returned
12855: will be a custom name for the role (if defined in the course's
12856: environment). If no custom name is defined the default is returned.
12857:
1.832 raeburn 12858: =item *
12859:
1.1172.2.23 raeburn 12860: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12861: All arguments are optional. Returns a hash of a roles, either for
12862: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12863: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12864: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12865: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12866: For each key, value is set to colon-separated start and end times for
12867: the role. If no username and domain are specified, will default to
1.934 raeburn 12868: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12869: of role statuses (active, future or previous), roles
12870: (e.g., cc,in, st etc.) and domains of the roles which can be used
12871: to restrict the list of roles reported. If no array ref is
12872: provided for types, will default to return only active roles.
1.834 albertel 12873:
1.1172.2.13 raeburn 12874: =item *
12875:
12876: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12877: user: $uname:$udom has a role in the course: $cdom_$cnum.
12878:
12879: Additional optional arguments are: $type (if role checking is to be restricted
12880: to certain user status types -- previous (expired roles), active (currently
12881: available roles) or future (roles available in the future), and
12882: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 12883: have active Domain Coordinator role in course's domain or in additional
12884: domains (specified in 'Domains to check for privileged users' in course
12885: environment -- set via: Course Settings -> Classlists and staff listing).
12886:
12887: =item *
12888:
12889: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12890: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12891: $possdomains and $possroles are optional array refs -- to domains to check and
12892: roles to check. If $possdomains is not specified, a dump will be done of the
12893: users' roles.db to check for a dc or su role in any domain. This can be
12894: time consuming if &privileged is called repeatedly (e.g., when displaying a
12895: classlist), so in such cases, supplying a $possdomains array is preferred, as
12896: this then allows &privileged_by_domain() to be used, which caches the identity
12897: of privileged users, eliminating the need for repeated calls to &dump().
12898:
12899: =item *
12900:
12901: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12902: where the outer hash keys are domains specified in the $possdomains array ref,
12903: next inner hash keys are privileged roles specified in the $roles array ref,
12904: and the innermost hash contains key = value pairs for username:domain = end:start
12905: for active or future "privileged" users with that role in that domain. To avoid
12906: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12907: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 12908:
1.243 albertel 12909: =back
12910:
12911: =head2 User Modification
12912:
12913: =over 4
12914:
12915: =item *
12916:
1.957 raeburn 12917: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12918: user for the level given by URL. Optional start and end dates (leave empty
12919: string or zero for "no date")
1.191 harris41 12920:
12921: =item *
12922:
1.243 albertel 12923: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12924: change a users, password, possible return values are: ok,
12925: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12926: refused
1.191 harris41 12927:
12928: =item *
12929:
1.243 albertel 12930: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12931:
12932: =item *
12933:
1.1058 raeburn 12934: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12935: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12936:
12937: will update user information (firstname,middlename,lastname,generation,
12938: permanentemail), and if forceid is true, student/employee ID also.
12939: A user's institutional affiliation(s) can also be updated.
12940: User information fields will not be overwritten with empty entries
12941: unless the field is included in the $candelete array reference.
12942: This array is included when a single user is modified via "Manage Users",
12943: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12944:
12945: =item *
12946:
1.286 matthew 12947: modifystudent
12948:
1.957 raeburn 12949: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 12950: The course id is resolved based on the current user's environment.
12951: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12952: associated with a course.
12953:
1.297 matthew 12954: This call is essentially a wrapper for lonnet::modifyuser and
12955: lonnet::modify_student_enrollment
1.286 matthew 12956:
12957: Inputs:
12958:
12959: =over 4
12960:
1.957 raeburn 12961: =item B<$udom> Student's loncapa domain
1.286 matthew 12962:
1.957 raeburn 12963: =item B<$uname> Student's loncapa login name
1.286 matthew 12964:
1.964 bisitz 12965: =item B<$uid> Student/Employee ID
1.286 matthew 12966:
1.957 raeburn 12967: =item B<$umode> Student's authentication mode
1.286 matthew 12968:
1.957 raeburn 12969: =item B<$upass> Student's password
1.286 matthew 12970:
1.957 raeburn 12971: =item B<$first> Student's first name
1.286 matthew 12972:
1.957 raeburn 12973: =item B<$middle> Student's middle name
1.286 matthew 12974:
1.957 raeburn 12975: =item B<$last> Student's last name
1.286 matthew 12976:
1.957 raeburn 12977: =item B<$gene> Student's generation
1.286 matthew 12978:
1.957 raeburn 12979: =item B<$usec> Student's section in course
1.286 matthew 12980:
12981: =item B<$end> Unix time of the roles expiration
12982:
12983: =item B<$start> Unix time of the roles start date
12984:
12985: =item B<$forceid> If defined, allow $uid to be changed
12986:
12987: =item B<$desiredhome> server to use as home server for student
12988:
1.957 raeburn 12989: =item B<$email> Student's permanent e-mail address
12990:
12991: =item B<$type> Type of enrollment (auto or manual)
12992:
1.963 raeburn 12993: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12994:
12995: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12996:
1.963 raeburn 12997: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12998:
1.963 raeburn 12999: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13000:
1.1172.2.19 raeburn 13001: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13002:
13003: =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 13004:
1.286 matthew 13005: =back
1.297 matthew 13006:
13007: =item *
13008:
13009: modify_student_enrollment
13010:
1.1172.2.31 raeburn 13011: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13012: 'role.request.course' must be defined for this function to proceed.
13013:
13014: Inputs:
13015:
13016: =over 4
13017:
1.1172.2.31 raeburn 13018: =item $udom, student's domain
1.297 matthew 13019:
1.1172.2.31 raeburn 13020: =item $uname, student's name
1.297 matthew 13021:
1.1172.2.31 raeburn 13022: =item $uid, student's user id
1.297 matthew 13023:
1.1172.2.31 raeburn 13024: =item $first, student's first name
1.297 matthew 13025:
13026: =item $middle
13027:
13028: =item $last
13029:
13030: =item $gene
13031:
13032: =item $usec
13033:
13034: =item $end
13035:
13036: =item $start
13037:
1.957 raeburn 13038: =item $type
13039:
13040: =item $locktype
13041:
13042: =item $cid
13043:
13044: =item $selfenroll
13045:
13046: =item $context
13047:
1.1172.2.19 raeburn 13048: =item $credits, number of credits student will earn from this class
13049:
1.297 matthew 13050: =back
13051:
1.191 harris41 13052:
13053: =item *
13054:
1.243 albertel 13055: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13056: custom role; give a custom role to a user for the level given by URL. Specify
13057: name and domain of role author, and role name
1.191 harris41 13058:
13059: =item *
13060:
1.243 albertel 13061: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13062:
13063: =item *
13064:
1.243 albertel 13065: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13066:
13067: =back
13068:
13069: =head2 Course Infomation
13070:
13071: =over 4
1.191 harris41 13072:
13073: =item *
13074:
1.1118 foxr 13075: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13076: specified course id, including all environment settings for the
13077: course, the description of the course will be in the hash under the
13078: key 'description'
1.191 harris41 13079:
1.1118 foxr 13080: $options is an optional parameter that if supplied is a hash reference that controls
13081: what how this function works. It has the following key/values:
13082:
13083: =over 4
13084:
13085: =item freshen_cache
13086:
13087: If defined, and the environment cache for the course is valid, it is
13088: returned in the returned hash.
13089:
13090: =item one_time
13091:
13092: If defined, the last cache time is set to _now_
13093:
13094: =item user
13095:
13096: If defined, the supplied username is used instead of the current user.
13097:
13098:
13099: =back
13100:
1.191 harris41 13101: =item *
13102:
1.624 albertel 13103: resdata($name,$domain,$type,@which) : request for current parameter
13104: setting for a specific $type, where $type is either 'course' or 'user',
13105: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13106: answers for 10 minutes.
1.243 albertel 13107:
1.877 foxr 13108: =item *
13109:
13110: get_courseresdata($courseid, $domain) : dump the entire course resource
13111: data base, returning a hash that is keyed by the resource name and has
13112: values that are the resource value. I believe that the timestamps and
13113: versions are also returned.
13114:
1.1172.2.31 raeburn 13115: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13116: supplemental content area. This routine caches the number of files for
13117: 10 minutes.
13118:
1.243 albertel 13119: =back
13120:
13121: =head2 Course Modification
13122:
13123: =over 4
1.191 harris41 13124:
13125: =item *
13126:
1.243 albertel 13127: writecoursepref($courseid,%prefs) : write preferences (environment
13128: database) for a course
1.191 harris41 13129:
13130: =item *
13131:
1.1011 raeburn 13132: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13133:
13134: =item *
13135:
1.1038 raeburn 13136: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13137:
1.1167 droeschl 13138: =item *
13139:
13140: is_course($courseid), is_course($cdom, $cnum)
13141:
13142: Accepts either a combined $courseid (in the form of domain_courseid) or the
13143: two component version $cdom, $cnum. It checks if the specified course exists.
13144:
13145: Returns:
13146: undef if the course doesn't exist, otherwise
13147: in scalar context the combined courseid.
13148: in list context the two components of the course identifier, domain and
13149: courseid.
13150:
1.243 albertel 13151: =back
13152:
13153: =head2 Resource Subroutines
13154:
13155: =over 4
1.191 harris41 13156:
13157: =item *
13158:
1.243 albertel 13159: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13160:
13161: =item *
13162:
1.243 albertel 13163: repcopy($filename) : subscribes to the requested file, and attempts to
13164: replicate from the owning library server, Might return
1.607 raeburn 13165: 'unavailable', 'not_found', 'forbidden', 'ok', or
13166: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13167: resource. Expects the local filesystem pathname
13168: (/home/httpd/html/res/....)
13169:
13170: =back
13171:
13172: =head2 Resource Information
13173:
13174: =over 4
1.191 harris41 13175:
13176: =item *
13177:
1.1172.2.28 raeburn 13178: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13179: and returns the value of a variety of different possible values,
13180: $varname should be a request string, and the other parameters can be
13181: used to specify who and what one is asking about. Ordinarily, $cid
13182: does not need to be specified, as it is retrived from
13183: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13184: within lonuserstate::loadmap() when initializing a course, before
13185: $env{'request.course.id'} has been set, so it needs to be provided
13186: in that one case.
1.243 albertel 13187:
13188: Possible values for $varname are environment.lastname (or other item
13189: from the envirnment hash), user.name (or someother aspect about the
13190: user), resource.0.maxtries (or some other part and parameter of a
13191: resource)
1.204 albertel 13192:
13193: =item *
13194:
1.243 albertel 13195: directcondval($number) : get current value of a condition; reads from a state
13196: string
1.204 albertel 13197:
13198: =item *
13199:
1.243 albertel 13200: condval($condidx) : value of condition index based on state
1.204 albertel 13201:
13202: =item *
13203:
1.243 albertel 13204: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13205: resource's metadata, $what should be either a specific key, or either
13206: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13207: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13208:
13209: this function automatically caches all requests
1.191 harris41 13210:
13211: =item *
13212:
1.243 albertel 13213: metadata_query($query,$custom,$customshow) : make a metadata query against the
13214: network of library servers; returns file handle of where SQL and regex results
13215: will be stored for query
1.191 harris41 13216:
13217: =item *
13218:
1.243 albertel 13219: symbread($filename) : return symbolic list entry (filename argument optional);
13220: returns the data handle
1.191 harris41 13221:
13222: =item *
13223:
1.1172.2.17 raeburn 13224: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13225: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13226: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13227: on failure, user must be in a course, as it assumes the existence of
13228: the course initial hash, and uses $env('request.course.id'}. The third
13229: arg is an optional reference to a scalar. If this arg is passed in the
13230: call to symbverify, it will be set to 1 if the symb has been set to be
13231: encrypted; otherwise it will be null.
1.243 albertel 13232:
1.191 harris41 13233: =item *
13234:
1.243 albertel 13235: symbclean($symb) : removes versions numbers from a symb, returns the
13236: cleaned symb
1.191 harris41 13237:
13238: =item *
13239:
1.243 albertel 13240: is_on_map($uri) : checks if the $uri is somewhere on the current
13241: course map, user must be in a course for it to work.
1.191 harris41 13242:
13243: =item *
13244:
1.243 albertel 13245: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13246:
13247: =item *
13248:
1.243 albertel 13249: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13250: a random seed, all arguments are optional, if they aren't sent it uses the
13251: environment to derive them. Note: if symb isn't sent and it can't get one
13252: from &symbread it will use the current time as its return value
1.191 harris41 13253:
13254: =item *
13255:
1.243 albertel 13256: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13257: unfakeable, receipt
1.191 harris41 13258:
13259: =item *
13260:
1.620 albertel 13261: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13262:
13263: =item *
13264:
1.243 albertel 13265: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13266:
13267: =item *
13268:
1.243 albertel 13269: 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 13270:
13271: =item *
13272:
1.243 albertel 13273: 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 13274:
13275: =item *
13276:
1.243 albertel 13277: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13278:
13279: =item *
13280:
1.243 albertel 13281: devalidate($symb) : devalidate temporary spreadsheet calculations,
13282: forcing spreadsheet to reevaluate the resource scores next time.
13283:
1.1172.2.13 raeburn 13284: =item *
13285:
13286: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13287: when viewing in course context.
13288:
13289: input: six args -- filename (decluttered), course number, course domain,
13290: url, symb (if registered) and group (if this is a
13291: group item -- e.g., bulletin board, group page etc.).
13292:
13293: output: array of five scalars --
13294: $cfile -- url for file editing if editable on current server
13295: $home -- homeserver of resource (i.e., for author if published,
13296: or course if uploaded.).
13297: $switchserver -- 1 if server switch will be needed.
13298: $forceedit -- 1 if icon/link should be to go to edit mode
13299: $forceview -- 1 if icon/link should be to go to view mode
13300:
13301: =item *
13302:
13303: is_course_upload($file,$cnum,$cdom)
13304:
13305: Used in course context to determine if current file was uploaded to
13306: the course (i.e., would be found in /userfiles/docs on the course's
13307: homeserver.
13308:
13309: input: 3 args -- filename (decluttered), course number and course domain.
13310: output: boolean -- 1 if file was uploaded.
13311:
1.243 albertel 13312: =back
13313:
13314: =head2 Storing/Retreiving Data
13315:
13316: =over 4
1.191 harris41 13317:
13318: =item *
13319:
1.243 albertel 13320: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13321: for this url; hashref needs to be given and should be a \%hashname; the
13322: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13323: be derived from the env
1.191 harris41 13324:
13325: =item *
13326:
1.243 albertel 13327: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13328: uses critical subroutine
1.191 harris41 13329:
13330: =item *
13331:
1.243 albertel 13332: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13333: all args are optional
1.191 harris41 13334:
13335: =item *
13336:
1.717 albertel 13337: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13338: dumps the complete (or key matching regexp) namespace into a hash
13339: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13340: normally &store()ed into
13341:
13342: $range should be either an integer '100' (give me the first 100
13343: matching records)
13344: or be two integers sperated by a - with no spaces
13345: '30-50' (give me the 30th through the 50th matching
13346: records)
13347:
13348:
13349: =item *
13350:
1.1172.2.59! raeburn 13351: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13352: replaces a &store() version of data with a replacement set of data
13353: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59! raeburn 13354: reference. If $tolog is true, the transaction is logged in the courselog
! 13355: with an action=PUTSTORE.
1.717 albertel 13356:
13357: =item *
13358:
1.243 albertel 13359: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13360: works very similar to store/cstore, but all data is stored in a
13361: temporary location and can be reset using tmpreset, $storehash should
13362: be a hash reference, returns nothing on success
1.191 harris41 13363:
13364: =item *
13365:
1.243 albertel 13366: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13367: similar to restore, but all data is stored in a temporary location and
13368: can be reset using tmpreset. Returns a hash of values on success,
13369: error string otherwise.
1.191 harris41 13370:
13371: =item *
13372:
1.243 albertel 13373: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13374: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13375:
13376: =item *
13377:
1.243 albertel 13378: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13379: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13380:
13381: =item *
13382:
1.243 albertel 13383: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13384: namesp ($udom and $uname are optional)
1.191 harris41 13385:
13386: =item *
13387:
1.702 albertel 13388: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13389: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13390: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13391:
1.702 albertel 13392: $range should be either an integer '100' (give me the first 100
13393: matching records)
13394: or be two integers sperated by a - with no spaces
13395: '30-50' (give me the 30th through the 50th matching
13396: records)
1.449 matthew 13397: =item *
13398:
13399: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13400: $store can be a scalar, an array reference, or if the amount to be
13401: incremented is > 1, a hash reference.
13402:
13403: ($udom and $uname are optional)
1.191 harris41 13404:
13405: =item *
13406:
1.243 albertel 13407: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13408: ($udom and $uname are optional)
1.191 harris41 13409:
13410: =item *
13411:
1.243 albertel 13412: cput($namespace,$storehash,$udom,$uname) : critical put
13413: ($udom and $uname are optional)
1.191 harris41 13414:
13415: =item *
13416:
1.748 albertel 13417: newput($namespace,$storehash,$udom,$uname) :
13418:
13419: Attempts to store the items in the $storehash, but only if they don't
13420: currently exist, if this succeeds you can be certain that you have
13421: successfully created a new key value pair in the $namespace db.
13422:
13423:
13424: Args:
13425: $namespace: name of database to store values to
13426: $storehash: hashref to store to the db
13427: $udom: (optional) domain of user containing the db
13428: $uname: (optional) name of user caontaining the db
13429:
13430: Returns:
13431: 'ok' -> succeeded in storing all keys of $storehash
13432: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13433: least <key> already existed in the db (other
13434: requested keys may also already exist)
1.967 bisitz 13435: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13436: 'con_lost' -> unable to contact request server
13437: 'refused' -> action was not allowed by remote machine
13438:
13439:
13440: =item *
13441:
1.243 albertel 13442: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13443: reference filled in from namesp (encrypts the return communication)
13444: ($udom and $uname are optional)
1.191 harris41 13445:
13446: =item *
13447:
1.243 albertel 13448: log($udom,$name,$home,$message) : write to permanent log for user; use
13449: critical subroutine
13450:
1.806 raeburn 13451: =item *
13452:
1.860 raeburn 13453: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13454: array reference filled in from namespace found in domain level on either
13455: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13456:
13457: =item *
13458:
1.860 raeburn 13459: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13460: domain level either on specified domain server ($uhome) or primary domain
13461: server ($udom and $uhome are optional)
1.806 raeburn 13462:
1.943 raeburn 13463: =item *
13464:
1.1172.2.35 raeburn 13465: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13466: for: authentication, language, quotas, timezone, date locale, and portal URL in
13467: the target domain.
13468:
13469: May also include additional key => value pairs for the following groups:
13470:
13471: =over
13472:
13473: =item
13474: disk quotas (MB allocated by default to portfolios and authoring spaces).
13475:
13476: =over
13477:
13478: =item defaultquota, authorquota
13479:
13480: =back
13481:
13482: =item
13483: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13484: portfolio for users).
13485:
13486: =over
13487:
13488: =item
13489: aboutme, blog, webdav, portfolio
13490:
13491: =back
13492:
13493: =item
13494: requestcourses: ability to request courses, and how requests are processed.
13495:
13496: =over
13497:
13498: =item
1.1172.2.37 raeburn 13499: official, unofficial, community, textbook
1.1172.2.35 raeburn 13500:
13501: =back
13502:
13503: =item
13504: inststatus: types of institutional affiliation, and order in which they are displayed.
13505:
13506: =over
13507:
13508: =item
1.1172.2.44 raeburn 13509: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 13510:
13511: =back
13512:
13513: =item
13514: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13515: for course's uploaded content.
13516:
13517: =over
13518:
13519: =item
1.1172.2.37 raeburn 13520: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
1.1172.2.35 raeburn 13521:
13522: =back
13523:
13524: =item
13525: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13526: on your servers.
13527:
13528: =over
13529:
13530: =item
13531: remotesessions, hostedsessions
13532:
13533: =back
13534:
13535: =back
13536:
13537: In cases where a domain coordinator has never used the "Set Domain Configuration"
13538: utility to create a configuration.db file on a domain's primary library server
13539: only the following domain defaults: auth_def, auth_arg_def, lang_def
13540: -- corresponding values are authentication type (internal, krb4, krb5,
13541: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13542: will be available. Values are retrieved from cache (if current), unless the
13543: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13544: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13545:
13546: Typical usage:
1.943 raeburn 13547:
1.1172.2.35 raeburn 13548: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13549:
1.243 albertel 13550: =back
13551:
13552: =head2 Network Status Functions
13553:
13554: =over 4
1.191 harris41 13555:
13556: =item *
13557:
1.1137 raeburn 13558: dirlist() : return directory list based on URI (first arg).
13559:
13560: Inputs: 1 required, 5 optional.
13561:
13562: =over
13563:
13564: =item
13565: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13566:
13567: =item
13568: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13569:
13570: =item
13571: $username - username of user/course to be listed. Extracted from $uri if absent.
13572:
13573: =item
13574: $getpropath - boolean: 1 if prepend path using &propath().
13575:
13576: =item
13577: $getuserdir - boolean: 1 if prepend path for "userfiles".
13578:
13579: =item
13580: $alternateRoot - path to prepend in place of path from $uri.
13581:
13582: =back
13583:
13584: Returns: Array of up to two items.
13585:
13586: =over
13587:
13588: a reference to an array of files/subdirectories
13589:
13590: =over
13591:
13592: Each element in the array of files/subdirectories is a & separated list of
13593: item name and the result of running stat on the item. If dirlist was requested
13594: for a file instead of a directory, the item name will be ''. For a directory
13595: listing, if the item is a metadata file, the element will end &N&M
13596: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13597: default copyright set (1).
13598:
13599: =back
13600:
13601: a scalar containing error condition (if encountered).
13602:
13603: =over
13604:
13605: =item
13606: no_host (no homeserver identified for $username:$domain).
13607:
13608: =item
13609: no_such_host (server contacted for listing not identified as valid host).
13610:
13611: =item
13612: con_lost (connection to remote server failed).
13613:
13614: =item
13615: refused (invalid $username:$domain received on lond side).
13616:
13617: =item
13618: no_such_dir (directory at specified path on lond side does not exist).
13619:
13620: =item
13621: empty (directory at specified path on lond side is empty).
13622:
13623: =over
13624:
13625: This is currently not encountered because the &ls3, &ls2,
13626: &ls (_handler) routines on the lond side do not filter out
13627: . and .. from a directory listing.
13628:
13629: =back
13630:
13631: =back
13632:
13633: =back
1.191 harris41 13634:
13635: =item *
13636:
1.243 albertel 13637: spareserver() : find server with least workload from spare.tab
13638:
1.986 foxr 13639:
13640: =item *
13641:
13642: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13643: if there is no corresponding loncapa host.
13644:
1.243 albertel 13645: =back
13646:
1.986 foxr 13647:
1.243 albertel 13648: =head2 Apache Request
13649:
13650: =over 4
1.191 harris41 13651:
13652: =item *
13653:
1.243 albertel 13654: ssi($url,%hash) : server side include, does a complete request cycle on url to
13655: localhost, posts hash
13656:
13657: =back
13658:
13659: =head2 Data to String to Data
13660:
13661: =over 4
1.191 harris41 13662:
13663: =item *
13664:
1.243 albertel 13665: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13666: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13667:
13668: =item *
13669:
1.243 albertel 13670: hashref2str($hashref) : convert a hashref into a string complete with
13671: escaping and '=' and '&' separators, supports elements that are
13672: arrayrefs and hashrefs
1.191 harris41 13673:
13674: =item *
13675:
1.243 albertel 13676: arrayref2str($arrayref) : convert an arrayref into a string complete
13677: with escaping and '&' separators, supports elements that are arrayrefs
13678: and hashrefs
1.191 harris41 13679:
13680: =item *
13681:
1.243 albertel 13682: str2hash($string) : convert string to hash using unescaping and
13683: splitting on '=' and '&', supports elements that are arrayrefs and
13684: hashrefs
1.191 harris41 13685:
13686: =item *
13687:
1.243 albertel 13688: str2array($string) : convert string to hash using unescaping and
13689: splitting on '&', supports elements that are arrayrefs and hashrefs
13690:
13691: =back
13692:
13693: =head2 Logging Routines
13694:
13695:
13696: These routines allow one to make log messages in the lonnet.log and
13697: lonnet.perm logfiles.
1.191 harris41 13698:
1.1119 foxr 13699: =over 4
13700:
1.191 harris41 13701: =item *
13702:
1.243 albertel 13703: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13704:
13705: =item *
13706:
1.243 albertel 13707: logthis() : append message to the normal lonnet.log file, it gets
13708: preiodically rolled over and deleted.
1.191 harris41 13709:
13710: =item *
13711:
1.243 albertel 13712: logperm() : append a permanent message to lonnet.perm.log, this log
13713: file never gets deleted by any automated portion of the system, only
13714: messages of critical importance should go in here.
13715:
1.1119 foxr 13716:
1.243 albertel 13717: =back
13718:
13719: =head2 General File Helper Routines
13720:
13721: =over 4
1.191 harris41 13722:
13723: =item *
13724:
1.481 raeburn 13725: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13726: (a) files in /uploaded
13727: (i) If a local copy of the file exists -
13728: compares modification date of local copy with last-modified date for
13729: definitive version stored on home server for course. If local copy is
13730: stale, requests a new version from the home server and stores it.
13731: If the original has been removed from the home server, then local copy
13732: is unlinked.
13733: (ii) If local copy does not exist -
13734: requests the file from the home server and stores it.
13735:
13736: If $caller is 'uploadrep':
13737: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13738: for request for files originally uploaded via DOCS.
13739: - returns 'ok' if fresh local copy now available, -1 otherwise.
13740:
13741: Otherwise:
13742: This indicates a call from the content generation phase of the request.
13743: - returns the entire contents of the file or -1.
13744:
13745: (b) files in /res
13746: - returns the entire contents of a file or -1;
13747: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13748:
1.712 albertel 13749:
13750: =item *
13751:
13752: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13753: reference
13754:
13755: returns either a stat() list of data about the file or an empty list
13756: if the file doesn't exist or couldn't find out about it (connection
13757: problems or user unknown)
13758:
1.191 harris41 13759: =item *
13760:
1.243 albertel 13761: filelocation($dir,$file) : returns file system location of a file
13762: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13763: directory that relative $file lookups are to looked in ($dir of /a/dir
13764: and a file of ../bob will become /a/bob)
1.191 harris41 13765:
13766: =item *
13767:
13768: hreflocation($dir,$file) : returns file system location or a URL; same as
13769: filelocation except for hrefs
13770:
13771: =item *
13772:
1.1172.2.49 raeburn 13773: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
13774: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 13775:
1.243 albertel 13776: =back
13777:
1.608 albertel 13778: =head2 Usererfile file routines (/uploaded*)
13779:
13780: =over 4
13781:
13782: =item *
13783:
13784: userfileupload(): main rotine for putting a file in a user or course's
13785: filespace, arguments are,
13786:
1.620 albertel 13787: formname - required - this is the name of the element in $env where the
1.608 albertel 13788: filename, and the contents of the file to create/modifed exist
1.620 albertel 13789: the filename is in $env{'form.'.$formname.'.filename'} and the
13790: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13791: context - if coursedoc, store the file in the course of the active role
13792: of the current user;
13793: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13794: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13795: subdir - required - subdirectory to put the file in under ../userfiles/
13796: if undefined, it will be placed in "unknown"
13797:
13798: (This routine calls clean_filename() to remove any dangerous
13799: characters from the filename, and then calls finuserfileupload() to
13800: complete the transaction)
13801:
13802: returns either the url of the uploaded file (/uploaded/....) if successful
13803: and /adm/notfound.html if unsuccessful
13804:
13805: =item *
13806:
13807: clean_filename(): routine for cleaing a filename up for storage in
13808: userfile space, argument is:
13809:
13810: filename - proposed filename
13811:
13812: returns: the new clean filename
13813:
13814: =item *
13815:
1.1090 raeburn 13816: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13817: userspace, probably shouldn't be called directly
13818:
13819: docuname: username or courseid of destination for the file
13820: docudom: domain of user/course of destination for the file
13821: formname: same as for userfileupload()
1.1090 raeburn 13822: fname: filename (including subdirectories) for the file
13823: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13824: allfiles: reference to hash used to store objects found by parser
13825: codebase: reference to hash used for codebases of java objects found by parser
13826: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13827: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13828: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13829: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13830: context: if 'overwrite', will move the uploaded file from its temporary location to
13831: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13832: mimetype: reference to scalar to accommodate mime type determined
13833: from File::MMagic if $parser = parse.
1.608 albertel 13834:
13835: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13836: and /adm/notfound.html if unsuccessful (or an error message if context
13837: was 'overwrite').
13838:
1.608 albertel 13839:
13840: =item *
13841:
13842: renameuserfile(): renames an existing userfile to a new name
13843:
13844: Args:
13845: docuname: username or courseid of destination for the file
13846: docudom: domain of user/course of destination for the file
13847: old: current file name (including any subdirs under userfiles)
13848: new: desired file name (including any subdirs under userfiles)
13849:
13850: =item *
13851:
13852: mkdiruserfile(): creates a directory is a userfiles dir
13853:
13854: Args:
13855: docuname: username or courseid of destination for the file
13856: docudom: domain of user/course of destination for the file
13857: dir: dir to create (including any subdirs under userfiles)
13858:
13859: =item *
13860:
13861: removeuserfile(): removes a file that exists in userfiles
13862:
13863: Args:
13864: docuname: username or courseid of destination for the file
13865: docudom: domain of user/course of destination for the file
13866: fname: filname to delete (including any subdirs under userfiles)
13867:
13868: =item *
13869:
13870: removeuploadedurl(): convience function for removeuserfile()
13871:
13872: Args:
13873: url: a full /uploaded/... url to delete
13874:
1.747 albertel 13875: =item *
13876:
13877: get_portfile_permissions():
13878: Args:
13879: domain: domain of user or course contain the portfolio files
13880: user: name of user or num of course contain the portfolio files
13881: Returns:
13882: hashref of a dump of the proper file_permissions.db
13883:
13884:
13885: =item *
13886:
13887: get_access_controls():
13888:
13889: Args:
13890: current_permissions: the hash ref returned from get_portfile_permissions()
13891: group: (optional) the group you want the files associated with
13892: file: (optional) the file you want access info on
13893:
13894: Returns:
1.749 raeburn 13895: a hash (keys are file names) of hashes containing
13896: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13897: values are XML containing access control settings (see below)
1.747 albertel 13898:
13899: Internal notes:
13900:
1.749 raeburn 13901: access controls are stored in file_permissions.db as key=value pairs.
13902: key -> path to file/file_name\0uniqueID:scope_end_start
13903: where scope -> public,guest,course,group,domains or users.
13904: end -> UNIX time for end of access (0 -> no end date)
13905: start -> UNIX time for start of access
13906:
13907: value -> XML description of access control
13908: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13909: <start></start>
13910: <end></end>
13911:
13912: <password></password> for scope type = guest
13913:
13914: <domain></domain> for scope type = course or group
13915: <number></number>
13916: <roles id="">
13917: <role></role>
13918: <access></access>
13919: <section></section>
13920: <group></group>
13921: </roles>
13922:
13923: <dom></dom> for scope type = domains
13924:
13925: <users> for scope type = users
13926: <user>
13927: <uname></uname>
13928: <udom></udom>
13929: </user>
13930: </users>
13931: </scope>
13932:
13933: Access data is also aggregated for each file in an additional key=value pair:
13934: key -> path to file/file_name\0accesscontrol
13935: value -> reference to hash
13936: hash contains key = value pairs
13937: where key = uniqueID:scope_end_start
13938: value = UNIX time record was last updated
13939:
13940: Used to improve speed of look-ups of access controls for each file.
13941:
13942: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13943:
1.1172.2.13 raeburn 13944: =item *
13945:
1.749 raeburn 13946: modify_access_controls():
13947:
13948: Modifies access controls for a portfolio file
13949: Args
13950: 1. file name
13951: 2. reference to hash of required changes,
13952: 3. domain
13953: 4. username
13954: where domain,username are the domain of the portfolio owner
13955: (either a user or a course)
13956:
13957: Returns:
13958: 1. result of additions or updates ('ok' or 'error', with error message).
13959: 2. result of deletions ('ok' or 'error', with error message).
13960: 3. reference to hash of any new or updated access controls.
13961: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13962: key = integer (inbound ID)
1.1172.2.13 raeburn 13963: value = uniqueID
13964:
13965: =item *
13966:
13967: get_timebased_id():
13968:
13969: Attempts to get a unique timestamp-based suffix for use with items added to a
13970: course via the Course Editor (e.g., folders, composite pages,
13971: group bulletin boards).
13972:
13973: Args: (first three required; six others optional)
13974:
13975: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13976: docssequence, or name of group
13977:
13978: 2. keyid (alphanumeric): name of temporary locking key in hash,
13979: e.g., num, boardids
13980:
13981: 3. namespace: name of gdbm file used to store suffixes already assigned;
13982: file will be named nohist_namespace.db
13983:
13984: 4. cdom: domain of course; default is current course domain from %env
13985:
13986: 5. cnum: course number; default is current course number from %env
13987:
13988: 6. idtype: set to concat if an additional digit is to be appended to the
13989: unix timestamp to form the suffix, if the plain timestamp is already
13990: in use. Default is to not do this, but simply increment the unix
13991: timestamp by 1 until a unique key is obtained.
13992:
13993: 7. who: holder of locking key; defaults to user:domain for user.
13994:
13995: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13996: retrying); default is 3.
13997:
13998: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13999:
14000: Returns:
14001:
14002: 1. suffix obtained (numeric)
14003:
14004: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14005:
14006: 3. error: contains (localized) error message if an error occurred.
14007:
1.747 albertel 14008:
1.608 albertel 14009: =back
14010:
1.243 albertel 14011: =head2 HTTP Helper Routines
14012:
14013: =over 4
14014:
1.191 harris41 14015: =item *
14016:
14017: escape() : unpack non-word characters into CGI-compatible hex codes
14018:
14019: =item *
14020:
14021: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14022:
1.243 albertel 14023: =back
14024:
14025: =head1 PRIVATE SUBROUTINES
14026:
14027: =head2 Underlying communication routines (Shouldn't call)
14028:
14029: =over 4
14030:
14031: =item *
14032:
14033: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14034:
14035: =item *
14036:
14037: reply() : uses subreply to send a message to remote machine, logs all failures
14038:
14039: =item *
14040:
14041: critical() : passes a critical message to another server; if cannot
14042: get through then place message in connection buffer directory and
14043: returns con_delayed, if incapable of saving message, returns
14044: con_failed
14045:
14046: =item *
14047:
14048: reconlonc() : tries to reconnect lonc client processes.
14049:
14050: =back
14051:
14052: =head2 Resource Access Logging
14053:
14054: =over 4
14055:
14056: =item *
14057:
14058: flushcourselogs() : flush (save) buffer logs and access logs
14059:
14060: =item *
14061:
14062: courselog($what) : save message for course in hash
14063:
14064: =item *
14065:
14066: courseacclog($what) : save message for course using &courselog(). Perform
14067: special processing for specific resource types (problems, exams, quizzes, etc).
14068:
1.191 harris41 14069: =item *
14070:
14071: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14072: as a PerlChildExitHandler
1.243 albertel 14073:
14074: =back
14075:
14076: =head2 Other
14077:
14078: =over 4
14079:
14080: =item *
14081:
14082: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14083:
14084: =back
14085:
14086: =cut
1.877 foxr 14087:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>