Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1329
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1329 ! raeburn 4: # $Id: lonnet.pm,v 1.1328 2016/10/30 01:44:24 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1182 foxr 78:
1.1173 foxr 79: use Encode;
80:
1.1245 raeburn 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
1.871 albertel 84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 88: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 89:
1.1 albertel 90: use IO::Socket;
1.31 www 91: use GDBM_File;
1.208 albertel 92: use HTML::LCParser;
1.88 www 93: use Fcntl qw(:flock);
1.870 albertel 94: use Storable qw(thaw nfreeze);
1.1289 damieng 95: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 96: use Cache::Memcached;
1.676 albertel 97: use Digest::MD5;
1.790 albertel 98: use Math::Random;
1.1024 raeburn 99: use File::MMagic;
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1167 droeschl 103: use LONCAPA::Lond;
1.1117 foxr 104:
1.1090 raeburn 105: use File::Copy;
1.676 albertel 106:
1.195 www 107: my $readit;
1.1288 damieng 108: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 109:
1.619 albertel 110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
1.449 matthew 115:
1.1187 raeburn 116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 117: {
118: my $logid;
1.1187 raeburn 119: sub write_log {
1.1188 raeburn 120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
1.957 raeburn 126: }
1.1184 raeburn 127: $logid ++;
1.957 raeburn 128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
1.1184 raeburn 130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 143: }
144: }
1.1 albertel 145:
1.163 harris41 146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
1.1 albertel 156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
1.448 albertel 161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
1.448 albertel 164: close($fh);
165: }
1.1 albertel 166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
1.448 albertel 174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
1.1 albertel 178: return 1;
179: }
180:
1.850 albertel 181: sub create_connection {
1.853 albertel 182: my ($hostname,$lonid) = @_;
1.851 albertel 183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
1.890 albertel 187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
1.983 raeburn 194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
1.850 albertel 208:
1.1106 raeburn 209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
1.1315 raeburn 232: sub get_servercerts_info {
233: my ($lonhost,$context) = @_;
234: my ($rep,$uselocal);
235: if (grep { $_ eq $lonhost } ¤t_machine_ids()) {
236: $uselocal = 1;
237: }
1.1316 raeburn 238: if (($context ne 'cgi') && ($uselocal)) {
1.1315 raeburn 239: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323 raeburn 240: if ($distro eq '') {
241: $uselocal = 0;
242: } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315 raeburn 243: if ($1 < 6) {
244: $uselocal = 0;
245: }
246: }
247: }
248: if ($uselocal) {
249: $rep = LONCAPA::Lond::server_certs(\%perlvar);
250: } else {
251: $rep=&reply('servercerts',$lonhost);
252: }
253: my ($result,%returnhash);
254: if (defined($lonhost)) {
255: if (!defined(&hostname($lonhost))) {
256: return;
257: }
258: }
259: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
260: ($rep eq 'unknown_cmd')) {
261: $result = $rep;
262: } else {
263: $result = 'ok';
264: my @pairs=split(/\&/,$rep);
265: foreach my $item (@pairs) {
266: my ($key,$value)=split(/=/,$item,2);
267: my $what = &unescape($key);
268: $returnhash{$what}=&thaw_unescape($value);
269: }
270: }
271: return ($result,\%returnhash);
272: }
273:
1.993 raeburn 274: sub get_server_loncaparev {
1.1073 raeburn 275: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 276: if (defined($lonhost)) {
277: if (!defined(&hostname($lonhost))) {
278: undef($lonhost);
279: }
280: }
281: if (!defined($lonhost)) {
282: if (defined(&domain($dom,'primary'))) {
283: $lonhost=&domain($dom,'primary');
284: if ($lonhost eq 'no_host') {
285: undef($lonhost);
286: }
287: }
288: }
289: if (defined($lonhost)) {
1.1073 raeburn 290: my $cachetime = 12*3600;
291: if (!$ignore_cache) {
292: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
293: if (defined($cached)) {
294: return $loncaparev;
295: }
296: }
297: my ($answer,$loncaparev);
298: my @ids=¤t_machine_ids();
299: if (grep(/^\Q$lonhost\E$/,@ids)) {
300: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 301: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 302: $loncaparev = $1;
303: }
304: } else {
305: $answer = &reply('serverloncaparev',$lonhost);
306: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
307: if ($caller eq 'loncron') {
308: my $ua=new LWP::UserAgent;
1.1082 raeburn 309: $ua->timeout(4);
1.1073 raeburn 310: my $protocol = $protocol{$lonhost};
311: $protocol = 'http' if ($protocol ne 'https');
312: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
313: my $request=new HTTP::Request('GET',$url);
314: my $response=$ua->request($request);
315: unless ($response->is_error()) {
316: my $content = $response->content;
1.1081 raeburn 317: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 318: $loncaparev = $1;
319: }
320: }
321: } else {
322: $loncaparev = $loncaparevs{$lonhost};
323: }
1.1081 raeburn 324: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 325: $loncaparev = $1;
326: }
1.993 raeburn 327: }
1.1073 raeburn 328: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 329: }
330: }
331:
1.1074 raeburn 332: sub get_server_homeID {
333: my ($hostname,$ignore_cache,$caller) = @_;
334: unless ($ignore_cache) {
335: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
336: if (defined($cached)) {
337: return $serverhomeID;
338: }
339: }
340: my $cachetime = 12*3600;
341: my $serverhomeID;
342: if ($caller eq 'loncron') {
343: my @machine_ids = &machine_ids($hostname);
344: foreach my $id (@machine_ids) {
345: my $response = &reply('serverhomeID',$id);
346: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
347: $serverhomeID = $response;
348: last;
349: }
350: }
351: if ($serverhomeID eq '') {
352: $serverhomeID = $machine_ids[-1];
353: }
354: } else {
355: $serverhomeID = $serverhomeIDs{$hostname};
356: }
357: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
358: }
359:
1.1121 raeburn 360: sub get_remote_globals {
361: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 362: my ($result,%returnhash,%whatneeded);
363: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 364: foreach my $what (sort(keys(%{$whathash}))) {
365: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 366: my ($response,$cached);
1.1121 raeburn 367: unless ($ignore_cache) {
1.1125 raeburn 368: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 369: }
370: if (defined($cached)) {
1.1125 raeburn 371: $returnhash{$what} = $response;
1.1121 raeburn 372: } else {
1.1125 raeburn 373: $whatneeded{$what} = 1;
1.1121 raeburn 374: }
375: }
1.1125 raeburn 376: if (keys(%whatneeded) == 0) {
377: $result = 'ok';
378: } else {
1.1121 raeburn 379: my $requested = &freeze_escape(\%whatneeded);
380: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 381: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
382: ($rep eq 'unknown_cmd')) {
383: $result = $rep;
384: } else {
385: $result = 'ok';
1.1121 raeburn 386: my @pairs=split(/\&/,$rep);
1.1125 raeburn 387: foreach my $item (@pairs) {
388: my ($key,$value)=split(/=/,$item,2);
389: my $what = &unescape($key);
390: my $hashid = $lonhost.'-'.$what;
391: $returnhash{$what}=&thaw_unescape($value);
392: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 393: }
394: }
395: }
396: }
1.1125 raeburn 397: return ($result,\%returnhash);
1.1121 raeburn 398: }
399:
1.1124 raeburn 400: sub remote_devalidate_cache {
1.1241 raeburn 401: my ($lonhost,$cachekeys) = @_;
402: my $items;
403: return unless (ref($cachekeys) eq 'ARRAY');
404: my $cachestr = join('&',@{$cachekeys});
405: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 406: return $response;
407: }
408:
1.1 albertel 409: # -------------------------------------------------- Non-critical communication
410: sub subreply {
411: my ($cmd,$server)=@_;
1.838 albertel 412: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 413: #
414: # With loncnew process trimming, there's a timing hole between lonc server
415: # process exit and the master server picking up the listen on the AF_UNIX
416: # socket. In that time interval, a lock file will exist:
417:
418: my $lockfile=$peerfile.".lock";
419: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1289 damieng 420: sleep(0.1);
1.549 foxr 421: }
422: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 423: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 424: #
1.550 foxr 425: # We'll give the connection a few tries before abandoning it. If
426: # connection is not possible, we'll con_lost back to the client.
427: #
428: my $client;
429: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
430: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
431: Type => SOCK_STREAM,
432: Timeout => 10);
1.869 albertel 433: if ($client) {
1.550 foxr 434: last; # Connected!
1.850 albertel 435: } else {
1.853 albertel 436: &create_connection(&hostname($server),$server);
1.550 foxr 437: }
1.1289 damieng 438: sleep(0.1); # Try again later if failed connection.
1.550 foxr 439: }
440: my $answer;
441: if ($client) {
1.704 albertel 442: print $client "sethost:$server:$cmd\n";
1.550 foxr 443: $answer=<$client>;
444: if (!$answer) { $answer="con_lost"; }
445: chomp($answer);
446: } else {
447: $answer = 'con_lost'; # Failed connection.
448: }
1.1 albertel 449: return $answer;
450: }
451:
452: sub reply {
453: my ($cmd,$server)=@_;
1.838 albertel 454: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 455: my $answer=subreply($cmd,$server);
1.65 www 456: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 457: &logthis("<font color=\"blue\">WARNING:".
1.12 www 458: " $cmd to $server returned $answer</font>");
459: }
1.1 albertel 460: return $answer;
461: }
462:
463: # ----------------------------------------------------------- Send USR1 to lonc
464:
465: sub reconlonc {
1.891 albertel 466: my ($lonid) = @_;
467: if ($lonid) {
1.1295 raeburn 468: my $hostname = &hostname($lonid);
1.891 albertel 469: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
470: if ($hostname && -e $peerfile) {
471: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
472: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
473: Type => SOCK_STREAM,
474: Timeout => 10);
475: if ($client) {
476: print $client ("reset_retries\n");
477: my $answer=<$client>;
478: #reset just this one.
479: }
480: }
481: return;
482: }
483:
1.836 www 484: &logthis("Trying to reconnect lonc");
1.1 albertel 485: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 486: if (open(my $fh,"<$loncfile")) {
1.1 albertel 487: my $loncpid=<$fh>;
488: chomp($loncpid);
489: if (kill 0 => $loncpid) {
490: &logthis("lonc at pid $loncpid responding, sending USR1");
491: kill USR1 => $loncpid;
492: sleep 1;
1.1295 raeburn 493: } else {
1.12 www 494: &logthis(
1.672 albertel 495: "<font color=\"blue\">WARNING:".
1.12 www 496: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 497: }
498: } else {
1.836 www 499: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 500: }
501: }
502:
503: # ------------------------------------------------------ Critical communication
1.12 www 504:
1.1 albertel 505: sub critical {
506: my ($cmd,$server)=@_;
1.838 albertel 507: unless (&hostname($server)) {
1.672 albertel 508: &logthis("<font color=\"blue\">WARNING:".
1.89 www 509: " Critical message to unknown server ($server)</font>");
510: return 'no_such_host';
511: }
1.1 albertel 512: my $answer=reply($cmd,$server);
513: if ($answer eq 'con_lost') {
1.1295 raeburn 514: &reconlonc($server);
1.589 albertel 515: my $answer=reply($cmd,$server);
1.1 albertel 516: if ($answer eq 'con_lost') {
517: my $now=time;
518: my $middlename=$cmd;
1.5 www 519: $middlename=substr($middlename,0,16);
1.1 albertel 520: $middlename=~s/\W//g;
521: my $dfilename=
1.305 www 522: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
523: $dumpcount++;
1.1 albertel 524: {
1.448 albertel 525: my $dfh;
526: if (open($dfh,">$dfilename")) {
527: print $dfh "$cmd\n";
528: close($dfh);
529: }
1.1 albertel 530: }
1.1288 damieng 531: sleep 1;
1.1 albertel 532: my $wcmd='';
533: {
1.448 albertel 534: my $dfh;
535: if (open($dfh,"<$dfilename")) {
536: $wcmd=<$dfh>;
537: close($dfh);
538: }
1.1 albertel 539: }
540: chomp($wcmd);
1.7 www 541: if ($wcmd eq $cmd) {
1.672 albertel 542: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 543: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 544: &logperm("D:$server:$cmd");
545: return 'con_delayed';
546: } else {
1.672 albertel 547: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 548: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 549: &logperm("F:$server:$cmd");
550: return 'con_failed';
551: }
552: }
553: }
554: return $answer;
1.405 albertel 555: }
556:
1.755 albertel 557: # ------------------------------------------- check if return value is an error
558:
559: sub error {
560: my ($result) = @_;
1.756 albertel 561: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 562: if ($2 == 2) { return undef; }
563: return $1;
564: }
565: return undef;
566: }
567:
1.783 albertel 568: sub convert_and_load_session_env {
569: my ($lonidsdir,$handle)=@_;
570: my @profile;
571: {
1.917 albertel 572: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
573: if (!$opened) {
1.915 albertel 574: return 0;
575: }
1.783 albertel 576: flock($idf,LOCK_SH);
577: @profile=<$idf>;
578: close($idf);
579: }
580: my %temp_env;
581: foreach my $line (@profile) {
1.786 albertel 582: if ($line !~ m/=/) {
583: return 0;
584: }
1.783 albertel 585: chomp($line);
586: my ($envname,$envvalue)=split(/=/,$line,2);
587: $temp_env{&unescape($envname)} = &unescape($envvalue);
588: }
589: unlink("$lonidsdir/$handle.id");
590: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
591: 0640)) {
592: %disk_env = %temp_env;
593: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
594: untie(%disk_env);
595: }
1.786 albertel 596: return 1;
1.783 albertel 597: }
598:
1.374 www 599: # ------------------------------------------- Transfer profile into environment
1.780 albertel 600: my $env_loaded;
601: sub transfer_profile_to_env {
1.788 albertel 602: my ($lonidsdir,$handle,$force_transfer) = @_;
603: if (!$force_transfer && $env_loaded) { return; }
1.374 www 604:
1.720 albertel 605: if (!defined($lonidsdir)) {
606: $lonidsdir = $perlvar{'lonIDsDir'};
607: }
608: if (!defined($handle)) {
609: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
610: }
611:
1.786 albertel 612: my $convert;
613: {
1.917 albertel 614: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
615: if (!$opened) {
1.915 albertel 616: return;
617: }
1.786 albertel 618: flock($idf,LOCK_SH);
619: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
620: &GDBM_READER(),0640)) {
621: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
622: untie(%disk_env);
623: } else {
624: $convert = 1;
625: }
626: }
627: if ($convert) {
628: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
629: &logthis("Failed to load session, or convert session.");
630: }
1.374 www 631: }
1.783 albertel 632:
1.786 albertel 633: my %remove;
1.783 albertel 634: while ( my $envname = each(%env) ) {
1.433 matthew 635: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
636: if ($time < time-300) {
1.783 albertel 637: $remove{$key}++;
1.433 matthew 638: }
639: }
640: }
1.783 albertel 641:
1.619 albertel 642: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 643: $env_loaded=1;
1.783 albertel 644: foreach my $expired_key (keys(%remove)) {
1.433 matthew 645: &delenv($expired_key);
1.374 www 646: }
1.1 albertel 647: }
648:
1.916 albertel 649: # ---------------------------------------------------- Check for valid session
650: sub check_for_valid_session {
1.1245 raeburn 651: my ($r,$name,$userhashref) = @_;
1.916 albertel 652: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 653: if ($name eq '') {
654: $name = 'lonID';
655: }
656: my $lonid=$cookies{$name};
1.916 albertel 657: return undef if (!$lonid);
658:
659: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 660: my $lonidsdir;
661: if ($name eq 'lonDAV') {
662: $lonidsdir=$r->dir_config('lonDAVsessDir');
663: } else {
664: $lonidsdir=$r->dir_config('lonIDsDir');
665: }
1.916 albertel 666: return undef if (!-e "$lonidsdir/$handle.id");
667:
1.917 albertel 668: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
669: return undef if (!$opened);
1.916 albertel 670:
671: flock($idf,LOCK_SH);
672: my %disk_env;
673: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
674: &GDBM_READER(),0640)) {
675: return undef;
676: }
677:
678: if (!defined($disk_env{'user.name'})
679: || !defined($disk_env{'user.domain'})) {
680: return undef;
681: }
1.1245 raeburn 682:
683: if (ref($userhashref) eq 'HASH') {
684: $userhashref->{'name'} = $disk_env{'user.name'};
685: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 686: }
1.1245 raeburn 687:
1.916 albertel 688: return $handle;
689: }
690:
1.830 albertel 691: sub timed_flock {
692: my ($file,$lock_type) = @_;
693: my $failed=0;
694: eval {
695: local $SIG{__DIE__}='DEFAULT';
696: local $SIG{ALRM}=sub {
697: $failed=1;
698: die("failed lock");
699: };
700: alarm(13);
701: flock($file,$lock_type);
702: alarm(0);
703: };
704: if ($failed) {
705: return undef;
706: } else {
707: return 1;
708: }
709: }
710:
1.5 www 711: # ---------------------------------------------------------- Append Environment
712:
713: sub appenv {
1.949 raeburn 714: my ($newenv,$roles) = @_;
715: if (ref($newenv) eq 'HASH') {
716: foreach my $key (keys(%{$newenv})) {
717: my $refused = 0;
718: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
719: $refused = 1;
720: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 721: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 722: if (grep(/^\Q$role\E$/,@{$roles})) {
723: $refused = 0;
724: }
725: }
726: }
727: if ($refused) {
728: &logthis("<font color=\"blue\">WARNING: ".
729: "Attempt to modify environment ".$key." to ".$newenv->{$key}
730: .'</font>');
731: delete($newenv->{$key});
732: } else {
733: $env{$key}=$newenv->{$key};
734: }
735: }
736: my $opened = open(my $env_file,'+<',$env{'user.environment'});
737: if ($opened
738: && &timed_flock($env_file,LOCK_EX)
739: &&
740: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
741: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
742: while (my ($key,$value) = each(%{$newenv})) {
743: $disk_env{$key} = $value;
744: }
745: untie(%disk_env);
1.35 www 746: }
1.191 harris41 747: }
1.56 www 748: return 'ok';
749: }
750: # ----------------------------------------------------- Delete from Environment
751:
752: sub delenv {
1.1104 raeburn 753: my ($delthis,$regexp,$roles) = @_;
754: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
755: my $refused = 1;
756: if (ref($roles) eq 'ARRAY') {
757: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
758: if (grep(/^\Q$role\E$/,@{$roles})) {
759: $refused = 0;
760: }
761: }
762: if ($refused) {
763: &logthis("<font color=\"blue\">WARNING: ".
764: "Attempt to delete from environment ".$delthis);
765: return 'error';
766: }
1.56 www 767: }
1.917 albertel 768: my $opened = open(my $env_file,'+<',$env{'user.environment'});
769: if ($opened
1.915 albertel 770: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 771: &&
772: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
773: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 774: foreach my $key (keys(%disk_env)) {
1.987 raeburn 775: if ($regexp) {
776: if ($key=~/^$delthis/) {
777: delete($env{$key});
778: delete($disk_env{$key});
779: }
780: } else {
781: if ($key=~/^\Q$delthis\E/) {
782: delete($env{$key});
783: delete($disk_env{$key});
784: }
785: }
1.448 albertel 786: }
1.783 albertel 787: untie(%disk_env);
1.5 www 788: }
789: return 'ok';
1.369 albertel 790: }
791:
1.790 albertel 792: sub get_env_multiple {
793: my ($name) = @_;
794: my @values;
795: if (defined($env{$name})) {
796: # exists is it an array
797: if (ref($env{$name})) {
798: @values=@{ $env{$name} };
799: } else {
800: $values[0]=$env{$name};
801: }
802: }
803: return(@values);
804: }
805:
1.958 www 806: # ------------------------------------------------------------------- Locking
807:
808: sub set_lock {
809: my ($text)=@_;
810: $locknum++;
811: my $id=$$.'-'.$locknum;
812: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
813: 'session.lock.'.$id => $text});
814: return $id;
815: }
816:
817: sub get_locks {
818: my $num=0;
819: my %texts=();
820: foreach my $lock (split(/\,/,$env{'session.locks'})) {
821: if ($lock=~/\w/) {
822: $num++;
823: $texts{$lock}=$env{'session.lock.'.$lock};
824: }
825: }
826: return ($num,%texts);
827: }
828:
829: sub remove_lock {
830: my ($id)=@_;
831: my $newlocks='';
832: foreach my $lock (split(/\,/,$env{'session.locks'})) {
833: if (($lock=~/\w/) && ($lock ne $id)) {
834: $newlocks.=','.$lock;
835: }
836: }
837: &appenv({'session.locks' => $newlocks});
838: &delenv('session.lock.'.$id);
839: }
840:
841: sub remove_all_locks {
842: my $activelocks=$env{'session.locks'};
843: foreach my $lock (split(/\,/,$env{'session.locks'})) {
844: if ($lock=~/\w/) {
845: &remove_lock($lock);
846: }
847: }
848: }
849:
850:
1.369 albertel 851: # ------------------------------------------ Find out current server userload
852: sub userload {
853: my $numusers=0;
854: {
855: opendir(LONIDS,$perlvar{'lonIDsDir'});
856: my $filename;
857: my $curtime=time;
858: while ($filename=readdir(LONIDS)) {
1.925 albertel 859: next if ($filename eq '.' || $filename eq '..');
860: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 861: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 862: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 863: }
864: closedir(LONIDS);
865: }
866: my $userloadpercent=0;
867: my $maxuserload=$perlvar{'lonUserLoadLim'};
868: if ($maxuserload) {
1.371 albertel 869: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 870: }
1.372 albertel 871: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 872: return $userloadpercent;
1.283 www 873: }
874:
1.1 albertel 875: # ------------------------------ Find server with least workload from spare.tab
1.11 www 876:
1.1 albertel 877: sub spareserver {
1.1083 raeburn 878: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 879: my $spare_server;
1.370 albertel 880: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 881: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
882: : $userloadpercent;
1.1083 raeburn 883: my ($uint_dom,$remotesessions);
884: if (($udom ne '') && (&domain($udom) ne '')) {
885: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
886: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
887: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
888: $remotesessions = $udomdefaults{'remotesessions'};
889: }
1.1123 raeburn 890: my $spareshash = &this_host_spares($udom);
891: if (ref($spareshash) eq 'HASH') {
892: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
893: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 894: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
895: $try_server));
1.1123 raeburn 896: ($spare_server, $lowest_load) =
897: &compare_server_load($try_server, $spare_server, $lowest_load);
898: }
1.1083 raeburn 899: }
1.784 albertel 900:
1.1123 raeburn 901: my $found_server = ($spare_server ne '' && $lowest_load < 100);
902:
903: if (!$found_server) {
904: if (ref($spareshash->{'default'}) eq 'ARRAY') {
905: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 906: next unless (&spare_can_host($udom,$uint_dom,
907: $remotesessions,$try_server));
1.1123 raeburn 908: ($spare_server, $lowest_load) =
909: &compare_server_load($try_server, $spare_server, $lowest_load);
910: }
911: }
912: }
1.784 albertel 913: }
914:
915: if (!$want_server_name) {
1.968 raeburn 916: my $protocol = 'http';
917: if ($protocol{$spare_server} eq 'https') {
918: $protocol = $protocol{$spare_server};
919: }
1.1001 raeburn 920: if (defined($spare_server)) {
921: my $hostname = &hostname($spare_server);
1.1083 raeburn 922: if (defined($hostname)) {
1.1001 raeburn 923: $spare_server = $protocol.'://'.$hostname;
924: }
925: }
1.784 albertel 926: }
927: return $spare_server;
928: }
929:
930: sub compare_server_load {
1.1253 raeburn 931: my ($try_server, $spare_server, $lowest_load, $required) = @_;
932:
933: if ($required) {
934: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
935: my $remoterev = &get_server_loncaparev(undef,$try_server);
936: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
937: if (($major eq '' && $minor eq '') ||
938: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
939: return ($spare_server,$lowest_load);
940: }
941: }
1.784 albertel 942:
943: my $loadans = &reply('load', $try_server);
944: my $userloadans = &reply('userload',$try_server);
945:
946: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 947: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 948: }
949:
950: my $load;
951: if ($loadans =~ /\d/) {
952: if ($userloadans =~ /\d/) {
953: #both are numbers, pick the bigger one
954: $load = ($loadans > $userloadans) ? $loadans
955: : $userloadans;
1.411 albertel 956: } else {
1.784 albertel 957: $load = $loadans;
1.411 albertel 958: }
1.784 albertel 959: } else {
960: $load = $userloadans;
961: }
962:
963: if (($load =~ /\d/) && ($load < $lowest_load)) {
964: $spare_server = $try_server;
965: $lowest_load = $load;
1.370 albertel 966: }
1.784 albertel 967: return ($spare_server,$lowest_load);
1.202 matthew 968: }
1.914 albertel 969:
970: # --------------------------- ask offload servers if user already has a session
971: sub find_existing_session {
972: my ($udom,$uname) = @_;
1.1123 raeburn 973: my $spareshash = &this_host_spares($udom);
974: if (ref($spareshash) eq 'HASH') {
975: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
976: foreach my $try_server (@{ $spareshash->{'primary'} }) {
977: return $try_server if (&has_user_session($try_server, $udom, $uname));
978: }
979: }
980: if (ref($spareshash->{'default'}) eq 'ARRAY') {
981: foreach my $try_server (@{ $spareshash->{'default'} }) {
982: return $try_server if (&has_user_session($try_server, $udom, $uname));
983: }
984: }
1.914 albertel 985: }
986: return;
987: }
988:
989: # -------------------------------- ask if server already has a session for user
990: sub has_user_session {
991: my ($lonid,$udom,$uname) = @_;
992: my $result = &reply(join(':','userhassession',
993: map {&escape($_)} ($udom,$uname)),$lonid);
994: return 1 if ($result eq 'ok');
995:
996: return 0;
997: }
998:
1.1076 raeburn 999: # --------- determine least loaded server in a user's domain which allows login
1000:
1001: sub choose_server {
1.1259 raeburn 1002: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1003: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1004: my %servers = &get_servers($udom);
1.1076 raeburn 1005: my $lowest_load = 30000;
1.1259 raeburn 1006: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1007: if ($skiploadbal) {
1008: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1009: unless (defined($cached)) {
1010: my $cachetime = 60*60*24;
1011: my %domconfig =
1012: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1013: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1014: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1015: $cachetime);
1016: }
1017: }
1018: }
1.1076 raeburn 1019: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1020: if ($skiploadbal) {
1021: if (ref($balancers) eq 'HASH') {
1022: next if (exists($balancers->{$lonhost}));
1023: }
1024: }
1.1115 raeburn 1025: my $loginvia;
1026: if ($checkloginvia) {
1027: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1028: if ($loginvia) {
1029: my ($server,$path) = split(/:/,$loginvia);
1030: ($login_host, $lowest_load) =
1.1253 raeburn 1031: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1032: if ($login_host eq $server) {
1033: $portal_path = $path;
1.1151 raeburn 1034: $isredirect = 1;
1.1116 raeburn 1035: }
1036: } else {
1037: ($login_host, $lowest_load) =
1.1253 raeburn 1038: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1039: if ($login_host eq $lonhost) {
1040: $portal_path = '';
1.1151 raeburn 1041: $isredirect = '';
1.1116 raeburn 1042: }
1043: }
1044: } else {
1.1076 raeburn 1045: ($login_host, $lowest_load) =
1.1253 raeburn 1046: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1047: }
1048: }
1049: if ($login_host ne '') {
1.1116 raeburn 1050: $hostname = &hostname($login_host);
1.1076 raeburn 1051: }
1.1151 raeburn 1052: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1053: }
1054:
1.202 matthew 1055: # --------------------------------------------- Try to change a user's password
1056:
1057: sub changepass {
1.799 raeburn 1058: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1059: $currentpass = &escape($currentpass);
1060: $newpass = &escape($newpass);
1.1030 raeburn 1061: my $lonhost = $perlvar{'lonHostID'};
1062: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1063: $server);
1064: if (! $answer) {
1065: &logthis("No reply on password change request to $server ".
1066: "by $uname in domain $udom.");
1067: } elsif ($answer =~ "^ok") {
1068: &logthis("$uname in $udom successfully changed their password ".
1069: "on $server.");
1070: } elsif ($answer =~ "^pwchange_failure") {
1071: &logthis("$uname in $udom was unable to change their password ".
1072: "on $server. The action was blocked by either lcpasswd ".
1073: "or pwchange");
1074: } elsif ($answer =~ "^non_authorized") {
1075: &logthis("$uname in $udom did not get their password correct when ".
1076: "attempting to change it on $server.");
1077: } elsif ($answer =~ "^auth_mode_error") {
1078: &logthis("$uname in $udom attempted to change their password despite ".
1079: "not being locally or internally authenticated on $server.");
1080: } elsif ($answer =~ "^unknown_user") {
1081: &logthis("$uname in $udom attempted to change their password ".
1082: "on $server but were unable to because $server is not ".
1083: "their home server.");
1084: } elsif ($answer =~ "^refused") {
1085: &logthis("$server refused to change $uname in $udom password because ".
1086: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1087: } elsif ($answer =~ "invalid_client") {
1088: &logthis("$server refused to change $uname in $udom password because ".
1089: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1090: }
1091: return $answer;
1.1 albertel 1092: }
1093:
1.169 harris41 1094: # ----------------------- Try to determine user's current authentication scheme
1095:
1096: sub queryauthenticate {
1097: my ($uname,$udom)=@_;
1.456 albertel 1098: my $uhome=&homeserver($uname,$udom);
1099: if (!$uhome) {
1100: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1101: return 'no_host';
1102: }
1103: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1104: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1105: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1106: }
1.456 albertel 1107: return $answer;
1.169 harris41 1108: }
1109:
1.1 albertel 1110: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1111:
1.1 albertel 1112: sub authenticate {
1.1073 raeburn 1113: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1114: $upass=&escape($upass);
1115: $uname= &LONCAPA::clean_username($uname);
1.836 www 1116: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1117: my $newhome;
1.836 www 1118: if ((!$uhome) || ($uhome eq 'no_host')) {
1119: # Maybe the machine was offline and only re-appeared again recently?
1120: &reconlonc();
1121: # One more
1.952 raeburn 1122: $uhome=&homeserver($uname,$udom,1);
1123: if (($uhome eq 'no_host') && $checkdefauth) {
1124: if (defined(&domain($udom,'primary'))) {
1125: $newhome=&domain($udom,'primary');
1126: }
1127: if ($newhome ne '') {
1128: $uhome = $newhome;
1129: }
1130: }
1.836 www 1131: if ((!$uhome) || ($uhome eq 'no_host')) {
1132: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1133: return 'no_host';
1134: }
1.1 albertel 1135: }
1.1073 raeburn 1136: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1137: if ($answer eq 'authorized') {
1.952 raeburn 1138: if ($newhome) {
1139: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1140: return 'no_account_on_host';
1141: } else {
1142: &logthis("User $uname at $udom authorized by $uhome");
1143: return $uhome;
1144: }
1.471 albertel 1145: }
1146: if ($answer eq 'non_authorized') {
1147: &logthis("User $uname at $udom rejected by $uhome");
1148: return 'no_host';
1.9 www 1149: }
1.471 albertel 1150: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1151: return 'no_host';
1152: }
1153:
1.1073 raeburn 1154: sub can_host_session {
1.1074 raeburn 1155: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1156: my $canhost = 1;
1.1074 raeburn 1157: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1158: if (ref($remotesessions) eq 'HASH') {
1159: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1160: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1161: $canhost = 0;
1162: } else {
1163: $canhost = 1;
1164: }
1165: }
1166: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1167: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1168: $canhost = 1;
1169: } else {
1170: $canhost = 0;
1171: }
1172: }
1173: if ($canhost) {
1174: if ($remotesessions->{'version'} ne '') {
1175: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1176: if ($reqmajor ne '' && $reqminor ne '') {
1177: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1178: my $major = $1;
1179: my $minor = $2;
1180: if (($major < $reqmajor ) ||
1181: (($major == $reqmajor) && ($minor < $reqminor))) {
1182: $canhost = 0;
1183: }
1184: } else {
1185: $canhost = 0;
1186: }
1187: }
1188: }
1189: }
1190: }
1191: if ($canhost) {
1192: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1193: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1194: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1195: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1196: if (($uint_dom ne '') &&
1197: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1198: $canhost = 0;
1199: } else {
1200: $canhost = 1;
1201: }
1202: }
1203: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1204: if (($uint_dom ne '') &&
1205: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1206: $canhost = 1;
1207: } else {
1208: $canhost = 0;
1209: }
1210: }
1211: }
1212: }
1213: return $canhost;
1214: }
1215:
1.1083 raeburn 1216: sub spare_can_host {
1217: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1218: my $canhost=1;
1.1279 raeburn 1219: my $try_server_hostname = &hostname($try_server);
1220: my $serverhomeID = &get_server_homeID($try_server_hostname);
1221: my $serverhomedom = &host_domain($serverhomeID);
1222: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1223: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1224: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1225: $canhost = 0;
1226: }
1227: }
1228: if (($canhost) && ($uint_dom)) {
1229: my @intdoms;
1230: my $internet_names = &get_internet_names($try_server);
1231: if (ref($internet_names) eq 'ARRAY') {
1232: @intdoms = @{$internet_names};
1233: }
1234: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1235: my $remoterev = &get_server_loncaparev(undef,$try_server);
1236: $canhost = &can_host_session($udom,$try_server,$remoterev,
1237: $remotesessions,
1238: $defdomdefaults{'hostedsessions'});
1239: }
1.1083 raeburn 1240: }
1241: return $canhost;
1242: }
1243:
1.1123 raeburn 1244: sub this_host_spares {
1245: my ($dom) = @_;
1.1126 raeburn 1246: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1247: my @hosts = ¤t_machine_ids();
1248: foreach my $lonhost (@hosts) {
1249: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1250: $dom_in_use = $dom;
1251: $lonhost_in_use = $lonhost;
1.1123 raeburn 1252: last;
1253: }
1254: }
1.1126 raeburn 1255: if ($dom_in_use ne '') {
1256: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1257: }
1258: if (ref($result) ne 'HASH') {
1259: $lonhost_in_use = $perlvar{'lonHostID'};
1260: $dom_in_use = &host_domain($lonhost_in_use);
1261: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1262: if (ref($result) ne 'HASH') {
1263: $result = \%spareid;
1264: }
1265: }
1266: return $result;
1267: }
1268:
1269: sub spares_for_offload {
1270: my ($dom_in_use,$lonhost_in_use) = @_;
1271: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1272: if (defined($cached)) {
1273: return $result;
1274: } else {
1.1126 raeburn 1275: my $cachetime = 60*60*24;
1276: my %domconfig =
1277: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1278: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1279: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1280: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1281: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1282: }
1283: }
1284: }
1285: }
1.1126 raeburn 1286: return;
1.1123 raeburn 1287: }
1288:
1.1129 raeburn 1289: sub get_lonbalancer_config {
1290: my ($servers) = @_;
1291: my ($currbalancer,$currtargets);
1292: if (ref($servers) eq 'HASH') {
1293: foreach my $server (keys(%{$servers})) {
1294: my %what = (
1295: spareid => 1,
1296: perlvar => 1,
1297: );
1298: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1299: if ($result eq 'ok') {
1300: if (ref($returnhash) eq 'HASH') {
1301: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1302: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1303: $currbalancer = $server;
1304: $currtargets = {};
1305: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1306: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1307: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1308: }
1309: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1310: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1311: }
1312: }
1313: last;
1314: }
1315: }
1316: }
1317: }
1318: }
1319: }
1320: return ($currbalancer,$currtargets);
1321: }
1322:
1323: sub check_loadbalancing {
1324: my ($uname,$udom) = @_;
1.1191 raeburn 1325: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1326: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1327: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1328: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1329: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1330: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1331: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1332: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1333: my $domneedscache;
1.1129 raeburn 1334: my $cachetime = 60*60*24;
1335:
1336: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1337: $dom_in_use = $udom;
1338: $homeintdom = 1;
1339: } else {
1340: $dom_in_use = $serverhomedom;
1341: }
1342: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1343: unless (defined($cached)) {
1344: my %domconfig =
1345: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1346: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1347: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1348: } else {
1349: $domneedscache = $dom_in_use;
1.1129 raeburn 1350: }
1351: }
1352: if (ref($result) eq 'HASH') {
1.1191 raeburn 1353: ($is_balancer,$currtargets,$currrules) =
1354: &check_balancer_result($result,@hosts);
1.1129 raeburn 1355: if ($is_balancer) {
1356: if (ref($currrules) eq 'HASH') {
1357: if ($homeintdom) {
1358: if ($uname ne '') {
1359: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1360: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1361: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1362: $rule_in_effect = $currrules->{'_LC_author'};
1363: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1364: $rule_in_effect = $currrules->{'_LC_adv'}
1365: }
1366: }
1367: if ($rule_in_effect eq '') {
1368: my %userenv = &userenvironment($udom,$uname,'inststatus');
1369: if ($userenv{'inststatus'} ne '') {
1370: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1371: my ($othertitle,$usertypes,$types) =
1372: &Apache::loncommon::sorted_inst_types($udom);
1373: if (ref($types) eq 'ARRAY') {
1374: foreach my $type (@{$types}) {
1375: if (grep(/^\Q$type\E$/,@statuses)) {
1376: if (exists($currrules->{$type})) {
1377: $rule_in_effect = $currrules->{$type};
1378: }
1379: }
1380: }
1381: }
1382: } else {
1383: if (exists($currrules->{'default'})) {
1384: $rule_in_effect = $currrules->{'default'};
1385: }
1386: }
1387: }
1388: } else {
1389: if (exists($currrules->{'default'})) {
1390: $rule_in_effect = $currrules->{'default'};
1391: }
1392: }
1393: } else {
1394: if ($currrules->{'_LC_external'} ne '') {
1395: $rule_in_effect = $currrules->{'_LC_external'};
1396: }
1397: }
1398: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1399: $uname,$udom);
1400: }
1401: }
1402: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1403: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1404: unless (defined($cached)) {
1405: my %domconfig =
1406: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1407: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1408: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1409: } else {
1410: $domneedscache = $serverhomedom;
1.1129 raeburn 1411: }
1412: }
1413: if (ref($result) eq 'HASH') {
1.1191 raeburn 1414: ($is_balancer,$currtargets,$currrules) =
1415: &check_balancer_result($result,@hosts);
1416: if ($is_balancer) {
1.1129 raeburn 1417: if (ref($currrules) eq 'HASH') {
1418: if ($currrules->{'_LC_internetdom'} ne '') {
1419: $rule_in_effect = $currrules->{'_LC_internetdom'};
1420: }
1421: }
1422: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1423: $uname,$udom);
1424: }
1425: } else {
1426: if ($perlvar{'lonBalancer'} eq 'yes') {
1427: $is_balancer = 1;
1428: $offloadto = &this_host_spares($dom_in_use);
1429: }
1.1307 raeburn 1430: unless (defined($cached)) {
1431: $domneedscache = $serverhomedom;
1432: }
1.1129 raeburn 1433: }
1434: } else {
1435: if ($perlvar{'lonBalancer'} eq 'yes') {
1436: $is_balancer = 1;
1437: $offloadto = &this_host_spares($dom_in_use);
1438: }
1.1307 raeburn 1439: unless (defined($cached)) {
1440: $domneedscache = $serverhomedom;
1441: }
1442: }
1443: if ($domneedscache) {
1444: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1445: }
1.1176 raeburn 1446: if ($is_balancer) {
1447: my $lowest_load = 30000;
1448: if (ref($offloadto) eq 'HASH') {
1449: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1450: foreach my $try_server (@{$offloadto->{'primary'}}) {
1451: ($otherserver,$lowest_load) =
1452: &compare_server_load($try_server,$otherserver,$lowest_load);
1453: }
1.1129 raeburn 1454: }
1.1176 raeburn 1455: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1456:
1.1176 raeburn 1457: if (!$found_server) {
1458: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1459: foreach my $try_server (@{$offloadto->{'default'}}) {
1460: ($otherserver,$lowest_load) =
1461: &compare_server_load($try_server,$otherserver,$lowest_load);
1462: }
1463: }
1464: }
1465: } elsif (ref($offloadto) eq 'ARRAY') {
1466: if (@{$offloadto} == 1) {
1467: $otherserver = $offloadto->[0];
1468: } elsif (@{$offloadto} > 1) {
1469: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1470: ($otherserver,$lowest_load) =
1471: &compare_server_load($try_server,$otherserver,$lowest_load);
1472: }
1473: }
1474: }
1.1176 raeburn 1475: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1476: $is_balancer = 0;
1477: if ($uname ne '' && $udom ne '') {
1478: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1479:
1480: &appenv({'user.loadbalexempt' => $lonhost,
1481: 'user.loadbalcheck.time' => time});
1482: }
1.1129 raeburn 1483: }
1484: }
1485: }
1486: return ($is_balancer,$otherserver);
1487: }
1488:
1.1191 raeburn 1489: sub check_balancer_result {
1490: my ($result,@hosts) = @_;
1491: my ($is_balancer,$currtargets,$currrules);
1492: if (ref($result) eq 'HASH') {
1493: if ($result->{'lonhost'} ne '') {
1494: my $currbalancer = $result->{'lonhost'};
1495: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1496: $is_balancer = 1;
1497: $currtargets = $result->{'targets'};
1498: $currrules = $result->{'rules'};
1499: }
1500: } else {
1501: foreach my $key (keys(%{$result})) {
1502: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1503: (ref($result->{$key}) eq 'HASH')) {
1504: $is_balancer = 1;
1505: $currrules = $result->{$key}{'rules'};
1506: $currtargets = $result->{$key}{'targets'};
1507: last;
1508: }
1509: }
1510: }
1511: }
1512: return ($is_balancer,$currtargets,$currrules);
1513: }
1514:
1.1129 raeburn 1515: sub get_loadbalancer_targets {
1516: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1517: my $offloadto;
1.1175 raeburn 1518: if ($rule_in_effect eq 'none') {
1519: return [$perlvar{'lonHostID'}];
1520: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1521: $offloadto = $currtargets;
1522: } else {
1523: if ($rule_in_effect eq 'homeserver') {
1524: my $homeserver = &homeserver($uname,$udom);
1525: if ($homeserver ne 'no_host') {
1526: $offloadto = [$homeserver];
1527: }
1528: } elsif ($rule_in_effect eq 'externalbalancer') {
1529: my %domconfig =
1530: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1531: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1532: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1533: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1534: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1535: }
1536: }
1537: } else {
1.1178 raeburn 1538: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1539: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1540: if (&hostname($remotebalancer) ne '') {
1541: $offloadto = [$remotebalancer];
1542: }
1543: }
1544: } elsif (&hostname($rule_in_effect) ne '') {
1545: $offloadto = [$rule_in_effect];
1546: }
1547: }
1548: return $offloadto;
1549: }
1550:
1.1127 raeburn 1551: sub internet_dom_servers {
1552: my ($dom) = @_;
1553: my (%uniqservers,%servers);
1554: my $primaryserver = &hostname(&domain($dom,'primary'));
1555: my @machinedoms = &machine_domains($primaryserver);
1556: foreach my $mdom (@machinedoms) {
1557: my %currservers = %servers;
1558: my %server = &get_servers($mdom);
1559: %servers = (%currservers,%server);
1560: }
1561: my %by_hostname;
1562: foreach my $id (keys(%servers)) {
1563: push(@{$by_hostname{$servers{$id}}},$id);
1564: }
1565: foreach my $hostname (sort(keys(%by_hostname))) {
1566: if (@{$by_hostname{$hostname}} > 1) {
1567: my $match = 0;
1568: foreach my $id (@{$by_hostname{$hostname}}) {
1569: if (&host_domain($id) eq $dom) {
1570: $uniqservers{$id} = $hostname;
1571: $match = 1;
1572: }
1573: }
1574: unless ($match) {
1575: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1576: }
1577: } else {
1578: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1579: }
1580: }
1581: return %uniqservers;
1582: }
1583:
1.1 albertel 1584: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1585:
1.599 albertel 1586: my %homecache;
1.1 albertel 1587: sub homeserver {
1.230 stredwic 1588: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1589: my $index="$uname:$udom";
1.426 albertel 1590:
1.599 albertel 1591: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1592:
1593: my %servers = &get_servers($udom,'library');
1594: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1595: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1596: exists($badServerCache{$tryserver}));
1.841 albertel 1597:
1598: my $answer=reply("home:$udom:$uname",$tryserver);
1599: if ($answer eq 'found') {
1600: delete($badServerCache{$tryserver});
1601: return $homecache{$index}=$tryserver;
1602: } elsif ($answer eq 'no_host') {
1603: $badServerCache{$tryserver}=1;
1604: }
1.1 albertel 1605: }
1606: return 'no_host';
1.70 www 1607: }
1608:
1.1300 raeburn 1609: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1610:
1611: sub idget {
1.1300 raeburn 1612: my ($udom,$idsref,$namespace)=@_;
1.70 www 1613: my %returnhash=();
1.1300 raeburn 1614: my @ids=();
1615: if (ref($idsref) eq 'ARRAY') {
1616: @ids = @{$idsref};
1617: } else {
1618: return %returnhash;
1619: }
1620: if ($namespace eq '') {
1621: $namespace = 'ids';
1622: }
1.70 www 1623:
1.841 albertel 1624: my %servers = &get_servers($udom,'library');
1625: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1626: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1627: if ($namespace eq 'ids') {
1628: $idlist=~tr/A-Z/a-z/;
1629: }
1630: my $reply;
1631: if ($namespace eq 'ids') {
1632: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1633: } else {
1634: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1635: }
1.841 albertel 1636: my @answer=();
1637: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1638: @answer=split(/\&/,$reply);
1639: } ;
1640: my $i;
1641: for ($i=0;$i<=$#ids;$i++) {
1642: if ($answer[$i]) {
1.1299 raeburn 1643: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1644: }
1.841 albertel 1645: }
1.1300 raeburn 1646: }
1.70 www 1647: return %returnhash;
1648: }
1649:
1650: # ------------------------------------- Find the IDs behind a list of usernames
1651:
1652: sub idrget {
1653: my ($udom,@unames)=@_;
1654: my %returnhash=();
1.800 albertel 1655: foreach my $uname (@unames) {
1656: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1657: }
1.70 www 1658: return %returnhash;
1659: }
1660:
1.1300 raeburn 1661: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 1662:
1663: sub idput {
1.1300 raeburn 1664: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 1665: my %servers=();
1.1300 raeburn 1666: my %ids=();
1667: my %byid = ();
1668: if (ref($idsref) eq 'HASH') {
1669: %ids=%{$idsref};
1670: }
1671: if ($namespace eq '') {
1672: $namespace = 'ids';
1673: }
1.800 albertel 1674: foreach my $uname (keys(%ids)) {
1675: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 1676: if ($uhom eq '') {
1677: $uhom=&homeserver($uname,$udom);
1678: }
1.70 www 1679: if ($uhom ne 'no_host') {
1.800 albertel 1680: my $esc_unam=&escape($uname);
1.1300 raeburn 1681: if ($namespace eq 'ids') {
1682: my $id=&escape($ids{$uname});
1683: $id=~tr/A-Z/a-z/;
1684: my $esc_unam=&escape($uname);
1685: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 1686: } else {
1.1300 raeburn 1687: my @currids = split(/,/,$ids{$uname});
1688: foreach my $id (@currids) {
1689: $byid{$uhom}{$id} .= $uname.',';
1690: }
1691: }
1692: }
1693: }
1694: if ($namespace eq 'clickers') {
1695: foreach my $server (keys(%byid)) {
1696: if (ref($byid{$server}) eq 'HASH') {
1697: foreach my $id (keys(%{$byid{$server}})) {
1698: $byid{$server} =~ s/,$//;
1699: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
1700: }
1.70 www 1701: }
1702: }
1.191 harris41 1703: }
1.800 albertel 1704: foreach my $server (keys(%servers)) {
1.1300 raeburn 1705: $servers{$server} =~ s/\&$//;
1706: if ($namespace eq 'ids') {
1707: &critical('idput:'.$udom.':'.$servers{$server},$server);
1708: } else {
1709: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
1710: }
1.191 harris41 1711: }
1.344 www 1712: }
1713:
1.1300 raeburn 1714: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 1715:
1716: sub iddel {
1.1300 raeburn 1717: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 1718: my %result=();
1.1300 raeburn 1719: my %ids=();
1720: my %byid = ();
1721: if (ref($idshashref) eq 'HASH') {
1722: %ids=%{$idshashref};
1723: } else {
1.1231 raeburn 1724: return %result;
1725: }
1.1300 raeburn 1726: if ($namespace eq '') {
1727: $namespace = 'ids';
1728: }
1.1231 raeburn 1729: my %servers=();
1.1300 raeburn 1730: while (my ($id,$unamestr) = each(%ids)) {
1731: if ($namespace eq 'ids') {
1732: my $uhom = $uhome;
1733: if ($uhom eq '') {
1734: $uhom=&homeserver($unamestr,$udom);
1735: }
1736: if ($uhom ne 'no_host') {
1737: $servers{$uhom}.='&'.&escape($id);
1738: }
1739: } else {
1740: my @curritems = split(/,/,$ids{$id});
1741: foreach my $uname (@curritems) {
1742: my $uhom = $uhome;
1743: if ($uhom eq '') {
1744: $uhom=&homeserver($uname,$udom);
1745: }
1746: if ($uhom ne 'no_host') {
1747: $byid{$uhom}{$id} .= $uname.',';
1748: }
1749: }
1.1231 raeburn 1750: }
1.1300 raeburn 1751: }
1752: if ($namespace eq 'clickers') {
1753: foreach my $server (keys(%byid)) {
1754: if (ref($byid{$server}) eq 'HASH') {
1755: foreach my $id (keys(%{$byid{$server}})) {
1756: $byid{$server}{$id} =~ s/,$//;
1757: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
1758: }
1.1231 raeburn 1759: }
1760: }
1761: }
1762: foreach my $server (keys(%servers)) {
1.1300 raeburn 1763: $servers{$server} =~ s/\&$//;
1764: if ($namespace eq 'ids') {
1765: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1766: } elsif ($namespace eq 'clickers') {
1767: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
1768: }
1.1231 raeburn 1769: }
1770: return %result;
1771: }
1772:
1.1300 raeburn 1773: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
1774:
1775: sub updateclickers {
1776: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
1777: my %clickers;
1778: if (ref($idshashref) eq 'HASH') {
1779: %clickers=%{$idshashref};
1780: } else {
1781: return;
1782: }
1783: my $items='';
1784: foreach my $item (keys(%clickers)) {
1785: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
1786: }
1787: $items=~s/\&$//;
1788: my $request = "updateclickers:$udom:$action:$items";
1789: if ($critical) {
1790: return &critical($request,$uhome);
1791: } else {
1792: return &reply($request,$uhome);
1793: }
1794: }
1795:
1.1023 raeburn 1796: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1797: sub dump_dom {
1.1165 droeschl 1798: my ($namespace, $udom, $regexp) = @_;
1799:
1800: $udom ||= $env{'user.domain'};
1801:
1802: return () unless $udom;
1803:
1804: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1805: }
1806:
1.1023 raeburn 1807: # ------------------------------------------ get items from domain db files
1.806 raeburn 1808:
1809: sub get_dom {
1.860 raeburn 1810: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1811: return if ($udom eq 'public');
1.806 raeburn 1812: my $items='';
1813: foreach my $item (@$storearr) {
1814: $items.=&escape($item).'&';
1815: }
1816: $items=~s/\&$//;
1.860 raeburn 1817: if (!$udom) {
1818: $udom=$env{'user.domain'};
1.1267 raeburn 1819: return if ($udom eq 'public');
1.860 raeburn 1820: if (defined(&domain($udom,'primary'))) {
1821: $uhome=&domain($udom,'primary');
1822: } else {
1.874 albertel 1823: undef($uhome);
1.860 raeburn 1824: }
1825: } else {
1826: if (!$uhome) {
1827: if (defined(&domain($udom,'primary'))) {
1828: $uhome=&domain($udom,'primary');
1829: }
1830: }
1831: }
1832: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1833: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1834: my %returnhash;
1.875 albertel 1835: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1836: return %returnhash;
1837: }
1.806 raeburn 1838: my @pairs=split(/\&/,$rep);
1839: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1840: return @pairs;
1841: }
1842: my $i=0;
1843: foreach my $item (@$storearr) {
1844: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1845: $i++;
1846: }
1847: return %returnhash;
1848: } else {
1.880 banghart 1849: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1850: }
1851: }
1852:
1853: # -------------------------------------------- put items in domain db files
1854:
1855: sub put_dom {
1.860 raeburn 1856: my ($namespace,$storehash,$udom,$uhome)=@_;
1857: if (!$udom) {
1858: $udom=$env{'user.domain'};
1859: if (defined(&domain($udom,'primary'))) {
1860: $uhome=&domain($udom,'primary');
1861: } else {
1.874 albertel 1862: undef($uhome);
1.860 raeburn 1863: }
1864: } else {
1865: if (!$uhome) {
1866: if (defined(&domain($udom,'primary'))) {
1867: $uhome=&domain($udom,'primary');
1868: }
1869: }
1870: }
1871: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1872: my $items='';
1873: foreach my $item (keys(%$storehash)) {
1874: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1875: }
1876: $items=~s/\&$//;
1877: return &reply("putdom:$udom:$namespace:$items",$uhome);
1878: } else {
1.860 raeburn 1879: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1880: }
1881: }
1882:
1.1023 raeburn 1883: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1884: sub newput_dom {
1.1023 raeburn 1885: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1886: my $result;
1887: if (!$udom) {
1888: $udom=$env{'user.domain'};
1889: }
1.1023 raeburn 1890: if ($udom) {
1891: my $uname = &get_domainconfiguser($udom);
1892: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1893: }
1894: return $result;
1895: }
1896:
1.1023 raeburn 1897: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1898: sub del_dom {
1.1023 raeburn 1899: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1900: if (ref($storearr) eq 'ARRAY') {
1901: if (!$udom) {
1902: $udom=$env{'user.domain'};
1903: }
1.1023 raeburn 1904: if ($udom) {
1905: my $uname = &get_domainconfiguser($udom);
1906: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1907: }
1908: }
1909: }
1910:
1.1023 raeburn 1911: # ----------------------------------construct domainconfig user for a domain
1912: sub get_domainconfiguser {
1913: my ($udom) = @_;
1914: return $udom.'-domainconfig';
1915: }
1916:
1.837 raeburn 1917: sub retrieve_inst_usertypes {
1918: my ($udom) = @_;
1919: my (%returnhash,@order);
1.989 raeburn 1920: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1921: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1922: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1923: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1924: } else {
1925: if (defined(&domain($udom,'primary'))) {
1926: my $uhome=&domain($udom,'primary');
1927: my $rep=&reply("inst_usertypes:$udom",$uhome);
1928: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1929: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1930: return (\%returnhash,\@order);
1931: }
1932: my ($hashitems,$orderitems) = split(/:/,$rep);
1933: my @pairs=split(/\&/,$hashitems);
1934: foreach my $item (@pairs) {
1935: my ($key,$value)=split(/=/,$item,2);
1936: $key = &unescape($key);
1937: next if ($key =~ /^error: 2 /);
1938: $returnhash{$key}=&thaw_unescape($value);
1939: }
1940: my @esc_order = split(/\&/,$orderitems);
1941: foreach my $item (@esc_order) {
1942: push(@order,&unescape($item));
1943: }
1944: } else {
1.1256 raeburn 1945: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1946: }
1.1256 raeburn 1947: return (\%returnhash,\@order);
1.837 raeburn 1948: }
1949: }
1950:
1.868 raeburn 1951: sub is_domainimage {
1952: my ($url) = @_;
1.1306 raeburn 1953: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1954: if (&domain($1) ne '') {
1955: return '1';
1956: }
1957: }
1958: return;
1959: }
1960:
1.899 raeburn 1961: sub inst_directory_query {
1962: my ($srch) = @_;
1963: my $udom = $srch->{'srchdomain'};
1964: my %results;
1965: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1966: my $outcome;
1.899 raeburn 1967: if ($homeserver ne '') {
1.904 albertel 1968: my $queryid=&reply("querysend:instdirsearch:".
1969: &escape($srch->{'srchby'}).':'.
1970: &escape($srch->{'srchterm'}).':'.
1971: &escape($srch->{'srchtype'}),$homeserver);
1972: my $host=&hostname($homeserver);
1973: if ($queryid !~/^\Q$host\E\_/) {
1974: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1975: return;
1976: }
1977: my $response = &get_query_reply($queryid);
1978: my $maxtries = 5;
1979: my $tries = 1;
1980: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1981: $response = &get_query_reply($queryid);
1982: $tries ++;
1983: }
1984:
1985: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1986: if ($response eq 'unavailable') {
1987: $outcome = $response;
1988: } else {
1989: $outcome = 'ok';
1990: my @matches = split(/\n/,$response);
1991: foreach my $match (@matches) {
1992: my ($key,$value) = split(/=/,$match);
1993: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1994: }
1.899 raeburn 1995: }
1996: }
1997: }
1.909 raeburn 1998: return ($outcome,%results);
1.899 raeburn 1999: }
2000:
2001: sub usersearch {
2002: my ($srch) = @_;
2003: my $dom = $srch->{'srchdomain'};
2004: my %results;
2005: my %libserv = &all_library();
2006: my $query = 'usersearch';
2007: foreach my $tryserver (keys(%libserv)) {
2008: if (&host_domain($tryserver) eq $dom) {
2009: my $host=&hostname($tryserver);
2010: my $queryid=
1.911 raeburn 2011: &reply("querysend:".&escape($query).':'.
2012: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2013: &escape($srch->{'srchtype'}).':'.
2014: &escape($srch->{'srchterm'}),$tryserver);
2015: if ($queryid !~/^\Q$host\E\_/) {
2016: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2017: next;
1.899 raeburn 2018: }
2019: my $reply = &get_query_reply($queryid);
2020: my $maxtries = 1;
2021: my $tries = 1;
2022: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2023: $reply = &get_query_reply($queryid);
2024: $tries ++;
2025: }
2026: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2027: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2028: } else {
1.911 raeburn 2029: my @matches;
2030: if ($reply =~ /\n/) {
2031: @matches = split(/\n/,$reply);
2032: } else {
2033: @matches = split(/\&/,$reply);
2034: }
1.899 raeburn 2035: foreach my $match (@matches) {
2036: my ($uname,$udom,%userhash);
1.911 raeburn 2037: foreach my $entry (split(/:/,$match)) {
2038: my ($key,$value) =
2039: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2040: $userhash{$key} = $value;
2041: if ($key eq 'username') {
2042: $uname = $value;
2043: } elsif ($key eq 'domain') {
2044: $udom = $value;
1.911 raeburn 2045: }
1.899 raeburn 2046: }
2047: $results{$uname.':'.$udom} = \%userhash;
2048: }
2049: }
2050: }
2051: }
2052: return %results;
2053: }
2054:
1.912 raeburn 2055: sub get_instuser {
2056: my ($udom,$uname,$id) = @_;
2057: my $homeserver = &domain($udom,'primary');
2058: my ($outcome,%results);
2059: if ($homeserver ne '') {
2060: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2061: &escape($id).':'.&escape($udom),$homeserver);
2062: my $host=&hostname($homeserver);
2063: if ($queryid !~/^\Q$host\E\_/) {
2064: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2065: return;
2066: }
2067: my $response = &get_query_reply($queryid);
2068: my $maxtries = 5;
2069: my $tries = 1;
2070: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2071: $response = &get_query_reply($queryid);
2072: $tries ++;
2073: }
2074: if (!&error($response) && $response ne 'refused') {
2075: if ($response eq 'unavailable') {
2076: $outcome = $response;
2077: } else {
2078: $outcome = 'ok';
2079: my @matches = split(/\n/,$response);
2080: foreach my $match (@matches) {
2081: my ($key,$value) = split(/=/,$match);
2082: $results{&unescape($key)} = &thaw_unescape($value);
2083: }
2084: }
2085: }
2086: }
2087: my %userinfo;
2088: if (ref($results{$uname}) eq 'HASH') {
2089: %userinfo = %{$results{$uname}};
2090: }
2091: return ($outcome,%userinfo);
2092: }
2093:
1.1290 raeburn 2094: sub get_multiple_instusers {
2095: my ($udom,$users,$caller) = @_;
2096: my ($outcome,$results);
2097: if (ref($users) eq 'HASH') {
2098: my $count = keys(%{$users});
2099: my $requested = &freeze_escape($users);
2100: my $homeserver = &domain($udom,'primary');
2101: if ($homeserver ne '') {
2102: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2103: my $host=&hostname($homeserver);
2104: if ($queryid !~/^\Q$host\E\_/) {
2105: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2106: ' for host: '.$homeserver.'in domain '.$udom);
2107: return ($outcome,$results);
2108: }
2109: my $response = &get_query_reply($queryid);
2110: my $maxtries = 5;
2111: if ($count > 100) {
2112: $maxtries = 1+int($count/20);
2113: }
2114: my $tries = 1;
2115: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2116: $response = &get_query_reply($queryid);
2117: $tries ++;
2118: }
2119: if ($response eq '') {
2120: $results = {};
2121: foreach my $key (keys(%{$users})) {
2122: my ($uname,$id);
2123: if ($caller eq 'id') {
2124: $id = $key;
2125: } else {
2126: $uname = $key;
2127: }
2128: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2129: $outcome = $resp;
1.1290 raeburn 2130: if ($resp eq 'ok') {
2131: %{$results} = (%{$results}, %info);
2132: } else {
2133: last;
2134: }
2135: }
2136: } elsif(!&error($response) && ($response ne 'refused')) {
2137: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2138: $outcome = $response;
2139: } else {
1.1291 raeburn 2140: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2141: if ($outcome eq 'ok') {
2142: $results = &thaw_unescape($userdata);
2143: }
2144: }
2145: }
2146: }
2147: }
2148: return ($outcome,$results);
2149: }
2150:
1.912 raeburn 2151: sub inst_rulecheck {
1.923 raeburn 2152: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2153: my %returnhash;
2154: if ($udom ne '') {
2155: if (ref($rules) eq 'ARRAY') {
2156: @{$rules} = map {&escape($_);} (@{$rules});
2157: my $rulestr = join(':',@{$rules});
2158: my $homeserver=&domain($udom,'primary');
2159: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2160: my $response;
2161: if ($item eq 'username') {
2162: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2163: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2164: $homeserver));
1.923 raeburn 2165: } elsif ($item eq 'id') {
2166: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2167: ':'.&escape($id).':'.$rulestr,
2168: $homeserver));
1.945 raeburn 2169: } elsif ($item eq 'selfcreate') {
2170: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2171: &escape($udom).':'.&escape($uname).
2172: ':'.$rulestr,$homeserver));
1.923 raeburn 2173: }
1.912 raeburn 2174: if ($response ne 'refused') {
2175: my @pairs=split(/\&/,$response);
2176: foreach my $item (@pairs) {
2177: my ($key,$value)=split(/=/,$item,2);
2178: $key = &unescape($key);
2179: next if ($key =~ /^error: 2 /);
2180: $returnhash{$key}=&thaw_unescape($value);
2181: }
2182: }
2183: }
2184: }
2185: }
2186: return %returnhash;
2187: }
2188:
2189: sub inst_userrules {
1.923 raeburn 2190: my ($udom,$check) = @_;
1.912 raeburn 2191: my (%ruleshash,@ruleorder);
2192: if ($udom ne '') {
2193: my $homeserver=&domain($udom,'primary');
2194: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2195: my $response;
2196: if ($check eq 'id') {
2197: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2198: $homeserver);
1.943 raeburn 2199: } elsif ($check eq 'email') {
2200: $response=&reply('instemailrules:'.&escape($udom),
2201: $homeserver);
1.923 raeburn 2202: } else {
2203: $response=&reply('instuserrules:'.&escape($udom),
2204: $homeserver);
2205: }
1.912 raeburn 2206: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2207: ($response ne 'unknown_cmd') &&
1.912 raeburn 2208: ($response ne 'no_such_host')) {
2209: my ($hashitems,$orderitems) = split(/:/,$response);
2210: my @pairs=split(/\&/,$hashitems);
2211: foreach my $item (@pairs) {
2212: my ($key,$value)=split(/=/,$item,2);
2213: $key = &unescape($key);
2214: next if ($key =~ /^error: 2 /);
2215: $ruleshash{$key}=&thaw_unescape($value);
2216: }
2217: my @esc_order = split(/\&/,$orderitems);
2218: foreach my $item (@esc_order) {
2219: push(@ruleorder,&unescape($item));
2220: }
2221: }
2222: }
2223: }
2224: return (\%ruleshash,\@ruleorder);
2225: }
2226:
1.976 raeburn 2227: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2228:
2229: sub get_domain_defaults {
1.1240 raeburn 2230: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2231: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2232: my $cachetime = 60*60*24;
1.1240 raeburn 2233: unless ($ignore_cache) {
2234: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2235: if (defined($cached)) {
2236: if (ref($result) eq 'HASH') {
2237: return %{$result};
2238: }
1.943 raeburn 2239: }
2240: }
2241: my %domdefaults;
2242: my %domconfig =
1.989 raeburn 2243: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2244: 'requestcourses','inststatus',
1.1183 raeburn 2245: 'coursedefaults','usersessions',
1.1258 raeburn 2246: 'requestauthor','selfenrollment',
1.1320 raeburn 2247: 'coursecategories','ssl','autoenroll',
2248: 'trust'],$domain);
1.1305 raeburn 2249: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2250: if (ref($domconfig{'defaults'}) eq 'HASH') {
2251: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2252: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2253: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2254: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2255: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2256: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2257: } else {
2258: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2259: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2260: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2261: }
1.976 raeburn 2262: if (ref($domconfig{'quotas'}) eq 'HASH') {
2263: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2264: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2265: } else {
2266: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2267: }
1.1177 raeburn 2268: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2269: foreach my $item (@usertools) {
2270: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2271: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2272: }
2273: }
1.1229 raeburn 2274: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2275: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2276: }
1.976 raeburn 2277: }
1.985 raeburn 2278: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2279: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2280: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2281: }
2282: }
1.1183 raeburn 2283: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2284: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2285: }
1.989 raeburn 2286: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2287: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2288: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2289: }
2290: }
1.1047 raeburn 2291: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2292: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2293: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2294: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2295: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2296: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2297: }
1.1254 raeburn 2298: foreach my $type (@coursetypes) {
2299: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2300: unless ($type eq 'community') {
2301: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2302: }
2303: }
2304: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2305: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2306: }
1.1277 raeburn 2307: if ($domdefaults{'postsubmit'} eq 'on') {
2308: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2309: $domdefaults{$type.'postsubtimeout'} =
2310: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2311: }
2312: }
1.1230 raeburn 2313: }
1.1286 raeburn 2314: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2315: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2316: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2317: if (@clonecodes) {
2318: $domdefaults{'canclone'} = join('+',@clonecodes);
2319: }
2320: }
2321: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2322: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2323: }
1.1047 raeburn 2324: }
1.1073 raeburn 2325: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2326: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2327: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2328: }
2329: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2330: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2331: }
1.1279 raeburn 2332: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2333: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2334: }
1.1073 raeburn 2335: }
1.1254 raeburn 2336: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2337: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2338: my @settings = ('types','registered','enroll_dates','access_dates','section',
2339: 'approval','limit');
2340: foreach my $type (@coursetypes) {
2341: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2342: my @mgrdc = ();
2343: foreach my $item (@settings) {
2344: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2345: push(@mgrdc,$item);
2346: }
2347: }
2348: if (@mgrdc) {
2349: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2350: }
2351: }
2352: }
2353: }
2354: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2355: foreach my $type (@coursetypes) {
2356: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2357: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2358: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2359: }
2360: }
2361: }
2362: }
2363: }
1.1258 raeburn 2364: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2365: $domdefaults{'catauth'} = 'std';
2366: $domdefaults{'catunauth'} = 'std';
2367: if ($domconfig{'coursecategories'}{'auth'}) {
2368: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2369: }
2370: if ($domconfig{'coursecategories'}{'unauth'}) {
2371: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2372: }
2373: }
1.1315 raeburn 2374: if (ref($domconfig{'ssl'}) eq 'HASH') {
2375: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2376: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2377: }
2378: if (ref($domconfig{'ssl'}{'connect'}) eq 'HASH') {
2379: $domdefaults{'connect'} = $domconfig{'ssl'}{'connect'};
2380: }
2381: }
1.1320 raeburn 2382: if (ref($domconfig{'trust'}) eq 'HASH') {
2383: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2384: foreach my $prefix (@prefixes) {
2385: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2386: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2387: }
2388: }
2389: }
1.1314 raeburn 2390: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2391: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2392: }
1.1219 raeburn 2393: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2394: return %domdefaults;
2395: }
2396:
1.1311 raeburn 2397: sub course_portal_url {
2398: my ($cnum,$cdom) = @_;
2399: my $chome = &homeserver($cnum,$cdom);
2400: my $hostname = &hostname($chome);
2401: my $protocol = $protocol{$chome};
2402: $protocol = 'http' if ($protocol ne 'https');
2403: my %domdefaults = &get_domain_defaults($cdom);
2404: my $firsturl;
2405: if ($domdefaults{'portal_def'}) {
2406: $firsturl = $domdefaults{'portal_def'};
2407: } else {
2408: $firsturl = $protocol.'://'.$hostname;
2409: }
2410: return $firsturl;
2411: }
2412:
1.344 www 2413: # --------------------------------------------------- Assign a key to a student
2414:
2415: sub assign_access_key {
1.364 www 2416: #
2417: # a valid key looks like uname:udom#comments
2418: # comments are being appended
2419: #
1.498 www 2420: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2421: $kdom=
1.620 albertel 2422: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2423: $knum=
1.620 albertel 2424: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2425: $cdom=
1.620 albertel 2426: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2427: $cnum=
1.620 albertel 2428: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2429: $udom=$env{'user.name'} unless (defined($udom));
2430: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2431: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2432: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2433: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2434: # assigned to this person
2435: # - this should not happen,
1.345 www 2436: # unless something went wrong
2437: # the first time around
2438: # ready to assign
1.364 www 2439: $logentry=$1.'; '.$logentry;
1.496 www 2440: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2441: $kdom,$knum) eq 'ok') {
1.345 www 2442: # key now belongs to user
1.346 www 2443: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2444: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2445: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2446: return 'ok';
2447: } else {
2448: return
2449: 'error: Count not permanently assign key, will need to be re-entered later.';
2450: }
2451: } else {
2452: return 'error: Could not assign key, try again later.';
2453: }
1.364 www 2454: } elsif (!$existing{$ckey}) {
1.345 www 2455: # the key does not exist
2456: return 'error: The key does not exist';
2457: } else {
2458: # the key is somebody else's
2459: return 'error: The key is already in use';
2460: }
1.344 www 2461: }
2462:
1.364 www 2463: # ------------------------------------------ put an additional comment on a key
2464:
2465: sub comment_access_key {
2466: #
2467: # a valid key looks like uname:udom#comments
2468: # comments are being appended
2469: #
2470: my ($ckey,$cdom,$cnum,$logentry)=@_;
2471: $cdom=
1.620 albertel 2472: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2473: $cnum=
1.620 albertel 2474: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2475: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2476: if ($existing{$ckey}) {
2477: $existing{$ckey}.='; '.$logentry;
2478: # ready to assign
1.367 www 2479: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2480: $cdom,$cnum) eq 'ok') {
2481: return 'ok';
2482: } else {
2483: return 'error: Count not store comment.';
2484: }
2485: } else {
2486: # the key does not exist
2487: return 'error: The key does not exist';
2488: }
2489: }
2490:
1.344 www 2491: # ------------------------------------------------------ Generate a set of keys
2492:
2493: sub generate_access_keys {
1.364 www 2494: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2495: $cdom=
1.620 albertel 2496: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2497: $cnum=
1.620 albertel 2498: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2499: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2500: unless (($cdom) && ($cnum)) { return 0; }
2501: if ($number>10000) { return 0; }
2502: sleep(2); # make sure don't get same seed twice
2503: srand(time()^($$+($$<<15))); # from "Programming Perl"
2504: my $total=0;
2505: for (my $i=1;$i<=$number;$i++) {
2506: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2507: sprintf("%lx",int(100000*rand)).'-'.
2508: sprintf("%lx",int(100000*rand));
2509: $newkey=~s/1/g/g; # folks mix up 1 and l
2510: $newkey=~s/0/h/g; # and also 0 and O
2511: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2512: if ($existing{$newkey}) {
2513: $i--;
2514: } else {
1.364 www 2515: if (&put('accesskeys',
2516: { $newkey => '# generated '.localtime().
1.620 albertel 2517: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2518: '; '.$logentry },
2519: $cdom,$cnum) eq 'ok') {
1.344 www 2520: $total++;
2521: }
2522: }
2523: }
1.620 albertel 2524: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2525: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2526: return $total;
2527: }
2528:
2529: # ------------------------------------------------------- Validate an accesskey
2530:
2531: sub validate_access_key {
2532: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2533: $cdom=
1.620 albertel 2534: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2535: $cnum=
1.620 albertel 2536: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2537: $udom=$env{'user.domain'} unless (defined($udom));
2538: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2539: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2540: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2541: }
2542:
2543: # ------------------------------------- Find the section of student in a course
1.652 albertel 2544: sub devalidate_getsection_cache {
2545: my ($udom,$unam,$courseid)=@_;
2546: my $hashid="$udom:$unam:$courseid";
2547: &devalidate_cache_new('getsection',$hashid);
2548: }
1.298 matthew 2549:
1.815 albertel 2550: sub courseid_to_courseurl {
2551: my ($courseid) = @_;
2552: #already url style courseid
2553: return $courseid if ($courseid =~ m{^/});
2554:
2555: if (exists($env{'course.'.$courseid.'.num'})) {
2556: my $cnum = $env{'course.'.$courseid.'.num'};
2557: my $cdom = $env{'course.'.$courseid.'.domain'};
2558: return "/$cdom/$cnum";
2559: }
2560:
2561: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2562: if (exists($courseinfo{'num'})) {
2563: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2564: }
2565:
2566: return undef;
2567: }
2568:
1.298 matthew 2569: sub getsection {
2570: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2571: my $cachetime=1800;
1.551 albertel 2572:
2573: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2574: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2575: if (defined($cached)) { return $result; }
2576:
1.298 matthew 2577: my %Pending;
2578: my %Expired;
2579: #
2580: # Each role can either have not started yet (pending), be active,
2581: # or have expired.
2582: #
2583: # If there is an active role, we are done.
2584: #
2585: # If there is more than one role which has not started yet,
2586: # choose the one which will start sooner
2587: # If there is one role which has not started yet, return it.
2588: #
2589: # If there is more than one expired role, choose the one which ended last.
2590: # If there is a role which has expired, return it.
2591: #
1.815 albertel 2592: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2593: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2594: foreach my $key (keys(%roleshash)) {
1.479 albertel 2595: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2596: my $section=$1;
2597: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2598: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2599: my $now=time;
1.548 albertel 2600: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2601: $Expired{$end}=$section;
2602: next;
2603: }
1.548 albertel 2604: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2605: $Pending{$start}=$section;
2606: next;
2607: }
1.599 albertel 2608: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2609: }
2610: #
2611: # Presumedly there will be few matching roles from the above
2612: # loop and the sorting time will be negligible.
2613: if (scalar(keys(%Pending))) {
2614: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2615: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2616: }
2617: if (scalar(keys(%Expired))) {
2618: my @sorted = sort {$a <=> $b} keys(%Expired);
2619: my $time = pop(@sorted);
1.599 albertel 2620: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2621: }
1.599 albertel 2622: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2623: }
1.70 www 2624:
1.599 albertel 2625: sub save_cache {
2626: &purge_remembered();
1.722 albertel 2627: #&Apache::loncommon::validate_page();
1.620 albertel 2628: undef(%env);
1.780 albertel 2629: undef($env_loaded);
1.599 albertel 2630: }
1.452 albertel 2631:
1.599 albertel 2632: my $to_remember=-1;
2633: my %remembered;
2634: my %accessed;
2635: my $kicks=0;
2636: my $hits=0;
1.849 albertel 2637: sub make_key {
2638: my ($name,$id) = @_;
1.872 albertel 2639: if (length($id) > 65
2640: && length(&escape($id)) > 200) {
2641: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2642: }
1.849 albertel 2643: return &escape($name.':'.$id);
2644: }
2645:
1.599 albertel 2646: sub devalidate_cache_new {
2647: my ($name,$id,$debug) = @_;
2648: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 2649: my $remembered_id=$name.':'.$id;
1.849 albertel 2650: $id=&make_key($name,$id);
1.599 albertel 2651: $memcache->delete($id);
1.1319 damieng 2652: delete($remembered{$remembered_id});
2653: delete($accessed{$remembered_id});
1.599 albertel 2654: }
2655:
2656: sub is_cached_new {
2657: my ($name,$id,$debug) = @_;
1.1319 damieng 2658: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
2659: if (exists($remembered{$remembered_id})) {
2660: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2661: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2662: $hits++;
1.1319 damieng 2663: return ($remembered{$remembered_id},1);
1.599 albertel 2664: }
1.1319 damieng 2665: $id=&make_key($name,$id);
1.599 albertel 2666: my $value = $memcache->get($id);
2667: if (!(defined($value))) {
2668: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2669: return (undef,undef);
1.416 albertel 2670: }
1.599 albertel 2671: if ($value eq '__undef__') {
2672: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2673: $value=undef;
2674: }
1.1319 damieng 2675: &make_room($remembered_id,$value,$debug);
1.599 albertel 2676: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2677: return ($value,1);
2678: }
2679:
2680: sub do_cache_new {
2681: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 2682: my $remembered_id=$name.':'.$id;
1.849 albertel 2683: $id=&make_key($name,$id);
1.599 albertel 2684: my $setvalue=$value;
2685: if (!defined($setvalue)) {
2686: $setvalue='__undef__';
2687: }
1.623 albertel 2688: if (!defined($time) ) {
2689: $time=600;
2690: }
1.599 albertel 2691: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2692: my $result = $memcache->set($id,$setvalue,$time);
2693: if (! $result) {
1.872 albertel 2694: &logthis("caching of id -> $id failed");
1.910 albertel 2695: $memcache->disconnect_all();
1.872 albertel 2696: }
1.600 albertel 2697: # need to make a copy of $value
1.1319 damieng 2698: &make_room($remembered_id,$value,$debug);
1.599 albertel 2699: return $value;
2700: }
2701:
2702: sub make_room {
1.1319 damieng 2703: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2704:
1.1319 damieng 2705: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2706: : $value;
1.599 albertel 2707: if ($to_remember<0) { return; }
1.1319 damieng 2708: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2709: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2710: my $to_kick;
2711: my $max_time=0;
2712: foreach my $other (keys(%accessed)) {
2713: if (&tv_interval($accessed{$other}) > $max_time) {
2714: $to_kick=$other;
2715: $max_time=&tv_interval($accessed{$other});
2716: }
2717: }
2718: delete($remembered{$to_kick});
2719: delete($accessed{$to_kick});
2720: $kicks++;
2721: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2722: return;
2723: }
2724:
1.599 albertel 2725: sub purge_remembered {
1.604 albertel 2726: #&logthis("Tossing ".scalar(keys(%remembered)));
2727: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2728: undef(%remembered);
2729: undef(%accessed);
1.428 albertel 2730: }
1.70 www 2731: # ------------------------------------- Read an entry from a user's environment
2732:
2733: sub userenvironment {
2734: my ($udom,$unam,@what)=@_;
1.976 raeburn 2735: my $items;
2736: foreach my $item (@what) {
2737: $items.=&escape($item).'&';
2738: }
2739: $items=~s/\&$//;
1.70 www 2740: my %returnhash=();
1.1009 raeburn 2741: my $uhome = &homeserver($unam,$udom);
2742: unless ($uhome eq 'no_host') {
2743: my @answer=split(/\&/,
2744: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2745: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2746: return %returnhash;
2747: }
1.1009 raeburn 2748: my $i;
2749: for ($i=0;$i<=$#what;$i++) {
2750: $returnhash{$what[$i]}=&unescape($answer[$i]);
2751: }
1.70 www 2752: }
2753: return %returnhash;
1.1 albertel 2754: }
2755:
1.617 albertel 2756: # ---------------------------------------------------------- Get a studentphoto
2757: sub studentphoto {
2758: my ($udom,$unam,$ext) = @_;
2759: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2760: if (defined($env{'request.course.id'})) {
1.708 raeburn 2761: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2762: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2763: return(&retrievestudentphoto($udom,$unam,$ext));
2764: } else {
2765: my ($result,$perm_reqd)=
1.707 albertel 2766: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2767: if ($result eq 'ok') {
2768: if (!($perm_reqd eq 'yes')) {
2769: return(&retrievestudentphoto($udom,$unam,$ext));
2770: }
2771: }
2772: }
2773: }
2774: } else {
2775: my ($result,$perm_reqd) =
1.707 albertel 2776: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2777: if ($result eq 'ok') {
2778: if (!($perm_reqd eq 'yes')) {
2779: return(&retrievestudentphoto($udom,$unam,$ext));
2780: }
2781: }
2782: }
2783: return '/adm/lonKaputt/lonlogo_broken.gif';
2784: }
2785:
2786: sub retrievestudentphoto {
2787: my ($udom,$unam,$ext,$type) = @_;
2788: my $home=&Apache::lonnet::homeserver($unam,$udom);
2789: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2790: if ($ret eq 'ok') {
2791: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2792: if ($type eq 'thumbnail') {
2793: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2794: }
2795: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2796: return $tokenurl;
2797: } else {
2798: if ($type eq 'thumbnail') {
2799: return '/adm/lonKaputt/genericstudent_tn.gif';
2800: } else {
2801: return '/adm/lonKaputt/lonlogo_broken.gif';
2802: }
1.617 albertel 2803: }
2804: }
2805:
1.263 www 2806: # -------------------------------------------------------------------- New chat
2807:
2808: sub chatsend {
1.724 raeburn 2809: my ($newentry,$anon,$group)=@_;
1.620 albertel 2810: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2811: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2812: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2813: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2814: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2815: &escape($newentry)).':'.$group,$chome);
1.292 www 2816: }
2817:
2818: # ------------------------------------------ Find current version of a resource
2819:
2820: sub getversion {
2821: my $fname=&clutter(shift);
1.1189 raeburn 2822: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2823: return ¤tversion(&filelocation('',$fname));
2824: }
2825:
2826: sub currentversion {
2827: my $fname=shift;
2828: my $author=$fname;
2829: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2830: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2831: my $home=&homeserver($uname,$udom);
1.292 www 2832: if ($home eq 'no_host') {
2833: return -1;
2834: }
1.1112 www 2835: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2836: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2837: return -1;
2838: }
1.1112 www 2839: return $answer;
1.263 www 2840: }
2841:
1.1111 www 2842: #
2843: # Return special version number of resource if set by override, empty otherwise
2844: #
2845: sub usedversion {
2846: my $fname=shift;
2847: unless ($fname) { $fname=$env{'request.uri'}; }
2848: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2849: if ($urlversion) { return $urlversion; }
2850: return '';
2851: }
2852:
1.1 albertel 2853: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2854:
1.1 albertel 2855: sub subscribe {
2856: my $fname=shift;
1.761 raeburn 2857: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2858: $fname=~s/[\n\r]//g;
1.1 albertel 2859: my $author=$fname;
2860: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2861: my ($udom,$uname)=split(/\//,$author);
2862: my $home=homeserver($uname,$udom);
1.335 albertel 2863: if ($home eq 'no_host') {
2864: return 'not_found';
1.1 albertel 2865: }
2866: my $answer=reply("sub:$fname",$home);
1.64 www 2867: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2868: $answer.=' by '.$home;
2869: }
1.1 albertel 2870: return $answer;
2871: }
2872:
1.8 www 2873: # -------------------------------------------------------------- Replicate file
2874:
2875: sub repcopy {
2876: my $filename=shift;
1.23 www 2877: $filename=~s/\/+/\//g;
1.1142 raeburn 2878: my $londocroot = $perlvar{'lonDocRoot'};
2879: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2880: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2881: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2882: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2883: return &repcopy_userfile($filename);
2884: }
1.532 albertel 2885: $filename=~s/[\n\r]//g;
1.8 www 2886: my $transname="$filename.in.transfer";
1.828 www 2887: # FIXME: this should flock
1.607 raeburn 2888: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2889: my $remoteurl=subscribe($filename);
1.64 www 2890: if ($remoteurl =~ /^con_lost by/) {
2891: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2892: return 'unavailable';
1.8 www 2893: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2894: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2895: return 'not_found';
1.64 www 2896: } elsif ($remoteurl =~ /^rejected by/) {
2897: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2898: return 'forbidden';
1.20 www 2899: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2900: return 'ok';
1.8 www 2901: } else {
1.290 www 2902: my $author=$filename;
2903: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2904: my ($udom,$uname)=split(/\//,$author);
2905: my $home=homeserver($uname,$udom);
2906: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2907: my @parts=split(/\//,$filename);
2908: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2909: if ($path ne "$londocroot/res") {
1.8 www 2910: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2911: return 'bad_request';
1.8 www 2912: }
2913: my $count;
2914: for ($count=5;$count<$#parts;$count++) {
2915: $path.="/$parts[$count]";
2916: if ((-e $path)!=1) {
2917: mkdir($path,0777);
2918: }
2919: }
2920: my $ua=new LWP::UserAgent;
2921: my $request=new HTTP::Request('GET',"$remoteurl");
2922: my $response=$ua->request($request,$transname);
2923: if ($response->is_error()) {
2924: unlink($transname);
2925: my $message=$response->status_line;
1.672 albertel 2926: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2927: ." LWP get: $message: $filename</font>");
1.607 raeburn 2928: return 'unavailable';
1.8 www 2929: } else {
1.16 www 2930: if ($remoteurl!~/\.meta$/) {
2931: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2932: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2933: if ($mresponse->is_error()) {
2934: unlink($filename.'.meta');
2935: &logthis(
1.672 albertel 2936: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2937: }
2938: }
1.8 www 2939: rename($transname,$filename);
1.607 raeburn 2940: return 'ok';
1.8 www 2941: }
1.290 www 2942: }
1.8 www 2943: }
1.330 www 2944: }
2945:
2946: # ------------------------------------------------ Get server side include body
2947: sub ssi_body {
1.381 albertel 2948: my ($filelink,%form)=@_;
1.606 matthew 2949: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2950: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2951: }
1.953 www 2952: my $output='';
2953: my $response;
1.980 raeburn 2954: if ($filelink=~/^https?\:/) {
1.954 raeburn 2955: ($output,$response)=&externalssi($filelink);
1.953 www 2956: } else {
1.1004 droeschl 2957: $filelink .= $filelink=~/\?/ ? '&' : '?';
2958: $filelink .= 'inhibitmenu=yes';
1.953 www 2959: ($output,$response)=&ssi($filelink,%form);
2960: }
1.778 albertel 2961: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2962: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2963: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2964: if (wantarray) {
2965: return ($output, $response);
2966: } else {
2967: return $output;
2968: }
1.8 www 2969: }
2970:
1.15 www 2971: # --------------------------------------------------------- Server Side Include
2972:
1.782 albertel 2973: sub absolute_url {
2974: my ($host_name) = @_;
2975: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2976: if ($host_name eq '') {
2977: $host_name = $ENV{'SERVER_NAME'};
2978: }
2979: return $protocol.$host_name;
2980: }
2981:
1.942 foxr 2982: #
2983: # Server side include.
2984: # Parameters:
2985: # fn Possibly encrypted resource name/id.
2986: # form Hash that describes how the rendering should be done
2987: # and other things.
1.944 foxr 2988: # Returns:
1.950 raeburn 2989: # Scalar context: The content of the response.
2990: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2991: #
1.15 www 2992: sub ssi {
2993:
1.944 foxr 2994: my ($fn,%form)=@_;
1.15 www 2995: my $ua=new LWP::UserAgent;
1.23 www 2996: my $request;
1.711 albertel 2997:
2998: $form{'no_update_last_known'}=1;
1.895 albertel 2999: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3000: if (%form) {
1.782 albertel 3001: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 3002: $request->content(join('&',map {
3003: my $name = escape($_);
3004: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3005: ? join("&$name=", map {escape($_) } @{$form{$_}})
3006: : &escape($form{$_}) );
3007: } keys(%form)));
1.23 www 3008: } else {
1.782 albertel 3009: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3010: }
3011:
1.15 www 3012: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 3013: my $response= $ua->request($request);
1.1182 foxr 3014: my $content = $response->content;
3015:
3016:
1.944 foxr 3017: if (wantarray) {
1.1173 foxr 3018: return ($content, $response);
1.944 foxr 3019: } else {
1.1173 foxr 3020: return $content;
1.942 foxr 3021: }
1.324 www 3022: }
3023:
3024: sub externalssi {
3025: my ($url)=@_;
3026: my $ua=new LWP::UserAgent;
3027: my $request=new HTTP::Request('GET',$url);
3028: my $response=$ua->request($request);
1.954 raeburn 3029: if (wantarray) {
3030: return ($response->content, $response);
3031: } else {
3032: return $response->content;
3033: }
1.15 www 3034: }
1.254 www 3035:
1.492 albertel 3036: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3037:
3038: sub allowuploaded {
3039: my ($srcurl,$url)=@_;
3040: $url=&clutter(&declutter($url));
3041: my $dir=$url;
3042: $dir=~s/\/[^\/]+$//;
3043: my %httpref=();
3044: my $httpurl=&hreflocation('',$url);
3045: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3046: &Apache::lonnet::appenv(\%httpref);
1.254 www 3047: }
1.477 raeburn 3048:
1.1193 raeburn 3049: #
3050: # Determine if the current user should be able to edit a particular resource,
3051: # when viewing in course context.
3052: # (a) When viewing resource used to determine if "Edit" item is included in
3053: # Functions.
3054: # (b) When displaying folder contents in course editor, used to determine if
3055: # "Edit" link will be displayed alongside resource.
3056: #
1.1196 raeburn 3057: # input: six args -- filename (decluttered), course number, course domain,
3058: # url, symb (if registered) and group (if this is a group
3059: # item -- e.g., bulletin board, group page etc.).
3060: # output: array of five scalars --
1.1193 raeburn 3061: # $cfile -- url for file editing if editable on current server
3062: # $home -- homeserver of resource (i.e., for author if published,
3063: # or course if uploaded.).
3064: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3065: # $forceedit -- 1 if icon/link should be to go to edit mode
3066: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3067: #
3068:
3069: sub can_edit_resource {
1.1194 raeburn 3070: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3071: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3072: #
3073: # For aboutme pages user can only edit his/her own.
3074: #
1.1199 raeburn 3075: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3076: my ($sdom,$sname) = ($1,$2);
3077: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3078: $home = $env{'user.home'};
3079: $cfile = $resurl;
3080: if ($env{'form.forceedit'}) {
3081: $forceview = 1;
3082: } else {
3083: $forceedit = 1;
3084: }
3085: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3086: } else {
3087: return;
3088: }
3089: }
3090:
3091: if ($env{'request.course.id'}) {
3092: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3093: if ($group ne '') {
3094: # if this is a group homepage or group bulletin board, check group privs
3095: my $allowed = 0;
1.1197 raeburn 3096: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3097: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3098: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3099: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3100: $allowed = 1;
3101: }
1.1197 raeburn 3102: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3103: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3104: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3105: $allowed = 1;
3106: }
3107: }
3108: if ($allowed) {
3109: $home=&homeserver($cnum,$cdom);
3110: if ($env{'form.forceedit'}) {
3111: $forceview = 1;
3112: } else {
3113: $forceedit = 1;
3114: }
3115: $cfile = $resurl;
3116: } else {
3117: return;
3118: }
3119: } else {
1.1208 raeburn 3120: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3121: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3122: return;
3123: }
3124: } elsif (!$crsedit) {
1.1194 raeburn 3125: #
3126: # No edit allowed where CC has switched to student role.
3127: #
3128: return;
3129: }
3130: }
3131: }
3132:
1.1193 raeburn 3133: if ($file ne '') {
3134: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3135: if (&is_course_upload($file,$cnum,$cdom)) {
3136: $uploaded = 1;
3137: $incourse = 1;
1.1193 raeburn 3138: if ($file =~/\.(htm|html|css|js|txt)$/) {
3139: $cfile = &hreflocation('',$file);
1.1201 raeburn 3140: if ($env{'form.forceedit'}) {
3141: $forceview = 1;
3142: } else {
3143: $forceedit = 1;
3144: }
1.1194 raeburn 3145: }
3146: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3147: $incourse = 1;
3148: if ($env{'form.forceedit'}) {
3149: $forceview = 1;
3150: } else {
3151: $forceedit = 1;
3152: }
3153: $cfile = $resurl;
3154: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3155: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3156: $incourse = 1;
3157: if ($env{'form.forceedit'}) {
3158: $forceview = 1;
3159: } else {
3160: $forceedit = 1;
3161: }
3162: $cfile = $resurl;
1.1199 raeburn 3163: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3164: $incourse = 1;
3165: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3166: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3167: $incourse = 1;
1.1199 raeburn 3168: if ($env{'form.forceedit'}) {
3169: $forceview = 1;
3170: } else {
3171: $forceedit = 1;
3172: }
3173: $cfile = $resurl;
1.1298 raeburn 3174: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
3175: $incourse = 1;
3176: if ($env{'form.forceedit'}) {
3177: $forceview = 1;
3178: } else {
3179: $forceedit = 1;
3180: }
3181: $cfile = $resurl;
1.1208 raeburn 3182: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3183: $incourse = 1;
3184: if ($env{'form.forceedit'}) {
3185: $forceview = 1;
3186: } else {
3187: $forceedit = 1;
3188: }
3189: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3190: }
3191: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3192: my $template = '/res/lib/templates/simpleproblem.problem';
3193: if (&is_on_map($template)) {
3194: $incourse = 1;
3195: $forceview = 1;
3196: $cfile = $template;
1.1193 raeburn 3197: }
1.1199 raeburn 3198: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3199: $incourse = 1;
3200: if ($env{'form.forceedit'}) {
3201: $forceview = 1;
3202: } else {
3203: $forceedit = 1;
3204: }
3205: $cfile = $resurl;
1.1298 raeburn 3206: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3207: $incourse = 1;
3208: if ($env{'form.forceedit'}) {
3209: $forceview = 1;
3210: } else {
3211: $forceedit = 1;
3212: }
3213: $cfile = $resurl;
1.1199 raeburn 3214: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3215: $incourse = 1;
3216: $forceview = 1;
3217: if ($symb) {
3218: my ($map,$id,$res)=&decode_symb($symb);
3219: $env{'request.symb'} = $symb;
3220: $cfile = &clutter($res);
3221: } else {
3222: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3223: my $escfile = &unescape($cfile);
3224: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
3225: $cfile = '/adm/wrapper'.$escfile;
3226: } else {
3227: $escfile =~ s{^http://}{};
3228: $cfile = &escape("/adm/wrapper/ext/$escfile");
3229: }
1.1199 raeburn 3230: }
1.1234 raeburn 3231: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3232: if ($env{'form.forceedit'}) {
3233: $forceview = 1;
3234: } else {
3235: $forceedit = 1;
3236: }
3237: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3238: }
3239: }
1.1194 raeburn 3240: if ($uploaded || $incourse) {
3241: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3242: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3243: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3244: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3245: # Check that the user has permission to edit this resource
3246: my $setpriv = 1;
3247: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3248: if (defined($cfudom)) {
3249: $home=&homeserver($cfuname,$cfudom);
3250: $cfile=$file;
3251: }
3252: }
1.1194 raeburn 3253: if (($cfile ne '') && (!$incourse || $uploaded) &&
3254: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3255: my @ids=¤t_machine_ids();
3256: unless (grep(/^\Q$home\E$/,@ids)) {
3257: $switchserver=1;
3258: }
3259: }
3260: }
1.1194 raeburn 3261: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3262: }
3263:
3264: sub is_course_upload {
3265: my ($file,$cnum,$cdom) = @_;
3266: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3267: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3268: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3269: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3270: return 1;
3271: }
3272: return;
3273: }
3274:
1.1194 raeburn 3275: sub in_course {
1.1195 raeburn 3276: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3277: if ($hideprivileged) {
3278: my $skipuser;
1.1219 raeburn 3279: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3280: my @possdoms = ($cdom);
3281: if ($coursehash{'checkforpriv'}) {
3282: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3283: }
3284: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3285: $skipuser = 1;
3286: if ($coursehash{'nothideprivileged'}) {
3287: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3288: my $user;
3289: if ($item =~ /:/) {
3290: $user = $item;
3291: } else {
3292: $user = join(':',split(/[\@]/,$item));
3293: }
3294: if ($user eq $uname.':'.$udom) {
3295: undef($skipuser);
3296: last;
3297: }
3298: }
3299: }
3300: if ($skipuser) {
3301: return 0;
3302: }
3303: }
3304: }
1.1194 raeburn 3305: $type ||= 'any';
3306: if (!defined($cdom) || !defined($cnum)) {
3307: my $cid = $env{'request.course.id'};
3308: $cdom = $env{'course.'.$cid.'.domain'};
3309: $cnum = $env{'course.'.$cid.'.num'};
3310: }
3311: my $typesref;
1.1195 raeburn 3312: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3313: $typesref = ['active','previous','future'];
3314: } elsif ($type eq 'previous' || $type eq 'future') {
3315: $typesref = [$type];
3316: }
3317: my %roles = &get_my_roles($uname,$udom,'userroles',
3318: $typesref,undef,[$cdom]);
3319: my ($tmp) = keys(%roles);
3320: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3321: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3322: if (@course_roles > 0) {
3323: return 1;
3324: }
3325: return 0;
3326: }
3327:
1.478 albertel 3328: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3329: # input: action, courseID, current domain, intended
1.637 raeburn 3330: # path to file, source of file, instruction to parse file for objects,
3331: # ref to hash for embedded objects,
3332: # ref to hash for codebase of java objects.
1.1095 raeburn 3333: # reference to scalar to accommodate mime type determined
3334: # from File::MMagic if $parser = parse.
1.637 raeburn 3335: #
1.485 raeburn 3336: # output: url to file (if action was uploaddoc),
3337: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3338: #
1.478 albertel 3339: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3340: # course.
1.477 raeburn 3341: #
1.478 albertel 3342: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3343: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3344: # course's home server.
1.477 raeburn 3345: #
1.478 albertel 3346: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3347: # be copied from $source (current location) to
3348: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3349: # and will then be copied to
3350: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3351: # course's home server.
1.485 raeburn 3352: #
1.481 raeburn 3353: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3354: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3355: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3356: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3357: # in course's home server.
1.637 raeburn 3358: #
1.477 raeburn 3359:
3360: sub process_coursefile {
1.1095 raeburn 3361: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3362: $mimetype)=@_;
1.477 raeburn 3363: my $fetchresult;
1.638 albertel 3364: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3365: if ($action eq 'propagate') {
1.638 albertel 3366: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3367: $home);
1.481 raeburn 3368: } else {
1.477 raeburn 3369: my $fpath = '';
3370: my $fname = $file;
1.478 albertel 3371: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3372: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3373: my $filepath = &build_filepath($fpath);
1.481 raeburn 3374: if ($action eq 'copy') {
3375: if ($source eq '') {
3376: $fetchresult = 'no source file';
3377: return $fetchresult;
3378: } else {
3379: my $destination = $filepath.'/'.$fname;
3380: rename($source,$destination);
3381: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3382: $home);
1.481 raeburn 3383: }
3384: } elsif ($action eq 'uploaddoc') {
3385: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3386: print $fh $env{'form.'.$source};
1.481 raeburn 3387: close($fh);
1.637 raeburn 3388: if ($parser eq 'parse') {
1.1024 raeburn 3389: my $mm = new File::MMagic;
1.1095 raeburn 3390: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3391: if ($type eq 'text/html') {
1.1024 raeburn 3392: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3393: unless ($parse_result eq 'ok') {
3394: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3395: }
1.637 raeburn 3396: }
1.1095 raeburn 3397: if (ref($mimetype)) {
3398: $$mimetype = $type;
3399: }
1.637 raeburn 3400: }
1.477 raeburn 3401: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3402: $home);
1.481 raeburn 3403: if ($fetchresult eq 'ok') {
3404: return '/uploaded/'.$fpath.'/'.$fname;
3405: } else {
3406: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3407: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3408: return '/adm/notfound.html';
3409: }
1.477 raeburn 3410: }
3411: }
1.485 raeburn 3412: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3413: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3414: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3415: }
3416: return $fetchresult;
3417: }
3418:
1.637 raeburn 3419: sub build_filepath {
3420: my ($fpath) = @_;
3421: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3422: unless ($fpath eq '') {
3423: my @parts=split('/',$fpath);
3424: foreach my $part (@parts) {
3425: $filepath.= '/'.$part;
3426: if ((-e $filepath)!=1) {
3427: mkdir($filepath,0777);
3428: }
3429: }
3430: }
3431: return $filepath;
3432: }
3433:
3434: sub store_edited_file {
1.638 albertel 3435: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3436: my $file = $primary_url;
3437: $file =~ s#^/uploaded/$docudom/$docuname/##;
3438: my $fpath = '';
3439: my $fname = $file;
3440: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3441: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3442: my $filepath = &build_filepath($fpath);
3443: open(my $fh,'>'.$filepath.'/'.$fname);
3444: print $fh $content;
3445: close($fh);
1.638 albertel 3446: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3447: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3448: $home);
1.637 raeburn 3449: if ($$fetchresult eq 'ok') {
3450: return '/uploaded/'.$fpath.'/'.$fname;
3451: } else {
1.638 albertel 3452: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3453: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3454: return '/adm/notfound.html';
3455: }
3456: }
3457:
1.531 albertel 3458: sub clean_filename {
1.831 albertel 3459: my ($fname,$args)=@_;
1.315 www 3460: # Replace Windows backslashes by forward slashes
1.257 www 3461: $fname=~s/\\/\//g;
1.831 albertel 3462: if (!$args->{'keep_path'}) {
3463: # Get rid of everything but the actual filename
3464: $fname=~s/^.*\/([^\/]+)$/$1/;
3465: }
1.315 www 3466: # Replace spaces by underscores
3467: $fname=~s/\s+/\_/g;
3468: # Replace all other weird characters by nothing
1.831 albertel 3469: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3470: # Replace all .\d. sequences with _\d. so they no longer look like version
3471: # numbers
3472: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3473: return $fname;
3474: }
1.1051 raeburn 3475: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3476: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3477: # image with the same aspect ratio as the original, but with dimensions which do
3478: # not exceed $resizewidth and $resizeheight.
3479:
1.984 neumanie 3480: sub resizeImage {
1.1051 raeburn 3481: my ($img_path,$resizewidth,$resizeheight) = @_;
3482: my $ima = Image::Magick->new;
3483: my $resized;
3484: if (-e $img_path) {
3485: $ima->Read($img_path);
3486: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3487: my $width = $ima->Get('width');
3488: my $height = $ima->Get('height');
3489: if ($width > $resizewidth) {
3490: my $factor = $width/$resizewidth;
3491: my $newheight = $height/$factor;
3492: $ima->Scale(width=>$resizewidth,height=>$newheight);
3493: $resized = 1;
3494: }
3495: }
3496: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3497: my $width = $ima->Get('width');
3498: my $height = $ima->Get('height');
3499: if ($height > $resizeheight) {
3500: my $factor = $height/$resizeheight;
3501: my $newwidth = $width/$factor;
3502: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3503: $resized = 1;
3504: }
3505: }
3506: if ($resized) {
3507: $ima->Write($img_path);
3508: }
3509: }
3510: return;
1.977 amueller 3511: }
3512:
1.608 albertel 3513: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3514: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3515: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3516: # $context - possible values: coursedoc, existingfile, overwrite,
3517: # canceloverwrite, or ''.
3518: # if 'coursedoc': upload to the current course
3519: # if 'existingfile': write file to tmp/overwrites directory
3520: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3521: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3522: # $subdir - directory in userfile to store the file into
1.858 raeburn 3523: # $parser - instruction to parse file for objects ($parser = parse)
3524: # $allfiles - reference to hash for embedded objects
3525: # $codebase - reference to hash for codebase of java objects
3526: # $desuname - username for permanent storage of uploaded file
3527: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3528: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3529: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3530: # $resizewidth - width (pixels) to which to resize uploaded image
3531: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3532: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3533: # from File::MMagic.
1.858 raeburn 3534: #
1.686 albertel 3535: # output: url of file in userspace, or error: <message>
3536: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3537:
1.531 albertel 3538: sub userfileupload {
1.1090 raeburn 3539: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3540: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3541: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3542: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3543: $fname=&clean_filename($fname);
1.1090 raeburn 3544: # See if there is anything left
1.257 www 3545: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3546: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3547: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3548: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3549: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3550: my $now = time;
1.1090 raeburn 3551: my $filepath;
1.1095 raeburn 3552: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3553: $filepath = 'tmp/helprequests/'.$now;
3554: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3555: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3556: '_'.$env{'user.domain'}.'/pending';
3557: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3558: my ($docuname,$docudom);
3559: if ($destudom) {
3560: $docudom = $destudom;
3561: } else {
3562: $docudom = $env{'user.domain'};
3563: }
3564: if ($destuname) {
3565: $docuname = $destuname;
3566: } else {
3567: $docuname = $env{'user.name'};
3568: }
3569: if (exists($env{'form.group'})) {
3570: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3571: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3572: }
3573: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3574: if ($context eq 'canceloverwrite') {
3575: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3576: if (-e $tempfile) {
3577: my @info = stat($tempfile);
3578: if ($info[9] eq $env{'form.timestamp'}) {
3579: unlink($tempfile);
3580: }
3581: }
3582: return;
1.523 raeburn 3583: }
3584: }
1.1090 raeburn 3585: # Create the directory if not present
1.741 raeburn 3586: my @parts=split(/\//,$filepath);
3587: my $fullpath = $perlvar{'lonDaemons'};
3588: for (my $i=0;$i<@parts;$i++) {
3589: $fullpath .= '/'.$parts[$i];
3590: if ((-e $fullpath)!=1) {
3591: mkdir($fullpath,0777);
3592: }
3593: }
3594: open(my $fh,'>'.$fullpath.'/'.$fname);
3595: print $fh $env{'form.'.$formname};
3596: close($fh);
1.1090 raeburn 3597: if ($context eq 'existingfile') {
3598: my @info = stat($fullpath.'/'.$fname);
3599: return ($fullpath.'/'.$fname,$info[9]);
3600: } else {
3601: return $fullpath.'/'.$fname;
3602: }
1.523 raeburn 3603: }
1.995 raeburn 3604: if ($subdir eq 'scantron') {
3605: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3606: } else {
1.995 raeburn 3607: $fname="$subdir/$fname";
3608: }
1.1090 raeburn 3609: if ($context eq 'coursedoc') {
1.638 albertel 3610: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3611: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3612: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3613: return &finishuserfileupload($docuname,$docudom,
3614: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3615: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3616: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3617: } else {
1.1218 raeburn 3618: if ($env{'form.folder'}) {
3619: $fname=$env{'form.folder'}.'/'.$fname;
3620: }
1.638 albertel 3621: return &process_coursefile('uploaddoc',$docuname,$docudom,
3622: $fname,$formname,$parser,
1.1095 raeburn 3623: $allfiles,$codebase,$mimetype);
1.481 raeburn 3624: }
1.719 banghart 3625: } elsif (defined($destuname)) {
3626: my $docuname=$destuname;
3627: my $docudom=$destudom;
1.860 raeburn 3628: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3629: $parser,$allfiles,$codebase,
1.1051 raeburn 3630: $thumbwidth,$thumbheight,
1.1095 raeburn 3631: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3632: } else {
1.638 albertel 3633: my $docuname=$env{'user.name'};
3634: my $docudom=$env{'user.domain'};
1.1220 raeburn 3635: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3636: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3637: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3638: }
1.860 raeburn 3639: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3640: $parser,$allfiles,$codebase,
1.1051 raeburn 3641: $thumbwidth,$thumbheight,
1.1095 raeburn 3642: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3643: }
1.271 www 3644: }
3645:
3646: sub finishuserfileupload {
1.860 raeburn 3647: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3648: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3649: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3650: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3651:
1.860 raeburn 3652: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3653: $file=$fname;
3654: if ($fname=~m|/|) {
3655: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3656: $path.=$fnamepath.'/';
3657: }
1.259 www 3658: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3659: my $count;
3660: for ($count=4;$count<=$#parts;$count++) {
3661: $filepath.="/$parts[$count]";
3662: if ((-e $filepath)!=1) {
3663: mkdir($filepath,0777);
3664: }
3665: }
1.984 neumanie 3666:
1.258 www 3667: # Save the file
3668: {
1.701 albertel 3669: if (!open(FH,'>'.$filepath.'/'.$file)) {
3670: &logthis('Failed to create '.$filepath.'/'.$file);
3671: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3672: return '/adm/notfound.html';
3673: }
1.1090 raeburn 3674: if ($context eq 'overwrite') {
1.1117 foxr 3675: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3676: my $target = $filepath.'/'.$file;
3677: if (-e $source) {
3678: my @info = stat($source);
3679: if ($info[9] eq $env{'form.timestamp'}) {
3680: unless (&File::Copy::move($source,$target)) {
3681: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3682: return "Moving from $source failed";
3683: }
3684: } else {
3685: return "Temporary file: $source had unexpected date/time for last modification";
3686: }
3687: } else {
3688: return "Temporary file: $source missing";
3689: }
3690: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3691: &logthis('Failed to write to '.$filepath.'/'.$file);
3692: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3693: return '/adm/notfound.html';
3694: }
1.570 albertel 3695: close(FH);
1.1051 raeburn 3696: if ($resizewidth && $resizeheight) {
3697: my $mm = new File::MMagic;
3698: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3699: if ($mime_type =~ m{^image/}) {
3700: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3701: }
1.977 amueller 3702: }
1.258 www 3703: }
1.1152 raeburn 3704: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3705: if (ref($mimetype)) {
3706: if ($$mimetype eq '') {
3707: my $mm = new File::MMagic;
3708: my $type = $mm->checktype_filename($filepath.'/'.$file);
3709: $$mimetype = $type;
3710: }
3711: }
3712: }
1.637 raeburn 3713: if ($parser eq 'parse') {
1.1152 raeburn 3714: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3715: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3716: $allfiles,$codebase);
3717: unless ($parse_result eq 'ok') {
3718: &logthis('Failed to parse '.$filepath.$file.
3719: ' for embedded media: '.$parse_result);
3720: }
1.637 raeburn 3721: }
3722: }
1.860 raeburn 3723: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3724: my $input = $filepath.'/'.$file;
3725: my $output = $filepath.'/'.'tn-'.$file;
3726: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3727: system("convert -sample $thumbsize $input $output");
3728: if (-e $filepath.'/'.'tn-'.$file) {
3729: $fetchthumb = 1;
3730: }
3731: }
1.858 raeburn 3732:
1.259 www 3733: # Notify homeserver to grep it
3734: #
1.984 neumanie 3735: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3736: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3737: if ($fetchresult eq 'ok') {
1.860 raeburn 3738: if ($fetchthumb) {
3739: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3740: if ($thumbresult ne 'ok') {
3741: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3742: $docuhome.': '.$thumbresult);
3743: }
3744: }
1.259 www 3745: #
1.258 www 3746: # Return the URL to it
1.494 albertel 3747: return '/uploaded/'.$path.$file;
1.263 www 3748: } else {
1.494 albertel 3749: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3750: ': '.$fetchresult);
1.263 www 3751: return '/adm/notfound.html';
1.858 raeburn 3752: }
1.493 albertel 3753: }
3754:
1.637 raeburn 3755: sub extract_embedded_items {
1.961 raeburn 3756: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3757: my @state = ();
1.1164 raeburn 3758: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3759: my %javafiles = (
3760: codebase => '',
3761: code => '',
3762: archive => ''
3763: );
3764: my %mediafiles = (
3765: src => '',
3766: movie => '',
3767: );
1.648 raeburn 3768: my $p;
3769: if ($content) {
3770: $p = HTML::LCParser->new($content);
3771: } else {
1.961 raeburn 3772: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3773: }
1.641 albertel 3774: while (my $t=$p->get_token()) {
1.640 albertel 3775: if ($t->[0] eq 'S') {
3776: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3777: push(@state, $tagname);
1.648 raeburn 3778: if (lc($tagname) eq 'allow') {
3779: &add_filetype($allfiles,$attr->{'src'},'src');
3780: }
1.640 albertel 3781: if (lc($tagname) eq 'img') {
3782: &add_filetype($allfiles,$attr->{'src'},'src');
3783: }
1.886 albertel 3784: if (lc($tagname) eq 'a') {
1.1222 raeburn 3785: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3786: &add_filetype($allfiles,$attr->{'href'},'href');
3787: }
1.886 albertel 3788: }
1.645 raeburn 3789: if (lc($tagname) eq 'script') {
1.1164 raeburn 3790: my $src;
1.645 raeburn 3791: if ($attr->{'archive'} =~ /\.jar$/i) {
3792: &add_filetype($allfiles,$attr->{'archive'},'archive');
3793: } else {
1.1164 raeburn 3794: if ($attr->{'src'} ne '') {
3795: $src = $attr->{'src'};
3796: &add_filetype($allfiles,$src,'src');
3797: }
3798: }
3799: my $text = $p->get_trimmed_text();
3800: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3801: my @swfargs = split(/,/,$1);
3802: foreach my $item (@swfargs) {
3803: $item =~ s/["']//g;
3804: $item =~ s/^\s+//;
3805: $item =~ s/\s+$//;
3806: }
3807: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3808: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3809: push(@{$related{$swfargs[0]}},$swfargs[2]);
3810: } else {
3811: $related{$swfargs[0]} = [$swfargs[2]];
3812: }
3813: }
1.645 raeburn 3814: }
3815: }
3816: if (lc($tagname) eq 'link') {
3817: if (lc($attr->{'rel'}) eq 'stylesheet') {
3818: &add_filetype($allfiles,$attr->{'href'},'href');
3819: }
3820: }
1.640 albertel 3821: if (lc($tagname) eq 'object' ||
3822: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3823: foreach my $item (keys(%javafiles)) {
3824: $javafiles{$item} = '';
3825: }
1.1164 raeburn 3826: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3827: $lastids{lc($tagname)} = $attr->{'id'};
3828: }
1.640 albertel 3829: }
3830: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3831: my $name = lc($attr->{'name'});
3832: foreach my $item (keys(%javafiles)) {
3833: if ($name eq $item) {
3834: $javafiles{$item} = $attr->{'value'};
3835: last;
3836: }
3837: }
1.1164 raeburn 3838: my $pathfrom;
1.640 albertel 3839: foreach my $item (keys(%mediafiles)) {
3840: if ($name eq $item) {
1.1164 raeburn 3841: $pathfrom = $attr->{'value'};
3842: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3843: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3844: last;
3845: }
3846: }
1.1164 raeburn 3847: if ($name eq 'flashvars') {
3848: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3849: }
3850: if ($pathfrom ne '') {
3851: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3852: $pathfrom);
3853: }
1.640 albertel 3854: }
3855: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3856: foreach my $item (keys(%javafiles)) {
3857: if ($attr->{$item}) {
3858: $javafiles{$item} = $attr->{$item};
3859: last;
3860: }
3861: }
3862: foreach my $item (keys(%mediafiles)) {
3863: if ($attr->{$item}) {
3864: &add_filetype($allfiles,$attr->{$item},$item);
3865: last;
3866: }
3867: }
1.1164 raeburn 3868: if (lc($tagname) eq 'embed') {
3869: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3870: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3871: $attr->{'src'});
3872: }
3873: }
1.640 albertel 3874: }
1.1243 raeburn 3875: if (lc($tagname) eq 'iframe') {
3876: my $src = $attr->{'src'} ;
3877: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3878: &add_filetype($allfiles,$src,'src');
3879: } elsif ($src =~ m{^/}) {
3880: if ($env{'request.course.id'}) {
3881: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3882: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3883: my $url = &hreflocation('',$fullpath);
3884: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3885: my $relpath = $1;
3886: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3887: &add_filetype($allfiles,$1,'src');
3888: }
3889: }
3890: }
3891: }
3892: }
1.1164 raeburn 3893: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3894: pop(@state);
1.1164 raeburn 3895: }
1.640 albertel 3896: } elsif ($t->[0] eq 'E') {
3897: my ($tagname) = ($t->[1]);
3898: if ($javafiles{'codebase'} ne '') {
3899: $javafiles{'codebase'} .= '/';
3900: }
3901: if (lc($tagname) eq 'applet' ||
3902: lc($tagname) eq 'object' ||
3903: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3904: ) {
3905: foreach my $item (keys(%javafiles)) {
3906: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3907: my $file=$javafiles{'codebase'}.$javafiles{$item};
3908: &add_filetype($allfiles,$file,$item);
3909: }
3910: }
3911: }
3912: pop @state;
3913: }
3914: }
1.1164 raeburn 3915: foreach my $id (sort(keys(%flashvars))) {
3916: if ($shockwave{$id} ne '') {
3917: my @pairs = split(/\&/,$flashvars{$id});
3918: foreach my $pair (@pairs) {
3919: my ($key,$value) = split(/\=/,$pair);
3920: if ($key eq 'thumb') {
3921: &add_filetype($allfiles,$value,$key);
3922: } elsif ($key eq 'content') {
3923: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3924: my ($ext) = ($value =~ /\.([^.]+)$/);
3925: if ($ext ne '') {
3926: &add_filetype($allfiles,$path.$value,$ext);
3927: }
3928: }
3929: }
3930: }
3931: }
1.637 raeburn 3932: return 'ok';
3933: }
3934:
1.639 albertel 3935: sub add_filetype {
3936: my ($allfiles,$file,$type)=@_;
3937: if (exists($allfiles->{$file})) {
3938: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3939: push(@{$allfiles->{$file}}, &escape($type));
3940: }
3941: } else {
3942: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3943: }
3944: }
3945:
1.1164 raeburn 3946: sub embedded_dependency {
3947: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3948: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3949: if (($identifier ne '') &&
3950: (ref($related->{$identifier}) eq 'ARRAY') &&
3951: ($pathfrom ne '')) {
3952: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3953: foreach my $dep (@{$related->{$identifier}}) {
3954: &add_filetype($allfiles,$path.$dep,'object');
3955: }
3956: }
3957: }
3958: return;
3959: }
3960:
1.493 albertel 3961: sub removeuploadedurl {
1.984 neumanie 3962: my ($url)=@_;
3963: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3964: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3965: }
3966:
3967: sub removeuserfile {
3968: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3969: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3970: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3971: if ($result eq 'ok') {
1.798 raeburn 3972: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3973: my $metafile = $fname.'.meta';
3974: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3975: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3976: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3977: my $sqlresult =
1.823 albertel 3978: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3979: 'portfolio_metadata',$group,
3980: 'delete');
1.798 raeburn 3981: }
3982: }
3983: return $result;
1.257 www 3984: }
1.15 www 3985:
1.530 albertel 3986: sub mkdiruserfile {
3987: my ($docuname,$docudom,$dir)=@_;
3988: my $home=&homeserver($docuname,$docudom);
3989: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3990: }
3991:
1.531 albertel 3992: sub renameuserfile {
3993: my ($docuname,$docudom,$old,$new)=@_;
3994: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3995: my $result = &reply("renameuserfile:$docudom:$docuname:".
3996: &escape("$old").':'.&escape("$new"),$home);
3997: if ($result eq 'ok') {
3998: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3999: my $oldmeta = $old.'.meta';
4000: my $newmeta = $new.'.meta';
4001: my $metaresult =
4002: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4003: my $url = "/uploaded/$docudom/$docuname/$old";
4004: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4005: my $sqlresult =
1.823 albertel 4006: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4007: 'portfolio_metadata',$group,
4008: 'delete');
1.798 raeburn 4009: }
4010: }
4011: return $result;
1.531 albertel 4012: }
4013:
1.14 www 4014: # ------------------------------------------------------------------------- Log
4015:
4016: sub log {
4017: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4018: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4019: }
4020:
4021: # ------------------------------------------------------------------ Course Log
1.352 www 4022: #
4023: # This routine flushes several buffers of non-mission-critical nature
4024: #
1.157 www 4025:
4026: sub flushcourselogs {
1.352 www 4027: &logthis('Flushing log buffers');
4028: #
4029: # course logs
4030: # This is a log of all transactions in a course, which can be used
4031: # for data mining purposes
4032: #
4033: # It also collects the courseid database, which lists last transaction
4034: # times and course titles for all courseids
4035: #
4036: my %courseidbuffer=();
1.921 raeburn 4037: foreach my $crsid (keys(%courselogs)) {
1.352 www 4038: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4039: &escape($courselogs{$crsid}),
4040: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4041: delete $courselogs{$crsid};
4042: } else {
4043: &logthis('Failed to flush log buffer for '.$crsid);
4044: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4045: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4046: " exceeded maximum size, deleting.</font>");
4047: delete $courselogs{$crsid};
4048: }
1.352 www 4049: }
1.920 raeburn 4050: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4051: 'description' => $coursedescrbuf{$crsid},
4052: 'inst_code' => $courseinstcodebuf{$crsid},
4053: 'type' => $coursetypebuf{$crsid},
4054: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4055: };
1.191 harris41 4056: }
1.352 www 4057: #
4058: # Write course id database (reverse lookup) to homeserver of courses
4059: # Is used in pickcourse
4060: #
1.840 albertel 4061: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4062: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4063: $courseidbuffer{$crs_home},
4064: $crs_home,'timeonly');
1.352 www 4065: }
4066: #
4067: # File accesses
4068: # Writes to the dynamic metadata of resources to get hit counts, etc.
4069: #
1.449 matthew 4070: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4071: if ($entry =~ /___count$/) {
4072: my ($dom,$name);
1.807 albertel 4073: ($dom,$name,undef)=
1.811 albertel 4074: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4075: if (! defined($dom) || $dom eq '' ||
4076: ! defined($name) || $name eq '') {
1.620 albertel 4077: my $cid = $env{'request.course.id'};
4078: $dom = $env{'request.'.$cid.'.domain'};
4079: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4080: }
1.450 matthew 4081: my $value = $accesshash{$entry};
4082: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4083: my %temphash=($url => $value);
1.449 matthew 4084: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4085: if ($result eq 'ok') {
4086: delete $accesshash{$entry};
4087: }
4088: } else {
1.811 albertel 4089: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4090: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4091: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4092: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4093: delete $accesshash{$entry};
4094: }
1.185 www 4095: }
1.191 harris41 4096: }
1.352 www 4097: #
4098: # Roles
4099: # Reverse lookup of user roles for course faculty/staff and co-authorship
4100: #
1.800 albertel 4101: foreach my $entry (keys(%userrolehash)) {
1.351 www 4102: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4103: split(/\:/,$entry);
4104: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4105: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4106: $rudom,$runame) eq 'ok') {
4107: delete $userrolehash{$entry};
4108: }
4109: }
1.662 raeburn 4110: #
1.1327 raeburn 4111: # Reverse lookup of domain roles (dc, ad, li, sc, dh, au)
1.662 raeburn 4112: #
4113: my %domrolebuffer = ();
1.1000 raeburn 4114: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4115: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4116: if ($domrolebuffer{$rudom}) {
4117: $domrolebuffer{$rudom}.='&'.&escape($entry).
4118: '='.&escape($domainrolehash{$entry});
4119: } else {
4120: $domrolebuffer{$rudom}.=&escape($entry).
4121: '='.&escape($domainrolehash{$entry});
4122: }
4123: delete $domainrolehash{$entry};
4124: }
4125: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 4126: my %servers;
4127: if (defined(&domain($dom,'primary'))) {
4128: my $primary=&domain($dom,'primary');
4129: my $hostname=&hostname($primary);
4130: $servers{$primary} = $hostname;
4131: } else {
4132: %servers = &get_servers($dom,'library');
4133: }
1.841 albertel 4134: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 4135: if (&reply('domroleput:'.$dom.':'.
4136: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4137: last;
4138: } else {
1.841 albertel 4139: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4140: }
1.662 raeburn 4141: }
4142: }
1.186 www 4143: $dumpcount++;
1.157 www 4144: }
4145:
4146: sub courselog {
4147: my $what=shift;
1.158 www 4148: $what=time.':'.$what;
1.620 albertel 4149: unless ($env{'request.course.id'}) { return ''; }
4150: $coursedombuf{$env{'request.course.id'}}=
4151: $env{'course.'.$env{'request.course.id'}.'.domain'};
4152: $coursenumbuf{$env{'request.course.id'}}=
4153: $env{'course.'.$env{'request.course.id'}.'.num'};
4154: $coursehombuf{$env{'request.course.id'}}=
4155: $env{'course.'.$env{'request.course.id'}.'.home'};
4156: $coursedescrbuf{$env{'request.course.id'}}=
4157: $env{'course.'.$env{'request.course.id'}.'.description'};
4158: $courseinstcodebuf{$env{'request.course.id'}}=
4159: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4160: $courseownerbuf{$env{'request.course.id'}}=
4161: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4162: $coursetypebuf{$env{'request.course.id'}}=
4163: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4164: if (defined $courselogs{$env{'request.course.id'}}) {
4165: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4166: } else {
1.620 albertel 4167: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4168: }
1.620 albertel 4169: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4170: &flushcourselogs();
4171: }
1.158 www 4172: }
4173:
4174: sub courseacclog {
4175: my $fnsymb=shift;
1.620 albertel 4176: unless ($env{'request.course.id'}) { return ''; }
4177: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4178: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4179: $what.=':POST';
1.583 matthew 4180: # FIXME: Probably ought to escape things....
1.800 albertel 4181: foreach my $key (keys(%env)) {
4182: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4183: my $formitem = $1;
4184: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4185: $what.=':'.$formitem.'='.$env{$key};
4186: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4187: $what.=':'.$formitem.'='.$env{$key};
4188: }
1.158 www 4189: }
1.191 harris41 4190: }
1.583 matthew 4191: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4192: # FIXME: We should not be depending on a form parameter that someone
4193: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4194: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4195: $what.= ':POST';
4196: # FIXME: Probably ought to escape things....
4197: foreach my $element ('courseexp','crsfulltext','crsrelated',
4198: 'crsdiscuss') {
1.620 albertel 4199: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4200: }
4201: }
1.158 www 4202: }
4203: &courselog($what);
1.149 www 4204: }
4205:
1.185 www 4206: sub countacc {
4207: my $url=&declutter(shift);
1.458 matthew 4208: return if (! defined($url) || $url eq '');
1.620 albertel 4209: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4210: #
4211: # Mark that this url was used in this course
4212: #
1.620 albertel 4213: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4214: #
4215: # Increase the access count for this resource in this child process
4216: #
1.281 www 4217: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4218: $accesshash{$key}++;
1.185 www 4219: }
1.349 www 4220:
1.361 www 4221: sub linklog {
4222: my ($from,$to)=@_;
4223: $from=&declutter($from);
4224: $to=&declutter($to);
4225: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4226: $accesshash{$to.'___'.$from.'___goto'}=1;
4227: }
1.1160 www 4228:
4229: sub statslog {
4230: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4231: if ($users<2) { return; }
4232: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4233: 'course' => $env{'request.course.id'},
4234: 'sections' => '"all"',
4235: 'num_students' => $users,
4236: 'part' => $part,
4237: 'symb' => $symb,
4238: 'mean_tries' => $av_attempts,
4239: 'deg_of_diff' => $degdiff});
4240: foreach my $key (keys(%dynstore)) {
4241: $accesshash{$key}=$dynstore{$key};
4242: }
4243: }
1.361 www 4244:
1.349 www 4245: sub userrolelog {
4246: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4247: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4248: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4249: $userrolehash
4250: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4251: =$tend.':'.$tstart;
1.662 raeburn 4252: }
1.1169 droeschl 4253: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4254: $userrolehash
4255: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4256: =$tend.':'.$tstart;
4257: }
1.1327 raeburn 4258: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh)/ ) {
1.662 raeburn 4259: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4260: $domainrolehash
4261: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4262: = $tend.':'.$tstart;
4263: }
1.351 www 4264: }
4265:
1.957 raeburn 4266: sub courserolelog {
4267: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 4268: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4269: my $cdom = $1;
4270: my $cnum = $2;
4271: my $sec = $3;
4272: my $namespace = 'rolelog';
4273: my %storehash = (
4274: role => $trole,
4275: start => $tstart,
4276: end => $tend,
4277: selfenroll => $selfenroll,
4278: context => $context,
4279: );
4280: if ($trole eq 'gr') {
4281: $namespace = 'groupslog';
4282: $storehash{'group'} = $sec;
4283: } else {
4284: $storehash{'section'} = $sec;
4285: }
1.1188 raeburn 4286: &write_log('course',$namespace,\%storehash,$delflag,$username,
4287: $domain,$cnum,$cdom);
1.1184 raeburn 4288: if (($trole ne 'st') || ($sec ne '')) {
4289: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4290: }
4291: }
4292: return;
4293: }
4294:
1.1184 raeburn 4295: sub domainrolelog {
4296: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4297: if ($area =~ m{^/($match_domain)/$}) {
4298: my $cdom = $1;
4299: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4300: my $namespace = 'rolelog';
4301: my %storehash = (
4302: role => $trole,
4303: start => $tstart,
4304: end => $tend,
4305: context => $context,
4306: );
1.1188 raeburn 4307: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4308: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4309: }
4310: return;
4311:
4312: }
4313:
4314: sub coauthorrolelog {
4315: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4316: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4317: my $audom = $1;
4318: my $auname = $2;
4319: my $namespace = 'rolelog';
4320: my %storehash = (
4321: role => $trole,
4322: start => $tstart,
4323: end => $tend,
4324: context => $context,
4325: );
1.1188 raeburn 4326: &write_log('author',$namespace,\%storehash,$delflag,$username,
4327: $domain,$auname,$audom);
1.1184 raeburn 4328: }
4329: return;
4330: }
4331:
1.351 www 4332: sub get_course_adv_roles {
1.948 raeburn 4333: my ($cid,$codes) = @_;
1.620 albertel 4334: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4335: my %coursehash=&coursedescription($cid);
1.988 raeburn 4336: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4337: my %nothide=();
1.800 albertel 4338: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4339: if ($user !~ /:/) {
4340: $nothide{join(':',split(/[\@]/,$user))}=1;
4341: } else {
4342: $nothide{$user}=1;
4343: }
1.470 www 4344: }
1.1219 raeburn 4345: my @possdoms = ($coursehash{'domain'});
4346: if ($coursehash{'checkforpriv'}) {
4347: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4348: }
1.351 www 4349: my %returnhash=();
4350: my %dumphash=
4351: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4352: my $now=time;
1.997 raeburn 4353: my %privileged;
1.1000 raeburn 4354: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4355: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4356: if (($tstart) && ($tstart<0)) { next; }
4357: if (($tend) && ($tend<$now)) { next; }
4358: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4359: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4360: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4361: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4362: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4363: if ($role eq 'cr') { next; }
1.948 raeburn 4364: if ($codes) {
4365: if ($section) { $role .= ':'.$section; }
4366: if ($returnhash{$role}) {
4367: $returnhash{$role}.=','.$username.':'.$domain;
4368: } else {
4369: $returnhash{$role}=$username.':'.$domain;
4370: }
1.351 www 4371: } else {
1.988 raeburn 4372: my $key=&plaintext($role,$crstype);
1.973 bisitz 4373: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4374: if ($returnhash{$key}) {
4375: $returnhash{$key}.=','.$username.':'.$domain;
4376: } else {
4377: $returnhash{$key}=$username.':'.$domain;
4378: }
1.351 www 4379: }
1.948 raeburn 4380: }
1.400 www 4381: return %returnhash;
4382: }
4383:
4384: sub get_my_roles {
1.937 raeburn 4385: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4386: unless (defined($uname)) { $uname=$env{'user.name'}; }
4387: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4388: my (%dumphash,%nothide);
1.1086 raeburn 4389: if ($context eq 'userroles') {
1.1166 raeburn 4390: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4391: } else {
1.1219 raeburn 4392: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4393: if ($hidepriv) {
4394: my %coursehash=&coursedescription($udom.'_'.$uname);
4395: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4396: if ($user !~ /:/) {
4397: $nothide{join(':',split(/[\@]/,$user))} = 1;
4398: } else {
4399: $nothide{$user} = 1;
4400: }
4401: }
4402: }
1.858 raeburn 4403: }
1.400 www 4404: my %returnhash=();
4405: my $now=time;
1.999 raeburn 4406: my %privileged;
1.800 albertel 4407: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4408: my ($role,$tend,$tstart);
4409: if ($context eq 'userroles') {
1.1149 raeburn 4410: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4411: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4412: } else {
4413: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4414: }
1.400 www 4415: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4416: my $status = 'active';
1.939 raeburn 4417: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4418: $status = 'previous';
4419: }
4420: if (($tstart) && ($now<$tstart)) {
4421: $status = 'future';
4422: }
4423: if (ref($types) eq 'ARRAY') {
4424: if (!grep(/^\Q$status\E$/,@{$types})) {
4425: next;
4426: }
4427: } else {
4428: if ($status ne 'active') {
4429: next;
4430: }
4431: }
1.867 raeburn 4432: my ($rolecode,$username,$domain,$section,$area);
4433: if ($context eq 'userroles') {
1.1186 raeburn 4434: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4435: (undef,$domain,$username,$section) = split(/\//,$area);
4436: } else {
4437: ($role,$username,$domain,$section) = split(/\:/,$entry);
4438: }
1.832 raeburn 4439: if (ref($roledoms) eq 'ARRAY') {
4440: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4441: next;
4442: }
4443: }
4444: if (ref($roles) eq 'ARRAY') {
4445: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4446: if ($role =~ /^cr\//) {
4447: if (!grep(/^cr$/,@{$roles})) {
4448: next;
4449: }
1.1104 raeburn 4450: } elsif ($role =~ /^gr\//) {
4451: if (!grep(/^gr$/,@{$roles})) {
4452: next;
4453: }
1.922 raeburn 4454: } else {
4455: next;
4456: }
1.832 raeburn 4457: }
1.867 raeburn 4458: }
1.937 raeburn 4459: if ($hidepriv) {
1.1219 raeburn 4460: my @privroles = ('dc','su');
1.999 raeburn 4461: if ($context eq 'userroles') {
1.1219 raeburn 4462: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4463: } else {
1.1219 raeburn 4464: my $possdoms = [$domain];
4465: if (ref($roledoms) eq 'ARRAY') {
4466: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4467: }
1.1219 raeburn 4468: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4469: if (!$nothide{$username.':'.$domain}) {
4470: next;
4471: }
4472: }
1.937 raeburn 4473: }
4474: }
1.933 raeburn 4475: if ($withsec) {
4476: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4477: $tstart.':'.$tend;
4478: } else {
4479: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4480: }
1.832 raeburn 4481: }
1.373 www 4482: return %returnhash;
1.399 www 4483: }
4484:
4485: # ----------------------------------------------------- Frontpage Announcements
4486: #
4487: #
4488:
4489: sub postannounce {
4490: my ($server,$text)=@_;
1.844 albertel 4491: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4492: unless ($text=~/\w/) { $text=''; }
4493: return &reply('setannounce:'.&escape($text),$server);
4494: }
4495:
4496: sub getannounce {
1.448 albertel 4497:
4498: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4499: my $announcement='';
1.800 albertel 4500: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4501: close($fh);
1.399 www 4502: if ($announcement=~/\w/) {
4503: return
4504: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4505: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4506: } else {
4507: return '';
4508: }
4509: } else {
4510: return '';
4511: }
1.351 www 4512: }
1.353 www 4513:
4514: # ---------------------------------------------------------- Course ID routines
4515: # Deal with domain's nohist_courseid.db files
4516: #
4517:
4518: sub courseidput {
1.921 raeburn 4519: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4520: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4521: my $outcome;
4522: if ($caller eq 'timeonly') {
4523: my $cids = '';
4524: foreach my $item (keys(%$storehash)) {
4525: $cids.=&escape($item).'&';
4526: }
4527: $cids=~s/\&$//;
4528: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4529: $coursehome);
4530: } else {
4531: my $items = '';
4532: foreach my $item (keys(%$storehash)) {
4533: $items.= &escape($item).'='.
4534: &freeze_escape($$storehash{$item}).'&';
4535: }
4536: $items=~s/\&$//;
4537: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4538: $coursehome);
1.918 raeburn 4539: }
4540: if ($outcome eq 'unknown_cmd') {
4541: my $what;
4542: foreach my $cid (keys(%$storehash)) {
4543: $what .= &escape($cid).'=';
1.921 raeburn 4544: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4545: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4546: }
4547: $what =~ s/\:$/&/;
4548: }
4549: $what =~ s/\&$//;
4550: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4551: } else {
4552: return $outcome;
4553: }
1.353 www 4554: }
4555:
4556: sub courseiddump {
1.921 raeburn 4557: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4558: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4559: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4560: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 4561: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4562: my $as_hash = 1;
4563: my %returnhash;
4564: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4565: my %libserv = &all_library();
4566: foreach my $tryserver (keys(%libserv)) {
4567: if ( ( $hostidflag == 1
4568: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4569: || (!defined($hostidflag)) ) {
4570:
1.918 raeburn 4571: if (($domfilter eq '') ||
4572: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4573: my $rep;
4574: if (grep { $_ eq $tryserver } current_machine_ids()) {
4575: $rep = LONCAPA::Lond::dump_course_id_handler(
4576: join(":", (&host_domain($tryserver), $sincefilter,
4577: &escape($descfilter), &escape($instcodefilter),
4578: &escape($ownerfilter), &escape($coursefilter),
4579: &escape($typefilter), &escape($regexp_ok),
4580: $as_hash, &escape($selfenrollonly),
4581: &escape($catfilter), $showhidden, $caller,
4582: &escape($cloner), &escape($cc_clone), $cloneonly,
4583: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 4584: &escape($creationcontext),$domcloner,$hasuniquecode,
4585: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 4586: } else {
4587: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4588: $sincefilter.':'.&escape($descfilter).':'.
4589: &escape($instcodefilter).':'.&escape($ownerfilter).
4590: ':'.&escape($coursefilter).':'.&escape($typefilter).
4591: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4592: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4593: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4594: &escape($cc_clone).':'.$cloneonly.':'.
4595: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 4596: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4597: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 4598: }
4599:
1.918 raeburn 4600: my @pairs=split(/\&/,$rep);
4601: foreach my $item (@pairs) {
4602: my ($key,$value)=split(/\=/,$item,2);
4603: $key = &unescape($key);
4604: next if ($key =~ /^error: 2 /);
4605: my $result = &thaw_unescape($value);
4606: if (ref($result) eq 'HASH') {
4607: $returnhash{$key}=$result;
4608: } else {
1.921 raeburn 4609: my @responses = split(/:/,$value);
4610: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4611: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4612: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4613: }
1.1008 raeburn 4614: }
1.353 www 4615: }
4616: }
4617: }
4618: }
4619: return %returnhash;
4620: }
4621:
1.1055 raeburn 4622: sub courselastaccess {
4623: my ($cdom,$cnum,$hostidref) = @_;
4624: my %returnhash;
4625: if ($cdom && $cnum) {
4626: my $chome = &homeserver($cnum,$cdom);
4627: if ($chome ne 'no_host') {
4628: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4629: &extract_lastaccess(\%returnhash,$rep);
4630: }
4631: } else {
4632: if (!$cdom) { $cdom=''; }
4633: my %libserv = &all_library();
4634: foreach my $tryserver (keys(%libserv)) {
4635: if (ref($hostidref) eq 'ARRAY') {
4636: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4637: }
4638: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4639: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4640: &extract_lastaccess(\%returnhash,$rep);
4641: }
4642: }
4643: }
4644: return %returnhash;
4645: }
4646:
4647: sub extract_lastaccess {
4648: my ($returnhash,$rep) = @_;
4649: if (ref($returnhash) eq 'HASH') {
4650: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4651: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4652: $rep eq '') {
4653: my @pairs=split(/\&/,$rep);
4654: foreach my $item (@pairs) {
4655: my ($key,$value)=split(/\=/,$item,2);
4656: $key = &unescape($key);
4657: next if ($key =~ /^error: 2 /);
4658: $returnhash->{$key} = &thaw_unescape($value);
4659: }
4660: }
4661: }
4662: return;
4663: }
4664:
1.658 raeburn 4665: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4666:
4667: sub dcmailput {
1.685 raeburn 4668: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4669: my $status = &Apache::lonnet::critical(
1.740 www 4670: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4671: &escape($message),$server);
1.662 raeburn 4672: return $status;
4673: }
4674:
1.658 raeburn 4675: sub dcmaildump {
4676: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4677: my %returnhash=();
1.846 albertel 4678:
4679: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4680: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4681: &escape($enddate).':';
4682: my @esc_senders=map { &escape($_)} @$senders;
4683: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4684: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4685: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4686: if (($key) && ($value)) {
4687: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4688: }
4689: }
4690: }
4691: return %returnhash;
4692: }
1.662 raeburn 4693: # ---------------------------------------------------------- Domain roles
4694:
4695: sub get_domain_roles {
4696: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4697: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4698: $startdate = '.';
4699: }
1.1018 raeburn 4700: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4701: $enddate = '.';
4702: }
1.922 raeburn 4703: my $rolelist;
4704: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4705: $rolelist = join('&',@{$roles});
1.922 raeburn 4706: }
1.662 raeburn 4707: my %personnel = ();
1.841 albertel 4708:
4709: my %servers = &get_servers($dom,'library');
4710: foreach my $tryserver (keys(%servers)) {
4711: %{$personnel{$tryserver}}=();
4712: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4713: &escape($startdate).':'.
4714: &escape($enddate).':'.
4715: &escape($rolelist), $tryserver))) {
4716: my ($key,$value) = split(/\=/,$line,2);
4717: if (($key) && ($value)) {
4718: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4719: }
4720: }
1.662 raeburn 4721: }
4722: return %personnel;
4723: }
1.658 raeburn 4724:
1.1057 www 4725: # ----------------------------------------------------------- Interval timing
1.149 www 4726:
1.1153 www 4727: {
4728: # Caches needed for speedup of navmaps
4729: # We don't want to cache this for very long at all (5 seconds at most)
4730: #
4731: # The user for whom we cache
4732: my $cachedkey='';
4733: # The cached times for this user
4734: my %cachedtimes=();
4735: # When this was last done
1.1282 raeburn 4736: my $cachedtime='';
1.1153 www 4737:
4738: sub load_all_first_access {
1.1308 raeburn 4739: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 4740: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 4741: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
4742: (!$ignorecache)) {
1.1154 raeburn 4743: return;
4744: }
4745: $cachedtime=time;
4746: $cachedkey=$uname.':'.$udom;
4747: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4748: }
4749:
1.504 albertel 4750: sub get_first_access {
1.1308 raeburn 4751: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 4752: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4753: if ($argsymb) { $symb=$argsymb; }
4754: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4755: if ($argmap) { $map = $argmap; }
1.926 albertel 4756: if ($type eq 'course') {
4757: $res='course';
4758: } elsif ($type eq 'map') {
1.588 albertel 4759: $res=&symbread($map);
4760: } else {
4761: $res=$symb;
4762: }
1.1308 raeburn 4763: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 4764: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4765: }
4766:
4767: sub set_first_access {
1.1162 raeburn 4768: my ($type,$interval)=@_;
1.790 albertel 4769: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4770: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4771: if ($type eq 'course') {
4772: $res='course';
4773: } elsif ($type eq 'map') {
1.588 albertel 4774: $res=&symbread($map);
4775: } else {
4776: $res=$symb;
4777: }
1.1153 www 4778: $cachedkey='';
1.1162 raeburn 4779: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4780: if (!$firstaccess) {
1.1162 raeburn 4781: my $start = time;
4782: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4783: $udom,$uname);
4784: if ($putres eq 'ok') {
4785: &put('timerinterval',{"$courseid\0$res"=>$interval},
4786: $udom,$uname);
4787: &appenv(
4788: {
4789: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4790: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4791: }
4792: );
4793: }
4794: return $putres;
1.505 albertel 4795: }
4796: return 'already_set';
1.504 albertel 4797: }
1.1153 www 4798: }
1.1282 raeburn 4799:
1.110 www 4800: # --------------------------------------------- Set Expire Date for Spreadsheet
4801:
4802: sub expirespread {
4803: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4804: my $cid=$env{'request.course.id'};
1.110 www 4805: if ($cid) {
4806: my $now=time;
4807: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4808: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4809: $env{'course.'.$cid.'.num'}.
1.110 www 4810: ':nohist_expirationdates:'.
4811: &escape($key).'='.$now,
1.620 albertel 4812: $env{'course.'.$cid.'.home'})
1.110 www 4813: }
4814: return 'ok';
1.14 www 4815: }
4816:
1.109 www 4817: # ----------------------------------------------------- Devalidate Spreadsheets
4818:
4819: sub devalidate {
1.325 www 4820: my ($symb,$uname,$udom)=@_;
1.620 albertel 4821: my $cid=$env{'request.course.id'};
1.109 www 4822: if ($cid) {
1.391 matthew 4823: # delete the stored spreadsheets for
4824: # - the student level sheet of this user in course's homespace
4825: # - the assessment level sheet for this resource
4826: # for this user in user's homespace
1.553 albertel 4827: # - current conditional state info
1.325 www 4828: my $key=$uname.':'.$udom.':';
1.109 www 4829: my $status=
1.299 matthew 4830: &del('nohist_calculatedsheets',
1.391 matthew 4831: [$key.'studentcalc:'],
1.620 albertel 4832: $env{'course.'.$cid.'.domain'},
4833: $env{'course.'.$cid.'.num'})
1.133 albertel 4834: .' '.
4835: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4836: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4837: unless ($status eq 'ok ok') {
4838: &logthis('Could not devalidate spreadsheet '.
1.325 www 4839: $uname.' at '.$udom.' for '.
1.109 www 4840: $symb.': '.$status);
1.133 albertel 4841: }
1.553 albertel 4842: &delenv('user.state.'.$cid);
1.109 www 4843: }
4844: }
4845:
1.265 albertel 4846: sub get_scalar {
4847: my ($string,$end) = @_;
4848: my $value;
4849: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4850: $value = $1;
4851: } elsif ($$string =~ s/^([^&]*?)&//) {
4852: $value = $1;
4853: }
4854: return &unescape($value);
4855: }
4856:
4857: sub array2str {
4858: my (@array) = @_;
4859: my $result=&arrayref2str(\@array);
4860: $result=~s/^__ARRAY_REF__//;
4861: $result=~s/__END_ARRAY_REF__$//;
4862: return $result;
4863: }
4864:
1.204 albertel 4865: sub arrayref2str {
4866: my ($arrayref) = @_;
1.265 albertel 4867: my $result='__ARRAY_REF__';
1.204 albertel 4868: foreach my $elem (@$arrayref) {
1.265 albertel 4869: if(ref($elem) eq 'ARRAY') {
4870: $result.=&arrayref2str($elem).'&';
4871: } elsif(ref($elem) eq 'HASH') {
4872: $result.=&hashref2str($elem).'&';
4873: } elsif(ref($elem)) {
4874: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4875: } else {
4876: $result.=&escape($elem).'&';
4877: }
4878: }
4879: $result=~s/\&$//;
1.265 albertel 4880: $result .= '__END_ARRAY_REF__';
1.204 albertel 4881: return $result;
4882: }
4883:
1.168 albertel 4884: sub hash2str {
1.204 albertel 4885: my (%hash) = @_;
4886: my $result=&hashref2str(\%hash);
1.265 albertel 4887: $result=~s/^__HASH_REF__//;
4888: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4889: return $result;
4890: }
4891:
4892: sub hashref2str {
4893: my ($hashref)=@_;
1.265 albertel 4894: my $result='__HASH_REF__';
1.800 albertel 4895: foreach my $key (sort(keys(%$hashref))) {
4896: if (ref($key) eq 'ARRAY') {
4897: $result.=&arrayref2str($key).'=';
4898: } elsif (ref($key) eq 'HASH') {
4899: $result.=&hashref2str($key).'=';
4900: } elsif (ref($key)) {
1.265 albertel 4901: $result.='=';
1.800 albertel 4902: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4903: } else {
1.1132 raeburn 4904: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4905: }
4906:
1.800 albertel 4907: if(ref($hashref->{$key}) eq 'ARRAY') {
4908: $result.=&arrayref2str($hashref->{$key}).'&';
4909: } elsif(ref($hashref->{$key}) eq 'HASH') {
4910: $result.=&hashref2str($hashref->{$key}).'&';
4911: } elsif(ref($hashref->{$key})) {
1.265 albertel 4912: $result.='&';
1.800 albertel 4913: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4914: } else {
1.800 albertel 4915: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4916: }
4917: }
1.168 albertel 4918: $result=~s/\&$//;
1.265 albertel 4919: $result .= '__END_HASH_REF__';
1.168 albertel 4920: return $result;
4921: }
4922:
4923: sub str2hash {
1.265 albertel 4924: my ($string)=@_;
4925: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4926: return %$hash;
4927: }
4928:
4929: sub str2hashref {
1.168 albertel 4930: my ($string) = @_;
1.265 albertel 4931:
4932: my %hash;
4933:
4934: if($string !~ /^__HASH_REF__/) {
4935: if (! ($string eq '' || !defined($string))) {
4936: $hash{'error'}='Not hash reference';
4937: }
4938: return (\%hash, $string);
4939: }
4940:
4941: $string =~ s/^__HASH_REF__//;
4942:
4943: while($string !~ /^__END_HASH_REF__/) {
4944: #key
4945: my $key='';
4946: if($string =~ /^__HASH_REF__/) {
4947: ($key, $string)=&str2hashref($string);
4948: if(defined($key->{'error'})) {
4949: $hash{'error'}='Bad data';
4950: return (\%hash, $string);
4951: }
4952: } elsif($string =~ /^__ARRAY_REF__/) {
4953: ($key, $string)=&str2arrayref($string);
4954: if($key->[0] eq 'Array reference error') {
4955: $hash{'error'}='Bad data';
4956: return (\%hash, $string);
4957: }
4958: } else {
4959: $string =~ s/^(.*?)=//;
1.267 albertel 4960: $key=&unescape($1);
1.265 albertel 4961: }
4962: $string =~ s/^=//;
4963:
4964: #value
4965: my $value='';
4966: if($string =~ /^__HASH_REF__/) {
4967: ($value, $string)=&str2hashref($string);
4968: if(defined($value->{'error'})) {
4969: $hash{'error'}='Bad data';
4970: return (\%hash, $string);
4971: }
4972: } elsif($string =~ /^__ARRAY_REF__/) {
4973: ($value, $string)=&str2arrayref($string);
4974: if($value->[0] eq 'Array reference error') {
4975: $hash{'error'}='Bad data';
4976: return (\%hash, $string);
4977: }
4978: } else {
4979: $value=&get_scalar(\$string,'__END_HASH_REF__');
4980: }
4981: $string =~ s/^&//;
4982:
4983: $hash{$key}=$value;
1.204 albertel 4984: }
1.265 albertel 4985:
4986: $string =~ s/^__END_HASH_REF__//;
4987:
4988: return (\%hash, $string);
1.204 albertel 4989: }
4990:
4991: sub str2array {
1.265 albertel 4992: my ($string)=@_;
4993: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4994: return @$array;
4995: }
4996:
4997: sub str2arrayref {
1.204 albertel 4998: my ($string) = @_;
1.265 albertel 4999: my @array;
5000:
5001: if($string !~ /^__ARRAY_REF__/) {
5002: if (! ($string eq '' || !defined($string))) {
5003: $array[0]='Array reference error';
5004: }
5005: return (\@array, $string);
5006: }
5007:
5008: $string =~ s/^__ARRAY_REF__//;
5009:
5010: while($string !~ /^__END_ARRAY_REF__/) {
5011: my $value='';
5012: if($string =~ /^__HASH_REF__/) {
5013: ($value, $string)=&str2hashref($string);
5014: if(defined($value->{'error'})) {
5015: $array[0] ='Array reference error';
5016: return (\@array, $string);
5017: }
5018: } elsif($string =~ /^__ARRAY_REF__/) {
5019: ($value, $string)=&str2arrayref($string);
5020: if($value->[0] eq 'Array reference error') {
5021: $array[0] ='Array reference error';
5022: return (\@array, $string);
5023: }
5024: } else {
5025: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5026: }
5027: $string =~ s/^&//;
5028:
5029: push(@array, $value);
1.191 harris41 5030: }
1.265 albertel 5031:
5032: $string =~ s/^__END_ARRAY_REF__//;
5033:
5034: return (\@array, $string);
1.168 albertel 5035: }
5036:
1.167 albertel 5037: # -------------------------------------------------------------------Temp Store
5038:
1.168 albertel 5039: sub tmpreset {
5040: my ($symb,$namespace,$domain,$stuname) = @_;
5041: if (!$symb) {
5042: $symb=&symbread();
1.620 albertel 5043: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5044: }
5045: $symb=escape($symb);
5046:
1.620 albertel 5047: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5048: $namespace=~s/\//\_/g;
5049: $namespace=~s/\W//g;
5050:
1.620 albertel 5051: if (!$domain) { $domain=$env{'user.domain'}; }
5052: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5053: if ($domain eq 'public' && $stuname eq 'public') {
5054: $stuname=$ENV{'REMOTE_ADDR'};
5055: }
1.1117 foxr 5056: my $path=LONCAPA::tempdir();
1.168 albertel 5057: my %hash;
5058: if (tie(%hash,'GDBM_File',
5059: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5060: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5061: foreach my $key (keys(%hash)) {
1.180 albertel 5062: if ($key=~ /:$symb/) {
1.168 albertel 5063: delete($hash{$key});
5064: }
5065: }
5066: }
5067: }
5068:
1.167 albertel 5069: sub tmpstore {
1.168 albertel 5070: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5071:
5072: if (!$symb) {
5073: $symb=&symbread();
1.620 albertel 5074: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5075: }
5076: $symb=escape($symb);
5077:
5078: if (!$namespace) {
5079: # I don't think we would ever want to store this for a course.
5080: # it seems this will only be used if we don't have a course.
1.620 albertel 5081: #$namespace=$env{'request.course.id'};
1.168 albertel 5082: #if (!$namespace) {
1.620 albertel 5083: $namespace=$env{'request.state'};
1.168 albertel 5084: #}
5085: }
5086: $namespace=~s/\//\_/g;
5087: $namespace=~s/\W//g;
1.620 albertel 5088: if (!$domain) { $domain=$env{'user.domain'}; }
5089: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5090: if ($domain eq 'public' && $stuname eq 'public') {
5091: $stuname=$ENV{'REMOTE_ADDR'};
5092: }
1.168 albertel 5093: my $now=time;
5094: my %hash;
1.1117 foxr 5095: my $path=LONCAPA::tempdir();
1.168 albertel 5096: if (tie(%hash,'GDBM_File',
5097: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5098: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5099: $hash{"version:$symb"}++;
5100: my $version=$hash{"version:$symb"};
5101: my $allkeys='';
5102: foreach my $key (keys(%$storehash)) {
5103: $allkeys.=$key.':';
1.591 albertel 5104: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5105: }
5106: $hash{"$version:$symb:timestamp"}=$now;
5107: $allkeys.='timestamp';
5108: $hash{"$version:keys:$symb"}=$allkeys;
5109: if (untie(%hash)) {
5110: return 'ok';
5111: } else {
5112: return "error:$!";
5113: }
5114: } else {
5115: return "error:$!";
5116: }
5117: }
1.167 albertel 5118:
1.168 albertel 5119: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5120:
1.168 albertel 5121: sub tmprestore {
5122: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5123:
1.168 albertel 5124: if (!$symb) {
5125: $symb=&symbread();
1.620 albertel 5126: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5127: }
5128: $symb=escape($symb);
5129:
1.620 albertel 5130: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5131:
1.620 albertel 5132: if (!$domain) { $domain=$env{'user.domain'}; }
5133: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5134: if ($domain eq 'public' && $stuname eq 'public') {
5135: $stuname=$ENV{'REMOTE_ADDR'};
5136: }
1.168 albertel 5137: my %returnhash;
5138: $namespace=~s/\//\_/g;
5139: $namespace=~s/\W//g;
5140: my %hash;
1.1117 foxr 5141: my $path=LONCAPA::tempdir();
1.168 albertel 5142: if (tie(%hash,'GDBM_File',
5143: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5144: &GDBM_READER(),0640)) {
1.168 albertel 5145: my $version=$hash{"version:$symb"};
5146: $returnhash{'version'}=$version;
5147: my $scope;
5148: for ($scope=1;$scope<=$version;$scope++) {
5149: my $vkeys=$hash{"$scope:keys:$symb"};
5150: my @keys=split(/:/,$vkeys);
5151: my $key;
5152: $returnhash{"$scope:keys"}=$vkeys;
5153: foreach $key (@keys) {
1.591 albertel 5154: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5155: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5156: }
5157: }
1.168 albertel 5158: if (!(untie(%hash))) {
5159: return "error:$!";
5160: }
5161: } else {
5162: return "error:$!";
5163: }
5164: return %returnhash;
1.167 albertel 5165: }
5166:
1.9 www 5167: # ----------------------------------------------------------------------- Store
5168:
5169: sub store {
1.1269 raeburn 5170: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5171: my $home='';
5172:
1.168 albertel 5173: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5174:
1.213 www 5175: $symb=&symbclean($symb);
1.122 albertel 5176: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5177:
1.620 albertel 5178: if (!$domain) { $domain=$env{'user.domain'}; }
5179: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5180:
5181: &devalidate($symb,$stuname,$domain);
1.109 www 5182:
5183: $symb=escape($symb);
1.187 www 5184: if (!$namespace) {
1.620 albertel 5185: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5186: return '';
5187: }
5188: }
1.620 albertel 5189: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5190:
5191: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5192: $$storehash{'host'}=$perlvar{'lonHostID'};
5193:
1.12 www 5194: my $namevalue='';
1.800 albertel 5195: foreach my $key (keys(%$storehash)) {
5196: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5197: }
1.12 www 5198: $namevalue=~s/\&$//;
1.187 www 5199: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 5200: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5201: }
5202:
1.47 www 5203: # -------------------------------------------------------------- Critical Store
5204:
5205: sub cstore {
1.1269 raeburn 5206: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5207: my $home='';
5208:
1.168 albertel 5209: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5210:
1.213 www 5211: $symb=&symbclean($symb);
1.122 albertel 5212: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5213:
1.620 albertel 5214: if (!$domain) { $domain=$env{'user.domain'}; }
5215: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5216:
5217: &devalidate($symb,$stuname,$domain);
1.109 www 5218:
5219: $symb=escape($symb);
1.187 www 5220: if (!$namespace) {
1.620 albertel 5221: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5222: return '';
5223: }
5224: }
1.620 albertel 5225: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5226:
5227: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5228: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5229:
1.47 www 5230: my $namevalue='';
1.800 albertel 5231: foreach my $key (keys(%$storehash)) {
5232: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5233: }
1.47 www 5234: $namevalue=~s/\&$//;
1.187 www 5235: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5236: return critical
1.1269 raeburn 5237: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5238: }
5239:
1.9 www 5240: # --------------------------------------------------------------------- Restore
5241:
5242: sub restore {
1.124 www 5243: my ($symb,$namespace,$domain,$stuname) = @_;
5244: my $home='';
5245:
1.168 albertel 5246: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5247:
1.122 albertel 5248: if (!$symb) {
1.1224 raeburn 5249: return if ($namespace eq 'courserequests');
5250: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5251: } else {
1.1224 raeburn 5252: unless ($namespace eq 'courserequests') {
5253: $symb=&escape(&symbclean($symb));
5254: }
1.122 albertel 5255: }
1.188 www 5256: if (!$namespace) {
1.620 albertel 5257: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5258: return '';
5259: }
5260: }
1.620 albertel 5261: if (!$domain) { $domain=$env{'user.domain'}; }
5262: if (!$stuname) { $stuname=$env{'user.name'}; }
5263: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5264: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5265:
1.12 www 5266: my %returnhash=();
1.800 albertel 5267: foreach my $line (split(/\&/,$answer)) {
5268: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5269: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5270: }
1.75 www 5271: my $version;
5272: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5273: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5274: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5275: }
1.75 www 5276: }
1.13 www 5277: return %returnhash;
1.34 www 5278: }
5279:
5280: # ---------------------------------------------------------- Course Description
1.1118 foxr 5281: #
5282: #
1.34 www 5283:
5284: sub coursedescription {
1.731 albertel 5285: my ($courseid,$args)=@_;
1.34 www 5286: $courseid=~s/^\///;
1.49 www 5287: $courseid=~s/\_/\//g;
1.34 www 5288: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5289: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5290: my $normalid=$cdomain.'_'.$cnum;
5291: # need to always cache even if we get errors otherwise we keep
5292: # trying and trying and trying to get the course description.
5293: my %envhash=();
5294: my %returnhash=();
1.731 albertel 5295:
5296: my $expiretime=600;
5297: if ($env{'request.course.id'} eq $normalid) {
5298: $expiretime=120;
5299: }
5300:
5301: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5302: if (!$args->{'freshen_cache'}
5303: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5304: foreach my $key (keys(%env)) {
5305: next if ($key !~ /^\Q$prefix\E(.*)/);
5306: my ($setting) = $1;
5307: $returnhash{$setting} = $env{$key};
5308: }
5309: return %returnhash;
5310: }
5311:
1.1118 foxr 5312: # get the data again
5313:
1.731 albertel 5314: if (!$args->{'one_time'}) {
5315: $envhash{'course.'.$normalid.'.last_cache'}=time;
5316: }
1.811 albertel 5317:
1.34 www 5318: if ($chome ne 'no_host') {
1.302 albertel 5319: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5320: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5321: my $username = $env{'user.name'}; # Defult username
5322: if(defined $args->{'user'}) {
5323: $username = $args->{'user'};
5324: }
1.129 albertel 5325: $returnhash{'home'}= $chome;
5326: $returnhash{'domain'} = $cdomain;
5327: $returnhash{'num'} = $cnum;
1.741 raeburn 5328: if (!defined($returnhash{'type'})) {
5329: $returnhash{'type'} = 'Course';
5330: }
1.130 albertel 5331: while (my ($name,$value) = each %returnhash) {
1.53 www 5332: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5333: }
1.270 www 5334: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5335: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5336: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5337: $envhash{'course.'.$normalid.'.home'}=$chome;
5338: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5339: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5340: }
5341: }
1.731 albertel 5342: if (!$args->{'one_time'}) {
1.949 raeburn 5343: &appenv(\%envhash);
1.731 albertel 5344: }
1.302 albertel 5345: return %returnhash;
1.461 www 5346: }
5347:
1.1080 raeburn 5348: sub update_released_required {
5349: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5350: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5351: $cid = $env{'request.course.id'};
5352: $cdom = $env{'course.'.$cid.'.domain'};
5353: $cnum = $env{'course.'.$cid.'.num'};
5354: $chome = $env{'course.'.$cid.'.home'};
5355: }
5356: if ($needsrelease) {
5357: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5358: my $needsupdate;
5359: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5360: $needsupdate = 1;
5361: } else {
5362: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5363: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5364: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5365: $needsupdate = 1;
5366: }
5367: }
5368: if ($needsupdate) {
5369: my %needshash = (
5370: 'internal.releaserequired' => $needsrelease,
5371: );
5372: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5373: if ($putresult eq 'ok') {
5374: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5375: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5376: if (ref($crsinfo{$cid}) eq 'HASH') {
5377: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5378: &courseidput($cdom,\%crsinfo,$chome,'notime');
5379: }
5380: }
5381: }
5382: }
5383: return;
5384: }
5385:
1.461 www 5386: # -------------------------------------------------See if a user is privileged
5387:
5388: sub privileged {
1.1219 raeburn 5389: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5390: my $now = time;
1.1219 raeburn 5391: my $roles;
5392: if (ref($possroles) eq 'ARRAY') {
5393: $roles = $possroles;
5394: } else {
5395: $roles = ['dc','su'];
5396: }
5397: if (ref($possdomains) eq 'ARRAY') {
5398: my %privileged = &privileged_by_domain($possdomains,$roles);
5399: foreach my $dom (@{$possdomains}) {
5400: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5401: (ref($privileged{$dom}) eq 'HASH')) {
5402: foreach my $role (@{$roles}) {
5403: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5404: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5405: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5406: return 1 unless (($end && $end < $now) ||
5407: ($start && $start > $now));
5408: }
5409: }
5410: }
5411: }
5412: }
5413: } else {
5414: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5415: my $now = time;
1.1170 droeschl 5416:
1.1275 musolffc 5417: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5418: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5419: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5420: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5421: or ($tstart && $tstart > $now);
1.1170 droeschl 5422: }
1.1219 raeburn 5423: }
5424: }
5425: return 0;
5426: }
1.1170 droeschl 5427:
1.1219 raeburn 5428: sub privileged_by_domain {
5429: my ($domains,$roles) = @_;
5430: my %privileged = ();
5431: my $cachetime = 60*60*24;
5432: my $now = time;
5433: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5434: return %privileged;
5435: }
5436: foreach my $dom (@{$domains}) {
5437: next if (ref($privileged{$dom}) eq 'HASH');
5438: my $needroles;
5439: foreach my $role (@{$roles}) {
5440: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5441: if (defined($cached)) {
5442: if (ref($result) eq 'HASH') {
5443: $privileged{$dom}{$role} = $result;
5444: }
5445: } else {
5446: $needroles = 1;
5447: }
5448: }
5449: if ($needroles) {
5450: my %dompersonnel = &get_domain_roles($dom,$roles);
5451: $privileged{$dom} = {};
5452: foreach my $server (keys(%dompersonnel)) {
5453: if (ref($dompersonnel{$server}) eq 'HASH') {
5454: foreach my $item (keys(%{$dompersonnel{$server}})) {
5455: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5456: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5457: next if ($end && $end < $now);
5458: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5459: $dompersonnel{$server}{$item};
5460: }
5461: }
5462: }
5463: if (ref($privileged{$dom}) eq 'HASH') {
5464: foreach my $role (@{$roles}) {
5465: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5466: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5467: } else {
5468: my %hash = ();
5469: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5470: }
5471: }
5472: }
5473: }
5474: }
5475: return %privileged;
1.9 www 5476: }
1.1 albertel 5477:
1.103 harris41 5478: # -------------------------------------------------------- Get user privileges
1.11 www 5479:
5480: sub rolesinit {
1.1169 droeschl 5481: my ($domain, $username) = @_;
5482: my %userroles = ('user.login.time' => time);
5483: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5484:
5485: # firstaccess and timerinterval are related to timed maps/resources.
5486: # also, blocking can be triggered by an activating timer
5487: # it's saved in the user's %env.
5488: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5489: my %timerinterval = &dump('timerinterval', $domain, $username);
5490: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5491: %timerintchk, %timerintenv);
5492:
1.1162 raeburn 5493: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5494: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5495: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5496: }
1.1169 droeschl 5497:
1.1162 raeburn 5498: foreach my $key (keys(%timerinterval)) {
5499: my ($cid,$rest) = split(/\0/,$key);
5500: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5501: }
1.1169 droeschl 5502:
1.11 www 5503: my %allroles=();
1.1162 raeburn 5504: my %allgroups=();
1.11 www 5505:
1.1274 raeburn 5506: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5507: my $role = $rolesdump{$area};
5508: $area =~ s/\_\w\w$//;
5509:
5510: my ($trole, $tend, $tstart, $group_privs);
5511:
5512: if ($role =~ /^cr/) {
5513: # Custom role, defined by a user
5514: # e.g., user.role.cr/msu/smith/mynewrole
5515: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5516: $trole = $1;
5517: ($tend, $tstart) = split('_', $2);
5518: } else {
5519: $trole = $role;
5520: }
5521: } elsif ($role =~ m|^gr/|) {
5522: # Role of member in a group, defined within a course/community
5523: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5524: ($trole, $tend, $tstart) = split(/_/, $role);
5525: next if $tstart eq '-1';
5526: ($trole, $group_privs) = split(/\//, $trole);
5527: $group_privs = &unescape($group_privs);
5528: } else {
5529: # Just a normal role, defined in roles.tab
5530: ($trole, $tend, $tstart) = split(/_/,$role);
5531: }
5532:
5533: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5534: $username);
5535: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5536:
5537: # role expired or not available yet?
5538: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5539: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5540:
5541: next if $area eq '' or $trole eq '';
5542:
5543: my $spec = "$trole.$area";
5544: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5545:
5546: if ($trole =~ /^cr\//) {
5547: # Custom role, defined by a user
5548: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5549: } elsif ($trole eq 'gr') {
5550: # Role of a member in a group, defined within a course/community
5551: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5552: next;
5553: } else {
5554: # Normal role, defined in roles.tab
5555: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5556: }
5557:
5558: my $cid = $tdomain.'_'.$trest;
5559: unless ($firstaccchk{$cid}) {
5560: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5561: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5562: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5563: $coursetimerstarts{$cid}{$item};
5564: }
5565: }
5566: $firstaccchk{$cid} = 1;
5567: }
5568: unless ($timerintchk{$cid}) {
5569: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5570: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5571: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5572: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5573: }
1.12 www 5574: }
1.1169 droeschl 5575: $timerintchk{$cid} = 1;
1.191 harris41 5576: }
1.11 www 5577: }
1.1169 droeschl 5578:
5579: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5580: \%allroles, \%allgroups);
5581: $env{'user.adv'} = $userroles{'user.adv'};
5582:
1.1162 raeburn 5583: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5584: }
5585:
1.567 raeburn 5586: sub set_arearole {
1.1215 raeburn 5587: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5588: unless ($nolog) {
1.567 raeburn 5589: # log the associated role with the area
1.1215 raeburn 5590: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5591: }
1.743 albertel 5592: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5593: }
5594:
5595: sub custom_roleprivs {
5596: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5597: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5598: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5599: if (&hostname($homsvr) ne '') {
1.567 raeburn 5600: my ($rdummy,$roledef)=
5601: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5602: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5603: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5604: if (defined($syspriv)) {
1.1043 raeburn 5605: if ($trest =~ /^$match_community$/) {
5606: $syspriv =~ s/bre\&S//;
5607: }
1.567 raeburn 5608: $$allroles{'cm./'}.=':'.$syspriv;
5609: $$allroles{$spec.'./'}.=':'.$syspriv;
5610: }
5611: if ($tdomain ne '') {
5612: if (defined($dompriv)) {
5613: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5614: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5615: }
5616: if (($trest ne '') && (defined($coursepriv))) {
5617: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5618: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5619: }
5620: }
5621: }
5622: }
5623: }
5624:
1.678 raeburn 5625: sub group_roleprivs {
5626: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5627: my $access = 1;
5628: my $now = time;
5629: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5630: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5631: if ($access) {
1.811 albertel 5632: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5633: $$allgroups{$course}{$group} .=':'.$group_privs;
5634: }
5635: }
1.567 raeburn 5636:
5637: sub standard_roleprivs {
5638: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5639: if (defined($pr{$trole.':s'})) {
5640: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5641: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5642: }
5643: if ($tdomain ne '') {
5644: if (defined($pr{$trole.':d'})) {
5645: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5646: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5647: }
5648: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5649: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5650: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5651: }
5652: }
5653: }
5654:
5655: sub set_userprivs {
1.1064 raeburn 5656: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5657: my $author=0;
5658: my $adv=0;
1.678 raeburn 5659: my %grouproles = ();
5660: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5661: my @groupkeys;
1.1000 raeburn 5662: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5663: push(@groupkeys,$role);
5664: }
5665: if (ref($groups_roles) eq 'HASH') {
5666: foreach my $key (keys(%{$groups_roles})) {
5667: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5668: push(@groupkeys,$key);
5669: }
5670: }
5671: }
5672: if (@groupkeys > 0) {
5673: foreach my $role (@groupkeys) {
5674: my ($trole,$area,$sec,$extendedarea);
5675: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5676: $trole = $1;
5677: $area = $2;
5678: $sec = $3;
5679: $extendedarea = $area.$sec;
5680: if (exists($$allgroups{$area})) {
5681: foreach my $group (keys(%{$$allgroups{$area}})) {
5682: my $spec = $trole.'.'.$extendedarea;
5683: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5684: $$allgroups{$area}{$group};
1.1064 raeburn 5685: }
1.678 raeburn 5686: }
5687: }
5688: }
5689: }
5690: }
1.800 albertel 5691: foreach my $group (keys(%grouproles)) {
5692: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5693: }
1.800 albertel 5694: foreach my $role (keys(%{$allroles})) {
5695: my %thesepriv;
1.941 raeburn 5696: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5697: foreach my $item (split(/:/,$$allroles{$role})) {
5698: if ($item ne '') {
5699: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5700: if ($restrictions eq '') {
5701: $thesepriv{$privilege}='F';
5702: } elsif ($thesepriv{$privilege} ne 'F') {
5703: $thesepriv{$privilege}.=$restrictions;
5704: }
5705: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5706: }
5707: }
5708: my $thesestr='';
1.1104 raeburn 5709: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5710: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5711: }
5712: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5713: }
5714: return ($author,$adv);
5715: }
5716:
1.994 raeburn 5717: sub role_status {
1.1104 raeburn 5718: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5719: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5720: my ($one,$two) = split(m{\./},$rolekey,2);
5721: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5722: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5723: $$where = '/'.$two;
1.994 raeburn 5724: $$trolecode=$$role.'.'.$$where;
5725: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5726: $$tstatus='is';
1.1104 raeburn 5727: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5728: $$tstatus='future';
1.1034 raeburn 5729: if ($$tstart<$now) {
5730: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5731: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5732: my (%allroles,%allgroups,$group_privs,
5733: %groups_roles,@rolecodes);
1.1002 raeburn 5734: my %userroles = (
5735: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5736: );
1.1064 raeburn 5737: @rolecodes = ('cm');
1.1002 raeburn 5738: my $spec=$$role.'.'.$$where;
5739: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5740: if ($$role =~ /^cr\//) {
5741: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5742: push(@rolecodes,'cr');
1.1002 raeburn 5743: } elsif ($$role eq 'gr') {
1.1064 raeburn 5744: push(@rolecodes,$$role);
1.1002 raeburn 5745: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5746: $env{'user.name'});
1.1064 raeburn 5747: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5748: (undef,my $group_privs) = split(/\//,$trole);
5749: $group_privs = &unescape($group_privs);
5750: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5751: 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 5752: &get_groups_roles($tdomain,$trest,
5753: \%course_roles,\@rolecodes,
5754: \%groups_roles);
1.1002 raeburn 5755: } else {
1.1064 raeburn 5756: push(@rolecodes,$$role);
1.1002 raeburn 5757: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5758: }
1.1064 raeburn 5759: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5760: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5761: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5762: }
5763: }
1.1034 raeburn 5764: $$tstatus = 'is';
1.1002 raeburn 5765: }
1.994 raeburn 5766: }
5767: if ($$tend) {
1.1104 raeburn 5768: if ($$tend<$update) {
1.994 raeburn 5769: $$tstatus='expired';
5770: } elsif ($$tend<$now) {
5771: $$tstatus='will_not';
5772: }
5773: }
5774: }
5775: }
5776: }
5777:
1.1104 raeburn 5778: sub get_groups_roles {
5779: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5780: return unless((ref($cdom_courseroles) eq 'HASH') &&
5781: (ref($rolecodes) eq 'ARRAY') &&
5782: (ref($groups_roles) eq 'HASH'));
5783: if (keys(%{$cdom_courseroles}) > 0) {
5784: my ($cnum) = ($rest =~ /^($match_courseid)/);
5785: if ($cdom ne '' && $cnum ne '') {
5786: foreach my $key (keys(%{$cdom_courseroles})) {
5787: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5788: my $crsrole = $1;
5789: my $crssec = $2;
5790: if ($crsrole =~ /^cr/) {
5791: unless (grep(/^cr$/,@{$rolecodes})) {
5792: push(@{$rolecodes},'cr');
5793: }
5794: } else {
5795: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5796: push(@{$rolecodes},$crsrole);
5797: }
5798: }
5799: my $rolekey = "$crsrole./$cdom/$cnum";
5800: if ($crssec ne '') {
5801: $rolekey .= "/$crssec";
5802: }
5803: $rolekey .= './';
5804: $groups_roles->{$rolekey} = $rolecodes;
5805: }
5806: }
5807: }
5808: }
5809: return;
5810: }
5811:
5812: sub delete_env_groupprivs {
5813: my ($where,$courseroles,$possroles) = @_;
5814: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5815: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5816: unless (ref($courseroles->{$udom}) eq 'HASH') {
5817: %{$courseroles->{$udom}} =
5818: &get_my_roles('','','userroles',['active'],
5819: $possroles,[$udom],1);
5820: }
5821: if (ref($courseroles->{$udom}) eq 'HASH') {
5822: foreach my $item (keys(%{$courseroles->{$udom}})) {
5823: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5824: my $area = '/'.$cdom.'/'.$cnum;
5825: my $privkey = "user.priv.$crsrole.$area";
5826: if ($crssec ne '') {
5827: $privkey .= '/'.$crssec;
5828: }
5829: $privkey .= ".$area/$group";
5830: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5831: }
5832: }
5833: return;
5834: }
5835:
1.994 raeburn 5836: sub check_adhoc_privs {
1.1329 ! raeburn 5837: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 5838: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 ! raeburn 5839: if ($sec) {
! 5840: $cckey .= '/'.$sec;
! 5841: }
1.1185 raeburn 5842: my $setprivs;
1.994 raeburn 5843: if ($env{$cckey}) {
5844: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5845: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5846: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 ! raeburn 5847: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 5848: $setprivs = 1;
1.994 raeburn 5849: }
5850: } else {
1.1088 raeburn 5851: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5852: $setprivs = 1;
1.994 raeburn 5853: }
1.1185 raeburn 5854: return $setprivs;
1.994 raeburn 5855: }
5856:
5857: sub set_adhoc_privileges {
1.1326 raeburn 5858: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 ! raeburn 5859: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 5860: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 ! raeburn 5861: if ($sec ne '') {
! 5862: $area .= '/'.$sec;
! 5863: }
1.994 raeburn 5864: my $spec = $role.'.'.$area;
5865: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5866: $env{'user.name'},1);
1.1326 raeburn 5867: my %rolehash = ();
5868: if ($role =~ m{^cr/$dcdom/$dcdom\Q-domainconfig\E/}) {
5869: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
5870: } else {
5871: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
5872: }
5873: my ($author,$adv)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 5874: &appenv(\%userroles,[$role,'cm']);
5875: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5876: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5877: &appenv( {'request.role' => $spec,
5878: 'request.role.domain' => $dcdom,
5879: 'request.course.sec' => ''
5880: }
5881: );
5882: my $tadv=0;
5883: if (&allowed('adv') eq 'F') { $tadv=1; }
5884: &appenv({'request.role.adv' => $tadv});
5885: }
1.994 raeburn 5886: }
5887:
1.12 www 5888: # --------------------------------------------------------------- get interface
5889:
5890: sub get {
1.131 albertel 5891: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5892: my $items='';
1.800 albertel 5893: foreach my $item (@$storearr) {
5894: $items.=&escape($item).'&';
1.191 harris41 5895: }
1.12 www 5896: $items=~s/\&$//;
1.620 albertel 5897: if (!$udomain) { $udomain=$env{'user.domain'}; }
5898: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5899: my $uhome=&homeserver($uname,$udomain);
5900:
1.133 albertel 5901: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5902: my @pairs=split(/\&/,$rep);
1.273 albertel 5903: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5904: return @pairs;
5905: }
1.15 www 5906: my %returnhash=();
1.42 www 5907: my $i=0;
1.800 albertel 5908: foreach my $item (@$storearr) {
5909: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5910: $i++;
1.191 harris41 5911: }
1.15 www 5912: return %returnhash;
1.27 www 5913: }
5914:
5915: # --------------------------------------------------------------- del interface
5916:
5917: sub del {
1.133 albertel 5918: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5919: my $items='';
1.800 albertel 5920: foreach my $item (@$storearr) {
5921: $items.=&escape($item).'&';
1.191 harris41 5922: }
1.984 neumanie 5923:
1.27 www 5924: $items=~s/\&$//;
1.620 albertel 5925: if (!$udomain) { $udomain=$env{'user.domain'}; }
5926: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5927: my $uhome=&homeserver($uname,$udomain);
5928: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5929: }
5930:
5931: # -------------------------------------------------------------- dump interface
5932:
1.1180 droeschl 5933: sub unserialize {
5934: my ($rep, $escapedkeys) = @_;
5935:
5936: return {} if $rep =~ /^error/;
5937:
5938: my %returnhash=();
1.1252 raeburn 5939: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5940: my ($key, $value) = split(/=/, $item, 2);
5941: $key = unescape($key) unless $escapedkeys;
5942: next if $key =~ /^error: 2 /;
1.1252 raeburn 5943: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5944: }
5945: #return %returnhash;
5946: return \%returnhash;
5947: }
5948:
5949: # see Lond::dump_with_regexp
5950: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5951: sub dump {
1.1180 droeschl 5952: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5953: if (!$udomain) { $udomain=$env{'user.domain'}; }
5954: if (!$uname) { $uname=$env{'user.name'}; }
5955: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5956:
1.1266 raeburn 5957: if ($regexp) {
5958: $regexp=&escape($regexp);
5959: } else {
5960: $regexp='.';
5961: }
1.1180 droeschl 5962: if (grep { $_ eq $uhome } current_machine_ids()) {
5963: # user is hosted on this machine
1.1266 raeburn 5964: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5965: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5966: return %{unserialize($reply, $escapedkeys)};
5967: }
1.1166 raeburn 5968: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5969: my @pairs=split(/\&/,$rep);
5970: my %returnhash=();
1.1098 foxr 5971: if (!($rep =~ /^error/ )) {
5972: foreach my $item (@pairs) {
5973: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5974: $key = unescape($key) unless $escapedkeys;
5975: #$key = &unescape($key);
1.1098 foxr 5976: next if ($key =~ /^error: 2 /);
5977: $returnhash{$key}=&thaw_unescape($value);
5978: }
1.755 albertel 5979: }
5980: return %returnhash;
1.407 www 5981: }
5982:
1.1098 foxr 5983:
1.717 albertel 5984: # --------------------------------------------------------- dumpstore interface
5985:
5986: sub dumpstore {
5987: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5988: # same as dump but keys must be escaped. They may contain colon separated
5989: # lists of values that may themself contain colons (e.g. symbs).
5990: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5991: }
5992:
1.407 www 5993: # -------------------------------------------------------------- keys interface
5994:
5995: sub getkeys {
5996: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5997: if (!$udomain) { $udomain=$env{'user.domain'}; }
5998: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5999: my $uhome=&homeserver($uname,$udomain);
6000: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6001: my @keyarray=();
1.800 albertel 6002: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6003: next if ($key =~ /^error: 2 /);
1.800 albertel 6004: push(@keyarray,&unescape($key));
1.407 www 6005: }
6006: return @keyarray;
1.318 matthew 6007: }
6008:
1.319 matthew 6009: # --------------------------------------------------------------- currentdump
6010: sub currentdump {
1.328 matthew 6011: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6012: $courseid = $env{'request.course.id'} if (! defined($courseid));
6013: $sdom = $env{'user.domain'} if (! defined($sdom));
6014: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6015: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 6016: my $rep;
6017:
6018: if (grep { $_ eq $uhome } current_machine_ids()) {
6019: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6020: $courseid)));
6021: } else {
6022: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6023: }
6024:
1.318 matthew 6025: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6026: #
1.318 matthew 6027: my %returnhash=();
1.319 matthew 6028: #
6029: if ($rep eq "unknown_cmd") {
6030: # an old lond will not know currentdump
6031: # Do a dump and make it look like a currentdump
1.822 albertel 6032: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6033: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6034: my %hash = @tmp;
6035: @tmp=();
1.424 matthew 6036: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6037: } else {
6038: my @pairs=split(/\&/,$rep);
1.800 albertel 6039: foreach my $pair (@pairs) {
6040: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6041: my ($symb,$param) = split(/:/,$key);
6042: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6043: &thaw_unescape($value);
1.319 matthew 6044: }
1.191 harris41 6045: }
1.12 www 6046: return %returnhash;
1.424 matthew 6047: }
6048:
6049: sub convert_dump_to_currentdump{
6050: my %hash = %{shift()};
6051: my %returnhash;
6052: # Code ripped from lond, essentially. The only difference
6053: # here is the unescaping done by lonnet::dump(). Conceivably
6054: # we might run in to problems with parameter names =~ /^v\./
6055: while (my ($key,$value) = each(%hash)) {
6056: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6057: $symb = &unescape($symb);
6058: $param = &unescape($param);
1.424 matthew 6059: next if ($v eq 'version' || $symb eq 'keys');
6060: next if (exists($returnhash{$symb}) &&
6061: exists($returnhash{$symb}->{$param}) &&
6062: $returnhash{$symb}->{'v.'.$param} > $v);
6063: $returnhash{$symb}->{$param}=$value;
6064: $returnhash{$symb}->{'v.'.$param}=$v;
6065: }
6066: #
6067: # Remove all of the keys in the hashes which keep track of
6068: # the version of the parameter.
6069: while (my ($symb,$param_hash) = each(%returnhash)) {
6070: # use a foreach because we are going to delete from the hash.
6071: foreach my $key (keys(%$param_hash)) {
6072: delete($param_hash->{$key}) if ($key =~ /^v\./);
6073: }
6074: }
6075: return \%returnhash;
1.12 www 6076: }
6077:
1.627 albertel 6078: # ------------------------------------------------------ critical inc interface
6079:
6080: sub cinc {
6081: return &inc(@_,'critical');
6082: }
6083:
1.449 matthew 6084: # --------------------------------------------------------------- inc interface
6085:
6086: sub inc {
1.627 albertel 6087: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6088: if (!$udomain) { $udomain=$env{'user.domain'}; }
6089: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6090: my $uhome=&homeserver($uname,$udomain);
6091: my $items='';
6092: if (! ref($store)) {
6093: # got a single value, so use that instead
6094: $items = &escape($store).'=&';
6095: } elsif (ref($store) eq 'SCALAR') {
6096: $items = &escape($$store).'=&';
6097: } elsif (ref($store) eq 'ARRAY') {
6098: $items = join('=&',map {&escape($_);} @{$store});
6099: } elsif (ref($store) eq 'HASH') {
6100: while (my($key,$value) = each(%{$store})) {
6101: $items.= &escape($key).'='.&escape($value).'&';
6102: }
6103: }
6104: $items=~s/\&$//;
1.627 albertel 6105: if ($critical) {
6106: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6107: } else {
6108: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6109: }
1.449 matthew 6110: }
6111:
1.12 www 6112: # --------------------------------------------------------------- put interface
6113:
6114: sub put {
1.134 albertel 6115: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6116: if (!$udomain) { $udomain=$env{'user.domain'}; }
6117: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6118: my $uhome=&homeserver($uname,$udomain);
1.12 www 6119: my $items='';
1.800 albertel 6120: foreach my $item (keys(%$storehash)) {
6121: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6122: }
1.12 www 6123: $items=~s/\&$//;
1.134 albertel 6124: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6125: }
6126:
1.631 albertel 6127: # ------------------------------------------------------------ newput interface
6128:
6129: sub newput {
6130: my ($namespace,$storehash,$udomain,$uname)=@_;
6131: if (!$udomain) { $udomain=$env{'user.domain'}; }
6132: if (!$uname) { $uname=$env{'user.name'}; }
6133: my $uhome=&homeserver($uname,$udomain);
6134: my $items='';
6135: foreach my $key (keys(%$storehash)) {
6136: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6137: }
6138: $items=~s/\&$//;
6139: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6140: }
6141:
6142: # --------------------------------------------------------- putstore interface
6143:
1.524 raeburn 6144: sub putstore {
1.1269 raeburn 6145: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6146: if (!$udomain) { $udomain=$env{'user.domain'}; }
6147: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6148: my $uhome=&homeserver($uname,$udomain);
6149: my $items='';
1.715 albertel 6150: foreach my $key (keys(%$storehash)) {
6151: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6152: }
1.715 albertel 6153: $items=~s/\&$//;
1.716 albertel 6154: my $esc_symb=&escape($symb);
6155: my $esc_v=&escape($version);
1.715 albertel 6156: my $reply =
1.716 albertel 6157: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6158: $uhome);
1.1269 raeburn 6159: if (($tolog) && ($reply eq 'ok')) {
6160: my $namevalue='';
6161: foreach my $key (keys(%{$storehash})) {
6162: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6163: }
6164: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6165: '&host='.&escape($perlvar{'lonHostID'}).
6166: '&version='.$esc_v.
6167: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6168: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6169: }
1.715 albertel 6170: if ($reply eq 'unknown_cmd') {
1.716 albertel 6171: # gfall back to way things use to be done
1.715 albertel 6172: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6173: $uname);
1.524 raeburn 6174: }
1.715 albertel 6175: return $reply;
6176: }
6177:
6178: sub old_putstore {
1.716 albertel 6179: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6180: if (!$udomain) { $udomain=$env{'user.domain'}; }
6181: if (!$uname) { $uname=$env{'user.name'}; }
6182: my $uhome=&homeserver($uname,$udomain);
6183: my %newstorehash;
1.800 albertel 6184: foreach my $item (keys(%$storehash)) {
6185: my $key = $version.':'.&escape($symb).':'.$item;
6186: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6187: }
6188: my $items='';
6189: my %allitems = ();
1.800 albertel 6190: foreach my $item (keys(%newstorehash)) {
6191: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6192: my $key = $1.':keys:'.$2;
6193: $allitems{$key} .= $3.':';
6194: }
1.800 albertel 6195: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6196: }
1.800 albertel 6197: foreach my $item (keys(%allitems)) {
6198: $allitems{$item} =~ s/\:$//;
6199: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6200: }
6201: $items=~s/\&$//;
6202: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6203: }
6204:
1.47 www 6205: # ------------------------------------------------------ critical put interface
6206:
6207: sub cput {
1.134 albertel 6208: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6209: if (!$udomain) { $udomain=$env{'user.domain'}; }
6210: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6211: my $uhome=&homeserver($uname,$udomain);
1.47 www 6212: my $items='';
1.800 albertel 6213: foreach my $item (keys(%$storehash)) {
6214: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6215: }
1.47 www 6216: $items=~s/\&$//;
1.134 albertel 6217: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6218: }
6219:
6220: # -------------------------------------------------------------- eget interface
6221:
6222: sub eget {
1.133 albertel 6223: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6224: my $items='';
1.800 albertel 6225: foreach my $item (@$storearr) {
6226: $items.=&escape($item).'&';
1.191 harris41 6227: }
1.12 www 6228: $items=~s/\&$//;
1.620 albertel 6229: if (!$udomain) { $udomain=$env{'user.domain'}; }
6230: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6231: my $uhome=&homeserver($uname,$udomain);
6232: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6233: my @pairs=split(/\&/,$rep);
6234: my %returnhash=();
1.42 www 6235: my $i=0;
1.800 albertel 6236: foreach my $item (@$storearr) {
6237: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6238: $i++;
1.191 harris41 6239: }
1.12 www 6240: return %returnhash;
6241: }
6242:
1.667 albertel 6243: # ------------------------------------------------------------ tmpput interface
6244: sub tmpput {
1.802 raeburn 6245: my ($storehash,$server,$context)=@_;
1.667 albertel 6246: my $items='';
1.800 albertel 6247: foreach my $item (keys(%$storehash)) {
6248: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6249: }
6250: $items=~s/\&$//;
1.802 raeburn 6251: if (defined($context)) {
6252: $items .= ':'.&escape($context);
6253: }
1.667 albertel 6254: return &reply("tmpput:$items",$server);
6255: }
6256:
6257: # ------------------------------------------------------------ tmpget interface
6258: sub tmpget {
1.688 albertel 6259: my ($token,$server)=@_;
6260: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6261: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6262: my %returnhash;
1.1328 raeburn 6263: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6264: return %returnhash;
6265: }
1.667 albertel 6266: foreach my $item (split(/\&/,$rep)) {
6267: my ($key,$value)=split(/=/,$item);
6268: $returnhash{&unescape($key)}=&thaw_unescape($value);
6269: }
6270: return %returnhash;
6271: }
6272:
1.1113 raeburn 6273: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6274: sub tmpdel {
6275: my ($token,$server)=@_;
6276: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6277: return &reply("tmpdel:$token",$server);
6278: }
6279:
1.1198 raeburn 6280: # ------------------------------------------------------------ get_timebased_id
6281:
6282: sub get_timebased_id {
6283: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6284: $maxtries) = @_;
6285: my ($newid,$error,$dellock);
6286: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6287: return ('','ok','invalid call to get suffix');
6288: }
6289:
6290: # set defaults for any optional args for which values were not supplied
6291: if ($who eq '') {
6292: $who = $env{'user.name'}.':'.$env{'user.domain'};
6293: }
6294: if (!$locktries) {
6295: $locktries = 3;
6296: }
6297: if (!$maxtries) {
6298: $maxtries = 10;
6299: }
6300:
6301: if (($cdom eq '') || ($cnum eq '')) {
6302: if ($env{'request.course.id'}) {
6303: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6304: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6305: }
6306: if (($cdom eq '') || ($cnum eq '')) {
6307: return ('','ok','call to get suffix not in course context');
6308: }
6309: }
6310:
6311: # construct locking item
6312: my $lockhash = {
6313: $prefix."\0".'locked_'.$keyid => $who,
6314: };
6315: my $tries = 0;
6316:
6317: # attempt to get lock on nohist_$namespace file
6318: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6319: while (($gotlock ne 'ok') && $tries <$locktries) {
6320: $tries ++;
6321: sleep 1;
6322: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6323: }
6324:
6325: # attempt to get unique identifier, based on current timestamp
6326: if ($gotlock eq 'ok') {
6327: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6328: my $id = time;
6329: $newid = $id;
1.1268 raeburn 6330: if ($idtype eq 'addcode') {
6331: $newid .= &sixnum_code();
6332: }
1.1198 raeburn 6333: my $idtries = 0;
6334: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6335: if ($idtype eq 'concat') {
6336: $newid = $id.$idtries;
1.1268 raeburn 6337: } elsif ($idtype eq 'addcode') {
6338: $newid = $newid.&sixnum_code();
1.1198 raeburn 6339: } else {
6340: $newid ++;
6341: }
6342: $idtries ++;
6343: }
6344: if (!exists($inuse{$prefix."\0".$newid})) {
6345: my %new_item = (
6346: $prefix."\0".$newid => $who,
6347: );
6348: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6349: $cdom,$cnum);
6350: if ($putresult ne 'ok') {
6351: undef($newid);
6352: $error = 'error saving new item: '.$putresult;
6353: }
6354: } else {
1.1268 raeburn 6355: undef($newid);
1.1198 raeburn 6356: $error = ('error: no unique suffix available for the new item ');
6357: }
6358: # remove lock
6359: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6360: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6361: } else {
6362: $error = "error: could not obtain lockfile\n";
6363: $dellock = 'ok';
1.1276 raeburn 6364: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6365: $dellock = 'nolock';
6366: }
1.1198 raeburn 6367: }
6368: return ($newid,$dellock,$error);
6369: }
6370:
1.1268 raeburn 6371: sub sixnum_code {
6372: my $code;
6373: for (0..6) {
6374: $code .= int( rand(9) );
6375: }
6376: return $code;
6377: }
6378:
1.765 albertel 6379: # -------------------------------------------------- portfolio access checking
6380:
6381: sub portfolio_access {
1.1270 raeburn 6382: my ($requrl,$clientip) = @_;
1.765 albertel 6383: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6384: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6385: if ($result) {
6386: my %setters;
6387: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6388: my ($startblock,$endblock) =
6389: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6390: if ($startblock && $endblock) {
6391: return 'B';
6392: }
6393: } else {
6394: my ($startblock,$endblock) =
6395: &Apache::loncommon::blockcheck(\%setters,'port');
6396: if ($startblock && $endblock) {
6397: return 'B';
6398: }
6399: }
6400: }
1.765 albertel 6401: if ($result eq 'ok') {
1.766 albertel 6402: return 'F';
1.765 albertel 6403: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6404: return 'A';
1.765 albertel 6405: }
1.766 albertel 6406: return '';
1.765 albertel 6407: }
6408:
6409: sub get_portfolio_access {
1.1270 raeburn 6410: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6411:
6412: if (!ref($access_hash)) {
6413: my $current_perms = &get_portfile_permissions($udom,$unum);
6414: my %access_controls = &get_access_controls($current_perms,$group,
6415: $file_name);
6416: $access_hash = $access_controls{$file_name};
6417: }
6418:
1.1270 raeburn 6419: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6420: my $now = time;
6421: if (ref($access_hash) eq 'HASH') {
6422: foreach my $key (keys(%{$access_hash})) {
6423: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6424: if ($start > $now) {
6425: next;
6426: }
6427: if ($end && $end<$now) {
6428: next;
6429: }
6430: if ($scope eq 'public') {
6431: $public = $key;
6432: last;
6433: } elsif ($scope eq 'guest') {
6434: $guest = $key;
6435: } elsif ($scope eq 'domains') {
6436: push(@domains,$key);
6437: } elsif ($scope eq 'users') {
6438: push(@users,$key);
6439: } elsif ($scope eq 'course') {
6440: push(@courses,$key);
6441: } elsif ($scope eq 'group') {
6442: push(@groups,$key);
1.1270 raeburn 6443: } elsif ($scope eq 'ip') {
6444: push(@ips,$key);
1.765 albertel 6445: }
6446: }
6447: if ($public) {
6448: return 'ok';
1.1270 raeburn 6449: } elsif (@ips > 0) {
6450: my $allowed;
6451: foreach my $ipkey (@ips) {
6452: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6453: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6454: $allowed = 1;
6455: last;
6456: }
6457: }
6458: }
6459: if ($allowed) {
6460: return 'ok';
6461: }
1.765 albertel 6462: }
6463: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6464: if ($guest) {
6465: return $guest;
6466: }
6467: } else {
6468: if (@domains > 0) {
6469: foreach my $domkey (@domains) {
6470: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6471: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6472: return 'ok';
6473: }
6474: }
6475: }
6476: }
6477: if (@users > 0) {
6478: foreach my $userkey (@users) {
1.865 raeburn 6479: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6480: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6481: if (ref($item) eq 'HASH') {
6482: if (($item->{'uname'} eq $env{'user.name'}) &&
6483: ($item->{'udom'} eq $env{'user.domain'})) {
6484: return 'ok';
6485: }
6486: }
6487: }
6488: }
1.765 albertel 6489: }
6490: }
6491: my %roleshash;
6492: my @courses_and_groups = @courses;
6493: push(@courses_and_groups,@groups);
6494: if (@courses_and_groups > 0) {
6495: my (%allgroups,%allroles);
6496: my ($start,$end,$role,$sec,$group);
6497: foreach my $envkey (%env) {
1.1060 raeburn 6498: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6499: my $cid = $2.'_'.$3;
6500: if ($1 eq 'gr') {
6501: $group = $4;
6502: $allgroups{$cid}{$group} = $env{$envkey};
6503: } else {
6504: if ($4 eq '') {
6505: $sec = 'none';
6506: } else {
6507: $sec = $4;
6508: }
6509: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6510: }
1.811 albertel 6511: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6512: my $cid = $2.'_'.$3;
6513: if ($4 eq '') {
6514: $sec = 'none';
6515: } else {
6516: $sec = $4;
6517: }
6518: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6519: }
6520: }
6521: if (keys(%allroles) == 0) {
6522: return;
6523: }
6524: foreach my $key (@courses_and_groups) {
6525: my %content = %{$$access_hash{$key}};
6526: my $cnum = $content{'number'};
6527: my $cdom = $content{'domain'};
6528: my $cid = $cdom.'_'.$cnum;
6529: if (!exists($allroles{$cid})) {
6530: next;
6531: }
6532: foreach my $role_id (keys(%{$content{'roles'}})) {
6533: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6534: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6535: my @status = @{$content{'roles'}{$role_id}{'access'}};
6536: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6537: foreach my $role (keys(%{$allroles{$cid}})) {
6538: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6539: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6540: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6541: if (grep/^all$/,@sections) {
6542: return 'ok';
6543: } else {
6544: if (grep/^$sec$/,@sections) {
6545: return 'ok';
6546: }
6547: }
6548: }
6549: }
6550: if (keys(%{$allgroups{$cid}}) == 0) {
6551: if (grep/^none$/,@groups) {
6552: return 'ok';
6553: }
6554: } else {
6555: if (grep/^all$/,@groups) {
6556: return 'ok';
6557: }
6558: foreach my $group (keys(%{$allgroups{$cid}})) {
6559: if (grep/^$group$/,@groups) {
6560: return 'ok';
6561: }
6562: }
6563: }
6564: }
6565: }
6566: }
6567: }
6568: }
6569: if ($guest) {
6570: return $guest;
6571: }
6572: }
6573: }
6574: return;
6575: }
6576:
6577: sub course_group_datechecker {
6578: my ($dates,$now,$status) = @_;
6579: my ($start,$end) = split(/\./,$dates);
6580: if (!$start && !$end) {
6581: return 'ok';
6582: }
6583: if (grep/^active$/,@{$status}) {
6584: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6585: return 'ok';
6586: }
6587: }
6588: if (grep/^previous$/,@{$status}) {
6589: if ($end > $now ) {
6590: return 'ok';
6591: }
6592: }
6593: if (grep/^future$/,@{$status}) {
6594: if ($start > $now) {
6595: return 'ok';
6596: }
6597: }
6598: return;
6599: }
6600:
6601: sub parse_portfolio_url {
6602: my ($url) = @_;
6603:
6604: my ($type,$udom,$unum,$group,$file_name);
6605:
1.823 albertel 6606: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6607: $type = 1;
6608: $udom = $1;
6609: $unum = $2;
6610: $file_name = $3;
1.823 albertel 6611: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6612: $type = 2;
6613: $udom = $1;
6614: $unum = $2;
6615: $group = $3;
6616: $file_name = $3.'/'.$4;
6617: }
6618: if (wantarray) {
6619: return ($type,$udom,$unum,$file_name,$group);
6620: }
6621: return $type;
6622: }
6623:
6624: sub is_portfolio_url {
6625: my ($url) = @_;
6626: return scalar(&parse_portfolio_url($url));
6627: }
6628:
1.798 raeburn 6629: sub is_portfolio_file {
6630: my ($file) = @_;
1.820 raeburn 6631: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6632: return 1;
6633: }
6634: return;
6635: }
6636:
1.976 raeburn 6637: sub usertools_access {
1.1084 raeburn 6638: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6639: my ($access,%tools);
6640: if ($context eq '') {
6641: $context = 'tools';
6642: }
6643: if ($context eq 'requestcourses') {
6644: %tools = (
6645: official => 1,
6646: unofficial => 1,
1.1006 raeburn 6647: community => 1,
1.1246 raeburn 6648: textbook => 1,
1.1305 raeburn 6649: placement => 1,
1.985 raeburn 6650: );
1.1183 raeburn 6651: } elsif ($context eq 'requestauthor') {
6652: %tools = (
6653: requestauthor => 1,
6654: );
1.985 raeburn 6655: } else {
6656: %tools = (
6657: aboutme => 1,
6658: blog => 1,
1.1177 raeburn 6659: webdav => 1,
1.985 raeburn 6660: portfolio => 1,
6661: );
6662: }
1.976 raeburn 6663: return if (!defined($tools{$tool}));
6664:
1.1242 raeburn 6665: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6666: $udom = $env{'user.domain'};
6667: $uname = $env{'user.name'};
6668: }
6669:
1.978 raeburn 6670: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6671: if ($action ne 'reload') {
1.985 raeburn 6672: if ($context eq 'requestcourses') {
6673: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6674: } elsif ($context eq 'requestauthor') {
6675: return $env{'environment.canrequest.author'};
1.985 raeburn 6676: } else {
6677: return $env{'environment.availabletools.'.$tool};
6678: }
6679: }
1.976 raeburn 6680: }
6681:
1.1183 raeburn 6682: my ($toolstatus,$inststatus,$envkey);
6683: if ($context eq 'requestauthor') {
6684: $envkey = $context;
6685: } else {
6686: $envkey = $context.'.'.$tool;
6687: }
1.976 raeburn 6688:
1.985 raeburn 6689: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6690: ($action ne 'reload')) {
1.1183 raeburn 6691: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6692: $inststatus = $env{'environment.inststatus'};
6693: } else {
1.1084 raeburn 6694: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6695: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6696: $inststatus = $userenvref->{'inststatus'};
6697: } else {
1.1183 raeburn 6698: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6699: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6700: $inststatus = $userenv{'inststatus'};
6701: }
1.976 raeburn 6702: }
6703:
6704: if ($toolstatus ne '') {
6705: if ($toolstatus) {
6706: $access = 1;
6707: } else {
6708: $access = 0;
6709: }
6710: return $access;
6711: }
6712:
1.1084 raeburn 6713: my ($is_adv,%domdef);
6714: if (ref($is_advref) eq 'HASH') {
6715: $is_adv = $is_advref->{'is_adv'};
6716: } else {
6717: $is_adv = &is_advanced_user($udom,$uname);
6718: }
6719: if (ref($domdefref) eq 'HASH') {
6720: %domdef = %{$domdefref};
6721: } else {
6722: %domdef = &get_domain_defaults($udom);
6723: }
1.976 raeburn 6724: if (ref($domdef{$tool}) eq 'HASH') {
6725: if ($is_adv) {
6726: if ($domdef{$tool}{'_LC_adv'} ne '') {
6727: if ($domdef{$tool}{'_LC_adv'}) {
6728: $access = 1;
6729: } else {
6730: $access = 0;
6731: }
6732: return $access;
6733: }
6734: }
6735: if ($inststatus ne '') {
6736: my ($hasaccess,$hasnoaccess);
6737: foreach my $affiliation (split(/:/,$inststatus)) {
6738: if ($domdef{$tool}{$affiliation} ne '') {
6739: if ($domdef{$tool}{$affiliation}) {
6740: $hasaccess = 1;
6741: } else {
6742: $hasnoaccess = 1;
6743: }
6744: }
6745: }
6746: if ($hasaccess || $hasnoaccess) {
6747: if ($hasaccess) {
6748: $access = 1;
6749: } elsif ($hasnoaccess) {
6750: $access = 0;
6751: }
6752: return $access;
6753: }
6754: } else {
6755: if ($domdef{$tool}{'default'} ne '') {
6756: if ($domdef{$tool}{'default'}) {
6757: $access = 1;
6758: } elsif ($domdef{$tool}{'default'} == 0) {
6759: $access = 0;
6760: }
6761: return $access;
6762: }
6763: }
6764: } else {
1.1177 raeburn 6765: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6766: $access = 1;
6767: } else {
6768: $access = 0;
6769: }
1.976 raeburn 6770: return $access;
6771: }
6772: }
6773:
1.1050 raeburn 6774: sub is_course_owner {
6775: my ($cdom,$cnum,$udom,$uname) = @_;
6776: if (($udom eq '') || ($uname eq '')) {
6777: $udom = $env{'user.domain'};
6778: $uname = $env{'user.name'};
6779: }
6780: unless (($udom eq '') || ($uname eq '')) {
6781: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6782: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6783: return 1;
6784: } else {
6785: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6786: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6787: return 1;
6788: }
6789: }
6790: }
6791: }
6792: return;
6793: }
6794:
1.976 raeburn 6795: sub is_advanced_user {
6796: my ($udom,$uname) = @_;
1.1085 raeburn 6797: if ($udom ne '' && $uname ne '') {
6798: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6799: if (wantarray) {
6800: return ($env{'user.adv'},$env{'user.author'});
6801: } else {
6802: return $env{'user.adv'};
6803: }
1.1085 raeburn 6804: }
6805: }
1.976 raeburn 6806: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6807: my %allroles;
1.1128 raeburn 6808: my ($is_adv,$is_author);
1.976 raeburn 6809: foreach my $role (keys(%roleshash)) {
6810: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6811: my $area = '/'.$tdomain.'/'.$trest;
6812: if ($sec ne '') {
6813: $area .= '/'.$sec;
6814: }
6815: if (($area ne '') && ($trole ne '')) {
6816: my $spec=$trole.'.'.$area;
6817: if ($trole =~ /^cr\//) {
6818: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6819: } elsif ($trole ne 'gr') {
6820: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6821: }
1.1128 raeburn 6822: if ($trole eq 'au') {
6823: $is_author = 1;
6824: }
1.976 raeburn 6825: }
6826: }
6827: foreach my $role (keys(%allroles)) {
6828: last if ($is_adv);
6829: foreach my $item (split(/:/,$allroles{$role})) {
6830: if ($item ne '') {
6831: my ($privilege,$restrictions)=split(/&/,$item);
6832: if ($privilege eq 'adv') {
6833: $is_adv = 1;
6834: last;
6835: }
6836: }
6837: }
6838: }
1.1128 raeburn 6839: if (wantarray) {
6840: return ($is_adv,$is_author);
6841: }
1.976 raeburn 6842: return $is_adv;
6843: }
1.798 raeburn 6844:
1.1035 raeburn 6845: sub check_can_request {
1.1036 raeburn 6846: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6847: my $canreq = 0;
6848: my ($types,$typename) = &Apache::loncommon::course_types();
6849: my @options = ('approval','validate','autolimit');
6850: my $optregex = join('|',@options);
6851: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6852: foreach my $type (@{$types}) {
6853: if (&usertools_access($env{'user.name'},
6854: $env{'user.domain'},
6855: $type,undef,'requestcourses')) {
6856: $canreq ++;
1.1036 raeburn 6857: if (ref($request_domains) eq 'HASH') {
6858: push(@{$request_domains->{$type}},$env{'user.domain'});
6859: }
1.1035 raeburn 6860: if ($dom eq $env{'user.domain'}) {
6861: $can_request->{$type} = 1;
6862: }
6863: }
6864: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6865: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6866: if (@curr > 0) {
1.1036 raeburn 6867: foreach my $item (@curr) {
6868: if (ref($request_domains) eq 'HASH') {
6869: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6870: if ($otherdom ne '') {
6871: if (ref($request_domains->{$type}) eq 'ARRAY') {
6872: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6873: push(@{$request_domains->{$type}},$otherdom);
6874: }
6875: } else {
6876: push(@{$request_domains->{$type}},$otherdom);
6877: }
6878: }
6879: }
6880: }
6881: unless($dom eq $env{'user.domain'}) {
6882: $canreq ++;
1.1035 raeburn 6883: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6884: $can_request->{$type} = 1;
6885: }
6886: }
6887: }
6888: }
6889: }
6890: }
6891: return $canreq;
6892: }
6893:
1.341 www 6894: # ---------------------------------------------- Custom access rule evaluation
6895:
6896: sub customaccess {
6897: my ($priv,$uri)=@_;
1.807 albertel 6898: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6899: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6900: $udom = &LONCAPA::clean_domain($udom);
6901: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6902: my $access=0;
1.800 albertel 6903: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6904: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6905: if ($type eq 'user') {
6906: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6907: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6908: if ($tdom) {
6909: if ($tdom ne $env{'user.domain'}) { next; }
6910: }
1.896 albertel 6911: if ($tuname) {
6912: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6913: }
6914: $access=($effect eq 'allow');
6915: last;
6916: }
6917: } else {
6918: if ($role) {
6919: if ($role ne $urole) { next; }
6920: }
6921: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6922: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6923: if ($tdom) {
6924: if ($tdom ne $udom) { next; }
6925: }
6926: if ($tcrs) {
6927: if ($tcrs ne $ucrs) { next; }
6928: }
6929: if ($tsec) {
6930: if ($tsec ne $usec) { next; }
6931: }
6932: $access=($effect eq 'allow');
6933: last;
6934: }
6935: if ($realm eq '' && $role eq '') {
6936: $access=($effect eq 'allow');
6937: }
1.402 bowersj2 6938: }
1.341 www 6939: }
6940: return $access;
6941: }
6942:
1.103 harris41 6943: # ------------------------------------------------- Check for a user privilege
1.12 www 6944:
6945: sub allowed {
1.1281 raeburn 6946: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6947: my $ver_orguri=$uri;
1.439 www 6948: $uri=&deversion($uri);
1.152 www 6949: my $orguri=$uri;
1.52 www 6950: $uri=&declutter($uri);
1.809 raeburn 6951:
1.810 raeburn 6952: if ($priv eq 'evb') {
6953: # Evade communication block restrictions for specified role in a course
6954: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6955: return $1;
6956: } else {
6957: return;
6958: }
6959: }
6960:
1.620 albertel 6961: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6962: # Free bre access to adm and meta resources
1.775 albertel 6963: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6964: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6965: && ($priv eq 'bre')) {
1.14 www 6966: return 'F';
1.159 www 6967: }
6968:
1.545 banghart 6969: # Free bre access to user's own portfolio contents
1.714 raeburn 6970: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6971: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6972: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6973: my %setters;
6974: my ($startblock,$endblock) =
6975: &Apache::loncommon::blockcheck(\%setters,'port');
6976: if ($startblock && $endblock) {
6977: return 'B';
6978: } else {
6979: return 'F';
6980: }
1.545 banghart 6981: }
6982:
1.762 raeburn 6983: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6984: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6985: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6986: if (exists($env{'request.course.id'})) {
6987: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6988: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6989: if (($domain eq $cdom) && ($name eq $cnum)) {
6990: my $courseprivid=$env{'request.course.id'};
6991: $courseprivid=~s/\_/\//;
6992: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6993: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6994: return $1;
1.762 raeburn 6995: } else {
6996: if ($env{'request.course.sec'}) {
6997: $courseprivid.='/'.$env{'request.course.sec'};
6998: }
6999: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7000: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7001: return $2;
7002: }
1.714 raeburn 7003: }
7004: }
7005: }
7006: }
7007:
1.159 www 7008: # Free bre to public access
7009:
7010: if ($priv eq 'bre') {
1.238 www 7011: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7012: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7013: return 'F';
7014: }
1.238 www 7015: if ($copyright eq 'priv') {
7016: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7017: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7018: return '';
7019: }
7020: }
7021: if ($copyright eq 'domain') {
7022: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7023: unless (($env{'user.domain'} eq $1) ||
7024: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7025: return '';
7026: }
1.262 matthew 7027: }
1.620 albertel 7028: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7029: # Library role, so allow browsing of resources in this domain.
7030: return 'F';
1.238 www 7031: }
1.341 www 7032: if ($copyright eq 'custom') {
7033: unless (&customaccess($priv,$uri)) { return ''; }
7034: }
1.14 www 7035: }
1.264 matthew 7036: # Domain coordinator is trying to create a course
1.620 albertel 7037: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7038: # uri is the requested domain in this case.
7039: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7040: # a role of dc for the domain in question.
1.620 albertel 7041: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7042: }
1.29 www 7043:
1.52 www 7044: my $thisallowed='';
7045: my $statecond=0;
7046: my $courseprivid='';
7047:
1.1039 raeburn 7048: my $ownaccess;
1.1043 raeburn 7049: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7050: if (($priv eq 'bro') && ($env{'user.author'})) {
7051: if ($uri eq '') {
7052: $ownaccess = 1;
7053: } else {
7054: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7055: my $udom = $env{'user.domain'};
7056: my $uname = $env{'user.name'};
7057: if ($uri =~ m{^\Q$udom\E/?$}) {
7058: $ownaccess = 1;
1.1040 raeburn 7059: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7060: unless ($uri =~ m{\.\./}) {
7061: $ownaccess = 1;
7062: }
7063: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7064: my $now = time;
7065: if ($uri =~ m{^([^/]+)/?$}) {
7066: my $adom = $1;
7067: foreach my $key (keys(%env)) {
1.1042 raeburn 7068: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7069: my ($start,$end) = split('.',$env{$key});
7070: if (($now >= $start) && (!$end || $end < $now)) {
7071: $ownaccess = 1;
7072: last;
7073: }
7074: }
7075: }
7076: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7077: my $adom = $1;
7078: my $aname = $2;
1.1042 raeburn 7079: foreach my $role ('ca','aa') {
7080: if ($env{"user.role.$role./$adom/$aname"}) {
7081: my ($start,$end) =
7082: split('.',$env{"user.role.$role./$adom/$aname"});
7083: if (($now >= $start) && (!$end || $end < $now)) {
7084: $ownaccess = 1;
7085: last;
7086: }
1.1039 raeburn 7087: }
7088: }
7089: }
7090: }
7091: }
7092: }
7093: }
7094:
1.52 www 7095: # Course
7096:
1.620 albertel 7097: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7098: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7099: $thisallowed.=$1;
7100: }
1.52 www 7101: }
1.29 www 7102:
1.52 www 7103: # Domain
7104:
1.620 albertel 7105: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7106: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7107: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7108: $thisallowed.=$1;
7109: }
1.12 www 7110: }
1.52 www 7111:
1.1141 raeburn 7112: # User who is not author or co-author might still be able to edit
7113: # resource of an author in the domain (e.g., if Domain Coordinator).
7114: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7115: (&allowed('mdc',$env{'request.course.id'}))) {
7116: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7117: $thisallowed.=$1;
7118: }
7119: }
7120:
1.52 www 7121: # Course: uri itself is a course
1.66 www 7122: my $courseuri=$uri;
7123: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7124: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7125:
1.620 albertel 7126: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7127: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7128: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7129: $thisallowed.=$1;
7130: }
1.12 www 7131: }
1.29 www 7132:
1.665 albertel 7133: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7134: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7135: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7136: $thisallowed='';
1.671 raeburn 7137: my ($match)=&is_on_map($uri);
7138: if ($match) {
7139: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7140: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 7141: my $value = $1;
7142: if ($noblockcheck) {
7143: $thisallowed.=$value;
1.1162 raeburn 7144: } else {
1.1281 raeburn 7145: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7146: if (@blockers > 0) {
7147: $thisallowed = 'B';
7148: } else {
7149: $thisallowed.=$value;
7150: }
1.1162 raeburn 7151: }
1.671 raeburn 7152: }
7153: } else {
1.705 albertel 7154: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7155: if ($refuri) {
7156: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7157: $thisallowed='F';
1.671 raeburn 7158: } else {
7159: $refuri=&declutter($refuri);
7160: my ($match) = &is_on_map($refuri);
7161: if ($match) {
1.1281 raeburn 7162: if ($noblockcheck) {
7163: $thisallowed='F';
1.1162 raeburn 7164: } else {
1.1281 raeburn 7165: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7166: if (@blockers > 0) {
7167: $thisallowed = 'B';
7168: } else {
7169: $thisallowed='F';
7170: }
1.1162 raeburn 7171: }
1.671 raeburn 7172: }
1.669 raeburn 7173: }
1.671 raeburn 7174: }
7175: }
1.314 www 7176: }
1.492 albertel 7177:
1.766 albertel 7178: if ($priv eq 'bre'
7179: && $thisallowed ne 'F'
7180: && $thisallowed ne '2'
7181: && &is_portfolio_url($uri)) {
1.1270 raeburn 7182: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7183: }
1.1250 raeburn 7184:
1.52 www 7185: # Full access at system, domain or course-wide level? Exit.
1.29 www 7186: if ($thisallowed=~/F/) {
7187: return 'F';
7188: }
7189:
1.52 www 7190: # If this is generating or modifying users, exit with special codes
1.29 www 7191:
1.643 www 7192: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7193: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7194: my ($audom,$auname)=split('/',$uri);
1.643 www 7195: # no author name given, so this just checks on the general right to make a co-author in this domain
7196: unless ($auname) { return $thisallowed; }
7197: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7198: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7199: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7200: ($audom ne $env{'request.role.domain'}))) { return ''; }
7201: }
1.52 www 7202: return $thisallowed;
7203: }
7204: #
1.103 harris41 7205: # Gathered so far: system, domain and course wide privileges
1.52 www 7206: #
7207: # Course: See if uri or referer is an individual resource that is part of
7208: # the course
7209:
1.620 albertel 7210: if ($env{'request.course.id'}) {
1.232 www 7211:
1.620 albertel 7212: $courseprivid=$env{'request.course.id'};
7213: if ($env{'request.course.sec'}) {
7214: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7215: }
7216: $courseprivid=~s/\_/\//;
7217: my $checkreferer=1;
1.232 www 7218: my ($match,$cond)=&is_on_map($uri);
7219: if ($match) {
7220: $statecond=$cond;
1.620 albertel 7221: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7222: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7223: my $value = $1;
7224: if ($priv eq 'bre') {
1.1281 raeburn 7225: if ($noblockcheck) {
7226: $thisallowed.=$value;
1.1162 raeburn 7227: } else {
1.1281 raeburn 7228: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7229: if (@blockers > 0) {
7230: $thisallowed = 'B';
7231: } else {
7232: $thisallowed.=$value;
7233: }
1.1162 raeburn 7234: }
7235: } else {
7236: $thisallowed.=$value;
7237: }
1.52 www 7238: $checkreferer=0;
7239: }
1.29 www 7240: }
1.83 www 7241:
1.148 www 7242: if ($checkreferer) {
1.620 albertel 7243: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7244: unless ($refuri) {
1.800 albertel 7245: foreach my $key (keys(%env)) {
7246: if ($key=~/^httpref\..*\*/) {
7247: my $pattern=$key;
1.156 www 7248: $pattern=~s/^httpref\.\/res\///;
1.148 www 7249: $pattern=~s/\*/\[\^\/\]\+/g;
7250: $pattern=~s/\//\\\//g;
1.152 www 7251: if ($orguri=~/$pattern/) {
1.800 albertel 7252: $refuri=$env{$key};
1.148 www 7253: }
7254: }
1.191 harris41 7255: }
1.148 www 7256: }
1.232 www 7257:
1.148 www 7258: if ($refuri) {
1.152 www 7259: $refuri=&declutter($refuri);
1.232 www 7260: my ($match,$cond)=&is_on_map($refuri);
7261: if ($match) {
7262: my $refstatecond=$cond;
1.620 albertel 7263: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7264: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7265: my $value = $1;
7266: if ($priv eq 'bre') {
1.1281 raeburn 7267: if ($noblockcheck) {
7268: $thisallowed.=$value;
1.1162 raeburn 7269: } else {
1.1281 raeburn 7270: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7271: if (@blockers > 0) {
7272: $thisallowed = 'B';
7273: } else {
7274: $thisallowed.=$value;
7275: }
1.1162 raeburn 7276: }
7277: } else {
7278: $thisallowed.=$value;
7279: }
1.53 www 7280: $uri=$refuri;
7281: $statecond=$refstatecond;
1.52 www 7282: }
7283: }
1.148 www 7284: }
1.29 www 7285: }
1.52 www 7286: }
1.29 www 7287:
1.52 www 7288: #
1.103 harris41 7289: # Gathered now: all privileges that could apply, and condition number
1.52 www 7290: #
7291: #
7292: # Full or no access?
7293: #
1.29 www 7294:
1.52 www 7295: if ($thisallowed=~/F/) {
7296: return 'F';
7297: }
1.29 www 7298:
1.52 www 7299: unless ($thisallowed) {
7300: return '';
7301: }
1.29 www 7302:
1.52 www 7303: # Restrictions exist, deal with them
7304: #
7305: # C:according to course preferences
7306: # R:according to resource settings
7307: # L:unless locked
7308: # X:according to user session state
7309: #
7310:
7311: # Possibly locked functionality, check all courses
1.54 www 7312: # Locks might take effect only after 10 minutes cache expiration for other
7313: # courses, and 2 minutes for current course
1.52 www 7314:
7315: my $envkey;
7316: if ($thisallowed=~/L/) {
1.1000 raeburn 7317: foreach $envkey (keys(%env)) {
1.54 www 7318: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7319: my $courseid=$2;
7320: my $roleid=$1.'.'.$2;
1.92 www 7321: $courseid=~s/^\///;
1.54 www 7322: my $expiretime=600;
1.620 albertel 7323: if ($env{'request.role'} eq $roleid) {
1.54 www 7324: $expiretime=120;
7325: }
7326: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7327: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7328: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7329: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7330: }
1.620 albertel 7331: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7332: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7333: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7334: &log($env{'user.domain'},$env{'user.name'},
7335: $env{'user.home'},
1.57 www 7336: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7337: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7338: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7339: return '';
7340: }
7341: }
1.620 albertel 7342: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7343: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7344: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7345: &log($env{'user.domain'},$env{'user.name'},
7346: $env{'user.home'},
1.57 www 7347: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7348: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7349: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7350: return '';
7351: }
7352: }
7353: }
1.29 www 7354: }
1.52 www 7355: }
7356:
7357: #
7358: # Rest of the restrictions depend on selected course
7359: #
7360:
1.620 albertel 7361: unless ($env{'request.course.id'}) {
1.766 albertel 7362: if ($thisallowed eq 'A') {
7363: return 'A';
1.814 raeburn 7364: } elsif ($thisallowed eq 'B') {
7365: return 'B';
1.766 albertel 7366: } else {
7367: return '1';
7368: }
1.52 www 7369: }
1.29 www 7370:
1.52 www 7371: #
7372: # Now user is definitely in a course
7373: #
1.53 www 7374:
7375:
7376: # Course preferences
7377:
7378: if ($thisallowed=~/C/) {
1.620 albertel 7379: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7380: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7381: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7382: =~/\Q$rolecode\E/) {
1.1304 raeburn 7383: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7384: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7385: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7386: $env{'request.course.id'});
7387: }
1.237 www 7388: return '';
7389: }
7390:
1.620 albertel 7391: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7392: =~/\Q$unamedom\E/) {
1.1304 raeburn 7393: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7394: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7395: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7396: $env{'request.course.id'});
7397: }
1.54 www 7398: return '';
7399: }
1.53 www 7400: }
7401:
7402: # Resource preferences
7403:
7404: if ($thisallowed=~/R/) {
1.620 albertel 7405: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7406: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7407: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7408: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7409: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7410: }
7411: return '';
1.54 www 7412: }
1.53 www 7413: }
1.30 www 7414:
1.246 www 7415: # Restricted by state or randomout?
1.30 www 7416:
1.52 www 7417: if ($thisallowed=~/X/) {
1.620 albertel 7418: if ($env{'acc.randomout'}) {
1.579 albertel 7419: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7420: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7421: return '';
7422: }
1.247 www 7423: }
7424: if (&condval($statecond)) {
1.52 www 7425: return '2';
7426: } else {
7427: return '';
7428: }
7429: }
1.30 www 7430:
1.766 albertel 7431: if ($thisallowed eq 'A') {
7432: return 'A';
1.814 raeburn 7433: } elsif ($thisallowed eq 'B') {
7434: return 'B';
1.766 albertel 7435: }
1.52 www 7436: return 'F';
1.232 www 7437: }
1.1162 raeburn 7438:
1.1192 raeburn 7439: # ------------------------------------------- Check construction space access
7440:
7441: sub constructaccess {
7442: my ($url,$setpriv)=@_;
7443:
7444: # We do not allow editing of previous versions of files
7445: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7446:
7447: # Get username and domain from URL
7448: my ($ownername,$ownerdomain,$ownerhome);
7449:
7450: ($ownerdomain,$ownername) =
1.1325 raeburn 7451: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 7452:
7453: # The URL does not really point to any authorspace, forget it
7454: unless (($ownername) && ($ownerdomain)) { return ''; }
7455:
7456: # Now we need to see if the user has access to the authorspace of
7457: # $ownername at $ownerdomain
7458:
7459: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7460: # Real author for this?
7461: $ownerhome = $env{'user.home'};
7462: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7463: return ($ownername,$ownerdomain,$ownerhome);
7464: }
7465: } else {
7466: # Co-author for this?
7467: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7468: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7469: $ownerhome = &homeserver($ownername,$ownerdomain);
7470: return ($ownername,$ownerdomain,$ownerhome);
7471: }
1.1312 raeburn 7472: if ($env{'request.course.id'}) {
7473: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
7474: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
7475: if (&allowed('mdc',$env{'request.course.id'})) {
7476: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
7477: return ($ownername,$ownerdomain,$ownerhome);
7478: }
7479: }
7480: }
1.1192 raeburn 7481: }
7482:
7483: # We don't have any access right now. If we are not possibly going to do anything about this,
7484: # we might as well leave
7485: unless ($setpriv) { return ''; }
7486:
7487: # Backdoor access?
7488: my $allowed=&allowed('eco',$ownerdomain);
7489: # Nope
7490: unless ($allowed) { return ''; }
7491: # Looks like we may have access, but could be locked by the owner of the construction space
7492: if ($allowed eq 'U') {
7493: my %blocked=&get('environment',['domcoord.author'],
7494: $ownerdomain,$ownername);
7495: # Is blocked by owner
7496: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7497: }
7498: if (($allowed eq 'F') || ($allowed eq 'U')) {
7499: # Grant temporary access
7500: my $then=$env{'user.login.time'};
1.1209 raeburn 7501: my $update=$env{'user.update.time'};
1.1192 raeburn 7502: if (!$update) { $update = $then; }
7503: my $refresh=$env{'user.refresh.time'};
7504: if (!$refresh) { $refresh = $update; }
7505: my $now = time;
7506: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7507: $now,'ca','constructaccess');
7508: $ownerhome = &homeserver($ownername,$ownerdomain);
7509: return($ownername,$ownerdomain,$ownerhome);
7510: }
7511: # No business here
7512: return '';
7513: }
7514:
1.1282 raeburn 7515: # ----------------------------------------------------------- Content Blocking
7516:
7517: {
7518: # Caches for faster Course Contents display where content blocking
7519: # is in operation (i.e., interval param set) for timed quiz.
7520: #
7521: # User for whom data are being temporarily cached.
7522: my $cacheduser='';
7523: # Cached blockers for this user (a hash of blocking items).
7524: my %cachedblockers=();
7525: # When the data were last cached.
7526: my $cachedlast='';
7527:
7528: sub load_all_blockers {
7529: my ($uname,$udom,$blocks)=@_;
7530: if (($uname ne '') && ($udom ne '')) {
7531: if (($cacheduser eq $uname.':'.$udom) &&
7532: (abs($cachedlast-time)<5)) {
7533: return;
7534: }
7535: }
7536: $cachedlast=time;
7537: $cacheduser=$uname.':'.$udom;
7538: %cachedblockers = &get_commblock_resources($blocks);
7539: }
7540:
1.1162 raeburn 7541: sub get_comm_blocks {
7542: my ($cdom,$cnum) = @_;
7543: if ($cdom eq '' || $cnum eq '') {
7544: return unless ($env{'request.course.id'});
7545: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7546: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7547: }
7548: my %commblocks;
7549: my $hashid=$cdom.'_'.$cnum;
7550: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7551: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7552: %commblocks = %{$blocksref};
7553: } else {
7554: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7555: my $cachetime = 600;
7556: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7557: }
7558: return %commblocks;
7559: }
7560:
1.1282 raeburn 7561: sub get_commblock_resources {
7562: my ($blocks) = @_;
7563: my %blockers = ();
7564: return %blockers unless ($env{'request.course.id'});
7565: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7566: my %commblocks;
7567: if (ref($blocks) eq 'HASH') {
7568: %commblocks = %{$blocks};
7569: } else {
7570: %commblocks = &get_comm_blocks();
7571: }
1.1282 raeburn 7572: return %blockers unless (keys(%commblocks) > 0);
7573: my $navmap = Apache::lonnavmaps::navmap->new();
7574: return %blockers unless (ref($navmap));
1.1162 raeburn 7575: my $now = time;
7576: foreach my $block (keys(%commblocks)) {
7577: if ($block =~ /^(\d+)____(\d+)$/) {
7578: my ($start,$end) = ($1,$2);
7579: if ($start <= $now && $end >= $now) {
7580: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7581: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7582: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 7583: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7584: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7585: }
7586: }
7587: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 7588: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7589: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7590: }
7591: }
7592: }
7593: }
7594: }
7595: } elsif ($block =~ /^firstaccess____(.+)$/) {
7596: my $item = $1;
1.1163 raeburn 7597: my @to_test;
1.1162 raeburn 7598: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7599: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 7600: my @interval;
7601: my $type = 'map';
7602: if ($item eq 'course') {
7603: $type = 'course';
7604: @interval=&EXT("resource.0.interval");
7605: } else {
7606: if ($item =~ /___\d+___/) {
7607: $type = 'resource';
7608: @interval=&EXT("resource.0.interval",$item);
7609: if (ref($navmap)) {
7610: my $res = $navmap->getBySymb($item);
7611: push(@to_test,$res);
7612: }
1.1162 raeburn 7613: } else {
1.1282 raeburn 7614: my $mapsymb = &symbread($item,1);
7615: if ($mapsymb) {
7616: if (ref($navmap)) {
7617: my $mapres = $navmap->getBySymb($mapsymb);
7618: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7619: foreach my $res (@to_test) {
7620: my $symb = $res->symb();
7621: next if ($symb eq $mapsymb);
7622: if ($symb ne '') {
7623: @interval=&EXT("resource.0.interval",$symb);
7624: if ($interval[1] eq 'map') {
7625: last;
1.1162 raeburn 7626: }
7627: }
7628: }
7629: }
7630: }
7631: }
1.1282 raeburn 7632: }
1.1310 raeburn 7633: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 7634: my $timelimit = $1;
1.1282 raeburn 7635: my $first_access;
7636: if ($type eq 'resource') {
7637: $first_access=&get_first_access($interval[1],$item);
7638: } elsif ($type eq 'map') {
7639: $first_access=&get_first_access($interval[1],undef,$item);
7640: } else {
7641: $first_access=&get_first_access($interval[1]);
7642: }
7643: if ($first_access) {
1.1292 raeburn 7644: my $timesup = $first_access+$timelimit;
1.1282 raeburn 7645: if ($timesup > $now) {
7646: my $activeblock;
7647: foreach my $res (@to_test) {
1.1283 raeburn 7648: if ($res->answerable()) {
1.1282 raeburn 7649: $activeblock = 1;
7650: last;
7651: }
7652: }
7653: if ($activeblock) {
7654: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7655: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7656: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7657: }
7658: }
7659: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7660: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7661: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7662: }
1.1162 raeburn 7663: }
7664: }
7665: }
7666: }
7667: }
7668: }
7669: }
7670: }
7671: }
1.1282 raeburn 7672: return %blockers;
1.1162 raeburn 7673: }
7674:
1.1282 raeburn 7675: sub has_comm_blocking {
7676: my ($priv,$symb,$uri,$blocks) = @_;
7677: my @blockers;
7678: return unless ($env{'request.course.id'});
7679: return unless ($priv eq 'bre');
7680: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7681: return if ($env{'request.state'} eq 'construct');
7682: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7683: return unless (keys(%cachedblockers) > 0);
7684: my (%possibles,@symbs);
7685: if (!$symb) {
7686: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7687: }
1.1282 raeburn 7688: if ($symb) {
7689: @symbs = ($symb);
7690: } elsif (keys(%possibles)) {
7691: @symbs = keys(%possibles);
7692: }
7693: my $noblock;
7694: foreach my $symb (@symbs) {
7695: last if ($noblock);
7696: my ($map,$resid,$resurl)=&decode_symb($symb);
7697: foreach my $block (keys(%cachedblockers)) {
7698: if ($block =~ /^firstaccess____(.+)$/) {
7699: my $item = $1;
7700: if (($item eq $map) || ($item eq $symb)) {
7701: $noblock = 1;
7702: last;
7703: }
7704: }
7705: if (ref($cachedblockers{$block}) eq 'HASH') {
7706: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7707: if ($cachedblockers{$block}{'resources'}{$symb}) {
7708: unless (grep(/^\Q$block\E$/,@blockers)) {
7709: push(@blockers,$block);
7710: }
7711: }
7712: }
1.1162 raeburn 7713: }
1.1282 raeburn 7714: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7715: if ($cachedblockers{$block}{'maps'}{$map}) {
7716: unless (grep(/^\Q$block\E$/,@blockers)) {
7717: push(@blockers,$block);
7718: }
7719: }
1.1162 raeburn 7720: }
7721: }
7722: }
1.1282 raeburn 7723: return if ($noblock);
7724: return @blockers;
7725: }
1.1162 raeburn 7726: }
7727:
1.1282 raeburn 7728: # -------------------------------- Deversion and split uri into path an filename
7729:
1.1133 foxr 7730: #
1.1282 raeburn 7731: # Removes the version from a URI and
1.1133 foxr 7732: # splits it in to its filename and path to the filename.
7733: # Seems like File::Basename could have done this more clearly.
7734: # Parameters:
7735: # $uri - input URI
7736: # Returns:
7737: # Two element list consisting of
7738: # $pathname - the URI up to and excluding the trailing /
7739: # $filename - The part of the URI following the last /
7740: # NOTE:
7741: # Another realization of this is simply:
7742: # use File::Basename;
7743: # ...
7744: # $uri = shift;
7745: # $filename = basename($uri);
7746: # $path = dirname($uri);
7747: # return ($filename, $path);
7748: #
7749: # The implementation below is probably faster however.
7750: #
1.710 albertel 7751: sub split_uri_for_cond {
7752: my $uri=&deversion(&declutter(shift));
7753: my @uriparts=split(/\//,$uri);
7754: my $filename=pop(@uriparts);
7755: my $pathname=join('/',@uriparts);
7756: return ($pathname,$filename);
7757: }
1.232 www 7758: # --------------------------------------------------- Is a resource on the map?
7759:
7760: sub is_on_map {
1.710 albertel 7761: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7762: #Trying to find the conditional for the file
1.620 albertel 7763: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7764: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7765: if ($match) {
1.289 bowersj2 7766: return (1,$1);
7767: } else {
1.434 www 7768: return (0,0);
1.289 bowersj2 7769: }
1.12 www 7770: }
7771:
1.427 www 7772: # --------------------------------------------------------- Get symb from alias
7773:
7774: sub get_symb_from_alias {
7775: my $symb=shift;
7776: my ($map,$resid,$url)=&decode_symb($symb);
7777: # Already is a symb
7778: if ($url) { return $symb; }
7779: # Must be an alias
7780: my $aliassymb='';
7781: my %bighash;
1.620 albertel 7782: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7783: &GDBM_READER(),0640)) {
7784: my $rid=$bighash{'mapalias_'.$symb};
7785: if ($rid) {
7786: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7787: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7788: $resid,$bighash{'src_'.$rid});
1.427 www 7789: }
7790: untie %bighash;
7791: }
7792: return $aliassymb;
7793: }
7794:
1.12 www 7795: # ----------------------------------------------------------------- Define Role
7796:
7797: sub definerole {
7798: if (allowed('mcr','/')) {
1.1326 raeburn 7799: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 7800: foreach my $role (split(':',$sysrole)) {
7801: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7802: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7803: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7804: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7805: return "refused:s:$crole&$cqual";
7806: }
7807: }
1.191 harris41 7808: }
1.800 albertel 7809: foreach my $role (split(':',$domrole)) {
7810: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7811: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7812: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7813: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7814: return "refused:d:$crole&$cqual";
7815: }
7816: }
1.191 harris41 7817: }
1.800 albertel 7818: foreach my $role (split(':',$courole)) {
7819: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7820: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7821: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7822: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7823: return "refused:c:$crole&$cqual";
7824: }
7825: }
1.191 harris41 7826: }
1.1326 raeburn 7827: my $uhome;
7828: if (($uname ne '') && ($udom ne '')) {
7829: $uhome = &homeserver($uname,$udom);
7830: return $uhome if ($uhome eq 'no_host');
7831: } else {
7832: $uname = $env{'user.name'};
7833: $udom = $env{'user.domain'};
7834: $uhome = $env{'user.home'};
7835: }
1.620 albertel 7836: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 7837: "$udom:$uname:rolesdef_$rolename=".
1.21 www 7838: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 7839: return reply($command,$uhome);
1.12 www 7840: } else {
7841: return 'refused';
7842: }
1.105 harris41 7843: }
7844:
7845: # ---------------- Make a metadata query against the network of library servers
7846:
7847: sub metadata_query {
1.1237 raeburn 7848: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7849: my %rhash;
1.845 albertel 7850: my %libserv = &all_library();
1.244 matthew 7851: my @server_list = (defined($server_array) ? @$server_array
7852: : keys(%libserv) );
7853: for my $server (@server_list) {
1.1237 raeburn 7854: my $domains = '';
7855: if (ref($domains_hash) eq 'HASH') {
7856: $domains = $domains_hash->{$server};
7857: }
1.118 harris41 7858: unless ($custom or $customshow) {
1.1237 raeburn 7859: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7860: $rhash{$server}=$reply;
7861: }
7862: else {
7863: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7864: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7865: $server);
7866: $rhash{$server}=$reply;
7867: }
1.112 harris41 7868: }
1.118 harris41 7869: return \%rhash;
1.240 www 7870: }
7871:
7872: # ----------------------------------------- Send log queries and wait for reply
7873:
7874: sub log_query {
7875: my ($uname,$udom,$query,%filters)=@_;
7876: my $uhome=&homeserver($uname,$udom);
7877: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7878: my $uhost=&hostname($uhome);
1.800 albertel 7879: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7880: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7881: $uhome);
1.479 albertel 7882: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7883: return get_query_reply($queryid);
7884: }
7885:
1.818 raeburn 7886: # -------------------------- Update MySQL table for portfolio file
7887:
7888: sub update_portfolio_table {
1.821 raeburn 7889: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7890: if ($group ne '') {
7891: $file_name =~s /^\Q$group\E//;
7892: }
1.818 raeburn 7893: my $homeserver = &homeserver($uname,$udom);
7894: my $queryid=
1.821 raeburn 7895: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7896: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7897: my $reply = &get_query_reply($queryid);
7898: return $reply;
7899: }
7900:
1.899 raeburn 7901: # -------------------------- Update MySQL allusers table
7902:
7903: sub update_allusers_table {
7904: my ($uname,$udom,$names) = @_;
7905: my $homeserver = &homeserver($uname,$udom);
7906: my $queryid=
7907: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7908: 'lastname='.&escape($names->{'lastname'}).'%%'.
7909: 'firstname='.&escape($names->{'firstname'}).'%%'.
7910: 'middlename='.&escape($names->{'middlename'}).'%%'.
7911: 'generation='.&escape($names->{'generation'}).'%%'.
7912: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7913: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7914: return;
1.899 raeburn 7915: }
7916:
1.508 raeburn 7917: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7918:
7919: sub fetch_enrollment_query {
1.511 raeburn 7920: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 7921: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 7922: my $maxtries = 1;
1.508 raeburn 7923: if ($context eq 'automated') {
7924: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 7925: $sleep = 2;
7926: $loopmax = 100;
1.547 raeburn 7927: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7928: } else {
7929: $homeserver = &homeserver($cnum,$dom);
7930: }
1.838 albertel 7931: my $host=&hostname($homeserver);
1.506 raeburn 7932: my $cmd = '';
1.1000 raeburn 7933: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7934: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7935: }
7936: $cmd =~ s/%%$//;
7937: $cmd = &escape($cmd);
7938: my $query = 'fetchenrollment';
1.620 albertel 7939: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7940: unless ($queryid=~/^\Q$host\E\_/) {
7941: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7942: return 'error: '.$queryid;
7943: }
1.1317 raeburn 7944: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 7945: my $tries = 1;
7946: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 7947: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 7948: $tries ++;
7949: }
1.526 raeburn 7950: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7951: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7952: } else {
1.901 albertel 7953: my @responses = split(/:/,$reply);
1.1322 raeburn 7954: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 7955: foreach my $line (@responses) {
7956: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7957: $$replyref{$key} = $value;
7958: }
7959: } else {
1.1117 foxr 7960: my $pathname = LONCAPA::tempdir();
1.800 albertel 7961: foreach my $line (@responses) {
7962: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7963: $$replyref{$key} = $value;
7964: if ($value > 0) {
1.800 albertel 7965: foreach my $item (@{$$affiliatesref{$key}}) {
7966: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7967: my $destname = $pathname.'/'.$filename;
7968: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7969: if ($xml_classlist =~ /^error/) {
7970: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7971: } else {
1.506 raeburn 7972: if ( open(FILE,">$destname") ) {
7973: print FILE &unescape($xml_classlist);
7974: close(FILE);
1.526 raeburn 7975: } else {
7976: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7977: }
7978: }
7979: }
7980: }
7981: }
7982: }
7983: return 'ok';
7984: }
7985: return 'error';
7986: }
7987:
1.242 www 7988: sub get_query_reply {
1.1317 raeburn 7989: my ($queryid,$sleep,$loopmax) = @_;;
7990: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
7991: $sleep = 0.2;
7992: }
7993: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
7994: $loopmax = 100;
7995: }
1.1117 foxr 7996: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7997: my $reply='';
1.1317 raeburn 7998: for (1..$loopmax) {
7999: sleep($sleep);
1.240 www 8000: if (-e $replyfile.'.end') {
1.448 albertel 8001: if (open(my $fh,$replyfile)) {
1.904 albertel 8002: $reply = join('',<$fh>);
8003: close($fh);
1.240 www 8004: } else { return 'error: reply_file_error'; }
1.242 www 8005: return &unescape($reply);
8006: }
1.240 www 8007: }
1.242 www 8008: return 'timeout:'.$queryid;
1.240 www 8009: }
8010:
8011: sub courselog_query {
1.241 www 8012: #
8013: # possible filters:
8014: # url: url or symb
8015: # username
8016: # domain
8017: # action: view, submit, grade
8018: # start: timestamp
8019: # end: timestamp
8020: #
1.240 www 8021: my (%filters)=@_;
1.620 albertel 8022: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8023: if ($filters{'url'}) {
8024: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8025: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8026: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8027: }
1.620 albertel 8028: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8029: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8030: return &log_query($cname,$cdom,'courselog',%filters);
8031: }
8032:
8033: sub userlog_query {
1.858 raeburn 8034: #
8035: # possible filters:
8036: # action: log check role
8037: # start: timestamp
8038: # end: timestamp
8039: #
1.240 www 8040: my ($uname,$udom,%filters)=@_;
8041: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8042: }
8043:
1.506 raeburn 8044: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8045:
8046: sub auto_run {
1.508 raeburn 8047: my ($cnum,$cdom) = @_;
1.876 raeburn 8048: my $response = 0;
8049: my $settings;
8050: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8051: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8052: $settings = $domconfig{'autoenroll'};
8053: if ($settings->{'run'} eq '1') {
8054: $response = 1;
8055: }
8056: } else {
1.934 raeburn 8057: my $homeserver;
8058: if (&is_course($cdom,$cnum)) {
8059: $homeserver = &homeserver($cnum,$cdom);
8060: } else {
8061: $homeserver = &domain($cdom,'primary');
8062: }
8063: if ($homeserver ne 'no_host') {
8064: $response = &reply('autorun:'.$cdom,$homeserver);
8065: }
1.876 raeburn 8066: }
1.506 raeburn 8067: return $response;
8068: }
1.776 albertel 8069:
1.506 raeburn 8070: sub auto_get_sections {
1.508 raeburn 8071: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8072: my $homeserver;
8073: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8074: $homeserver = &homeserver($cnum,$cdom);
8075: }
8076: if (!defined($homeserver)) {
8077: if ($cdom =~ /^$match_domain$/) {
8078: $homeserver = &domain($cdom,'primary');
8079: }
8080: }
8081: my @secs;
8082: if (defined($homeserver)) {
8083: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8084: unless ($response eq 'refused') {
8085: @secs = split(/:/,$response);
8086: }
1.506 raeburn 8087: }
8088: return @secs;
8089: }
1.776 albertel 8090:
1.506 raeburn 8091: sub auto_new_course {
1.1099 raeburn 8092: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8093: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8094: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8095: return $response;
8096: }
1.776 albertel 8097:
1.506 raeburn 8098: sub auto_validate_courseID {
1.508 raeburn 8099: my ($cnum,$cdom,$inst_course_id) = @_;
8100: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8101: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8102: return $response;
8103: }
1.776 albertel 8104:
1.1007 raeburn 8105: sub auto_validate_instcode {
1.1020 raeburn 8106: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8107: my ($homeserver,$response);
8108: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8109: $homeserver = &homeserver($cnum,$cdom);
8110: }
8111: if (!defined($homeserver)) {
8112: if ($cdom =~ /^$match_domain$/) {
8113: $homeserver = &domain($cdom,'primary');
8114: }
8115: }
1.1065 raeburn 8116: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8117: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 8118: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8119: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8120: }
8121:
1.506 raeburn 8122: sub auto_create_password {
1.873 raeburn 8123: my ($cnum,$cdom,$authparam,$udom) = @_;
8124: my ($homeserver,$response);
1.506 raeburn 8125: my $create_passwd = 0;
8126: my $authchk = '';
1.873 raeburn 8127: if ($udom =~ /^$match_domain$/) {
8128: $homeserver = &domain($udom,'primary');
8129: }
8130: if ($homeserver eq '') {
8131: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8132: $homeserver = &homeserver($cnum,$cdom);
8133: }
8134: }
8135: if ($homeserver eq '') {
8136: $authchk = 'nodomain';
1.506 raeburn 8137: } else {
1.873 raeburn 8138: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8139: if ($response eq 'refused') {
8140: $authchk = 'refused';
8141: } else {
1.901 albertel 8142: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8143: }
1.506 raeburn 8144: }
8145: return ($authparam,$create_passwd,$authchk);
8146: }
8147:
1.706 raeburn 8148: sub auto_photo_permission {
8149: my ($cnum,$cdom,$students) = @_;
8150: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8151: my ($outcome,$perm_reqd,$conditions) =
8152: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8153: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8154: return (undef,undef);
8155: }
1.706 raeburn 8156: return ($outcome,$perm_reqd,$conditions);
8157: }
8158:
8159: sub auto_checkphotos {
8160: my ($uname,$udom,$pid) = @_;
8161: my $homeserver = &homeserver($uname,$udom);
8162: my ($result,$resulttype);
8163: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8164: &escape($uname).':'.&escape($pid),
8165: $homeserver));
1.709 albertel 8166: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8167: return (undef,undef);
8168: }
1.706 raeburn 8169: if ($outcome) {
8170: ($result,$resulttype) = split(/:/,$outcome);
8171: }
8172: return ($result,$resulttype);
8173: }
8174:
8175: sub auto_photochoice {
8176: my ($cnum,$cdom) = @_;
8177: my $homeserver = &homeserver($cnum,$cdom);
8178: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8179: &escape($cdom),
8180: $homeserver)));
1.709 albertel 8181: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8182: return (undef,undef);
8183: }
1.706 raeburn 8184: return ($update,$comment);
8185: }
8186:
8187: sub auto_photoupdate {
8188: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8189: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8190: my $host=&hostname($homeserver);
1.706 raeburn 8191: my $cmd = '';
8192: my $maxtries = 1;
1.800 albertel 8193: foreach my $affiliate (keys(%{$affiliatesref})) {
8194: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8195: }
8196: $cmd =~ s/%%$//;
8197: $cmd = &escape($cmd);
8198: my $query = 'institutionalphotos';
8199: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8200: unless ($queryid=~/^\Q$host\E\_/) {
8201: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8202: return 'error: '.$queryid;
8203: }
8204: my $reply = &get_query_reply($queryid);
8205: my $tries = 1;
8206: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8207: $reply = &get_query_reply($queryid);
8208: $tries ++;
8209: }
8210: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8211: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8212: } else {
8213: my @responses = split(/:/,$reply);
8214: my $outcome = shift(@responses);
8215: foreach my $item (@responses) {
8216: my ($key,$value) = split(/=/,$item);
8217: $$photo{$key} = $value;
8218: }
8219: return $outcome;
8220: }
8221: return 'error';
8222: }
8223:
1.521 raeburn 8224: sub auto_instcode_format {
1.793 albertel 8225: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8226: $cat_order) = @_;
1.521 raeburn 8227: my $courses = '';
1.772 raeburn 8228: my @homeservers;
1.521 raeburn 8229: if ($caller eq 'global') {
1.841 albertel 8230: my %servers = &get_servers($codedom,'library');
8231: foreach my $tryserver (keys(%servers)) {
8232: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8233: push(@homeservers,$tryserver);
8234: }
1.584 raeburn 8235: }
1.1022 raeburn 8236: } elsif ($caller eq 'requests') {
8237: if ($codedom =~ /^$match_domain$/) {
8238: my $chome = &domain($codedom,'primary');
8239: unless ($chome eq 'no_host') {
8240: push(@homeservers,$chome);
8241: }
8242: }
1.521 raeburn 8243: } else {
1.772 raeburn 8244: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8245: }
1.793 albertel 8246: foreach my $code (keys(%{$instcodes})) {
8247: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8248: }
8249: chop($courses);
1.772 raeburn 8250: my $ok_response = 0;
8251: my $response;
8252: while (@homeservers > 0 && $ok_response == 0) {
8253: my $server = shift(@homeservers);
8254: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8255: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8256: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8257: split(/:/,$response);
1.772 raeburn 8258: %{$codes} = (%{$codes},&str2hash($codes_str));
8259: push(@{$codetitles},&str2array($codetitles_str));
8260: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8261: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8262: $ok_response = 1;
8263: }
8264: }
8265: if ($ok_response) {
1.521 raeburn 8266: return 'ok';
1.772 raeburn 8267: } else {
8268: return $response;
1.521 raeburn 8269: }
8270: }
8271:
1.792 raeburn 8272: sub auto_instcode_defaults {
8273: my ($domain,$returnhash,$code_order) = @_;
8274: my @homeservers;
1.841 albertel 8275:
8276: my %servers = &get_servers($domain,'library');
8277: foreach my $tryserver (keys(%servers)) {
8278: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8279: push(@homeservers,$tryserver);
8280: }
1.792 raeburn 8281: }
1.841 albertel 8282:
1.792 raeburn 8283: my $response;
1.841 albertel 8284: foreach my $server (@homeservers) {
1.792 raeburn 8285: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8286: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8287:
8288: foreach my $pair (split(/\&/,$response)) {
8289: my ($name,$value)=split(/\=/,$pair);
8290: if ($name eq 'code_order') {
8291: @{$code_order} = split(/\&/,&unescape($value));
8292: } else {
8293: $returnhash->{&unescape($name)}=&unescape($value);
8294: }
8295: }
8296: return 'ok';
1.792 raeburn 8297: }
1.841 albertel 8298:
8299: return $response;
1.1003 raeburn 8300: }
8301:
8302: sub auto_possible_instcodes {
1.1007 raeburn 8303: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8304: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8305: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8306: return;
8307: }
1.1003 raeburn 8308: my (@homeservers,$uhome);
8309: if (defined(&domain($domain,'primary'))) {
8310: $uhome=&domain($domain,'primary');
8311: push(@homeservers,&domain($domain,'primary'));
8312: } else {
8313: my %servers = &get_servers($domain,'library');
8314: foreach my $tryserver (keys(%servers)) {
8315: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8316: push(@homeservers,$tryserver);
8317: }
8318: }
8319: }
8320: my $response;
8321: foreach my $server (@homeservers) {
8322: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8323: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8324: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8325: split(':',$response);
8326: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8327: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8328: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8329: my ($name,$value)=split('=',$item);
8330: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8331: }
8332: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8333: my ($name,$value)=split('=',$item);
8334: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8335: }
8336: return 'ok';
8337: }
8338: return $response;
8339: }
1.792 raeburn 8340:
1.1010 raeburn 8341: sub auto_courserequest_checks {
8342: my ($dom) = @_;
1.1020 raeburn 8343: my ($homeserver,%validations);
8344: if ($dom =~ /^$match_domain$/) {
8345: $homeserver = &domain($dom,'primary');
8346: }
8347: unless ($homeserver eq 'no_host') {
8348: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8349: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8350: my @items = split(/&/,$response);
8351: foreach my $item (@items) {
8352: my ($key,$value) = split('=',$item);
8353: $validations{&unescape($key)} = &thaw_unescape($value);
8354: }
8355: }
8356: }
1.1010 raeburn 8357: return %validations;
8358: }
8359:
1.1020 raeburn 8360: sub auto_courserequest_validation {
1.1255 raeburn 8361: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8362: my ($homeserver,$response);
8363: if ($dom =~ /^$match_domain$/) {
8364: $homeserver = &domain($dom,'primary');
8365: }
1.1255 raeburn 8366: unless ($homeserver eq 'no_host') {
8367: my $customdata;
8368: if (ref($custominfo) eq 'HASH') {
8369: $customdata = &freeze_escape($custominfo);
8370: }
1.1020 raeburn 8371: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8372: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8373: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8374: $customdata,$homeserver));
1.1020 raeburn 8375: }
8376: return $response;
8377: }
8378:
1.777 albertel 8379: sub auto_validate_class_sec {
1.918 raeburn 8380: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8381: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8382: my $ownerlist;
8383: if (ref($owners) eq 'ARRAY') {
8384: $ownerlist = join(',',@{$owners});
8385: } else {
8386: $ownerlist = $owners;
8387: }
1.773 raeburn 8388: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8389: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8390: return $response;
8391: }
8392:
1.1248 raeburn 8393: sub auto_crsreq_update {
8394: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8395: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8396: my ($homeserver,%crsreqresponse);
8397: if ($cdom =~ /^$match_domain$/) {
8398: $homeserver = &domain($cdom,'primary');
8399: }
8400: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8401: my $info;
8402: if (ref($inbound) eq 'HASH') {
8403: $info = &freeze_escape($inbound);
8404: }
8405: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8406: ':'.&escape($action).':'.&escape($ownername).':'.
8407: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8408: &escape($title).':'.&escape($code).':'.
8409: &escape($accessstart).':'.&escape($accessend).':'.$info,
8410: $homeserver);
1.1248 raeburn 8411: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8412: my @items = split(/&/,$response);
8413: foreach my $item (@items) {
8414: my ($key,$value) = split('=',$item);
8415: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8416: }
8417: }
8418: }
8419: return \%crsreqresponse;
8420: }
8421:
1.1305 raeburn 8422: sub auto_export_grades {
1.1309 raeburn 8423: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8424: my ($homeserver,%exportresponse);
8425: if ($cdom =~ /^$match_domain$/) {
8426: $homeserver = &domain($cdom,'primary');
8427: }
8428: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8429: my $info;
8430: if (ref($inforef) eq 'HASH') {
8431: $info = &freeze_escape($inforef);
8432: }
8433: if (ref($gradesref) eq 'HASH') {
8434: my $grades = &freeze_escape($gradesref);
8435: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8436: $info.':'.$grades,$homeserver);
8437: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8438: my @items = split(/&/,$response);
8439: foreach my $item (@items) {
8440: my ($key,$value) = split('=',$item);
8441: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8442: }
8443: }
8444: }
8445: }
8446: return \%exportresponse;
1.1305 raeburn 8447: }
8448:
1.1287 raeburn 8449: sub check_instcode_cloning {
8450: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8451: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8452: return;
8453: }
8454: my $canclone;
8455: if (@{$code_order} > 0) {
8456: my $instcoderegexp ='^';
8457: my @clonecodes = split(/\&/,$cloner);
8458: foreach my $item (@{$code_order}) {
8459: if (grep(/^\Q$item\E=/,@clonecodes)) {
8460: foreach my $pair (@clonecodes) {
8461: my ($key,$val) = split(/\=/,$pair,2);
8462: $val = &unescape($val);
8463: if ($key eq $item) {
8464: $instcoderegexp .= '('.$val.')';
8465: last;
8466: }
8467: }
8468: } else {
8469: $instcoderegexp .= $codedefaults->{$item};
8470: }
8471: }
8472: $instcoderegexp .= '$';
8473: my (@from,@to);
8474: eval {
8475: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8476: (@to) = ($clonetocode =~ /$instcoderegexp/);
8477: };
8478: if ((@from > 0) && (@to > 0)) {
8479: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8480: if (!@diffs) {
8481: $canclone = 1;
8482: }
8483: }
8484: }
8485: return $canclone;
8486: }
8487:
8488: sub default_instcode_cloning {
8489: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8490: my (%codedefaults,@code_order,$canclone);
8491: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8492: %codedefaults = %{$codedefaultsref};
8493: @code_order = @{$codeorderref};
8494: } elsif ($clonedom) {
8495: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8496: }
8497: if (($domdefclone) && (@code_order)) {
8498: my @clonecodes = split(/\+/,$domdefclone);
8499: my $instcoderegexp ='^';
8500: foreach my $item (@code_order) {
8501: if (grep(/^\Q$item\E$/,@clonecodes)) {
8502: $instcoderegexp .= '('.$codedefaults{$item}.')';
8503: } else {
8504: $instcoderegexp .= $codedefaults{$item};
8505: }
8506: }
8507: $instcoderegexp .= '$';
8508: my (@from,@to);
8509: eval {
8510: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8511: (@to) = ($clonetocode =~ /$instcoderegexp/);
8512: };
8513: if ((@from > 0) && (@to > 0)) {
8514: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8515: if (!@diffs) {
8516: $canclone = 1;
8517: }
8518: }
8519: }
8520: return $canclone;
8521: }
8522:
1.679 raeburn 8523: # ------------------------------------------------------- Course Group routines
8524:
8525: sub get_coursegroups {
1.809 raeburn 8526: my ($cdom,$cnum,$group,$namespace) = @_;
8527: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8528: }
8529:
1.679 raeburn 8530: sub modify_coursegroup {
8531: my ($cdom,$cnum,$groupsettings) = @_;
8532: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8533: }
8534:
1.809 raeburn 8535: sub toggle_coursegroup_status {
8536: my ($cdom,$cnum,$group,$action) = @_;
8537: my ($from_namespace,$to_namespace);
8538: if ($action eq 'delete') {
8539: $from_namespace = 'coursegroups';
8540: $to_namespace = 'deleted_groups';
8541: } else {
8542: $from_namespace = 'deleted_groups';
8543: $to_namespace = 'coursegroups';
8544: }
8545: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8546: if (my $tmp = &error(%curr_group)) {
8547: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8548: return ('read error',$tmp);
8549: } else {
8550: my %savedsettings = %curr_group;
1.809 raeburn 8551: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8552: my $deloutcome;
8553: if ($result eq 'ok') {
1.809 raeburn 8554: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8555: } else {
8556: return ('write error',$result);
8557: }
8558: if ($deloutcome eq 'ok') {
8559: return 'ok';
8560: } else {
8561: return ('delete error',$deloutcome);
8562: }
8563: }
8564: }
8565:
1.679 raeburn 8566: sub modify_group_roles {
1.957 raeburn 8567: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8568: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8569: my $role = 'gr/'.&escape($userprivs);
8570: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8571: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8572: if ($result eq 'ok') {
8573: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8574: }
1.679 raeburn 8575: return $result;
8576: }
8577:
8578: sub modify_coursegroup_membership {
8579: my ($cdom,$cnum,$membership) = @_;
8580: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8581: return $result;
8582: }
8583:
1.682 raeburn 8584: sub get_active_groups {
8585: my ($udom,$uname,$cdom,$cnum) = @_;
8586: my $now = time;
8587: my %groups = ();
8588: foreach my $key (keys(%env)) {
1.811 albertel 8589: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8590: my ($start,$end) = split(/\./,$env{$key});
8591: if (($end!=0) && ($end<$now)) { next; }
8592: if (($start!=0) && ($start>$now)) { next; }
8593: if ($1 eq $cdom && $2 eq $cnum) {
8594: $groups{$3} = $env{$key} ;
8595: }
8596: }
8597: }
8598: return %groups;
8599: }
8600:
1.683 raeburn 8601: sub get_group_membership {
8602: my ($cdom,$cnum,$group) = @_;
8603: return(&dump('groupmembership',$cdom,$cnum,$group));
8604: }
8605:
8606: sub get_users_groups {
8607: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8608: my @usersgroups;
1.683 raeburn 8609: my $cachetime=1800;
8610:
8611: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8612: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8613: if (defined($cached)) {
1.734 albertel 8614: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8615: } else {
8616: $grouplist = '';
1.816 raeburn 8617: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8618: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8619: my $access_end = $env{'course.'.$courseid.
8620: '.default_enrollment_end_date'};
8621: my $now = time;
8622: foreach my $key (keys(%roleshash)) {
8623: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8624: my $group = $1;
8625: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8626: my $start = $2;
8627: my $end = $1;
8628: if ($start == -1) { next; } # deleted from group
8629: if (($start!=0) && ($start>$now)) { next; }
8630: if (($end!=0) && ($end<$now)) {
8631: if ($access_end && $access_end < $now) {
8632: if ($access_end - $end < 86400) {
8633: push(@usersgroups,$group);
1.733 raeburn 8634: }
8635: }
1.817 raeburn 8636: next;
1.733 raeburn 8637: }
1.817 raeburn 8638: push(@usersgroups,$group);
1.683 raeburn 8639: }
8640: }
8641: }
1.817 raeburn 8642: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8643: $grouplist = join(':',@usersgroups);
8644: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8645: }
1.733 raeburn 8646: return @usersgroups;
1.683 raeburn 8647: }
8648:
8649: sub devalidate_getgroups_cache {
8650: my ($udom,$uname,$cdom,$cnum)=@_;
8651: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8652:
1.683 raeburn 8653: my $hashid="$udom:$uname:$courseid";
8654: &devalidate_cache_new('getgroups',$hashid);
8655: }
8656:
1.12 www 8657: # ------------------------------------------------------------------ Plain Text
8658:
8659: sub plaintext {
1.988 raeburn 8660: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8661: if ($short =~ m{^cr/}) {
1.758 albertel 8662: return (split('/',$short))[-1];
8663: }
1.742 raeburn 8664: if (!defined($cid)) {
8665: $cid = $env{'request.course.id'};
8666: }
8667: my %rolenames = (
1.1008 raeburn 8668: Course => 'std',
8669: Community => 'alt1',
1.1305 raeburn 8670: Placement => 'std',
1.742 raeburn 8671: );
1.1037 raeburn 8672: if ($cid ne '') {
8673: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8674: unless ($forcedefault) {
8675: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8676: &Apache::lonlocal::mt_escape(\$roletext);
8677: return &Apache::lonlocal::mt($roletext);
8678: }
8679: }
8680: }
8681: if ((defined($type)) && (defined($rolenames{$type})) &&
8682: (defined($rolenames{$type})) &&
8683: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8684: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8685: } elsif ($cid ne '') {
8686: my $crstype = $env{'course.'.$cid.'.type'};
8687: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8688: (defined($prp{$short}{$rolenames{$crstype}}))) {
8689: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8690: }
1.742 raeburn 8691: }
1.1037 raeburn 8692: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8693: }
8694:
8695: # ----------------------------------------------------------------- Assign Role
8696:
8697: sub assignrole {
1.957 raeburn 8698: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8699: $context)=@_;
1.21 www 8700: my $mrole;
8701: if ($role =~ /^cr\//) {
1.393 www 8702: my $cwosec=$url;
1.811 albertel 8703: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8704: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8705: my $refused = 1;
8706: if ($context eq 'requestcourses') {
8707: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8708: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8709: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8710: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8711: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8712: if ($crsenv{'internal.courseowner'} eq
8713: $env{'user.name'}.':'.$env{'user.domain'}) {
8714: $refused = '';
8715: }
8716: }
8717: }
8718: }
8719: }
8720: if ($refused) {
8721: &logthis('Refused custom assignrole: '.
8722: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8723: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8724: return 'refused';
8725: }
1.104 www 8726: }
1.21 www 8727: $mrole='cr';
1.678 raeburn 8728: } elsif ($role =~ /^gr\//) {
8729: my $cwogrp=$url;
1.811 albertel 8730: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8731: unless (&allowed('mdg',$cwogrp)) {
8732: &logthis('Refused group assignrole: '.
8733: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8734: $env{'user.name'}.' at '.$env{'user.domain'});
8735: return 'refused';
8736: }
8737: $mrole='gr';
1.21 www 8738: } else {
1.82 www 8739: my $cwosec=$url;
1.811 albertel 8740: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8741: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8742: my $refused;
8743: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8744: if (!(&allowed('c'.$role,$url))) {
8745: $refused = 1;
8746: }
8747: } else {
8748: $refused = 1;
8749: }
1.947 raeburn 8750: if ($refused) {
1.1045 raeburn 8751: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8752: if (!$selfenroll && $context eq 'course') {
8753: my %crsenv;
8754: if ($role eq 'cc' || $role eq 'co') {
8755: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8756: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8757: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8758: if ($crsenv{'internal.courseowner'} eq
8759: $env{'user.name'}.':'.$env{'user.domain'}) {
8760: $refused = '';
8761: }
8762: }
8763: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8764: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8765: if ($crsenv{'internal.courseowner'} eq
8766: $env{'user.name'}.':'.$env{'user.domain'}) {
8767: $refused = '';
8768: }
8769: }
8770: }
8771: }
8772: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8773: $refused = '';
1.1017 raeburn 8774: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8775: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8776: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8777: my $wrongcc;
8778: if ($cnum =~ /^$match_community$/) {
8779: $wrongcc = 1 if ($role eq 'cc');
8780: } else {
8781: $wrongcc = 1 if ($role eq 'co');
8782: }
8783: unless ($wrongcc) {
8784: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8785: if ($crsenv{'internal.courseowner'} eq
8786: $env{'user.name'}.':'.$env{'user.domain'}) {
8787: $refused = '';
8788: }
1.1017 raeburn 8789: }
8790: }
1.1183 raeburn 8791: } elsif ($context eq 'requestauthor') {
8792: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8793: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8794: if ($env{'environment.requestauthor'} eq 'automatic') {
8795: $refused = '';
8796: } else {
8797: my %domdefaults = &get_domain_defaults($udom);
8798: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8799: my $checkbystatus;
8800: if ($env{'user.adv'}) {
8801: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8802: if ($disposition eq 'automatic') {
8803: $refused = '';
8804: } elsif ($disposition eq '') {
8805: $checkbystatus = 1;
8806: }
8807: } else {
8808: $checkbystatus = 1;
8809: }
8810: if ($checkbystatus) {
8811: if ($env{'environment.inststatus'}) {
8812: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8813: foreach my $type (@inststatuses) {
8814: if (($type ne '') &&
8815: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8816: $refused = '';
8817: }
8818: }
8819: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8820: $refused = '';
8821: }
8822: }
8823: }
8824: }
8825: }
1.1017 raeburn 8826: }
8827: if ($refused) {
1.947 raeburn 8828: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8829: ' '.$role.' '.$end.' '.$start.' by '.
8830: $env{'user.name'}.' at '.$env{'user.domain'});
8831: return 'refused';
8832: }
1.932 raeburn 8833: }
1.1131 raeburn 8834: } elsif ($role eq 'au') {
8835: if ($url ne '/'.$udom.'/') {
8836: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8837: ' to assign author role for '.$uname.':'.$udom.
8838: ' in domain: '.$url.' refused (wrong domain).');
8839: return 'refused';
8840: }
1.104 www 8841: }
1.21 www 8842: $mrole=$role;
8843: }
1.620 albertel 8844: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8845: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8846: if ($end) { $command.='_'.$end; }
1.21 www 8847: if ($start) {
8848: if ($end) {
1.81 www 8849: $command.='_'.$start;
1.21 www 8850: } else {
1.81 www 8851: $command.='_0_'.$start;
1.21 www 8852: }
8853: }
1.739 raeburn 8854: my $origstart = $start;
8855: my $origend = $end;
1.957 raeburn 8856: my $delflag;
1.357 www 8857: # actually delete
8858: if ($deleteflag) {
1.373 www 8859: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8860: # modify command to delete the role
1.620 albertel 8861: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8862: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8863: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8864: # set start and finish to negative values for userrolelog
8865: $start=-1;
8866: $end=-1;
1.957 raeburn 8867: $delflag = 1;
1.357 www 8868: }
8869: }
8870: # send command
1.349 www 8871: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8872: # log new user role if status is ok
1.349 www 8873: if ($answer eq 'ok') {
1.663 raeburn 8874: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8875: if (($role eq 'cc') || ($role eq 'in') ||
8876: ($role eq 'ep') || ($role eq 'ad') ||
8877: ($role eq 'ta') || ($role eq 'st') ||
8878: ($role=~/^cr/) || ($role eq 'gr') ||
8879: ($role eq 'co')) {
1.1200 raeburn 8880: # for course roles, perform group memberships changes triggered by role change.
8881: unless ($role =~ /^gr/) {
8882: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8883: $origstart,$selfenroll,$context);
8884: }
1.1184 raeburn 8885: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8886: $selfenroll,$context);
8887: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1327 raeburn 8888: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh')) {
1.1184 raeburn 8889: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8890: $context);
8891: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8892: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8893: $context);
8894: }
1.1053 raeburn 8895: if ($role eq 'cc') {
8896: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8897: }
1.349 www 8898: }
8899: return $answer;
1.169 harris41 8900: }
8901:
1.1053 raeburn 8902: sub autoupdate_coowners {
8903: my ($url,$end,$start,$uname,$udom) = @_;
8904: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8905: if (($cdom ne '') && ($cnum ne '')) {
8906: my $now = time;
8907: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8908: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8909: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8910: my $instcode = $coursehash{'internal.coursecode'};
8911: if ($instcode ne '') {
1.1056 raeburn 8912: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8913: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8914: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8915: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8916: if ($result eq 'valid') {
8917: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8918: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8919: push(@newcoowners,$coowner);
8920: }
8921: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8922: push(@newcoowners,$uname.':'.$udom);
8923: }
8924: @newcoowners = sort(@newcoowners);
8925: } else {
8926: push(@newcoowners,$uname.':'.$udom);
8927: }
8928: } else {
8929: if ($coursehash{'internal.co-owners'}) {
8930: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8931: unless ($coowner eq $uname.':'.$udom) {
8932: push(@newcoowners,$coowner);
8933: }
8934: }
8935: unless (@newcoowners > 0) {
8936: $delcoowners = 1;
8937: $coowners = '';
8938: }
8939: }
8940: }
8941: if (@newcoowners || $delcoowners) {
8942: &store_coowners($cdom,$cnum,$coursehash{'home'},
8943: $delcoowners,@newcoowners);
8944: }
8945: }
8946: }
8947: }
8948: }
8949: }
8950: }
8951:
8952: sub store_coowners {
8953: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8954: my $cid = $cdom.'_'.$cnum;
8955: my ($coowners,$delresult,$putresult);
8956: if (@newcoowners) {
8957: $coowners = join(',',@newcoowners);
8958: my %coownershash = (
8959: 'internal.co-owners' => $coowners,
8960: );
8961: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8962: if ($putresult eq 'ok') {
8963: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8964: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8965: }
8966: }
8967: }
8968: if ($delcoowners) {
8969: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8970: if ($delresult eq 'ok') {
8971: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8972: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8973: }
8974: }
8975: }
8976: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8977: my %crsinfo =
8978: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8979: if (ref($crsinfo{$cid}) eq 'HASH') {
8980: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8981: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8982: }
8983: }
8984: }
8985:
1.169 harris41 8986: # -------------------------------------------------- Modify user authentication
1.197 www 8987: # Overrides without validation
8988:
1.169 harris41 8989: sub modifyuserauth {
8990: my ($udom,$uname,$umode,$upass)=@_;
8991: my $uhome=&homeserver($uname,$udom);
1.197 www 8992: unless (&allowed('mau',$udom)) { return 'refused'; }
8993: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8994: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8995: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8996: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8997: &escape($upass),$uhome);
1.620 albertel 8998: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8999: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9000: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9001: &log($udom,,$uname,$uhome,
1.620 albertel 9002: 'Authentication changed by '.$env{'user.domain'}.', '.
9003: $env{'user.name'}.', '.$umode.
1.197 www 9004: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9005: unless ($reply eq 'ok') {
1.197 www 9006: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9007: return 'error: '.$reply;
9008: }
1.170 harris41 9009: return 'ok';
1.80 www 9010: }
9011:
1.81 www 9012: # --------------------------------------------------------------- Modify a user
1.80 www 9013:
1.81 www 9014: sub modifyuser {
1.206 matthew 9015: my ($udom, $uname, $uid,
9016: $umode, $upass, $first,
9017: $middle, $last, $gene,
1.1058 raeburn 9018: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9019: $udom= &LONCAPA::clean_domain($udom);
9020: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9021: my $showcandelete = 'none';
9022: if (ref($candelete) eq 'ARRAY') {
9023: if (@{$candelete} > 0) {
9024: $showcandelete = join(', ',@{$candelete});
9025: }
9026: }
1.81 www 9027: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9028: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9029: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9030: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9031: ' desiredhome not specified').
1.620 albertel 9032: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9033: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9034: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9035: my $newuser;
9036: if ($uhome eq 'no_host') {
9037: $newuser = 1;
9038: }
1.80 www 9039: # ----------------------------------------------------------------- Create User
1.406 albertel 9040: if (($uhome eq 'no_host') &&
9041: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9042: my $unhome='';
1.844 albertel 9043: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9044: $unhome = $desiredhome;
1.620 albertel 9045: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9046: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9047: } else { # load balancing routine for determining $unhome
1.81 www 9048: my $loadm=10000000;
1.841 albertel 9049: my %servers = &get_servers($udom,'library');
9050: foreach my $tryserver (keys(%servers)) {
9051: my $answer=reply('load',$tryserver);
9052: if (($answer=~/\d+/) && ($answer<$loadm)) {
9053: $loadm=$answer;
9054: $unhome=$tryserver;
9055: }
1.80 www 9056: }
9057: }
9058: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9059: return 'error: unable to find a home server for '.$uname.
9060: ' in domain '.$udom;
1.80 www 9061: }
9062: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9063: &escape($upass),$unhome);
9064: unless ($reply eq 'ok') {
9065: return 'error: '.$reply;
9066: }
1.230 stredwic 9067: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9068: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9069: return 'error: unable verify users home machine.';
1.80 www 9070: }
1.209 matthew 9071: } # End of creation of new user
1.80 www 9072: # ---------------------------------------------------------------------- Add ID
9073: if ($uid) {
9074: $uid=~tr/A-Z/a-z/;
9075: my %uidhash=&idrget($udom,$uname);
1.196 www 9076: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9077: && (!$forceid)) {
1.80 www 9078: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9079: return 'error: user id "'.$uid.'" does not match '.
9080: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9081: }
9082: } else {
1.1300 raeburn 9083: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 9084: }
9085: }
9086: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9087: my @tmp=&get('environment',
1.899 raeburn 9088: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9089: 'permanentemail','inststatus'],
1.134 albertel 9090: $udom,$uname);
1.1075 raeburn 9091: my (%names,%oldnames);
1.313 matthew 9092: if ($tmp[0] =~ m/^error:.*/) {
9093: %names=();
9094: } else {
9095: %names = @tmp;
1.1075 raeburn 9096: %oldnames = %names;
1.313 matthew 9097: }
1.388 www 9098: #
1.1058 raeburn 9099: # If name, email and/or uid are blank (e.g., because an uploaded file
9100: # of users did not contain them), do not overwrite existing values
9101: # unless field is in $candelete array ref.
9102: #
9103:
9104: my @fields = ('firstname','middlename','lastname','generation',
9105: 'permanentemail','id');
9106: my %newvalues;
9107: if (ref($candelete) eq 'ARRAY') {
9108: foreach my $field (@fields) {
9109: if (grep(/^\Q$field\E$/,@{$candelete})) {
9110: if ($field eq 'firstname') {
9111: $names{$field} = $first;
9112: } elsif ($field eq 'middlename') {
9113: $names{$field} = $middle;
9114: } elsif ($field eq 'lastname') {
9115: $names{$field} = $last;
9116: } elsif ($field eq 'generation') {
9117: $names{$field} = $gene;
9118: } elsif ($field eq 'permanentemail') {
9119: $names{$field} = $email;
9120: } elsif ($field eq 'id') {
9121: $names{$field} = $uid;
9122: }
9123: }
9124: }
9125: }
1.388 www 9126: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9127: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9128: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9129: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9130: if ($email) {
9131: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9132: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9133: }
1.899 raeburn 9134: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9135: if (defined($inststatus)) {
9136: $names{'inststatus'} = '';
9137: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9138: if (ref($usertypes) eq 'HASH') {
9139: my @okstatuses;
9140: foreach my $item (split(/:/,$inststatus)) {
9141: if (defined($usertypes->{$item})) {
9142: push(@okstatuses,$item);
9143: }
9144: }
9145: if (@okstatuses) {
9146: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9147: }
9148: }
9149: }
1.1075 raeburn 9150: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9151: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9152: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9153: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9154: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9155: } else {
9156: $logmsg .= ' during self creation';
9157: }
1.1075 raeburn 9158: my $changed;
9159: if ($newuser) {
9160: $changed = 1;
9161: } else {
9162: foreach my $field (@fields) {
9163: if ($names{$field} ne $oldnames{$field}) {
9164: $changed = 1;
9165: last;
9166: }
9167: }
9168: }
9169: unless ($changed) {
9170: $logmsg = 'No changes in user information needed for: '.$logmsg;
9171: &logthis($logmsg);
9172: return 'ok';
9173: }
9174: my $reply = &put('environment', \%names, $udom,$uname);
9175: if ($reply ne 'ok') {
9176: return 'error: '.$reply;
9177: }
1.1087 raeburn 9178: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9179: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9180: }
1.1075 raeburn 9181: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9182: &devalidate_cache_new('namescache',$uname.':'.$udom);
9183: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9184: &logthis($logmsg);
1.134 albertel 9185: return 'ok';
1.80 www 9186: }
9187:
1.81 www 9188: # -------------------------------------------------------------- Modify student
1.80 www 9189:
1.81 www 9190: sub modifystudent {
9191: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9192: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 9193: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9194: if (!$cid) {
1.620 albertel 9195: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9196: return 'not_in_class';
9197: }
1.80 www 9198: }
9199: # --------------------------------------------------------------- Make the user
1.81 www 9200: my $reply=&modifyuser
1.209 matthew 9201: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9202: $desiredhome,$email,$inststatus);
1.80 www 9203: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9204: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 9205: # student's environment
1.297 matthew 9206: $uid = undef if (!$forceid);
1.455 albertel 9207: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 9208: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 9209: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9210: return $reply;
9211: }
9212:
9213: sub modify_student_enrollment {
1.1216 raeburn 9214: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 9215: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9216: my ($cdom,$cnum,$chome);
9217: if (!$cid) {
1.620 albertel 9218: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9219: return 'not_in_class';
9220: }
1.620 albertel 9221: $cdom=$env{'course.'.$cid.'.domain'};
9222: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9223: } else {
9224: ($cdom,$cnum)=split(/_/,$cid);
9225: }
1.620 albertel 9226: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9227: if (!$chome) {
1.457 raeburn 9228: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9229: }
1.455 albertel 9230: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9231: # Make sure the user exists
1.81 www 9232: my $uhome=&homeserver($uname,$udom);
9233: if (($uhome eq '') || ($uhome eq 'no_host')) {
9234: return 'error: no such user';
9235: }
1.297 matthew 9236: # Get student data if we were not given enough information
9237: if (!defined($first) || $first eq '' ||
9238: !defined($last) || $last eq '' ||
9239: !defined($uid) || $uid eq '' ||
9240: !defined($middle) || $middle eq '' ||
9241: !defined($gene) || $gene eq '') {
1.294 matthew 9242: # They did not supply us with enough data to enroll the student, so
9243: # we need to pick up more information.
1.297 matthew 9244: my %tmp = &get('environment',
1.294 matthew 9245: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9246: ,$udom,$uname);
9247:
1.800 albertel 9248: #foreach my $key (keys(%tmp)) {
9249: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9250: #}
1.294 matthew 9251: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9252: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9253: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9254: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9255: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9256: }
1.556 albertel 9257: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9258: my $user = "$uname:$udom";
9259: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9260: my $reply=cput('classlist',
1.1148 raeburn 9261: {$user =>
1.1314 raeburn 9262: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9263: $cdom,$cnum);
1.1148 raeburn 9264: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9265: &devalidate_getsection_cache($udom,$uname,$cid);
9266: } else {
1.81 www 9267: return 'error: '.$reply;
9268: }
1.297 matthew 9269: # Add student role to user
1.83 www 9270: my $uurl='/'.$cid;
1.81 www 9271: $uurl=~s/\_/\//g;
9272: if ($usec) {
9273: $uurl.='/'.$usec;
9274: }
1.1148 raeburn 9275: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9276: $selfenroll,$context);
9277: if ($result ne 'ok') {
9278: if ($old_entry{$user} ne '') {
9279: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9280: } else {
9281: $reply = &del('classlist',[$user],$cdom,$cnum);
9282: }
9283: }
9284: return $result;
1.21 www 9285: }
9286:
1.556 albertel 9287: sub format_name {
9288: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9289: my $name;
9290: if ($first ne 'lastname') {
9291: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9292: } else {
9293: if ($lastname=~/\S/) {
9294: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9295: $name=~s/\s+,/,/;
9296: } else {
9297: $name.= $firstname.' '.$middlename.' '.$generation;
9298: }
9299: }
9300: $name=~s/^\s+//;
9301: $name=~s/\s+$//;
9302: $name=~s/\s+/ /g;
9303: return $name;
9304: }
9305:
1.84 www 9306: # ------------------------------------------------- Write to course preferences
9307:
9308: sub writecoursepref {
9309: my ($courseid,%prefs)=@_;
9310: $courseid=~s/^\///;
9311: $courseid=~s/\_/\//g;
9312: my ($cdomain,$cnum)=split(/\//,$courseid);
9313: my $chome=homeserver($cnum,$cdomain);
9314: if (($chome eq '') || ($chome eq 'no_host')) {
9315: return 'error: no such course';
9316: }
9317: my $cstring='';
1.800 albertel 9318: foreach my $pref (keys(%prefs)) {
9319: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9320: }
1.84 www 9321: $cstring=~s/\&$//;
9322: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9323: }
9324:
9325: # ---------------------------------------------------------- Make/modify course
9326:
9327: sub createcourse {
1.741 raeburn 9328: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9329: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9330: $url=&declutter($url);
9331: my $cid='';
1.1028 raeburn 9332: if ($context eq 'requestcourses') {
9333: my $can_create = 0;
9334: my ($ownername,$ownerdom) = split(':',$course_owner);
9335: if ($udom eq $ownerdom) {
9336: if (&usertools_access($ownername,$ownerdom,$category,undef,
9337: $context)) {
9338: $can_create = 1;
9339: }
9340: } else {
9341: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9342: $category);
9343: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9344: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9345: if (@curr > 0) {
9346: my @options = qw(approval validate autolimit);
9347: my $optregex = join('|',@options);
9348: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9349: $can_create = 1;
9350: }
9351: }
9352: }
9353: }
9354: if ($can_create) {
9355: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9356: unless (&allowed('ccc',$udom)) {
9357: return 'refused';
9358: }
1.1017 raeburn 9359: }
9360: } else {
9361: return 'refused';
9362: }
1.1028 raeburn 9363: } elsif (!&allowed('ccc',$udom)) {
9364: return 'refused';
1.84 www 9365: }
1.1011 raeburn 9366: # --------------------------------------------------------------- Get Unique ID
9367: my $uname;
9368: if ($cnum =~ /^$match_courseid$/) {
9369: my $chome=&homeserver($cnum,$udom,'true');
9370: if (($chome eq '') || ($chome eq 'no_host')) {
9371: $uname = $cnum;
9372: } else {
1.1038 raeburn 9373: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9374: }
9375: } else {
1.1038 raeburn 9376: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9377: }
9378: return $uname if ($uname =~ /^error/);
9379: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9380: if (!defined($course_server)) {
9381: if (defined(&domain($udom,'primary'))) {
9382: $course_server = &domain($udom,'primary');
9383: } else {
9384: $course_server = $env{'user.home'};
9385: }
9386: }
9387: my %host_servers =
9388: &Apache::lonnet::get_servers($udom,'library');
9389: unless ($host_servers{$course_server}) {
9390: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9391: }
1.84 www 9392: # ------------------------------------------------------------- Make the course
9393: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9394: $course_server);
1.84 www 9395: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9396: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9397: if (($uhome eq '') || ($uhome eq 'no_host')) {
9398: return 'error: no such course';
9399: }
1.271 www 9400: # ----------------------------------------------------------------- Course made
1.516 raeburn 9401: # log existence
1.1029 raeburn 9402: my $now = time;
1.918 raeburn 9403: my $newcourse = {
9404: $udom.'_'.$uname => {
1.921 raeburn 9405: description => $description,
9406: inst_code => $inst_code,
9407: owner => $course_owner,
9408: type => $crstype,
1.1029 raeburn 9409: creator => $env{'user.name'}.':'.
9410: $env{'user.domain'},
9411: created => $now,
9412: context => $context,
1.918 raeburn 9413: },
9414: };
1.921 raeburn 9415: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9416: # set toplevel url
1.271 www 9417: my $topurl=$url;
9418: unless ($nonstandard) {
9419: # ------------------------------------------ For standard courses, make top url
9420: my $mapurl=&clutter($url);
1.278 www 9421: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9422: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9423: <map>
9424: <resource id="1" type="start"></resource>
9425: <resource id="2" src="$mapurl"></resource>
9426: <resource id="3" type="finish"></resource>
9427: <link index="1" from="1" to="2"></link>
9428: <link index="2" from="2" to="3"></link>
9429: </map>
9430: ENDINITMAP
9431: $topurl=&declutter(
1.638 albertel 9432: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9433: );
9434: }
9435: # ----------------------------------------------------------- Write preferences
1.84 www 9436: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9437: ('description' => $description,
9438: 'url' => $topurl,
9439: 'internal.creator' => $env{'user.name'}.':'.
9440: $env{'user.domain'},
9441: 'internal.created' => $now,
9442: 'internal.creationcontext' => $context)
9443: );
1.84 www 9444: return '/'.$udom.'/'.$uname;
9445: }
9446:
1.1011 raeburn 9447: # ------------------------------------------------------------------- Create ID
9448: sub generate_coursenum {
1.1038 raeburn 9449: my ($udom,$crstype) = @_;
1.1011 raeburn 9450: my $domdesc = &domain($udom);
9451: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9452: my $first;
9453: if ($crstype eq 'Community') {
9454: $first = '0';
9455: } else {
9456: $first = int(1+rand(9));
9457: }
9458: my $uname=$first.
1.1011 raeburn 9459: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9460: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9461: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9462: # ----------------------------------------------- Make sure that does not exist
9463: my $uhome=&homeserver($uname,$udom,'true');
9464: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9465: if ($crstype eq 'Community') {
9466: $first = '0';
9467: } else {
9468: $first = int(1+rand(9));
9469: }
9470: $uname=$first.
1.1011 raeburn 9471: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9472: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9473: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9474: $uhome=&homeserver($uname,$udom,'true');
9475: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9476: return 'error: unable to generate unique course-ID';
9477: }
9478: }
9479: return $uname;
9480: }
9481:
1.813 albertel 9482: sub is_course {
1.1167 droeschl 9483: my ($cdom, $cnum) = scalar(@_) == 1 ?
9484: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9485:
9486: return unless $cdom and $cnum;
9487:
9488: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9489: '.');
9490:
1.1219 raeburn 9491: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9492: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9493: }
9494:
1.1015 raeburn 9495: sub store_userdata {
9496: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9497: my $result;
1.1016 raeburn 9498: if ($datakey ne '') {
1.1013 raeburn 9499: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9500: if ($udom eq '' || $uname eq '') {
9501: $udom = $env{'user.domain'};
9502: $uname = $env{'user.name'};
9503: }
9504: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9505: if (($uhome eq '') || ($uhome eq 'no_host')) {
9506: $result = 'error: no_host';
9507: } else {
9508: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9509: $storehash->{'host'} = $perlvar{'lonHostID'};
9510:
9511: my $namevalue='';
9512: foreach my $key (keys(%{$storehash})) {
9513: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9514: }
9515: $namevalue=~s/\&$//;
1.1224 raeburn 9516: unless ($namespace eq 'courserequests') {
9517: $datakey = &escape($datakey);
9518: }
1.1105 raeburn 9519: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9520: $namevalue,$uhome);
1.1013 raeburn 9521: }
9522: } else {
9523: $result = 'error: data to store was not a hash reference';
9524: }
9525: } else {
9526: $result= 'error: invalid requestkey';
9527: }
9528: return $result;
9529: }
9530:
1.21 www 9531: # ---------------------------------------------------------- Assign Custom Role
9532:
9533: sub assigncustomrole {
1.957 raeburn 9534: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9535: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9536: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9537: }
9538:
9539: # ----------------------------------------------------------------- Revoke Role
9540:
9541: sub revokerole {
1.957 raeburn 9542: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9543: my $now=time;
1.965 raeburn 9544: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9545: }
9546:
9547: # ---------------------------------------------------------- Revoke Custom Role
9548:
9549: sub revokecustomrole {
1.957 raeburn 9550: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9551: my $now=time;
1.357 www 9552: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9553: $deleteflag,$selfenroll,$context);
1.17 www 9554: }
9555:
1.533 banghart 9556: # ------------------------------------------------------------ Disk usage
1.535 albertel 9557: sub diskusage {
1.955 raeburn 9558: my ($udom,$uname,$directorypath,$getpropath)=@_;
9559: $directorypath =~ s/\/$//;
9560: my $listing=&reply('du2:'.&escape($directorypath).':'
9561: .&escape($getpropath).':'.&escape($uname).':'
9562: .&escape($udom),homeserver($uname,$udom));
9563: if ($listing eq 'unknown_cmd') {
9564: if ($getpropath) {
9565: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9566: }
9567: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9568: }
1.514 albertel 9569: return $listing;
1.512 banghart 9570: }
9571:
1.566 banghart 9572: sub is_locked {
1.1096 raeburn 9573: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9574: my @check;
9575: my $is_locked;
1.1093 raeburn 9576: push (@check,$file_name);
1.613 albertel 9577: my %locked = &get('file_permissions',\@check,
1.620 albertel 9578: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9579: my ($tmp)=keys(%locked);
9580: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9581:
1.566 banghart 9582: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9583: $is_locked = 'false';
9584: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9585: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9586: $is_locked = 'true';
1.1096 raeburn 9587: if (ref($which) eq 'ARRAY') {
9588: push(@{$which},$entry);
9589: } else {
9590: last;
9591: }
1.745 raeburn 9592: }
9593: }
1.566 banghart 9594: } else {
9595: $is_locked = 'false';
9596: }
1.1093 raeburn 9597: return $is_locked;
1.566 banghart 9598: }
9599:
1.759 albertel 9600: sub declutter_portfile {
9601: my ($file) = @_;
1.833 albertel 9602: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9603: return $file;
9604: }
9605:
1.559 banghart 9606: # ------------------------------------------------------------- Mark as Read Only
9607:
9608: sub mark_as_readonly {
9609: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9610: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9611: my ($tmp)=keys(%current_permissions);
9612: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9613: foreach my $file (@{$files}) {
1.759 albertel 9614: $file = &declutter_portfile($file);
1.561 banghart 9615: push(@{$current_permissions{$file}},$what);
1.559 banghart 9616: }
1.613 albertel 9617: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9618: return;
9619: }
9620:
1.572 banghart 9621: # ------------------------------------------------------------Save Selected Files
9622:
9623: sub save_selected_files {
9624: my ($user, $path, @files) = @_;
9625: my $filename = $user."savedfiles";
1.573 banghart 9626: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9627: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9628: foreach my $file (@files) {
1.620 albertel 9629: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9630: }
9631: foreach my $file (@other_files) {
1.574 banghart 9632: print (OUT $file."\n");
1.572 banghart 9633: }
1.574 banghart 9634: close (OUT);
1.572 banghart 9635: return 'ok';
9636: }
9637:
1.574 banghart 9638: sub clear_selected_files {
9639: my ($user) = @_;
9640: my $filename = $user."savedfiles";
1.1117 foxr 9641: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9642: print (OUT undef);
9643: close (OUT);
9644: return ("ok");
9645: }
9646:
1.572 banghart 9647: sub files_in_path {
9648: my ($user, $path) = @_;
9649: my $filename = $user."savedfiles";
9650: my %return_files;
1.1117 foxr 9651: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9652: while (my $line_in = <IN>) {
1.574 banghart 9653: chomp ($line_in);
9654: my @paths_and_file = split (m!/!, $line_in);
9655: my $file_part = pop (@paths_and_file);
9656: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9657: $path_part.='/';
9658: my $path_and_file = $path_part.$file_part;
9659: if ($path_part eq $path) {
9660: $return_files{$file_part}= 'selected';
9661: }
9662: }
1.574 banghart 9663: close (IN);
9664: return (\%return_files);
1.572 banghart 9665: }
9666:
9667: # called in portfolio select mode, to show files selected NOT in current directory
9668: sub files_not_in_path {
9669: my ($user, $path) = @_;
9670: my $filename = $user."savedfiles";
9671: my @return_files;
9672: my $path_part;
1.1117 foxr 9673: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9674: while (my $line = <IN>) {
1.572 banghart 9675: #ok, I know it's clunky, but I want it to work
1.800 albertel 9676: my @paths_and_file = split(m|/|, $line);
9677: my $file_part = pop(@paths_and_file);
9678: chomp($file_part);
9679: my $path_part = join('/', @paths_and_file);
1.572 banghart 9680: $path_part .= '/';
9681: my $path_and_file = $path_part.$file_part;
9682: if ($path_part ne $path) {
1.800 albertel 9683: push(@return_files, ($path_and_file));
1.572 banghart 9684: }
9685: }
1.800 albertel 9686: close(OUT);
1.574 banghart 9687: return (@return_files);
1.572 banghart 9688: }
9689:
1.1273 raeburn 9690: #------------------------------Submitted/Handedback Portfolio Files Versioning
9691:
9692: sub portfiles_versioning {
9693: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9694: my $portfolio_root = '/userfiles/portfolio';
9695: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9696: foreach my $file (@{$portfiles}) {
9697: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9698: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9699: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9700: my $getpropath = 1;
9701: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9702: $stu_name,$getpropath);
9703: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9704: my $new_answer =
9705: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9706: if ($new_answer ne 'problem getting file') {
9707: push(@{$versioned_portfiles}, $directory.$new_answer);
9708: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9709: [$symb,$env{'request.course.id'},'graded']);
9710: }
9711: }
9712: }
9713:
9714: sub get_next_version {
9715: my ($answer_name, $answer_ext, $dir_list) = @_;
9716: my $version;
9717: if (ref($dir_list) eq 'ARRAY') {
9718: foreach my $row (@{$dir_list}) {
9719: my ($file) = split(/\&/,$row,2);
9720: my ($file_name,$file_version,$file_ext) =
9721: &file_name_version_ext($file);
9722: if (($file_name eq $answer_name) &&
9723: ($file_ext eq $answer_ext)) {
9724: # gets here if filename and extension match,
9725: # regardless of version
9726: if ($file_version ne '') {
9727: # a versioned file is found so save it for later
9728: if ($file_version > $version) {
9729: $version = $file_version;
9730: }
9731: }
9732: }
9733: }
9734: }
9735: $version ++;
9736: return($version);
9737: }
9738:
9739: sub version_selected_portfile {
9740: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
9741: my ($answer_name,$answer_ver,$answer_ext) =
9742: &file_name_version_ext($file_name);
9743: my $new_answer;
9744: $env{'form.copy'} =
9745: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
9746: if($env{'form.copy'} eq '-1') {
9747: $new_answer = 'problem getting file';
9748: } else {
9749: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
9750: my $copy_result =
9751: &finishuserfileupload($stu_name,$domain,'copy',
9752: '/portfolio'.$directory.$new_answer);
9753: }
9754: undef($env{'form.copy'});
9755: return ($new_answer);
9756: }
9757:
9758: sub file_name_version_ext {
9759: my ($file)=@_;
9760: my @file_parts = split(/\./, $file);
9761: my ($name,$version,$ext);
9762: if (@file_parts > 1) {
9763: $ext=pop(@file_parts);
9764: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
9765: $version=pop(@file_parts);
9766: }
9767: $name=join('.',@file_parts);
9768: } else {
9769: $name=join('.',@file_parts);
9770: }
9771: return($name,$version,$ext);
9772: }
9773:
1.745 raeburn 9774: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9775:
1.745 raeburn 9776: sub get_portfile_permissions {
9777: my ($domain,$user) = @_;
1.613 albertel 9778: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9779: my ($tmp)=keys(%current_permissions);
9780: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9781: return \%current_permissions;
9782: }
9783:
9784: #---------------------------------------------Get portfolio file access controls
9785:
1.749 raeburn 9786: sub get_access_controls {
1.745 raeburn 9787: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9788: my %access;
9789: my $real_file = $file;
9790: $file =~ s/\.meta$//;
1.745 raeburn 9791: if (defined($file)) {
1.749 raeburn 9792: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9793: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9794: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9795: }
9796: }
1.745 raeburn 9797: } else {
1.749 raeburn 9798: foreach my $key (keys(%{$current_permissions})) {
9799: if ($key =~ /\0accesscontrol$/) {
9800: if (defined($group)) {
9801: if ($key !~ m-^\Q$group\E/-) {
9802: next;
9803: }
9804: }
9805: my ($fullpath) = split(/\0/,$key);
9806: if (ref($$current_permissions{$key}) eq 'HASH') {
9807: foreach my $control (keys(%{$$current_permissions{$key}})) {
9808: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9809: }
9810: }
9811: }
9812: }
9813: }
9814: return %access;
9815: }
9816:
9817: sub modify_access_controls {
9818: my ($file_name,$changes,$domain,$user)=@_;
9819: my ($outcome,$deloutcome);
9820: my %store_permissions;
9821: my %new_values;
9822: my %new_control;
9823: my %translation;
9824: my @deletions = ();
9825: my $now = time;
9826: if (exists($$changes{'activate'})) {
9827: if (ref($$changes{'activate'}) eq 'HASH') {
9828: my @newitems = sort(keys(%{$$changes{'activate'}}));
9829: my $numnew = scalar(@newitems);
9830: for (my $i=0; $i<$numnew; $i++) {
9831: my $newkey = $newitems[$i];
9832: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9833: if ($newkey =~ /^\d+:/) {
9834: $newkey =~ s/^(\d+)/$newid/;
9835: $translation{$1} = $newid;
9836: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9837: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9838: $translation{$1} = $newid;
9839: }
1.749 raeburn 9840: $new_values{$file_name."\0".$newkey} =
9841: $$changes{'activate'}{$newitems[$i]};
9842: $new_control{$newkey} = $now;
9843: }
9844: }
9845: }
9846: my %todelete;
9847: my %changed_items;
9848: foreach my $action ('delete','update') {
9849: if (exists($$changes{$action})) {
9850: if (ref($$changes{$action}) eq 'HASH') {
9851: foreach my $key (keys(%{$$changes{$action}})) {
9852: my ($itemnum) = ($key =~ /^([^:]+):/);
9853: if ($action eq 'delete') {
9854: $todelete{$itemnum} = 1;
9855: } else {
9856: $changed_items{$itemnum} = $key;
9857: }
9858: }
1.745 raeburn 9859: }
9860: }
1.749 raeburn 9861: }
9862: # get lock on access controls for file.
9863: my $lockhash = {
9864: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9865: ':'.$env{'user.domain'},
9866: };
9867: my $tries = 0;
9868: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9869:
1.1288 damieng 9870: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 9871: $tries ++;
1.1289 damieng 9872: sleep(0.1);
1.749 raeburn 9873: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9874: }
9875: if ($gotlock eq 'ok') {
9876: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9877: my ($tmp)=keys(%curr_permissions);
9878: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9879: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9880: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9881: if (ref($curr_controls) eq 'HASH') {
9882: foreach my $control_item (keys(%{$curr_controls})) {
9883: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9884: if (defined($todelete{$itemnum})) {
9885: push(@deletions,$file_name."\0".$control_item);
9886: } else {
9887: if (defined($changed_items{$itemnum})) {
9888: $new_control{$changed_items{$itemnum}} = $now;
9889: push(@deletions,$file_name."\0".$control_item);
9890: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9891: } else {
9892: $new_control{$control_item} = $$curr_controls{$control_item};
9893: }
9894: }
1.745 raeburn 9895: }
9896: }
9897: }
1.970 raeburn 9898: my ($group);
9899: if (&is_course($domain,$user)) {
9900: ($group,my $file) = split(/\//,$file_name,2);
9901: }
1.749 raeburn 9902: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9903: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9904: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9905: # remove lock
9906: my @del_lock = ($file_name."\0".'locked_access_records');
9907: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9908: my $sqlresult =
1.970 raeburn 9909: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9910: $group);
1.749 raeburn 9911: } else {
9912: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9913: }
1.749 raeburn 9914: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9915: }
9916:
1.827 raeburn 9917: sub make_public_indefinitely {
1.1271 raeburn 9918: my (@requrl) = @_;
9919: return &automated_portfile_access('public',\@requrl);
9920: }
9921:
9922: sub automated_portfile_access {
9923: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 9924: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
9925: return 'invalid';
9926: }
1.1271 raeburn 9927: my %urls;
9928: if (ref($addsref) eq 'ARRAY') {
9929: foreach my $requrl (@{$addsref}) {
9930: if (&is_portfolio_url($requrl)) {
9931: unless (exists($urls{$requrl})) {
9932: $urls{$requrl} = 'add';
9933: }
9934: }
9935: }
9936: }
9937: if (ref($delsref) eq 'ARRAY') {
9938: foreach my $requrl (@{$delsref}) {
9939: if (&is_portfolio_url($requrl)) {
9940: unless (exists($urls{$requrl})) {
9941: $urls{$requrl} = 'delete';
9942: }
9943: }
9944: }
9945: }
9946: unless (keys(%urls)) {
9947: return 'invalid';
9948: }
9949: my $ip;
9950: if ($accesstype eq 'ip') {
9951: if (ref($info) eq 'HASH') {
9952: if ($info->{'ip'} ne '') {
9953: $ip = $info->{'ip'};
9954: }
9955: }
9956: if ($ip eq '') {
9957: return 'invalid';
9958: }
9959: }
9960: my $errors;
1.827 raeburn 9961: my $now = time;
1.1271 raeburn 9962: my %current_perms;
9963: foreach my $requrl (sort(keys(%urls))) {
9964: my $action;
9965: if ($urls{$requrl} eq 'add') {
9966: $action = 'activate';
9967: } else {
9968: $action = 'none';
9969: }
9970: my $aclnum = 0;
1.827 raeburn 9971: my (undef,$udom,$unum,$file_name,$group) =
9972: &parse_portfolio_url($requrl);
1.1271 raeburn 9973: unless (exists($current_perms{$unum.':'.$udom})) {
9974: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
9975: }
9976: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 9977: $group,$file_name);
9978: foreach my $key (keys(%{$access_controls{$file_name}})) {
9979: my ($num,$scope,$end,$start) =
9980: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 9981: if ($scope eq $accesstype) {
9982: if (($start <= $now) && ($end == 0)) {
9983: if ($accesstype eq 'ip') {
9984: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
9985: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
9986: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
9987: if ($urls{$requrl} eq 'add') {
9988: $action = 'none';
9989: last;
9990: } else {
9991: $action = 'delete';
9992: $aclnum = $num;
9993: last;
9994: }
9995: }
9996: }
9997: }
9998: } elsif ($accesstype eq 'public') {
9999: if ($urls{$requrl} eq 'add') {
10000: $action = 'none';
10001: last;
10002: } else {
10003: $action = 'delete';
10004: $aclnum = $num;
10005: last;
10006: }
10007: }
10008: } elsif ($accesstype eq 'public') {
1.827 raeburn 10009: $action = 'update';
10010: $aclnum = $num;
1.1271 raeburn 10011: last;
1.827 raeburn 10012: }
10013: }
10014: }
10015: if ($action eq 'none') {
1.1271 raeburn 10016: next;
1.827 raeburn 10017: } else {
10018: my %changes;
10019: my $newend = 0;
10020: my $newstart = $now;
1.1271 raeburn 10021: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 10022: $changes{$action}{$newkey} = {
1.1271 raeburn 10023: type => $accesstype,
1.827 raeburn 10024: time => {
10025: start => $newstart,
10026: end => $newend,
10027: },
10028: };
1.1271 raeburn 10029: if ($accesstype eq 'ip') {
10030: $changes{$action}{$newkey}{'ip'} = [$ip];
10031: }
1.827 raeburn 10032: my ($outcome,$deloutcome,$new_values,$translation) =
10033: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 10034: unless ($outcome eq 'ok') {
10035: $errors .= $outcome.' ';
10036: }
1.827 raeburn 10037: }
1.1271 raeburn 10038: }
10039: if ($errors) {
10040: $errors =~ s/\s$//;
10041: return $errors;
1.827 raeburn 10042: } else {
1.1271 raeburn 10043: return 'ok';
1.827 raeburn 10044: }
10045: }
10046:
1.745 raeburn 10047: #------------------------------------------------------Get Marked as Read Only
10048:
10049: sub get_marked_as_readonly {
10050: my ($domain,$user,$what,$group) = @_;
10051: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10052: my @readonly_files;
1.629 banghart 10053: my $cmp1=$what;
10054: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10055: while (my ($file_name,$value) = each(%{$current_permissions})) {
10056: if (defined($group)) {
10057: if ($file_name !~ m-^\Q$group\E/-) {
10058: next;
10059: }
10060: }
1.561 banghart 10061: if (ref($value) eq "ARRAY"){
10062: foreach my $stored_what (@{$value}) {
1.629 banghart 10063: my $cmp2=$stored_what;
1.759 albertel 10064: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10065: $cmp2=join('',@{$stored_what});
1.745 raeburn 10066: }
1.629 banghart 10067: if ($cmp1 eq $cmp2) {
1.561 banghart 10068: push(@readonly_files, $file_name);
1.745 raeburn 10069: last;
1.563 banghart 10070: } elsif (!defined($what)) {
10071: push(@readonly_files, $file_name);
1.745 raeburn 10072: last;
1.561 banghart 10073: }
10074: }
1.745 raeburn 10075: }
1.561 banghart 10076: }
10077: return @readonly_files;
10078: }
1.577 banghart 10079: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10080:
1.577 banghart 10081: sub get_marked_as_readonly_hash {
1.745 raeburn 10082: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10083: my %readonly_files;
1.745 raeburn 10084: while (my ($file_name,$value) = each(%{$current_permissions})) {
10085: if (defined($group)) {
10086: if ($file_name !~ m-^\Q$group\E/-) {
10087: next;
10088: }
10089: }
1.577 banghart 10090: if (ref($value) eq "ARRAY"){
10091: foreach my $stored_what (@{$value}) {
1.745 raeburn 10092: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10093: foreach my $lock_descriptor(@{$stored_what}) {
10094: if ($lock_descriptor eq 'graded') {
10095: $readonly_files{$file_name} = 'graded';
10096: } elsif ($lock_descriptor eq 'handback') {
10097: $readonly_files{$file_name} = 'handback';
10098: } else {
10099: if (!exists($readonly_files{$file_name})) {
10100: $readonly_files{$file_name} = 'locked';
10101: }
10102: }
1.745 raeburn 10103: }
1.750 banghart 10104: }
1.577 banghart 10105: }
10106: }
10107: }
10108: return %readonly_files;
10109: }
1.559 banghart 10110: # ------------------------------------------------------------ Unmark as Read Only
10111:
10112: sub unmark_as_readonly {
1.629 banghart 10113: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10114: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10115: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10116: $file_name = &declutter_portfile($file_name);
1.634 albertel 10117: my $symb_crs = $what;
10118: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10119: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10120: my ($tmp)=keys(%current_permissions);
10121: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10122: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10123: foreach my $file (@readonly_files) {
1.759 albertel 10124: my $clean_file = &declutter_portfile($file);
10125: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10126: my $current_locks = $current_permissions{$file};
1.563 banghart 10127: my @new_locks;
10128: my @del_keys;
10129: if (ref($current_locks) eq "ARRAY"){
10130: foreach my $locker (@{$current_locks}) {
1.632 albertel 10131: my $compare=$locker;
1.749 raeburn 10132: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10133: $compare=join('',@{$locker});
1.746 raeburn 10134: if ($compare ne $symb_crs) {
10135: push(@new_locks, $locker);
10136: }
1.563 banghart 10137: }
10138: }
1.650 albertel 10139: if (scalar(@new_locks) > 0) {
1.563 banghart 10140: $current_permissions{$file} = \@new_locks;
10141: } else {
10142: push(@del_keys, $file);
1.613 albertel 10143: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10144: delete($current_permissions{$file});
1.563 banghart 10145: }
10146: }
1.561 banghart 10147: }
1.613 albertel 10148: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10149: return;
10150: }
1.512 banghart 10151:
1.17 www 10152: # ------------------------------------------------------------ Directory lister
10153:
10154: sub dirlist {
1.955 raeburn 10155: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10156: $uri=~s/^\///;
10157: $uri=~s/\/$//;
1.253 stredwic 10158: my ($udom, $uname);
1.955 raeburn 10159: if ($getuserdir) {
1.253 stredwic 10160: $udom = $userdomain;
10161: $uname = $username;
1.955 raeburn 10162: } else {
10163: (undef,$udom,$uname)=split(/\//,$uri);
10164: if(defined($userdomain)) {
10165: $udom = $userdomain;
10166: }
10167: if(defined($username)) {
10168: $uname = $username;
10169: }
1.253 stredwic 10170: }
1.955 raeburn 10171: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10172:
1.955 raeburn 10173: $dirRoot = $perlvar{'lonDocRoot'};
10174: if (defined($getpropath)) {
10175: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10176: $dirRoot =~ s/\/$//;
1.955 raeburn 10177: } elsif (defined($getuserdir)) {
10178: my $subdir=$uname.'__';
10179: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10180: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10181: ."/$udom/$subdir/$uname";
10182: } elsif (defined($alternateRoot)) {
10183: $dirRoot = $alternateRoot;
1.751 banghart 10184: }
1.253 stredwic 10185:
10186: if($udom) {
10187: if($uname) {
1.1135 raeburn 10188: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10189: if ($uhome eq 'no_host') {
10190: return ([],'no_host');
10191: }
1.955 raeburn 10192: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10193: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10194: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10195: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10196: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10197: } else {
10198: @listing_results = map { &unescape($_); } split(/:/,$listing);
10199: }
1.605 matthew 10200: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10201: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10202: @listing_results = split(/:/,$listing);
10203: } else {
10204: @listing_results = map { &unescape($_); } split(/:/,$listing);
10205: }
1.1135 raeburn 10206: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10207: ($listing eq 'rejected') || ($listing eq 'refused') ||
10208: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10209: return ([],$listing);
10210: } else {
10211: return (\@listing_results);
1.1135 raeburn 10212: }
1.955 raeburn 10213: } elsif(!$alternateRoot) {
1.1136 raeburn 10214: my (%allusers,%listerror);
1.841 albertel 10215: my %servers = &get_servers($udom,'library');
1.955 raeburn 10216: foreach my $tryserver (keys(%servers)) {
10217: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10218: &escape($udom),$tryserver);
10219: if ($listing eq 'unknown_cmd') {
10220: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10221: $udom, $tryserver);
10222: } else {
10223: @listing_results = map { &unescape($_); } split(/:/,$listing);
10224: }
1.841 albertel 10225: if ($listing eq 'unknown_cmd') {
10226: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10227: $udom, $tryserver);
10228: @listing_results = split(/:/,$listing);
10229: } else {
10230: @listing_results =
10231: map { &unescape($_); } split(/:/,$listing);
10232: }
1.1136 raeburn 10233: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10234: ($listing eq 'rejected') || ($listing eq 'refused') ||
10235: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10236: $listerror{$tryserver} = $listing;
10237: } else {
1.841 albertel 10238: foreach my $line (@listing_results) {
10239: my ($entry) = split(/&/,$line,2);
10240: $allusers{$entry} = 1;
10241: }
10242: }
1.253 stredwic 10243: }
1.1136 raeburn 10244: my @alluserslist=();
1.800 albertel 10245: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10246: push(@alluserslist,$user.'&user');
1.253 stredwic 10247: }
1.1318 droeschl 10248:
10249: if (!%listerror) {
10250: # no errors
10251: return (\@alluserslist);
10252: } elsif (scalar(keys(%servers)) == 1) {
10253: # one library server, one error
10254: my ($key) = keys(%listerror);
10255: return (\@alluserslist, $listerror{$key});
10256: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10257: # con_lost indicates that we might miss data from at least one
10258: # library server
10259: return (\@alluserslist, 'con_lost');
10260: } else {
10261: # multiple library servers and no con_lost -> data should be
10262: # complete.
10263: return (\@alluserslist);
10264: }
10265:
1.253 stredwic 10266: } else {
1.1136 raeburn 10267: return ([],'missing username');
1.253 stredwic 10268: }
1.955 raeburn 10269: } elsif(!defined($getpropath)) {
1.1136 raeburn 10270: my $path = $perlvar{'lonDocRoot'}.'/res/';
10271: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10272: return (\@all_domains);
1.955 raeburn 10273: } else {
1.1136 raeburn 10274: return ([],'missing domain');
1.275 stredwic 10275: }
10276: }
10277:
10278: # --------------------------------------------- GetFileTimestamp
10279: # This function utilizes dirlist and returns the date stamp for
10280: # when it was last modified. It will also return an error of -1
10281: # if an error occurs
10282:
10283: sub GetFileTimestamp {
1.955 raeburn 10284: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10285: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10286: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10287: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10288: undef,$getuserdir);
10289: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10290: return -1;
10291: }
10292: if (ref($fileref) eq 'ARRAY') {
10293: my @stats = split('&',$fileref->[0]);
1.375 matthew 10294: # @stats contains first the filename, then the stat output
10295: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10296: } else {
10297: return -1;
1.253 stredwic 10298: }
1.26 www 10299: }
10300:
1.712 albertel 10301: sub stat_file {
10302: my ($uri) = @_;
1.787 albertel 10303: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10304:
1.955 raeburn 10305: my ($udom,$uname,$file);
1.712 albertel 10306: if ($uri =~ m-^/(uploaded|editupload)/-) {
10307: ($udom,$uname,$file) =
1.811 albertel 10308: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10309: $file = 'userfiles/'.$file;
10310: }
10311: if ($uri =~ m-^/res/-) {
10312: ($udom,$uname) =
1.807 albertel 10313: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10314: $file = $uri;
10315: }
10316:
10317: if (!$udom || !$uname || !$file) {
10318: # unable to handle the uri
10319: return ();
10320: }
1.956 raeburn 10321: my $getpropath;
10322: if ($file =~ /^userfiles\//) {
10323: $getpropath = 1;
10324: }
1.1136 raeburn 10325: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10326: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10327: return ();
10328: } else {
10329: if (ref($listref) eq 'ARRAY') {
10330: my @stats = split('&',$listref->[0]);
10331: shift(@stats); #filename is first
10332: return @stats;
10333: }
1.712 albertel 10334: }
10335: return ();
10336: }
10337:
1.1313 raeburn 10338: # --------------------------------------------------------- recursedirs
10339: # Recursive function to traverse either a specific user's Authoring Space
10340: # or corresponding Published Resource Space, and populate the hash ref:
10341: # $dirhashref with URLs of all directories, and if $filehashref hash
10342: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10343: # or .rights files in resource space, and .meta, .save, .log, and .bak
10344: # files in Authoring Space.
10345: #
10346: # Inputs:
10347: #
10348: # $is_home - true if current server is home server for user's space
10349: # $context - either: priv, or res respectively for Authoring or Resource Space.
10350: # $docroot - Document root (i.e., /home/httpd/html
10351: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10352: # $relpath - Current path (relative to top level).
10353: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10354: # $filehashref - reference to hash to populate with URLs of files (Optional)
10355: #
10356: # Returns: nothing
10357: #
10358: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10359: #
10360: # Currently used by interface/londocs.pm to create linked select boxes for
10361: # directory and filename to import a Course "Author" resource into a course, and
10362: # also to create linked select boxes for Authoring Space and Directory to choose
10363: # save location for creation of a new "standard" problem from the Course Editor.
10364: #
10365:
10366: sub recursedirs {
10367: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10368: return unless (ref($dirhashref) eq 'HASH');
10369: my $currpath = $docroot.$toppath;
10370: if ($relpath) {
10371: $currpath .= "/$relpath";
10372: }
10373: my $savefile;
10374: if (ref($filehashref)) {
10375: $savefile = 1;
10376: }
10377: if ($is_home) {
10378: if (opendir(my $dirh,$currpath)) {
10379: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10380: next if ($item eq '');
10381: if (-d "$currpath/$item") {
10382: my $newpath;
10383: if ($relpath) {
10384: $newpath = "$relpath/$item";
10385: } else {
10386: $newpath = $item;
10387: }
10388: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10389: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10390: } elsif ($savefile) {
10391: if ($context eq 'priv') {
10392: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10393: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10394: }
10395: } else {
10396: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10397: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10398: }
10399: }
10400: }
10401: }
10402: closedir($dirh);
10403: }
10404: } else {
10405: my ($dirlistref,$listerror) =
10406: &dirlist($toppath.$relpath);
10407: my @dir_lines;
10408: my $dirptr=16384;
10409: if (ref($dirlistref) eq 'ARRAY') {
10410: foreach my $dir_line (sort
10411: {
10412: my ($afile)=split('&',$a,2);
10413: my ($bfile)=split('&',$b,2);
10414: return (lc($afile) cmp lc($bfile));
10415: } (@{$dirlistref})) {
10416: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10417: split(/\&/,$dir_line,16);
10418: $item =~ s/\s+$//;
10419: next if (($item =~ /^\.\.?$/) || ($obs));
10420: if ($dirptr&$testdir) {
10421: my $newpath;
10422: if ($relpath) {
10423: $newpath = "$relpath/$item";
10424: } else {
10425: $relpath = '/';
10426: $newpath = $item;
10427: }
10428: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10429: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10430: } elsif ($savefile) {
10431: if ($context eq 'priv') {
10432: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10433: $filehashref->{$relpath}{$item} = 1;
10434: }
10435: } else {
10436: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10437: $filehashref->{$relpath}{$item} = 1;
10438: }
10439: }
10440: }
10441: }
10442: }
10443: }
10444: return;
10445: }
10446:
1.26 www 10447: # -------------------------------------------------------- Value of a Condition
10448:
1.713 albertel 10449: # gets the value of a specific preevaluated condition
10450: # stored in the string $env{user.state.<cid>}
10451: # or looks up a condition reference in the bighash and if if hasn't
10452: # already been evaluated recurses into docondval to get the value of
10453: # the condition, then memoizing it to
10454: # $env{user.state.<cid>.<condition>}
1.40 www 10455: sub directcondval {
10456: my $number=shift;
1.620 albertel 10457: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10458: &Apache::lonuserstate::evalstate();
10459: }
1.713 albertel 10460: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10461: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10462: } elsif ($number =~ /^_/) {
10463: my $sub_condition;
10464: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10465: &GDBM_READER(),0640)) {
10466: $sub_condition=$bighash{'conditions'.$number};
10467: untie(%bighash);
10468: }
10469: my $value = &docondval($sub_condition);
1.949 raeburn 10470: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10471: return $value;
10472: }
1.620 albertel 10473: if ($env{'user.state.'.$env{'request.course.id'}}) {
10474: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10475: } else {
10476: return 2;
10477: }
10478: }
10479:
1.713 albertel 10480: # get the collection of conditions for this resource
1.26 www 10481: sub condval {
10482: my $condidx=shift;
1.54 www 10483: my $allpathcond='';
1.713 albertel 10484: foreach my $cond (split(/\|/,$condidx)) {
10485: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10486: $allpathcond.=
10487: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10488: }
1.191 harris41 10489: }
1.54 www 10490: $allpathcond=~s/\|$//;
1.713 albertel 10491: return &docondval($allpathcond);
10492: }
10493:
10494: #evaluates an expression of conditions
10495: sub docondval {
10496: my ($allpathcond) = @_;
10497: my $result=0;
10498: if ($env{'request.course.id'}
10499: && defined($allpathcond)) {
10500: my $operand='|';
10501: my @stack;
10502: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10503: if ($chunk eq '(') {
10504: push @stack,($operand,$result);
10505: } elsif ($chunk eq ')') {
10506: my $before=pop @stack;
10507: if (pop @stack eq '&') {
10508: $result=$result>$before?$before:$result;
10509: } else {
10510: $result=$result>$before?$result:$before;
10511: }
10512: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10513: $operand=$chunk;
10514: } else {
10515: my $new=directcondval($chunk);
10516: if ($operand eq '&') {
10517: $result=$result>$new?$new:$result;
10518: } else {
10519: $result=$result>$new?$result:$new;
10520: }
10521: }
10522: }
1.26 www 10523: }
10524: return $result;
1.421 albertel 10525: }
10526:
10527: # ---------------------------------------------------- Devalidate courseresdata
10528:
10529: sub devalidatecourseresdata {
10530: my ($coursenum,$coursedomain)=@_;
10531: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10532: &devalidate_cache_new('courseres',$hashid);
1.28 www 10533: }
10534:
1.763 www 10535:
1.200 www 10536: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10537: #
10538: # Parameters:
10539: # $coursenum - Number of the course.
10540: # $coursedomain - Domain at which the course was created.
10541: # Returns:
10542: # A hash of the course parameters along (I think) with timestamps
10543: # and version info.
1.877 foxr 10544:
1.624 albertel 10545: sub get_courseresdata {
10546: my ($coursenum,$coursedomain)=@_;
1.200 www 10547: my $coursehom=&homeserver($coursenum,$coursedomain);
10548: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10549: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10550: my %dumpreply;
1.417 albertel 10551: unless (defined($cached)) {
1.624 albertel 10552: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10553: $result=\%dumpreply;
1.251 albertel 10554: my ($tmp) = keys(%dumpreply);
10555: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10556: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10557: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10558: return $tmp;
1.416 albertel 10559: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10560: $result=undef;
1.599 albertel 10561: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10562: }
10563: }
1.624 albertel 10564: return $result;
10565: }
10566:
1.633 albertel 10567: sub devalidateuserresdata {
10568: my ($uname,$udom)=@_;
10569: my $hashid="$udom:$uname";
10570: &devalidate_cache_new('userres',$hashid);
10571: }
10572:
1.624 albertel 10573: sub get_userresdata {
10574: my ($uname,$udom)=@_;
10575: #most student don\'t have any data set, check if there is some data
10576: if (&EXT_cache_status($udom,$uname)) { return undef; }
10577:
10578: my $hashid="$udom:$uname";
10579: my ($result,$cached)=&is_cached_new('userres',$hashid);
10580: if (!defined($cached)) {
10581: my %resourcedata=&dump('resourcedata',$udom,$uname);
10582: $result=\%resourcedata;
10583: &do_cache_new('userres',$hashid,$result,600);
10584: }
10585: my ($tmp)=keys(%$result);
10586: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10587: return $result;
10588: }
10589: #error 2 occurs when the .db doesn't exist
10590: if ($tmp!~/error: 2 /) {
1.1294 raeburn 10591: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10592: &logthis("<font color=\"blue\">WARNING:".
10593: " Trying to get resource data for ".
10594: $uname." at ".$udom.": ".
10595: $tmp."</font>");
10596: }
1.624 albertel 10597: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10598: #&EXT_cache_set($udom,$uname);
10599: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10600: undef($tmp); # not really an error so don't send it back
1.624 albertel 10601: }
10602: return $tmp;
10603: }
1.879 foxr 10604: #----------------------------------------------- resdata - return resource data
10605: # Purpose:
10606: # Return resource data for either users or for a course.
10607: # Parameters:
10608: # $name - Course/user name.
10609: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 10610: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 10611: # $mapp - decluttered URL of enclosing map
10612: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
10613: # $recurseup - Ref to array of map URLs, starting with map containing
10614: # $mapp up through hierarchy of nested maps to top level map.
10615: # $courseid - CourseID (first part of param identifier).
10616: # $modifier - Middle part of param identifier.
10617: # $what - Last part of param identifier.
1.879 foxr 10618: # @which - Array of names of resources desired.
10619: # Returns:
10620: # The value of the first reasource in @which that is found in the
10621: # resource hash.
10622: # Exceptional Conditions:
10623: # If the $type passed in is not valid (not the string 'course' or
10624: # 'user', an undefined reference is returned.
10625: # If none of the resources are found, an undef is returned
1.624 albertel 10626: sub resdata {
1.1301 raeburn 10627: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
10628: $modifier,$what,@which)=@_;
1.624 albertel 10629: my $result;
10630: if ($type eq 'course') {
10631: $result=&get_courseresdata($name,$domain);
10632: } elsif ($type eq 'user') {
10633: $result=&get_userresdata($name,$domain);
10634: }
10635: if (!ref($result)) { return $result; }
1.251 albertel 10636: foreach my $item (@which) {
1.1301 raeburn 10637: if ($item->[1] eq 'course') {
10638: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
10639: unless ($$recursed) {
1.1302 raeburn 10640: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 10641: $$recursed = 1;
10642: }
10643: foreach my $item (@${recurseup}) {
10644: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
10645: last if (defined($result->{$norecursechk}));
10646: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
10647: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
10648: }
10649: }
10650: }
10651: if (defined($result->{$item->[0]})) {
1.927 albertel 10652: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10653: }
1.250 albertel 10654: }
1.291 albertel 10655: return undef;
1.200 www 10656: }
10657:
1.1298 raeburn 10658: sub get_domain_ltitools {
10659: my ($cdom) = @_;
10660: my %ltitools;
10661: my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10662: if (defined($cached)) {
10663: if (ref($result) eq 'HASH') {
10664: %ltitools = %{$result};
10665: }
10666: } else {
10667: my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10668: if (ref($domconfig{'ltitools'}) eq 'HASH') {
10669: %ltitools = %{$domconfig{'ltitools'}};
10670: }
10671: my $cachetime = 24*60*60;
10672: &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10673: }
10674: return %ltitools;
10675: }
10676:
1.1236 raeburn 10677: sub get_numsuppfiles {
10678: my ($cnum,$cdom,$ignorecache)=@_;
10679: my $hashid=$cnum.':'.$cdom;
10680: my ($suppcount,$cached);
10681: unless ($ignorecache) {
10682: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10683: }
10684: unless (defined($cached)) {
10685: my $chome=&homeserver($cnum,$cdom);
10686: unless ($chome eq 'no_host') {
10687: ($suppcount,my $errors) = (0,0);
10688: my $suppmap = 'supplemental.sequence';
10689: ($suppcount,$errors) =
10690: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10691: }
10692: &do_cache_new('suppcount',$hashid,$suppcount,600);
10693: }
10694: return $suppcount;
10695: }
10696:
1.379 matthew 10697: #
10698: # EXT resource caching routines
10699: #
10700:
1.1302 raeburn 10701: {
10702: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
10703: #
10704: # The course for which we cache
10705: my $cachedmapkey='';
10706: # The cached recursive maps for this course
10707: my %cachedmaps=();
10708: # When this was last done
10709: my $cachedmaptime='';
10710:
1.379 matthew 10711: sub clear_EXT_cache_status {
1.383 albertel 10712: &delenv('cache.EXT.');
1.379 matthew 10713: }
10714:
10715: sub EXT_cache_status {
10716: my ($target_domain,$target_user) = @_;
1.383 albertel 10717: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10718: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10719: # We know already the user has no data
10720: return 1;
10721: } else {
10722: return 0;
10723: }
10724: }
10725:
10726: sub EXT_cache_set {
10727: my ($target_domain,$target_user) = @_;
1.383 albertel 10728: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10729: #&appenv({$cachename => time});
1.379 matthew 10730: }
10731:
1.28 www 10732: # --------------------------------------------------------- Value of a Variable
1.58 www 10733: sub EXT {
1.715 albertel 10734:
1.1228 raeburn 10735: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10736: unless ($varname) { return ''; }
1.218 albertel 10737: #get real user name/domain, courseid and symb
10738: my $courseid;
1.359 albertel 10739: my $publicuser;
1.427 www 10740: if ($symbparm) {
10741: $symbparm=&get_symb_from_alias($symbparm);
10742: }
1.218 albertel 10743: if (!($uname && $udom)) {
1.790 albertel 10744: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10745: if (!$symbparm) { $symbparm=$cursymb; }
10746: } else {
1.620 albertel 10747: $courseid=$env{'request.course.id'};
1.218 albertel 10748: }
1.48 www 10749: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10750: my $rest;
1.320 albertel 10751: if (defined($therest[0])) {
1.48 www 10752: $rest=join('.',@therest);
10753: } else {
10754: $rest='';
10755: }
1.320 albertel 10756:
1.57 www 10757: my $qualifierrest=$qualifier;
10758: if ($rest) { $qualifierrest.='.'.$rest; }
10759: my $spacequalifierrest=$space;
10760: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10761: if ($realm eq 'user') {
1.48 www 10762: # --------------------------------------------------------------- user.resource
10763: if ($space eq 'resource') {
1.651 albertel 10764: if ( (defined($Apache::lonhomework::parsing_a_problem)
10765: || defined($Apache::lonhomework::parsing_a_task))
10766: &&
1.744 albertel 10767: ($symbparm eq &symbread()) ) {
10768: # if we are in the middle of processing the resource the
10769: # get the value we are planning on committing
10770: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10771: return $Apache::lonhomework::results{$qualifierrest};
10772: } else {
10773: return $Apache::lonhomework::history{$qualifierrest};
10774: }
1.335 albertel 10775: } else {
1.359 albertel 10776: my %restored;
1.620 albertel 10777: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10778: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10779: } else {
10780: %restored=&restore($symbparm,$courseid,$udom,$uname);
10781: }
1.335 albertel 10782: return $restored{$qualifierrest};
10783: }
1.48 www 10784: # ----------------------------------------------------------------- user.access
10785: } elsif ($space eq 'access') {
1.218 albertel 10786: # FIXME - not supporting calls for a specific user
1.48 www 10787: return &allowed($qualifier,$rest);
10788: # ------------------------------------------ user.preferences, user.environment
10789: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10790: if (($uname eq $env{'user.name'}) &&
10791: ($udom eq $env{'user.domain'})) {
10792: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10793: } else {
1.359 albertel 10794: my %returnhash;
10795: if (!$publicuser) {
10796: %returnhash=&userenvironment($udom,$uname,
10797: $qualifierrest);
10798: }
1.218 albertel 10799: return $returnhash{$qualifierrest};
10800: }
1.48 www 10801: # ----------------------------------------------------------------- user.course
10802: } elsif ($space eq 'course') {
1.218 albertel 10803: # FIXME - not supporting calls for a specific user
1.620 albertel 10804: return $env{join('.',('request.course',$qualifier))};
1.48 www 10805: # ------------------------------------------------------------------- user.role
10806: } elsif ($space eq 'role') {
1.218 albertel 10807: # FIXME - not supporting calls for a specific user
1.620 albertel 10808: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10809: if ($qualifier eq 'value') {
10810: return $role;
10811: } elsif ($qualifier eq 'extent') {
10812: return $where;
10813: }
10814: # ----------------------------------------------------------------- user.domain
10815: } elsif ($space eq 'domain') {
1.218 albertel 10816: return $udom;
1.48 www 10817: # ------------------------------------------------------------------- user.name
10818: } elsif ($space eq 'name') {
1.218 albertel 10819: return $uname;
1.48 www 10820: # ---------------------------------------------------- Any other user namespace
1.29 www 10821: } else {
1.359 albertel 10822: my %reply;
10823: if (!$publicuser) {
10824: %reply=&get($space,[$qualifierrest],$udom,$uname);
10825: }
10826: return $reply{$qualifierrest};
1.48 www 10827: }
1.236 www 10828: } elsif ($realm eq 'query') {
10829: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10830: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10831: [$spacequalifierrest]);
1.620 albertel 10832: return $env{'form.'.$spacequalifierrest};
1.236 www 10833: } elsif ($realm eq 'request') {
1.48 www 10834: # ------------------------------------------------------------- request.browser
10835: if ($space eq 'browser') {
1.1145 bisitz 10836: return $env{'browser.'.$qualifier};
1.57 www 10837: # ------------------------------------------------------------ request.filename
10838: } else {
1.620 albertel 10839: return $env{'request.'.$spacequalifierrest};
1.29 www 10840: }
1.28 www 10841: } elsif ($realm eq 'course') {
1.48 www 10842: # ---------------------------------------------------------- course.description
1.620 albertel 10843: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10844: } elsif ($realm eq 'resource') {
1.165 www 10845:
1.620 albertel 10846: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10847: if (!$symbparm) { $symbparm=&symbread(); }
10848: }
1.693 albertel 10849:
1.1232 raeburn 10850: if ($qualifier eq '') {
10851: if ($space eq 'title') {
10852: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10853: return &gettitle($symbparm);
10854: }
1.693 albertel 10855:
1.1232 raeburn 10856: if ($space eq 'map') {
10857: my ($map) = &decode_symb($symbparm);
10858: return &symbread($map);
10859: }
10860: if ($space eq 'maptitle') {
10861: my ($map) = &decode_symb($symbparm);
10862: return &gettitle($map);
10863: }
10864: if ($space eq 'filename') {
10865: if ($symbparm) {
10866: return &clutter((&decode_symb($symbparm))[2]);
10867: }
10868: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10869: }
1.1232 raeburn 10870:
1.1233 raeburn 10871: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10872: if ($space eq 'visibleparts') {
10873: my $navmap = Apache::lonnavmaps::navmap->new();
10874: my $item;
10875: if (ref($navmap)) {
10876: my $res = $navmap->getBySymb($symbparm);
10877: my $parts = $res->parts();
10878: if (ref($parts) eq 'ARRAY') {
10879: $item = join(',',@{$parts});
10880: }
10881: undef($navmap);
1.1232 raeburn 10882: }
1.1233 raeburn 10883: return $item;
1.1232 raeburn 10884: }
10885: }
10886: }
1.693 albertel 10887:
1.1301 raeburn 10888: my ($section, $group, @groups, @recurseup, $recursed);
10889: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 10890: if (($courseid eq '') && ($cid)) {
10891: $courseid = $cid;
10892: }
10893: if (($symbparm && $courseid) &&
10894: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10895:
1.218 albertel 10896: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10897:
1.60 www 10898: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10899: my $symbp=$symbparm;
1.1301 raeburn 10900: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10901: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 10902: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 10903: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 10904: if (($env{'user.name'} eq $uname) &&
10905: ($env{'user.domain'} eq $udom)) {
10906: $section=$env{'request.course.sec'};
1.733 raeburn 10907: @groups = split(/:/,$env{'request.course.groups'});
10908: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10909: } else {
1.539 albertel 10910: if (! defined($usection)) {
1.551 albertel 10911: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10912: } else {
10913: $section = $usection;
10914: }
1.733 raeburn 10915: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10916: }
10917:
10918: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10919: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 10920: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 10921: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10922:
1.593 albertel 10923: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10924: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 10925: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 10926: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10927:
1.60 www 10928: # ----------------------------------------------------------- first, check user
1.624 albertel 10929:
1.1301 raeburn 10930: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
10931: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 10932: ([$courselevelr,'resource'],
10933: [$courselevelm,'map' ],
1.1301 raeburn 10934: [$courseleveli,'map' ],
1.927 albertel 10935: [$courselevel, 'course' ]));
1.931 albertel 10936: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10937:
1.594 albertel 10938: # ------------------------------------------------ second, check some of course
1.684 raeburn 10939: my $coursereply;
1.691 raeburn 10940: if (@groups > 0) {
10941: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 10942: $recurseparm,$mapparm,$spacequalifierrest,
10943: $mapp,\$recursed,\@recurseup);
10944: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10945: }
1.96 www 10946:
1.684 raeburn 10947: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10948: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 10949: 'course',$mapp,\$recursed,\@recurseup,
10950: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 10951: ([$seclevelr, 'resource'],
10952: [$seclevelm, 'map' ],
1.1301 raeburn 10953: [$secleveli, 'map' ],
1.927 albertel 10954: [$seclevel, 'course' ],
10955: [$courselevelr,'resource']));
10956: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10957:
1.60 www 10958: # ------------------------------------------------------ third, check map parms
1.218 albertel 10959: my %parmhash=();
10960: my $thisparm='';
10961: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10962: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10963: &GDBM_READER(),0640)) {
1.218 albertel 10964: $thisparm=$parmhash{$symbparm};
10965: untie(%parmhash);
10966: }
1.927 albertel 10967: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10968: }
1.594 albertel 10969: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 10970:
10971: my $what = $spacequalifierrest;
10972: $what=~s/\./\_/;
1.282 albertel 10973: my $filename;
10974: if (!$symbparm) { $symbparm=&symbread(); }
10975: if ($symbparm) {
1.409 www 10976: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10977: } else {
1.620 albertel 10978: $filename=$env{'request.filename'};
1.282 albertel 10979: }
1.1301 raeburn 10980: my $metadata=&metadata($filename,$what);
1.927 albertel 10981: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301 raeburn 10982: $metadata=&metadata($filename,'parameter_'.$what);
1.927 albertel 10983: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10984:
1.1301 raeburn 10985: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 10986: if ($symbparm && defined($courseid) &&
1.620 albertel 10987: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10988: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10989: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 10990: 'course',$mapp,\$recursed,\@recurseup,
10991: $courseid,'.',$spacequalifierrest,
1.927 albertel 10992: ([$courselevelm,'map' ],
1.1301 raeburn 10993: [$courseleveli,'map' ],
1.927 albertel 10994: [$courselevel, 'course']));
10995: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10996: }
1.145 www 10997: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10998: unless ($space eq '0') {
1.336 albertel 10999: my @parts=split(/_/,$space);
11000: my $id=pop(@parts);
11001: my $part=join('_',@parts);
11002: if ($part eq '') { $part='0'; }
1.927 albertel 11003: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11004: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11005: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11006: }
1.395 albertel 11007: if ($recurse) { return undef; }
11008: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11009: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11010: # ---------------------------------------------------- Any other user namespace
11011: } elsif ($realm eq 'environment') {
11012: # ----------------------------------------------------------------- environment
1.620 albertel 11013: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11014: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11015: } else {
1.770 albertel 11016: if ($uname eq 'anonymous' && $udom eq '') {
11017: return '';
11018: }
1.219 albertel 11019: my %returnhash=&userenvironment($udom,$uname,
11020: $spacequalifierrest);
11021: return $returnhash{$spacequalifierrest};
11022: }
1.28 www 11023: } elsif ($realm eq 'system') {
1.48 www 11024: # ----------------------------------------------------------------- system.time
11025: if ($space eq 'time') {
11026: return time;
11027: }
1.696 albertel 11028: } elsif ($realm eq 'server') {
11029: # ----------------------------------------------------------------- system.time
11030: if ($space eq 'name') {
11031: return $ENV{'SERVER_NAME'};
11032: }
1.28 www 11033: }
1.48 www 11034: return '';
1.61 www 11035: }
11036:
1.927 albertel 11037: sub get_reply {
11038: my ($reply_value) = @_;
1.940 raeburn 11039: if (ref($reply_value) eq 'ARRAY') {
11040: if (wantarray) {
11041: return @$reply_value;
11042: }
11043: return $reply_value->[0];
11044: } else {
11045: return $reply_value;
1.927 albertel 11046: }
11047: }
11048:
1.691 raeburn 11049: sub check_group_parms {
1.1301 raeburn 11050: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11051: $recursed,$recurseupref) = @_;
11052: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11053: [$what,'course']);
11054: my $coursereply;
1.691 raeburn 11055: foreach my $group (@{$groups}) {
1.1301 raeburn 11056: my @groupitems = ();
1.691 raeburn 11057: foreach my $level (@levels) {
1.927 albertel 11058: my $item = $courseid.'.['.$group.'].'.$level->[0];
11059: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11060: }
1.1301 raeburn 11061: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11062: $env{'course.'.$courseid.'.domain'},
11063: 'course',$mapp,$recursed,$recurseupref,
11064: $courseid,'.['.$group.'].',$what,
11065: @groupitems);
11066: last if (defined($coursereply));
1.691 raeburn 11067: }
11068: return $coursereply;
11069: }
11070:
1.1301 raeburn 11071: sub get_map_hierarchy {
1.1302 raeburn 11072: my ($mapname,$courseid) = @_;
11073: my @recurseup = ();
1.1301 raeburn 11074: if ($mapname) {
1.1302 raeburn 11075: if (($cachedmapkey eq $courseid) &&
11076: (abs($cachedmaptime-time)<5)) {
11077: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11078: return @{$cachedmaps{$mapname}};
11079: }
11080: }
1.1301 raeburn 11081: my $navmap = Apache::lonnavmaps::navmap->new();
11082: if (ref($navmap)) {
11083: @recurseup = $navmap->recurseup_maps($mapname);
11084: undef($navmap);
1.1302 raeburn 11085: $cachedmaps{$mapname} = \@recurseup;
11086: $cachedmaptime=time;
11087: $cachedmapkey=$courseid;
1.1301 raeburn 11088: }
11089: }
11090: return @recurseup;
11091: }
11092:
1.1302 raeburn 11093: }
11094:
1.691 raeburn 11095: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11096: my ($courseid,@groups) = @_;
11097: @groups = sort(@groups);
1.691 raeburn 11098: return @groups;
11099: }
11100:
1.395 albertel 11101: sub packages_tab_default {
11102: my ($uri,$varname)=@_;
11103: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11104:
11105: my (@extension,@specifics,$do_default);
11106: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11107: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11108: if ($pack_type eq 'default') {
11109: $do_default=1;
11110: } elsif ($pack_type eq 'extension') {
11111: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11112: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11113: # only look at packages defaults for packages that this id is
1.738 albertel 11114: push(@specifics,[$package,$pack_type,$pack_part]);
11115: }
11116: }
11117: # first look for a package that matches the requested part id
11118: foreach my $package (@specifics) {
11119: my (undef,$pack_type,$pack_part)=@{$package};
11120: next if ($pack_part ne $part);
11121: if (defined($packagetab{"$pack_type&$name&default"})) {
11122: return $packagetab{"$pack_type&$name&default"};
11123: }
11124: }
11125: # look for any possible matching non extension_ package
11126: foreach my $package (@specifics) {
11127: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11128: if (defined($packagetab{"$pack_type&$name&default"})) {
11129: return $packagetab{"$pack_type&$name&default"};
11130: }
1.585 albertel 11131: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11132: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11133: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11134: }
11135: }
1.738 albertel 11136: # look for any posible extension_ match
11137: foreach my $package (@extension) {
11138: my ($package,$pack_type)=@{$package};
11139: if (defined($packagetab{"$pack_type&$name&default"})) {
11140: return $packagetab{"$pack_type&$name&default"};
11141: }
11142: if (defined($packagetab{$package."&$name&default"})) {
11143: return $packagetab{$package."&$name&default"};
11144: }
11145: }
11146: # look for a global default setting
11147: if ($do_default && defined($packagetab{"default&$name&default"})) {
11148: return $packagetab{"default&$name&default"};
11149: }
1.395 albertel 11150: return undef;
11151: }
11152:
1.334 albertel 11153: sub add_prefix_and_part {
11154: my ($prefix,$part)=@_;
11155: my $keyroot;
11156: if (defined($prefix) && $prefix !~ /^__/) {
11157: # prefix that has a part already
11158: $keyroot=$prefix;
11159: } elsif (defined($prefix)) {
11160: # prefix that is missing a part
11161: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11162: } else {
11163: # no prefix at all
11164: if (defined($part)) { $keyroot='_'.$part; }
11165: }
11166: return $keyroot;
11167: }
11168:
1.71 www 11169: # ---------------------------------------------------------------- Get metadata
11170:
1.599 albertel 11171: my %metaentry;
1.1070 www 11172: my %importedpartids;
1.71 www 11173: sub metadata {
1.176 www 11174: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11175: $uri=&declutter($uri);
1.288 albertel 11176: # if it is a non metadata possible uri return quickly
1.529 albertel 11177: if (($uri eq '') ||
11178: (($uri =~ m|^/*adm/|) &&
1.1298 raeburn 11179: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108 raeburn 11180: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11181: return undef;
11182: }
1.1261 raeburn 11183: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11184: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11185: return undef;
1.288 albertel 11186: }
1.73 www 11187: my $filename=$uri;
11188: $uri=~s/\.meta$//;
1.172 www 11189: #
11190: # Is the metadata already cached?
1.177 www 11191: # Look at timestamp of caching
1.172 www 11192: # Everything is cached by the main uri, libraries are never directly cached
11193: #
1.428 albertel 11194: if (!defined($liburi)) {
1.599 albertel 11195: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11196: if (defined($cached)) { return $result->{':'.$what}; }
11197: }
11198: {
1.1069 www 11199: # Imported parts would go here
1.1070 www 11200: my %importedids=();
11201: my @origfileimportpartids=();
1.1069 www 11202: my $importedparts=0;
1.172 www 11203: #
11204: # Is this a recursive call for a library?
11205: #
1.599 albertel 11206: # if (! exists($metacache{$uri})) {
11207: # $metacache{$uri}={};
11208: # }
1.924 albertel 11209: my $cachetime = 60*60;
1.171 www 11210: if ($liburi) {
11211: $liburi=&declutter($liburi);
11212: $filename=$liburi;
1.401 bowersj2 11213: } else {
1.599 albertel 11214: &devalidate_cache_new('meta',$uri);
11215: undef(%metaentry);
1.401 bowersj2 11216: }
1.140 www 11217: my %metathesekeys=();
1.73 www 11218: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11219: my $metastring;
1.1140 www 11220: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11221: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11222: $metastring =
1.929 albertel 11223: &Apache::lonnet::ssi_body($which,
1.924 albertel 11224: ('grade_target' => 'meta'));
11225: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11226: } elsif (($uri !~ m -^(editupload)/-) &&
11227: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11228: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11229: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11230: $metastring=&getfile($file);
1.489 albertel 11231: }
1.208 albertel 11232: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11233: my $token;
1.140 www 11234: undef %metathesekeys;
1.71 www 11235: while ($token=$parser->get_token) {
1.339 albertel 11236: if ($token->[0] eq 'S') {
11237: if (defined($token->[2]->{'package'})) {
1.172 www 11238: #
11239: # This is a package - get package info
11240: #
1.339 albertel 11241: my $package=$token->[2]->{'package'};
11242: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11243: if (defined($token->[2]->{'id'})) {
11244: $keyroot.='_'.$token->[2]->{'id'};
11245: }
1.599 albertel 11246: if ($metaentry{':packages'}) {
11247: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11248: } else {
1.599 albertel 11249: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11250: }
1.736 albertel 11251: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11252: my $part=$keyroot;
11253: $part=~s/^\_//;
1.736 albertel 11254: if ($pack_entry=~/^\Q$package\E\&/ ||
11255: $pack_entry=~/^\Q$package\E_0\&/) {
11256: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11257: # ignore package.tab specified default values
11258: # here &package_tab_default() will fetch those
11259: if ($subp eq 'default') { next; }
1.736 albertel 11260: my $value=$packagetab{$pack_entry};
1.432 albertel 11261: my $unikey;
11262: if ($pack =~ /_0$/) {
11263: $unikey='parameter_0_'.$name;
11264: $part=0;
11265: } else {
11266: $unikey='parameter'.$keyroot.'_'.$name;
11267: }
1.339 albertel 11268: if ($subp eq 'display') {
11269: $value.=' [Part: '.$part.']';
11270: }
1.599 albertel 11271: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11272: $metathesekeys{$unikey}=1;
1.599 albertel 11273: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11274: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11275: }
1.599 albertel 11276: if (defined($metaentry{':'.$unikey.'.default'})) {
11277: $metaentry{':'.$unikey}=
11278: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11279: }
1.339 albertel 11280: }
11281: }
11282: } else {
1.172 www 11283: #
11284: # This is not a package - some other kind of start tag
1.339 albertel 11285: #
11286: my $entry=$token->[1];
1.1068 www 11287: my $unikey='';
1.175 www 11288:
1.339 albertel 11289: if ($entry eq 'import') {
1.175 www 11290: #
11291: # Importing a library here
1.339 albertel 11292: #
1.1067 www 11293: my $location=$parser->get_text('/import');
11294: my $dir=$filename;
11295: $dir=~s|[^/]*$||;
11296: $location=&filelocation($dir,$location);
1.1069 www 11297:
1.1068 www 11298: my $importmode=$token->[2]->{'importmode'};
11299: if ($importmode eq 'problem') {
1.1069 www 11300: # Import as problem/response
1.1068 www 11301: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11302: } elsif ($importmode eq 'part') {
11303: # Import as part(s)
1.1069 www 11304: $importedparts=1;
11305: # We need to get the original file and the imported file to get the part order correct
11306: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11307: # Load and inspect original file
1.1070 www 11308: if ($#origfileimportpartids<0) {
11309: undef(%importedpartids);
11310: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11311: my $origfile=&getfile($origfilelocation);
11312: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11313: }
11314:
1.1069 www 11315: # Load and inspect imported file
11316: my $impfile=&getfile($location);
11317: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11318: if ($#impfilepartids>=0) {
11319: # This problem had parts
1.1070 www 11320: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11321: } else {
11322: # Importing by turning a single problem into a problem part
11323: # It gets the import-tags ID as part-ID
11324: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11325: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11326: }
1.1068 www 11327: } else {
11328: # Normal import
11329: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11330: if (defined($token->[2]->{'id'})) {
11331: $unikey.='_'.$token->[2]->{'id'};
11332: }
1.1067 www 11333: }
11334:
1.339 albertel 11335: if ($depthcount<20) {
1.736 albertel 11336: my $metadata =
11337: &metadata($uri,'keys', $location,$unikey,
11338: $depthcount+1);
11339: foreach my $meta (split(',',$metadata)) {
11340: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11341: $metathesekeys{$meta}=1;
1.339 albertel 11342: }
1.1068 www 11343:
11344: }
1.1067 www 11345: } else {
11346: #
11347: # Not importing, some other kind of non-package, non-library start tag
11348: #
11349: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11350: if (defined($token->[2]->{'id'})) {
11351: $unikey.='_'.$token->[2]->{'id'};
11352: }
1.339 albertel 11353: if (defined($token->[2]->{'name'})) {
11354: $unikey.='_'.$token->[2]->{'name'};
11355: }
11356: $metathesekeys{$unikey}=1;
1.736 albertel 11357: foreach my $param (@{$token->[3]}) {
11358: $metaentry{':'.$unikey.'.'.$param} =
11359: $token->[2]->{$param};
1.339 albertel 11360: }
11361: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11362: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11363: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11364: # only ws inside the tag, and not in default, so use default
11365: # as value
1.599 albertel 11366: $metaentry{':'.$unikey}=$default;
1.908 albertel 11367: } elsif ( $internaltext =~ /\S/ ) {
11368: # something interesting inside the tag
11369: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11370: } else {
1.908 albertel 11371: # no interesting values, don't set a default
1.339 albertel 11372: }
1.172 www 11373: # end of not-a-package not-a-library import
1.339 albertel 11374: }
1.172 www 11375: # end of not-a-package start tag
1.339 albertel 11376: }
1.172 www 11377: # the next is the end of "start tag"
1.339 albertel 11378: }
11379: }
1.483 albertel 11380: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11381: $extension = lc($extension);
11382: if ($extension eq 'htm') { $extension='html'; }
11383:
1.737 albertel 11384: foreach my $key (keys(%packagetab)) {
1.483 albertel 11385: #no specific packages #how's our extension
11386: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11387: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11388: \%metathesekeys);
11389: }
1.883 albertel 11390:
11391: if (!exists($metaentry{':packages'})
11392: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11393: foreach my $key (keys(%packagetab)) {
1.483 albertel 11394: #no specific packages well let's get default then
11395: if ($key!~/^default&/) { next; }
1.488 albertel 11396: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11397: \%metathesekeys);
11398: }
11399: }
1.338 www 11400: # are there custom rights to evaluate
1.599 albertel 11401: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11402:
1.338 www 11403: #
11404: # Importing a rights file here
1.339 albertel 11405: #
11406: unless ($depthcount) {
1.599 albertel 11407: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11408: my $dir=$filename;
11409: $dir=~s|[^/]*$||;
11410: $location=&filelocation($dir,$location);
1.736 albertel 11411: my $rights_metadata =
11412: &metadata($uri,'keys',$location,'_rights',
11413: $depthcount+1);
11414: foreach my $rights (split(',',$rights_metadata)) {
11415: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11416: $metathesekeys{$rights}=1;
1.339 albertel 11417: }
11418: }
11419: }
1.737 albertel 11420: # uniqifiy package listing
11421: my %seen;
11422: my @uniq_packages =
11423: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11424: $metaentry{':packages'} = join(',',@uniq_packages);
11425:
1.1070 www 11426: if ($importedparts) {
11427: # We had imported parts and need to rebuild partorder
11428: $metaentry{':partorder'}='';
11429: $metathesekeys{'partorder'}=1;
11430: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11431: if ($origfileimportpartids[$index] eq 'part') {
11432: # original part, part of the problem
11433: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11434: } else {
11435: # we have imported parts at this position
11436: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11437: }
11438: }
11439: $metaentry{':partorder'}=~s/^\,//;
11440: }
11441:
1.737 albertel 11442: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11443: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 11444: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11445: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11446: # this is the end of "was not already recently cached
1.71 www 11447: }
1.599 albertel 11448: return $metaentry{':'.$what};
1.261 albertel 11449: }
11450:
1.488 albertel 11451: sub metadata_create_package_def {
1.483 albertel 11452: my ($uri,$key,$package,$metathesekeys)=@_;
11453: my ($pack,$name,$subp)=split(/\&/,$key);
11454: if ($subp eq 'default') { next; }
11455:
1.599 albertel 11456: if (defined($metaentry{':packages'})) {
11457: $metaentry{':packages'}.=','.$package;
1.483 albertel 11458: } else {
1.599 albertel 11459: $metaentry{':packages'}=$package;
1.483 albertel 11460: }
11461: my $value=$packagetab{$key};
11462: my $unikey;
11463: $unikey='parameter_0_'.$name;
1.599 albertel 11464: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11465: $$metathesekeys{$unikey}=1;
1.599 albertel 11466: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11467: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11468: }
1.599 albertel 11469: if (defined($metaentry{':'.$unikey.'.default'})) {
11470: $metaentry{':'.$unikey}=
11471: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11472: }
11473: }
11474:
1.261 albertel 11475: sub metadata_generate_part0 {
11476: my ($metadata,$metacache,$uri) = @_;
11477: my %allnames;
1.737 albertel 11478: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11479: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11480: my $part=$$metacache{':'.$metakey.'.part'};
11481: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11482: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11483: $allnames{$name}=$part;
11484: }
11485: }
11486: }
11487: foreach my $name (keys(%allnames)) {
11488: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11489: my $key=":parameter_0_$name";
1.261 albertel 11490: $$metacache{"$key.part"}='0';
11491: $$metacache{"$key.name"}=$name;
1.428 albertel 11492: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11493: $allnames{$name}.'_'.$name.
11494: '.type'};
1.428 albertel 11495: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11496: '.display'};
1.644 www 11497: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11498: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11499: $$metacache{"$key.display"}=$olddis;
11500: }
1.71 www 11501: }
11502:
1.764 albertel 11503: # ------------------------------------------------------ Devalidate title cache
11504:
11505: sub devalidate_title_cache {
11506: my ($url)=@_;
11507: if (!$env{'request.course.id'}) { return; }
11508: my $symb=&symbread($url);
11509: if (!$symb) { return; }
11510: my $key=$env{'request.course.id'}."\0".$symb;
11511: &devalidate_cache_new('title',$key);
11512: }
11513:
1.1014 droeschl 11514: # ------------------------------------------------- Get the title of a course
11515:
11516: sub current_course_title {
11517: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11518: }
1.301 www 11519: # ------------------------------------------------- Get the title of a resource
11520:
11521: sub gettitle {
11522: my $urlsymb=shift;
11523: my $symb=&symbread($urlsymb);
1.534 albertel 11524: if ($symb) {
1.620 albertel 11525: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11526: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11527: if (defined($cached)) {
11528: return $result;
11529: }
1.534 albertel 11530: my ($map,$resid,$url)=&decode_symb($symb);
11531: my $title='';
1.907 albertel 11532: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11533: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11534: } else {
11535: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11536: &GDBM_READER(),0640)) {
11537: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11538: $title=$bighash{'title_'.$mapid.'.'.$resid};
11539: untie(%bighash);
11540: }
1.534 albertel 11541: }
11542: $title=~s/\&colon\;/\:/gs;
11543: if ($title) {
1.1159 www 11544: # Remember both $symb and $title for dynamic metadata
11545: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11546: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11547: # Cache this title and then return it
1.599 albertel 11548: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11549: }
11550: $urlsymb=$url;
11551: }
11552: my $title=&metadata($urlsymb,'title');
11553: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11554: return $title;
1.301 www 11555: }
1.613 albertel 11556:
1.614 albertel 11557: sub get_slot {
11558: my ($which,$cnum,$cdom)=@_;
11559: if (!$cnum || !$cdom) {
1.790 albertel 11560: (undef,my $courseid)=&whichuser();
1.620 albertel 11561: $cdom=$env{'course.'.$courseid.'.domain'};
11562: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11563: }
1.703 albertel 11564: my $key=join("\0",'slots',$cdom,$cnum,$which);
11565: my %slotinfo;
11566: if (exists($remembered{$key})) {
11567: $slotinfo{$which} = $remembered{$key};
11568: } else {
11569: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11570: &Apache::lonhomework::showhash(%slotinfo);
11571: my ($tmp)=keys(%slotinfo);
11572: if ($tmp=~/^error:/) { return (); }
11573: $remembered{$key} = $slotinfo{$which};
11574: }
1.616 albertel 11575: if (ref($slotinfo{$which}) eq 'HASH') {
11576: return %{$slotinfo{$which}};
11577: }
11578: return $slotinfo{$which};
1.614 albertel 11579: }
1.1150 raeburn 11580:
11581: sub get_reservable_slots {
11582: my ($cnum,$cdom,$uname,$udom) = @_;
11583: my $now = time;
11584: my $reservable_info;
11585: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11586: if (exists($remembered{$key})) {
11587: $reservable_info = $remembered{$key};
11588: } else {
11589: my %resv;
11590: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11591: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11592: $reservable_info = \%resv;
11593: $remembered{$key} = $reservable_info;
11594: }
11595: return $reservable_info;
11596: }
11597:
11598: sub get_course_slots {
11599: my ($cnum,$cdom) = @_;
11600: my $hashid=$cnum.':'.$cdom;
11601: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11602: if (defined($cached)) {
11603: if (ref($result) eq 'HASH') {
11604: return %{$result};
11605: }
11606: } else {
11607: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11608: my ($tmp) = keys(%slots);
11609: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 11610: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11611: return %slots;
11612: }
11613: }
11614: return;
11615: }
11616:
11617: sub devalidate_slots_cache {
11618: my ($cnum,$cdom)=@_;
11619: my $hashid=$cnum.':'.$cdom;
11620: &devalidate_cache_new('allslots',$hashid);
11621: }
11622:
1.1181 raeburn 11623: sub get_coursechange {
11624: my ($cdom,$cnum) = @_;
11625: if ($cdom eq '' || $cnum eq '') {
11626: return unless ($env{'request.course.id'});
11627: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11628: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11629: }
11630: my $hashid=$cdom.'_'.$cnum;
11631: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11632: if ((defined($cached)) && ($change ne '')) {
11633: return $change;
11634: } else {
11635: my %crshash;
11636: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11637: if ($crshash{'internal.contentchange'} eq '') {
11638: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11639: if ($change eq '') {
11640: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11641: $change = $crshash{'internal.created'};
11642: }
11643: } else {
11644: $change = $crshash{'internal.contentchange'};
11645: }
11646: my $cachetime = 600;
11647: &do_cache_new('crschange',$hashid,$change,$cachetime);
11648: }
11649: return $change;
11650: }
11651:
11652: sub devalidate_coursechange_cache {
11653: my ($cnum,$cdom)=@_;
11654: my $hashid=$cnum.':'.$cdom;
11655: &devalidate_cache_new('crschange',$hashid);
11656: }
11657:
1.31 www 11658: # ------------------------------------------------- Update symbolic store links
11659:
11660: sub symblist {
11661: my ($mapname,%newhash)=@_;
1.438 www 11662: $mapname=&deversion(&declutter($mapname));
1.31 www 11663: my %hash;
1.620 albertel 11664: if (($env{'request.course.fn'}) && (%newhash)) {
11665: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11666: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11667: foreach my $url (keys(%newhash)) {
1.711 albertel 11668: next if ($url eq 'last_known'
11669: && $env{'form.no_update_last_known'});
11670: $hash{declutter($url)}=&encode_symb($mapname,
11671: $newhash{$url}->[1],
11672: $newhash{$url}->[0]);
1.191 harris41 11673: }
1.31 www 11674: if (untie(%hash)) {
11675: return 'ok';
11676: }
11677: }
11678: }
11679: return 'error';
1.212 www 11680: }
11681:
11682: # --------------------------------------------------------------- Verify a symb
11683:
11684: sub symbverify {
1.1190 raeburn 11685: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11686: my $thisfn=$thisurl;
1.439 www 11687: $thisfn=&declutter($thisfn);
1.215 www 11688: # direct jump to resource in page or to a sequence - will construct own symbs
11689: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11690: # check URL part
1.409 www 11691: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11692:
1.431 www 11693: unless ($url eq $thisfn) { return 0; }
1.213 www 11694:
1.216 www 11695: $symb=&symbclean($symb);
1.510 www 11696: $thisurl=&deversion($thisurl);
1.439 www 11697: $thisfn=&deversion($thisfn);
1.213 www 11698:
11699: my %bighash;
11700: my $okay=0;
1.431 www 11701:
1.620 albertel 11702: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11703: &GDBM_READER(),0640)) {
1.1204 raeburn 11704: my $noclutter;
1.1032 raeburn 11705: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11706: $thisurl =~ s/\?.+$//;
1.1204 raeburn 11707: if ($map =~ m{^uploaded/.+\.page$}) {
11708: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11709: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11710: $noclutter = 1;
11711: }
11712: }
11713: my $ids;
11714: if ($noclutter) {
11715: $ids=$bighash{'ids_'.$thisurl};
11716: } else {
11717: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11718: }
1.1102 raeburn 11719: unless ($ids) {
11720: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
11721: $ids=$bighash{$idkey};
1.216 www 11722: }
11723: if ($ids) {
11724: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 11725: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 11726: $symb =~ s/\?.+$//;
1.1202 raeburn 11727: }
1.800 albertel 11728: foreach my $id (split(/\,/,$ids)) {
11729: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11730: if (
11731: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 11732: eq $symb) {
11733: if (ref($encstate)) {
11734: $$encstate = $bighash{'encrypted_'.$id};
11735: }
1.620 albertel 11736: if (($env{'request.role.adv'}) ||
1.1101 raeburn 11737: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11738: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 11739: $okay=1;
1.1202 raeburn 11740: last;
1.582 albertel 11741: }
11742: }
1.216 www 11743: }
11744: }
1.213 www 11745: untie(%bighash);
11746: }
11747: return $okay;
1.31 www 11748: }
11749:
1.210 www 11750: # --------------------------------------------------------------- Clean-up symb
11751:
11752: sub symbclean {
11753: my $symb=shift;
1.568 albertel 11754: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11755: # remove version from map
11756: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11757:
1.210 www 11758: # remove version from URL
11759: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11760:
1.507 www 11761: # remove wrapper
11762:
1.510 www 11763: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11764: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11765: return $symb;
1.409 www 11766: }
11767:
11768: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11769:
11770: sub encode_symb {
11771: my ($map,$resid,$url)=@_;
11772: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11773: }
1.409 www 11774:
11775: sub decode_symb {
1.568 albertel 11776: my $symb=shift;
11777: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11778: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11779: return (&fixversion($map),$resid,&fixversion($url));
11780: }
11781:
11782: sub fixversion {
11783: my $fn=shift;
1.609 banghart 11784: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11785: my %bighash;
11786: my $uri=&clutter($fn);
1.620 albertel 11787: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11788: # is this cached?
1.599 albertel 11789: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11790: if (defined($cached)) { return $result; }
11791: # unfortunately not cached, or expired
1.620 albertel 11792: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11793: &GDBM_READER(),0640)) {
11794: if ($bighash{'version_'.$uri}) {
11795: my $version=$bighash{'version_'.$uri};
1.444 www 11796: unless (($version eq 'mostrecent') ||
11797: ($version==&getversion($uri))) {
1.440 www 11798: $uri=~s/\.(\w+)$/\.$version\.$1/;
11799: }
11800: }
11801: untie %bighash;
1.413 www 11802: }
1.599 albertel 11803: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11804: }
11805:
11806: sub deversion {
11807: my $url=shift;
11808: $url=~s/\.\d+\.(\w+)$/\.$1/;
11809: return $url;
1.210 www 11810: }
11811:
1.31 www 11812: # ------------------------------------------------------ Return symb list entry
11813:
11814: sub symbread {
1.1282 raeburn 11815: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 11816: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 11817: if (defined($env{$cache_str})) {
11818: if ($ignorecachednull) {
11819: return $env{$cache_str} unless ($env{$cache_str} eq '');
11820: } else {
11821: return $env{$cache_str};
11822: }
11823: }
1.242 www 11824: # no filename provided? try from environment
1.1265 raeburn 11825: unless ($thisfn) {
1.620 albertel 11826: if ($env{'request.symb'}) {
11827: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 11828: }
1.620 albertel 11829: $thisfn=$env{'request.filename'};
1.44 www 11830: }
1.569 albertel 11831: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11832: # is that filename actually a symb? Verify, clean, and return
11833: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11834: if (&symbverify($thisfn,$1)) {
1.620 albertel 11835: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11836: }
1.242 www 11837: }
1.44 www 11838: $thisfn=declutter($thisfn);
1.31 www 11839: my %hash;
1.37 www 11840: my %bighash;
11841: my $syval='';
1.620 albertel 11842: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11843: my $targetfn = $thisfn;
1.609 banghart 11844: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11845: $targetfn = 'adm/wrapper/'.$thisfn;
11846: }
1.687 albertel 11847: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11848: $targetfn=$1;
11849: }
1.620 albertel 11850: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11851: &GDBM_READER(),0640)) {
1.481 raeburn 11852: $syval=$hash{$targetfn};
1.37 www 11853: untie(%hash);
11854: }
11855: # ---------------------------------------------------------- There was an entry
11856: if ($syval) {
1.601 albertel 11857: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11858: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11859: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11860: #return $env{$cache_str}='';
1.601 albertel 11861: #}
11862: #$syval.=$1;
11863: #}
1.37 www 11864: } else {
11865: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11866: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11867: &GDBM_READER(),0640)) {
1.37 www 11868: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11869: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11870: unless ($ids) {
11871: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11872: }
11873: unless ($ids) {
11874: # alias?
11875: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11876: }
1.37 www 11877: if ($ids) {
11878: # ------------------------------------------------------------------- Has ID(s)
11879: my @possibilities=split(/\,/,$ids);
1.39 www 11880: if ($#possibilities==0) {
11881: # ----------------------------------------------- There is only one possibility
1.37 www 11882: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11883: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11884: $resid,$thisfn);
1.1282 raeburn 11885: if (ref($possibles) eq 'HASH') {
11886: $possibles->{$syval} = 1;
11887: }
11888: if ($checkforblock) {
11889: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11890: if (@blockers) {
11891: $syval = '';
11892: return;
11893: }
11894: }
11895: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11896: # ------------------------------------------ There is more than one possibility
11897: my $realpossible=0;
1.800 albertel 11898: foreach my $id (@possibilities) {
11899: my $file=$bighash{'src_'.$id};
1.1282 raeburn 11900: my $canaccess;
11901: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11902: $canaccess = 1;
11903: } else {
11904: $canaccess = &allowed('bre',$file);
11905: }
11906: if ($canaccess) {
11907: my ($mapid,$resid)=split(/\./,$id);
11908: if ($bighash{'map_type_'.$mapid} ne 'page') {
11909: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11910: $resid,$thisfn);
11911: if (ref($possibles) eq 'HASH') {
11912: $possibles->{$syval} = 1;
11913: }
11914: if ($checkforblock) {
11915: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11916: unless (@blockers > 0) {
11917: $syval = $poss_syval;
11918: $realpossible++;
11919: }
11920: } else {
11921: $syval = $poss_syval;
11922: $realpossible++;
11923: }
11924: }
1.39 www 11925: }
1.191 harris41 11926: }
1.39 www 11927: if ($realpossible!=1) { $syval=''; }
1.249 www 11928: } else {
11929: $syval='';
1.37 www 11930: }
11931: }
1.1282 raeburn 11932: untie(%bighash);
1.481 raeburn 11933: }
1.31 www 11934: }
1.62 www 11935: if ($syval) {
1.620 albertel 11936: return $env{$cache_str}=$syval;
1.62 www 11937: }
1.31 www 11938: }
1.949 raeburn 11939: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11940: return $env{$cache_str}='';
1.31 www 11941: }
11942:
11943: # ---------------------------------------------------------- Return random seed
11944:
1.32 www 11945: sub numval {
11946: my $txt=shift;
11947: $txt=~tr/A-J/0-9/;
11948: $txt=~tr/a-j/0-9/;
11949: $txt=~tr/K-T/0-9/;
11950: $txt=~tr/k-t/0-9/;
11951: $txt=~tr/U-Z/0-5/;
11952: $txt=~tr/u-z/0-5/;
11953: $txt=~s/\D//g;
1.564 albertel 11954: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11955: return int($txt);
1.368 albertel 11956: }
11957:
1.484 albertel 11958: sub numval2 {
11959: my $txt=shift;
11960: $txt=~tr/A-J/0-9/;
11961: $txt=~tr/a-j/0-9/;
11962: $txt=~tr/K-T/0-9/;
11963: $txt=~tr/k-t/0-9/;
11964: $txt=~tr/U-Z/0-5/;
11965: $txt=~tr/u-z/0-5/;
11966: $txt=~s/\D//g;
11967: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11968: my $total;
11969: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11970: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11971: return int($total);
11972: }
11973:
1.575 albertel 11974: sub numval3 {
11975: use integer;
11976: my $txt=shift;
11977: $txt=~tr/A-J/0-9/;
11978: $txt=~tr/a-j/0-9/;
11979: $txt=~tr/K-T/0-9/;
11980: $txt=~tr/k-t/0-9/;
11981: $txt=~tr/U-Z/0-5/;
11982: $txt=~tr/u-z/0-5/;
11983: $txt=~s/\D//g;
11984: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11985: my $total;
11986: foreach my $val (@txts) { $total+=$val; }
11987: if ($_64bit) { $total=(($total<<32)>>32); }
11988: return $total;
11989: }
11990:
1.675 albertel 11991: sub digest {
11992: my ($data)=@_;
11993: my $digest=&Digest::MD5::md5($data);
11994: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11995: my ($e,$f);
11996: {
11997: use integer;
11998: $e=($a+$b);
11999: $f=($c+$d);
12000: if ($_64bit) {
12001: $e=(($e<<32)>>32);
12002: $f=(($f<<32)>>32);
12003: }
12004: }
12005: if (wantarray) {
12006: return ($e,$f);
12007: } else {
12008: my $g;
12009: {
12010: use integer;
12011: $g=($e+$f);
12012: if ($_64bit) {
12013: $g=(($g<<32)>>32);
12014: }
12015: }
12016: return $g;
12017: }
12018: }
12019:
1.368 albertel 12020: sub latest_rnd_algorithm_id {
1.675 albertel 12021: return '64bit5';
1.366 albertel 12022: }
1.32 www 12023:
1.503 albertel 12024: sub get_rand_alg {
12025: my ($courseid)=@_;
1.790 albertel 12026: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12027: if ($courseid) {
1.620 albertel 12028: return $env{"course.$courseid.rndseed"};
1.503 albertel 12029: }
12030: return &latest_rnd_algorithm_id();
12031: }
12032:
1.562 albertel 12033: sub validCODE {
12034: my ($CODE)=@_;
12035: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12036: return 0;
12037: }
12038:
1.491 albertel 12039: sub getCODE {
1.620 albertel 12040: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12041: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12042: defined($Apache::lonhomework::parsing_a_task) ) &&
12043: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12044: return $Apache::lonhomework::history{'resource.CODE'};
12045: }
12046: return undef;
12047: }
1.1133 foxr 12048: #
12049: # Determines the random seed for a specific context:
12050: #
12051: # parameters:
12052: # symb - in course context the symb for the seed.
12053: # course_id - The course id of the form domain_coursenum.
12054: # domain - Domain for the user.
12055: # course - Course for the user.
12056: # cenv - environment of the course.
12057: #
12058: # NOTE:
12059: # All parameters are picked out of the environment if missing
12060: # or not defined.
12061: # If a symb cannot be determined the current time is used instead.
12062: #
12063: # For a given well defined symb, courside, domain, username,
12064: # and course environment, the seed is reproducible.
12065: #
1.31 www 12066: sub rndseed {
1.1133 foxr 12067: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12068: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12069: if (!defined($symb)) {
1.366 albertel 12070: unless ($symb=$wsymb) { return time; }
12071: }
1.1146 foxr 12072: if (!defined $courseid) {
12073: $courseid=$wcourseid;
12074: }
12075: if (!defined $domain) { $domain=$wdomain; }
12076: if (!defined $username) { $username=$wusername }
1.1133 foxr 12077:
12078: my $which;
12079: if (defined($cenv->{'rndseed'})) {
12080: $which = $cenv->{'rndseed'};
12081: } else {
12082: $which =&get_rand_alg($courseid);
12083: }
1.491 albertel 12084: if (defined(&getCODE())) {
1.1133 foxr 12085:
1.675 albertel 12086: if ($which eq '64bit5') {
12087: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12088: } elsif ($which eq '64bit4') {
1.575 albertel 12089: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12090: } else {
12091: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12092: }
1.675 albertel 12093: } elsif ($which eq '64bit5') {
12094: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12095: } elsif ($which eq '64bit4') {
12096: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12097: } elsif ($which eq '64bit3') {
12098: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12099: } elsif ($which eq '64bit2') {
12100: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12101: } elsif ($which eq '64bit') {
12102: return &rndseed_64bit($symb,$courseid,$domain,$username);
12103: }
12104: return &rndseed_32bit($symb,$courseid,$domain,$username);
12105: }
12106:
12107: sub rndseed_32bit {
12108: my ($symb,$courseid,$domain,$username)=@_;
12109: {
12110: use integer;
12111: my $symbchck=unpack("%32C*",$symb) << 27;
12112: my $symbseed=numval($symb) << 22;
12113: my $namechck=unpack("%32C*",$username) << 17;
12114: my $nameseed=numval($username) << 12;
12115: my $domainseed=unpack("%32C*",$domain) << 7;
12116: my $courseseed=unpack("%32C*",$courseid);
12117: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12118: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12119: #&logthis("rndseed :$num:$symb");
1.564 albertel 12120: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12121: return $num;
12122: }
12123: }
12124:
12125: sub rndseed_64bit {
12126: my ($symb,$courseid,$domain,$username)=@_;
12127: {
12128: use integer;
12129: my $symbchck=unpack("%32S*",$symb) << 21;
12130: my $symbseed=numval($symb) << 10;
12131: my $namechck=unpack("%32S*",$username);
12132:
12133: my $nameseed=numval($username) << 21;
12134: my $domainseed=unpack("%32S*",$domain) << 10;
12135: my $courseseed=unpack("%32S*",$courseid);
12136:
12137: my $num1=$symbchck+$symbseed+$namechck;
12138: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12139: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12140: #&logthis("rndseed :$num:$symb");
1.564 albertel 12141: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12142: return "$num1,$num2";
1.155 albertel 12143: }
1.366 albertel 12144: }
12145:
1.443 albertel 12146: sub rndseed_64bit2 {
12147: my ($symb,$courseid,$domain,$username)=@_;
12148: {
12149: use integer;
12150: # strings need to be an even # of cahracters long, it it is odd the
12151: # last characters gets thrown away
12152: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12153: my $symbseed=numval($symb) << 10;
12154: my $namechck=unpack("%32S*",$username.' ');
12155:
12156: my $nameseed=numval($username) << 21;
1.501 albertel 12157: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12158: my $courseseed=unpack("%32S*",$courseid.' ');
12159:
12160: my $num1=$symbchck+$symbseed+$namechck;
12161: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12162: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12163: #&logthis("rndseed :$num:$symb");
1.803 albertel 12164: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12165: return "$num1,$num2";
12166: }
12167: }
12168:
12169: sub rndseed_64bit3 {
12170: my ($symb,$courseid,$domain,$username)=@_;
12171: {
12172: use integer;
12173: # strings need to be an even # of cahracters long, it it is odd the
12174: # last characters gets thrown away
12175: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12176: my $symbseed=numval2($symb) << 10;
12177: my $namechck=unpack("%32S*",$username.' ');
12178:
12179: my $nameseed=numval2($username) << 21;
1.443 albertel 12180: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12181: my $courseseed=unpack("%32S*",$courseid.' ');
12182:
12183: my $num1=$symbchck+$symbseed+$namechck;
12184: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12185: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12186: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12187: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12188:
1.503 albertel 12189: return "$num1:$num2";
1.443 albertel 12190: }
12191: }
12192:
1.575 albertel 12193: sub rndseed_64bit4 {
12194: my ($symb,$courseid,$domain,$username)=@_;
12195: {
12196: use integer;
12197: # strings need to be an even # of cahracters long, it it is odd the
12198: # last characters gets thrown away
12199: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12200: my $symbseed=numval3($symb) << 10;
12201: my $namechck=unpack("%32S*",$username.' ');
12202:
12203: my $nameseed=numval3($username) << 21;
12204: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12205: my $courseseed=unpack("%32S*",$courseid.' ');
12206:
12207: my $num1=$symbchck+$symbseed+$namechck;
12208: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12209: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12210: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12211: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12212:
1.575 albertel 12213: return "$num1:$num2";
12214: }
12215: }
12216:
1.675 albertel 12217: sub rndseed_64bit5 {
12218: my ($symb,$courseid,$domain,$username)=@_;
12219: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12220: return "$num1:$num2";
12221: }
12222:
1.366 albertel 12223: sub rndseed_CODE_64bit {
12224: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12225: {
1.366 albertel 12226: use integer;
1.443 albertel 12227: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12228: my $symbseed=numval2($symb);
1.491 albertel 12229: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12230: my $CODEseed=numval(&getCODE());
1.443 albertel 12231: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12232: my $num1=$symbseed+$CODEchck;
12233: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12234: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12235: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12236: if ($_64bit) { $num1=(($num1<<32)>>32); }
12237: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12238: return "$num1:$num2";
1.366 albertel 12239: }
12240: }
12241:
1.575 albertel 12242: sub rndseed_CODE_64bit4 {
12243: my ($symb,$courseid,$domain,$username)=@_;
12244: {
12245: use integer;
12246: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12247: my $symbseed=numval3($symb);
12248: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12249: my $CODEseed=numval3(&getCODE());
12250: my $courseseed=unpack("%32S*",$courseid.' ');
12251: my $num1=$symbseed+$CODEchck;
12252: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12253: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12254: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12255: if ($_64bit) { $num1=(($num1<<32)>>32); }
12256: if ($_64bit) { $num2=(($num2<<32)>>32); }
12257: return "$num1:$num2";
12258: }
12259: }
12260:
1.675 albertel 12261: sub rndseed_CODE_64bit5 {
12262: my ($symb,$courseid,$domain,$username)=@_;
12263: my $code = &getCODE();
12264: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12265: return "$num1:$num2";
12266: }
12267:
1.366 albertel 12268: sub setup_random_from_rndseed {
12269: my ($rndseed)=@_;
1.503 albertel 12270: if ($rndseed =~/([,:])/) {
1.1262 raeburn 12271: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12272: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12273: &Math::Random::random_set_seed_from_phrase($rndseed);
12274: } else {
12275: &Math::Random::random_set_seed($num1,$num2);
12276: }
1.366 albertel 12277: } else {
12278: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12279: }
1.36 albertel 12280: }
12281:
1.474 albertel 12282: sub latest_receipt_algorithm_id {
1.835 albertel 12283: return 'receipt3';
1.474 albertel 12284: }
12285:
1.480 www 12286: sub recunique {
12287: my $fucourseid=shift;
12288: my $unique;
1.835 albertel 12289: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12290: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12291: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12292: } else {
12293: $unique=$perlvar{'lonReceipt'};
12294: }
12295: return unpack("%32C*",$unique);
12296: }
12297:
12298: sub recprefix {
12299: my $fucourseid=shift;
12300: my $prefix;
1.835 albertel 12301: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12302: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12303: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12304: } else {
12305: $prefix=$perlvar{'lonHostID'};
12306: }
12307: return unpack("%32C*",$prefix);
12308: }
12309:
1.76 www 12310: sub ireceipt {
1.474 albertel 12311: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12312:
12313: my $return =&recprefix($fucourseid).'-';
12314:
12315: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12316: $env{'request.state'} eq 'construct') {
12317: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12318: return $return;
12319: }
12320:
1.76 www 12321: my $cuname=unpack("%32C*",$funame);
12322: my $cudom=unpack("%32C*",$fudom);
12323: my $cucourseid=unpack("%32C*",$fucourseid);
12324: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12325: my $cunique=&recunique($fucourseid);
1.474 albertel 12326: my $cpart=unpack("%32S*",$part);
1.835 albertel 12327: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12328:
1.790 albertel 12329: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12330:
12331: $return.= ($cunique%$cuname+
12332: $cunique%$cudom+
12333: $cusymb%$cuname+
12334: $cusymb%$cudom+
12335: $cucourseid%$cuname+
12336: $cucourseid%$cudom+
12337: $cpart%$cuname+
12338: $cpart%$cudom);
12339: } else {
12340: $return.= ($cunique%$cuname+
12341: $cunique%$cudom+
12342: $cusymb%$cuname+
12343: $cusymb%$cudom+
12344: $cucourseid%$cuname+
12345: $cucourseid%$cudom);
12346: }
12347: return $return;
1.76 www 12348: }
12349:
12350: sub receipt {
1.474 albertel 12351: my ($part)=@_;
1.790 albertel 12352: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12353: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12354: }
1.260 ng 12355:
1.790 albertel 12356: sub whichuser {
12357: my ($passedsymb)=@_;
12358: my ($symb,$courseid,$domain,$name,$publicuser);
12359: if (defined($env{'form.grade_symb'})) {
12360: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12361: my $allowed=&allowed('vgr',$tmp_courseid);
12362: if (!$allowed &&
12363: exists($env{'request.course.sec'}) &&
12364: $env{'request.course.sec'} !~ /^\s*$/) {
12365: $allowed=&allowed('vgr',$tmp_courseid.
12366: '/'.$env{'request.course.sec'});
12367: }
12368: if ($allowed) {
12369: ($symb)=&get_env_multiple('form.grade_symb');
12370: $courseid=$tmp_courseid;
12371: ($domain)=&get_env_multiple('form.grade_domain');
12372: ($name)=&get_env_multiple('form.grade_username');
12373: return ($symb,$courseid,$domain,$name,$publicuser);
12374: }
12375: }
12376: if (!$passedsymb) {
12377: $symb=&symbread();
12378: } else {
12379: $symb=$passedsymb;
12380: }
12381: $courseid=$env{'request.course.id'};
12382: $domain=$env{'user.domain'};
12383: $name=$env{'user.name'};
12384: if ($name eq 'public' && $domain eq 'public') {
12385: if (!defined($env{'form.username'})) {
12386: $env{'form.username'}.=time.rand(10000000);
12387: }
12388: $name.=$env{'form.username'};
12389: }
12390: return ($symb,$courseid,$domain,$name,$publicuser);
12391:
12392: }
12393:
1.36 albertel 12394: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12395: # returns either the contents of the file or
12396: # -1 if the file doesn't exist
1.481 raeburn 12397: #
12398: # if the target is a file that was uploaded via DOCS,
12399: # a check will be made to see if a current copy exists on the local server,
12400: # if it does this will be served, otherwise a copy will be retrieved from
12401: # the home server for the course and stored in /home/httpd/html/userfiles on
12402: # the local server.
1.472 albertel 12403:
1.36 albertel 12404: sub getfile {
1.538 albertel 12405: my ($file) = @_;
1.609 banghart 12406: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12407: &repcopy($file);
12408: return &readfile($file);
12409: }
12410:
12411: sub repcopy_userfile {
12412: my ($file)=@_;
1.1142 raeburn 12413: my $londocroot = $perlvar{'lonDocRoot'};
12414: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12415: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12416: my ($cdom,$cnum,$filename) =
1.811 albertel 12417: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12418: my $uri="/uploaded/$cdom/$cnum/$filename";
12419: if (-e "$file") {
1.828 www 12420: # we already have a local copy, check it out
1.538 albertel 12421: my @fileinfo = stat($file);
1.828 www 12422: my $rtncode;
12423: my $info;
1.538 albertel 12424: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12425: if ($lwpresp ne 'ok') {
1.828 www 12426: # there is no such file anymore, even though we had a local copy
1.482 albertel 12427: if ($rtncode eq '404') {
1.538 albertel 12428: unlink($file);
1.482 albertel 12429: }
12430: return -1;
12431: }
12432: if ($info < $fileinfo[9]) {
1.828 www 12433: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12434: return 'ok';
1.828 www 12435: } else {
12436: # the file is outdated, get rid of it
12437: unlink($file);
1.482 albertel 12438: }
1.828 www 12439: }
12440: # one way or the other, at this point, we don't have the file
12441: # construct the correct path for the file
12442: my @parts = ($cdom,$cnum);
12443: if ($filename =~ m|^(.+)/[^/]+$|) {
12444: push @parts, split(/\//,$1);
12445: }
12446: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12447: foreach my $part (@parts) {
12448: $path .= '/'.$part;
12449: if (!-e $path) {
12450: mkdir($path,0770);
1.482 albertel 12451: }
12452: }
1.828 www 12453: # now the path exists for sure
12454: # get a user agent
12455: my $ua=new LWP::UserAgent;
12456: my $transferfile=$file.'.in.transfer';
12457: # FIXME: this should flock
12458: if (-e $transferfile) { return 'ok'; }
12459: my $request;
12460: $uri=~s/^\///;
1.980 raeburn 12461: my $homeserver = &homeserver($cnum,$cdom);
12462: my $protocol = $protocol{$homeserver};
12463: $protocol = 'http' if ($protocol ne 'https');
12464: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12465: my $response=$ua->request($request,$transferfile);
12466: # did it work?
12467: if ($response->is_error()) {
12468: unlink($transferfile);
12469: &logthis("Userfile repcopy failed for $uri");
12470: return -1;
12471: }
12472: # worked, rename the transfer file
12473: rename($transferfile,$file);
1.607 raeburn 12474: return 'ok';
1.481 raeburn 12475: }
12476:
1.517 albertel 12477: sub tokenwrapper {
12478: my $uri=shift;
1.980 raeburn 12479: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12480: $uri=~s|^/||;
1.620 albertel 12481: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12482: my $token=$1;
1.552 albertel 12483: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12484: if ($udom && $uname && $file) {
12485: $file=~s|(\?\.*)*$||;
1.949 raeburn 12486: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12487: my $homeserver = &homeserver($uname,$udom);
12488: my $protocol = $protocol{$homeserver};
12489: $protocol = 'http' if ($protocol ne 'https');
12490: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12491: (($uri=~/\?/)?'&':'?').'token='.$token.
12492: '&tokenissued='.$perlvar{'lonHostID'};
12493: } else {
12494: return '/adm/notfound.html';
12495: }
12496: }
12497:
1.828 www 12498: # call with reqtype HEAD: get last modification time
12499: # call with reqtype GET: get the file contents
12500: # Do not call this with reqtype GET for large files! It loads everything into memory
12501: #
1.481 raeburn 12502: sub getuploaded {
12503: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12504: $uri=~s/^\///;
1.980 raeburn 12505: my $homeserver = &homeserver($cnum,$cdom);
12506: my $protocol = $protocol{$homeserver};
12507: $protocol = 'http' if ($protocol ne 'https');
12508: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12509: my $ua=new LWP::UserAgent;
12510: my $request=new HTTP::Request($reqtype,$uri);
12511: my $response=$ua->request($request);
12512: $$rtncode = $response->code;
1.482 albertel 12513: if (! $response->is_success()) {
12514: return 'failed';
12515: }
12516: if ($reqtype eq 'HEAD') {
1.486 www 12517: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12518: } elsif ($reqtype eq 'GET') {
12519: $$info = $response->content;
1.472 albertel 12520: }
1.482 albertel 12521: return 'ok';
1.36 albertel 12522: }
12523:
1.481 raeburn 12524: sub readfile {
12525: my $file = shift;
12526: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12527: my $fh;
12528: open($fh,"<$file");
12529: my $a='';
1.800 albertel 12530: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12531: return $a;
12532: }
12533:
1.36 albertel 12534: sub filelocation {
1.590 banghart 12535: my ($dir,$file) = @_;
12536: my $location;
12537: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12538:
12539: if ($file =~ m-^/adm/-) {
12540: $file=~s-^/adm/wrapper/-/-;
12541: $file=~s-^/adm/coursedocs/showdoc/-/-;
12542: }
1.882 albertel 12543:
1.1139 www 12544: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12545: $location = $file;
1.609 banghart 12546: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12547: my ($udom,$uname,$filename)=
1.811 albertel 12548: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12549: my $home=&homeserver($uname,$udom);
12550: my $is_me=0;
12551: my @ids=¤t_machine_ids();
12552: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12553: if ($is_me) {
1.1117 foxr 12554: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12555: } else {
12556: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12557: $udom.'/'.$uname.'/'.$filename;
12558: }
1.882 albertel 12559: } elsif ($file =~ m-^/adm/-) {
12560: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12561: } else {
12562: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12563: $file=~s:^/(res|priv)/:/:;
12564: my $space=$1;
1.590 banghart 12565: if ( !( $file =~ m:^/:) ) {
12566: $location = $dir. '/'.$file;
12567: } else {
1.1142 raeburn 12568: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12569: }
1.59 albertel 12570: }
1.590 banghart 12571: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12572: while ($location=~m{/\.\./}) {
12573: if ($location =~ m{/[^/]+/\.\./}) {
12574: $location=~ s{/[^/]+/\.\./}{/}g;
12575: } else {
12576: $location=~ s{/\.\./}{/}g;
12577: }
12578: } #remove dir/..
1.590 banghart 12579: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12580: return $location;
1.46 www 12581: }
1.36 albertel 12582:
1.46 www 12583: sub hreflocation {
12584: my ($dir,$file)=@_;
1.980 raeburn 12585: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12586: $file=filelocation($dir,$file);
1.700 albertel 12587: } elsif ($file=~m-^/adm/-) {
12588: $file=~s-^/adm/wrapper/-/-;
12589: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12590: }
12591: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12592: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12593: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12594: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12595: {/uploaded/$1/$2/}x;
1.46 www 12596: }
1.913 albertel 12597: if ($file=~ m{^/userfiles/}) {
12598: $file =~ s{^/userfiles/}{/uploaded/};
12599: }
1.462 albertel 12600: return $file;
1.465 albertel 12601: }
12602:
1.1139 www 12603:
12604:
12605:
12606:
1.465 albertel 12607: sub current_machine_domains {
1.853 albertel 12608: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12609: }
12610:
12611: sub machine_domains {
12612: my ($hostname) = @_;
1.465 albertel 12613: my @domains;
1.838 albertel 12614: my %hostname = &all_hostnames();
1.465 albertel 12615: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12616: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12617: if ($hostname eq $name) {
1.844 albertel 12618: push(@domains,&host_domain($id));
1.465 albertel 12619: }
12620: }
12621: return @domains;
12622: }
12623:
12624: sub current_machine_ids {
1.853 albertel 12625: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12626: }
12627:
12628: sub machine_ids {
12629: my ($hostname) = @_;
12630: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12631: my @ids;
1.888 albertel 12632: my %name_to_host = &all_names();
1.889 albertel 12633: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12634: return @{ $name_to_host{$hostname} };
12635: }
12636: return;
1.31 www 12637: }
12638:
1.824 raeburn 12639: sub additional_machine_domains {
12640: my @domains;
12641: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12642: while( my $line = <$fh>) {
12643: $line =~ s/\s//g;
12644: push(@domains,$line);
12645: }
12646: return @domains;
12647: }
12648:
12649: sub default_login_domain {
12650: my $domain = $perlvar{'lonDefDomain'};
12651: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12652: foreach my $posdom (¤t_machine_domains(),
12653: &additional_machine_domains()) {
12654: if (lc($posdom) eq lc($testdomain)) {
12655: $domain=$posdom;
12656: last;
12657: }
12658: }
12659: return $domain;
12660: }
12661:
1.31 www 12662: # ------------------------------------------------------------- Declutters URLs
12663:
12664: sub declutter {
12665: my $thisfn=shift;
1.569 albertel 12666: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 12667: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12668: $thisfn=~s{^/home/httpd/html}{};
12669: }
1.31 www 12670: $thisfn=~s/^\///;
1.697 albertel 12671: $thisfn=~s|^adm/wrapper/||;
12672: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12673: $thisfn=~s/^res\///;
1.1172 bisitz 12674: $thisfn=~s/^priv\///;
1.1032 raeburn 12675: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12676: $thisfn=~s/\?.+$//;
12677: }
1.268 www 12678: return $thisfn;
12679: }
12680:
12681: # ------------------------------------------------------------- Clutter up URLs
12682:
12683: sub clutter {
12684: my $thisfn='/'.&declutter(shift);
1.887 albertel 12685: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12686: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12687: $thisfn='/res'.$thisfn;
12688: }
1.1031 raeburn 12689: if ($thisfn !~m|^/adm|) {
12690: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12691: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12692: } else {
12693: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12694: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12695: if ($embstyle eq 'ssi'
12696: || ($embstyle eq 'hdn')
12697: || ($embstyle eq 'rat')
12698: || ($embstyle eq 'prv')
12699: || ($embstyle eq 'ign')) {
12700: #do nothing with these
12701: } elsif (($embstyle eq 'img')
1.695 albertel 12702: || ($embstyle eq 'emb')
12703: || ($embstyle eq 'wrp')) {
12704: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12705: } elsif ($embstyle eq 'unk'
12706: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12707: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12708: } else {
1.718 www 12709: # &logthis("Got a blank emb style");
1.695 albertel 12710: }
1.694 albertel 12711: }
1.1298 raeburn 12712: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
12713: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 12714: }
1.31 www 12715: return $thisfn;
1.12 www 12716: }
12717:
1.787 albertel 12718: sub clutter_with_no_wrapper {
12719: my $uri = &clutter(shift);
12720: if ($uri =~ m-^/adm/-) {
12721: $uri =~ s-^/adm/wrapper/-/-;
12722: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12723: }
12724: return $uri;
12725: }
12726:
1.557 albertel 12727: sub freeze_escape {
12728: my ($value)=@_;
12729: if (ref($value)) {
12730: $value=&nfreeze($value);
12731: return '__FROZEN__'.&escape($value);
12732: }
12733: return &escape($value);
12734: }
12735:
1.11 www 12736:
1.557 albertel 12737: sub thaw_unescape {
12738: my ($value)=@_;
12739: if ($value =~ /^__FROZEN__/) {
12740: substr($value,0,10,undef);
12741: $value=&unescape($value);
12742: return &thaw($value);
12743: }
12744: return &unescape($value);
12745: }
12746:
1.436 albertel 12747: sub correct_line_ends {
12748: my ($result)=@_;
12749: $$result =~s/\r\n/\n/mg;
12750: $$result =~s/\r/\n/mg;
1.415 albertel 12751: }
1.1 albertel 12752: # ================================================================ Main Program
12753:
1.184 www 12754: sub goodbye {
1.204 albertel 12755: &logthis("Starting Shut down");
1.443 albertel 12756: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12757: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12758: #converted
1.599 albertel 12759: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12760: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12761: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12762: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12763: #1.1 only
1.870 albertel 12764: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12765: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12766: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12767: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12768: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12769: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12770: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12771: &flushcourselogs();
12772: &logthis("Shutting down");
12773: }
12774:
1.852 albertel 12775: sub get_dns {
1.1210 raeburn 12776: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12777: if (!$ignore_cache) {
12778: my ($content,$cached)=
12779: &Apache::lonnet::is_cached_new('dns',$url);
12780: if ($cached) {
1.1210 raeburn 12781: &$func($content,$hashref);
1.869 albertel 12782: return;
12783: }
12784: }
12785:
12786: my %alldns;
1.852 albertel 12787: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12788: foreach my $dns (<$config>) {
12789: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12790: my $line = $1;
12791: my ($host,$protocol) = split(/:/,$line);
12792: if ($protocol ne 'https') {
12793: $protocol = 'http';
12794: }
12795: $alldns{$host} = $protocol;
1.869 albertel 12796: }
12797: while (%alldns) {
1.1263 raeburn 12798: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12799: my $ua=new LWP::UserAgent;
1.1134 raeburn 12800: $ua->timeout(30);
1.979 raeburn 12801: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12802: my $response=$ua->request($request);
1.979 raeburn 12803: delete($alldns{$dns});
1.852 albertel 12804: next if ($response->is_error());
12805: my @content = split("\n",$response->content);
1.1210 raeburn 12806: unless ($nocache) {
1.1219 raeburn 12807: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 12808: }
12809: &$func(\@content,$hashref);
1.869 albertel 12810: return;
1.852 albertel 12811: }
12812: close($config);
1.871 albertel 12813: my $which = (split('/',$url))[3];
12814: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12815: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12816: my @content = <$config>;
1.1210 raeburn 12817: &$func(\@content,$hashref);
12818: return;
12819: }
12820:
12821: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 12822: sub parse_dns_checksums_tab {
1.1210 raeburn 12823: my ($lines,$hashref) = @_;
1.1264 raeburn 12824: my $lonhost = $perlvar{'lonHostID'};
12825: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 12826: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 12827: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12828: my $webconfdir = '/etc/httpd/conf';
12829: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12830: $webconfdir = '/etc/apache2';
12831: } elsif ($distro =~ /^sles(\d+)$/) {
12832: if ($1 >= 10) {
12833: $webconfdir = '/etc/apache2';
12834: }
12835: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12836: if ($1 >= 10.0) {
12837: $webconfdir = '/etc/apache2';
12838: }
12839: }
1.1210 raeburn 12840: my ($release,$timestamp) = split(/\-/,$loncaparev);
12841: my (%chksum,%revnum);
12842: if (ref($lines) eq 'ARRAY') {
12843: chomp(@{$lines});
1.1238 raeburn 12844: my $version = shift(@{$lines});
12845: if ($version eq $release) {
1.1210 raeburn 12846: foreach my $line (@{$lines}) {
1.1238 raeburn 12847: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 12848: if ($file =~ m{^/etc/httpd/conf}) {
12849: if ($webconfdir eq '/etc/apache2') {
12850: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12851: }
12852: }
1.1238 raeburn 12853: $chksum{$file} = $shasum;
12854: $revnum{$file} = $version;
1.1210 raeburn 12855: }
12856: if (ref($hashref) eq 'HASH') {
12857: %{$hashref} = (
12858: sums => \%chksum,
12859: versions => \%revnum,
12860: );
12861: }
12862: }
12863: }
1.869 albertel 12864: return;
1.852 albertel 12865: }
1.1210 raeburn 12866:
12867: sub fetch_dns_checksums {
1.1238 raeburn 12868: my %checksums;
12869: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 12870: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 12871: my ($release,$timestamp) = split(/\-/,$loncaparev);
12872: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 12873: \%checksums);
1.1210 raeburn 12874: return \%checksums;
12875: }
12876:
1.327 albertel 12877: # ------------------------------------------------------------ Read domain file
12878: {
1.852 albertel 12879: my $loaded;
1.846 albertel 12880: my %domain;
12881:
1.852 albertel 12882: sub parse_domain_tab {
12883: my ($lines) = @_;
12884: foreach my $line (@$lines) {
12885: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12886:
1.846 albertel 12887: chomp($line);
1.852 albertel 12888: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12889: my %this_domain;
12890: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12891: 'lang_def', 'city', 'longi', 'lati',
12892: 'primary') {
12893: $this_domain{$field} = shift(@elements);
12894: }
12895: $domain{$name} = \%this_domain;
1.852 albertel 12896: }
12897: }
1.864 albertel 12898:
12899: sub reset_domain_info {
12900: undef($loaded);
12901: undef(%domain);
12902: }
12903:
1.852 albertel 12904: sub load_domain_tab {
1.1293 raeburn 12905: my ($ignore_cache,$nocache) = @_;
12906: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12907: my $fh;
12908: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12909: my @lines = <$fh>;
12910: &parse_domain_tab(\@lines);
1.448 albertel 12911: }
1.852 albertel 12912: close($fh);
12913: $loaded = 1;
1.327 albertel 12914: }
1.846 albertel 12915:
12916: sub domain {
1.852 albertel 12917: &load_domain_tab() if (!$loaded);
12918:
1.846 albertel 12919: my ($name,$what) = @_;
12920: return if ( !exists($domain{$name}) );
12921:
12922: if (!$what) {
12923: return $domain{$name}{'description'};
12924: }
12925: return $domain{$name}{$what};
12926: }
1.974 raeburn 12927:
12928: sub domain_info {
12929: &load_domain_tab() if (!$loaded);
12930: return %domain;
12931: }
12932:
1.327 albertel 12933: }
12934:
12935:
1.1 albertel 12936: # ------------------------------------------------------------- Read hosts file
12937: {
1.838 albertel 12938: my %hostname;
1.844 albertel 12939: my %hostdom;
1.845 albertel 12940: my %libserv;
1.852 albertel 12941: my $loaded;
1.888 albertel 12942: my %name_to_host;
1.1074 raeburn 12943: my %internetdom;
1.1107 raeburn 12944: my %LC_dns_serv;
1.852 albertel 12945:
12946: sub parse_hosts_tab {
12947: my ($file) = @_;
12948: foreach my $configline (@$file) {
12949: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12950: chomp($configline);
12951: if ($configline =~ /^\^/) {
12952: if ($configline =~ /^\^([\w.\-]+)/) {
12953: $LC_dns_serv{$1} = 1;
12954: }
12955: next;
12956: }
1.1074 raeburn 12957: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12958: $name=~s/\s//g;
12959: if ($id && $domain && $role && $name) {
12960: $hostname{$id}=$name;
1.888 albertel 12961: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12962: $hostdom{$id}=$domain;
12963: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12964: if (defined($protocol)) {
12965: if ($protocol eq 'https') {
12966: $protocol{$id} = $protocol;
12967: } else {
12968: $protocol{$id} = 'http';
12969: }
1.968 raeburn 12970: } else {
1.969 raeburn 12971: $protocol{$id} = 'http';
1.968 raeburn 12972: }
1.1074 raeburn 12973: if (defined($intdom)) {
12974: $internetdom{$id} = $intdom;
12975: }
1.852 albertel 12976: }
12977: }
12978: }
1.864 albertel 12979:
12980: sub reset_hosts_info {
1.897 albertel 12981: &purge_remembered();
1.864 albertel 12982: &reset_domain_info();
12983: &reset_hosts_ip_info();
1.892 albertel 12984: undef(%name_to_host);
1.864 albertel 12985: undef(%hostname);
12986: undef(%hostdom);
12987: undef(%libserv);
12988: undef($loaded);
12989: }
1.1 albertel 12990:
1.852 albertel 12991: sub load_hosts_tab {
1.1293 raeburn 12992: my ($ignore_cache,$nocache) = @_;
12993: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12994: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12995: my @config = <$config>;
12996: &parse_hosts_tab(\@config);
12997: close($config);
12998: $loaded=1;
1.1 albertel 12999: }
1.852 albertel 13000:
1.838 albertel 13001: sub hostname {
1.852 albertel 13002: &load_hosts_tab() if (!$loaded);
13003:
1.838 albertel 13004: my ($lonid) = @_;
13005: return $hostname{$lonid};
13006: }
1.845 albertel 13007:
1.838 albertel 13008: sub all_hostnames {
1.852 albertel 13009: &load_hosts_tab() if (!$loaded);
13010:
1.838 albertel 13011: return %hostname;
13012: }
1.845 albertel 13013:
1.888 albertel 13014: sub all_names {
1.1293 raeburn 13015: my ($ignore_cache,$nocache) = @_;
13016: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13017:
13018: return %name_to_host;
13019: }
13020:
1.974 raeburn 13021: sub all_host_domain {
13022: &load_hosts_tab() if (!$loaded);
13023: return %hostdom;
13024: }
13025:
1.845 albertel 13026: sub is_library {
1.852 albertel 13027: &load_hosts_tab() if (!$loaded);
13028:
1.845 albertel 13029: return exists($libserv{$_[0]});
13030: }
13031:
13032: sub all_library {
1.852 albertel 13033: &load_hosts_tab() if (!$loaded);
13034:
1.845 albertel 13035: return %libserv;
13036: }
13037:
1.1062 droeschl 13038: sub unique_library {
13039: #2x reverse removes all hostnames that appear more than once
13040: my %unique = reverse &all_library();
13041: return reverse %unique;
13042: }
13043:
1.841 albertel 13044: sub get_servers {
1.852 albertel 13045: &load_hosts_tab() if (!$loaded);
13046:
1.841 albertel 13047: my ($domain,$type) = @_;
13048: my %possible_hosts = ($type eq 'library') ? %libserv
13049: : %hostname;
13050: my %result;
1.842 albertel 13051: if (ref($domain) eq 'ARRAY') {
13052: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13053: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13054: $result{$host} = $hostname;
13055: }
13056: }
13057: } else {
13058: while ( my ($host,$hostname) = each(%possible_hosts)) {
13059: if ($hostdom{$host} eq $domain) {
13060: $result{$host} = $hostname;
13061: }
1.841 albertel 13062: }
13063: }
13064: return %result;
13065: }
1.845 albertel 13066:
1.1062 droeschl 13067: sub get_unique_servers {
13068: my %unique = reverse &get_servers(@_);
13069: return reverse %unique;
13070: }
13071:
1.844 albertel 13072: sub host_domain {
1.852 albertel 13073: &load_hosts_tab() if (!$loaded);
13074:
1.844 albertel 13075: my ($lonid) = @_;
13076: return $hostdom{$lonid};
13077: }
13078:
1.841 albertel 13079: sub all_domains {
1.852 albertel 13080: &load_hosts_tab() if (!$loaded);
13081:
1.841 albertel 13082: my %seen;
13083: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13084: return @uniq;
13085: }
1.1074 raeburn 13086:
13087: sub internet_dom {
13088: &load_hosts_tab() if (!$loaded);
13089:
13090: my ($lonid) = @_;
13091: return $internetdom{$lonid};
13092: }
1.1107 raeburn 13093:
13094: sub is_LC_dns {
13095: &load_hosts_tab() if (!$loaded);
13096:
13097: my ($hostname) = @_;
13098: return exists($LC_dns_serv{$hostname});
13099: }
13100:
1.1 albertel 13101: }
13102:
1.847 albertel 13103: {
13104: my %iphost;
1.856 albertel 13105: my %name_to_ip;
13106: my %lonid_to_ip;
1.869 albertel 13107:
1.847 albertel 13108: sub get_hosts_from_ip {
13109: my ($ip) = @_;
13110: my %iphosts = &get_iphost();
13111: if (ref($iphosts{$ip})) {
13112: return @{$iphosts{$ip}};
13113: }
13114: return;
1.839 albertel 13115: }
1.864 albertel 13116:
13117: sub reset_hosts_ip_info {
13118: undef(%iphost);
13119: undef(%name_to_ip);
13120: undef(%lonid_to_ip);
13121: }
1.856 albertel 13122:
13123: sub get_host_ip {
13124: my ($lonid) = @_;
13125: if (exists($lonid_to_ip{$lonid})) {
13126: return $lonid_to_ip{$lonid};
13127: }
13128: my $name=&hostname($lonid);
13129: my $ip = gethostbyname($name);
13130: return if (!$ip || length($ip) ne 4);
13131: $ip=inet_ntoa($ip);
13132: $name_to_ip{$name} = $ip;
13133: $lonid_to_ip{$lonid} = $ip;
13134: return $ip;
13135: }
1.847 albertel 13136:
13137: sub get_iphost {
1.1293 raeburn 13138: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13139:
1.869 albertel 13140: if (!$ignore_cache) {
13141: if (%iphost) {
13142: return %iphost;
13143: }
13144: my ($ip_info,$cached)=
13145: &Apache::lonnet::is_cached_new('iphost','iphost');
13146: if ($cached) {
13147: %iphost = %{$ip_info->[0]};
13148: %name_to_ip = %{$ip_info->[1]};
13149: %lonid_to_ip = %{$ip_info->[2]};
13150: return %iphost;
13151: }
13152: }
1.894 albertel 13153:
13154: # get yesterday's info for fallback
13155: my %old_name_to_ip;
13156: my ($ip_info,$cached)=
13157: &Apache::lonnet::is_cached_new('iphost','iphost');
13158: if ($cached) {
13159: %old_name_to_ip = %{$ip_info->[1]};
13160: }
13161:
1.1293 raeburn 13162: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13163: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13164: my $ip;
13165: if (!exists($name_to_ip{$name})) {
13166: $ip = gethostbyname($name);
13167: if (!$ip || length($ip) ne 4) {
1.894 albertel 13168: if (defined($old_name_to_ip{$name})) {
13169: $ip = $old_name_to_ip{$name};
13170: &logthis("Can't find $name defaulting to old $ip");
13171: } else {
13172: &logthis("Name $name no IP found");
13173: next;
13174: }
13175: } else {
13176: $ip=inet_ntoa($ip);
1.847 albertel 13177: }
13178: $name_to_ip{$name} = $ip;
13179: } else {
13180: $ip = $name_to_ip{$name};
1.653 albertel 13181: }
1.888 albertel 13182: foreach my $id (@{ $name_to_host{$name} }) {
13183: $lonid_to_ip{$id} = $ip;
13184: }
13185: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13186: }
1.1293 raeburn 13187: unless ($nocache) {
13188: &do_cache_new('iphost','iphost',
13189: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13190: 48*60*60);
13191: }
1.869 albertel 13192:
1.847 albertel 13193: return %iphost;
1.598 albertel 13194: }
13195:
1.992 raeburn 13196: #
13197: # Given a DNS returns the loncapa host name for that DNS
13198: #
13199: sub host_from_dns {
13200: my ($dns) = @_;
13201: my @hosts;
13202: my $ip;
13203:
1.993 raeburn 13204: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13205: $ip = $name_to_ip{$dns};
13206: }
13207: if (!$ip) {
13208: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13209: if (length($ip) == 4) {
13210: $ip = &IO::Socket::inet_ntoa($ip);
13211: }
13212: }
13213: if ($ip) {
13214: @hosts = get_hosts_from_ip($ip);
13215: return $hosts[0];
13216: }
13217: return undef;
1.986 foxr 13218: }
1.992 raeburn 13219:
1.1074 raeburn 13220: sub get_internet_names {
13221: my ($lonid) = @_;
13222: return if ($lonid eq '');
13223: my ($idnref,$cached)=
13224: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13225: if ($cached) {
13226: return $idnref;
13227: }
13228: my $ip = &get_host_ip($lonid);
13229: my @hosts = &get_hosts_from_ip($ip);
13230: my %iphost = &get_iphost();
13231: my (@idns,%seen);
13232: foreach my $id (@hosts) {
13233: my $dom = &host_domain($id);
13234: my $prim_id = &domain($dom,'primary');
13235: my $prim_ip = &get_host_ip($prim_id);
13236: next if ($seen{$prim_ip});
13237: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13238: foreach my $id (@{$iphost{$prim_ip}}) {
13239: my $intdom = &internet_dom($id);
13240: unless (grep(/^\Q$intdom\E$/,@idns)) {
13241: push(@idns,$intdom);
13242: }
13243: }
13244: }
13245: $seen{$prim_ip} = 1;
13246: }
1.1219 raeburn 13247: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13248: }
13249:
1.986 foxr 13250: }
13251:
1.1079 raeburn 13252: sub all_loncaparevs {
1.1249 raeburn 13253: 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 13254: }
13255:
1.1227 raeburn 13256: # ---------------------------------------------------------- Read loncaparev table
13257: {
13258: sub load_loncaparevs {
13259: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13260: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13261: while (my $configline=<$config>) {
13262: chomp($configline);
13263: my ($hostid,$loncaparev)=split(/:/,$configline);
13264: $loncaparevs{$hostid}=$loncaparev;
13265: }
13266: close($config);
13267: }
13268: }
13269: }
13270: }
13271:
13272: # ---------------------------------------------------------- Read serverhostID table
13273: {
13274: sub load_serverhomeIDs {
13275: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13276: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13277: while (my $configline=<$config>) {
13278: chomp($configline);
13279: my ($name,$id)=split(/:/,$configline);
13280: $serverhomeIDs{$name}=$id;
13281: }
13282: close($config);
13283: }
13284: }
13285: }
13286: }
13287:
13288:
1.862 albertel 13289: BEGIN {
13290:
13291: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13292: unless ($readit) {
13293: {
13294: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13295: %perlvar = (%perlvar,%{$configvars});
13296: }
13297:
13298:
1.1 albertel 13299: # ------------------------------------------------------ Read spare server file
13300: {
1.448 albertel 13301: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13302:
13303: while (my $configline=<$config>) {
13304: chomp($configline);
1.284 matthew 13305: if ($configline) {
1.784 albertel 13306: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13307: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13308: push(@{ $spareid{$type} }, $host);
1.1 albertel 13309: }
13310: }
1.448 albertel 13311: close($config);
1.1 albertel 13312: }
1.11 www 13313: # ------------------------------------------------------------ Read permissions
13314: {
1.448 albertel 13315: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13316:
13317: while (my $configline=<$config>) {
1.448 albertel 13318: chomp($configline);
13319: if ($configline) {
13320: my ($role,$perm)=split(/ /,$configline);
13321: if ($perm ne '') { $pr{$role}=$perm; }
13322: }
1.11 www 13323: }
1.448 albertel 13324: close($config);
1.11 www 13325: }
13326:
13327: # -------------------------------------------- Read plain texts for permissions
13328: {
1.448 albertel 13329: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13330:
13331: while (my $configline=<$config>) {
1.448 albertel 13332: chomp($configline);
13333: if ($configline) {
1.742 raeburn 13334: my ($short,@plain)=split(/:/,$configline);
13335: %{$prp{$short}} = ();
13336: if (@plain > 0) {
13337: $prp{$short}{'std'} = $plain[0];
13338: for (my $i=1; $i<@plain; $i++) {
13339: $prp{$short}{'alt'.$i} = $plain[$i];
13340: }
13341: }
1.448 albertel 13342: }
1.135 www 13343: }
1.448 albertel 13344: close($config);
1.135 www 13345: }
13346:
13347: # ---------------------------------------------------------- Read package table
13348: {
1.448 albertel 13349: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13350:
13351: while (my $configline=<$config>) {
1.483 albertel 13352: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13353: chomp($configline);
13354: my ($short,$plain)=split(/:/,$configline);
13355: my ($pack,$name)=split(/\&/,$short);
13356: if ($plain ne '') {
13357: $packagetab{$pack.'&'.$name.'&name'}=$name;
13358: $packagetab{$short}=$plain;
13359: }
1.11 www 13360: }
1.448 albertel 13361: close($config);
1.329 matthew 13362: }
13363:
1.1073 raeburn 13364: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 13365:
13366: &load_loncaparevs();
1.1073 raeburn 13367:
1.1074 raeburn 13368: # ---------------------------------------------------------- Read serverhostID table
13369:
1.1227 raeburn 13370: &load_serverhomeIDs();
13371:
13372: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13373: {
13374: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13375: if (-e $file) {
13376: my $parser = HTML::LCParser->new($file);
13377: while (my $token = $parser->get_token()) {
13378: if ($token->[0] eq 'S') {
13379: my $item = $token->[1];
13380: my $name = $token->[2]{'name'};
13381: my $value = $token->[2]{'value'};
1.1285 raeburn 13382: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 13383: my $namematch = $token->[2]{'namematch'};
13384: if ($item eq 'parameter') {
13385: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13386: my $release = $parser->get_text();
13387: $release =~ s/(^\s*|\s*$ )//gx;
13388: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13389: }
13390: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 13391: my $release = $parser->get_text();
13392: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 13393: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 13394: }
13395: }
13396: }
13397: }
1.1073 raeburn 13398: }
13399:
1.1138 raeburn 13400: # ---------------------------------------------------------- Read managers table
13401: {
13402: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13403: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13404: while (my $configline=<$config>) {
13405: chomp($configline);
13406: next if ($configline =~ /^\#/);
13407: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13408: $managerstab{$configline} = 1;
13409: }
13410: }
13411: close($config);
13412: }
13413: }
13414: }
13415:
1.329 matthew 13416: # ------------- set up temporary directory
13417: {
1.1117 foxr 13418: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13419:
1.11 www 13420: }
13421:
1.794 albertel 13422: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13423: 'compress_threshold'=> 20_000,
13424: });
1.185 www 13425:
1.281 www 13426: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13427: $dumpcount=0;
1.958 www 13428: $locknum=0;
1.22 www 13429:
1.163 harris41 13430: &logtouch();
1.672 albertel 13431: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13432: $readit=1;
1.564 albertel 13433: {
13434: use integer;
13435: my $test=(2**32)+1;
1.568 albertel 13436: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13437: &logthis(" Detected 64bit platform ($_64bit)");
13438: }
1.195 www 13439: }
1.1 albertel 13440: }
1.179 www 13441:
1.1 albertel 13442: 1;
1.191 harris41 13443: __END__
13444:
1.243 albertel 13445: =pod
13446:
1.191 harris41 13447: =head1 NAME
13448:
1.243 albertel 13449: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13450:
13451: =head1 SYNOPSIS
13452:
1.243 albertel 13453: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13454:
13455: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13456:
1.243 albertel 13457: Common parameters:
13458:
13459: =over 4
13460:
13461: =item *
13462:
13463: $uname : an internal username (if $cname expecting a course Id specifically)
13464:
13465: =item *
13466:
13467: $udom : a domain (if $cdom expecting a course's domain specifically)
13468:
13469: =item *
13470:
13471: $symb : a resource instance identifier
13472:
13473: =item *
13474:
13475: $namespace : the name of a .db file that contains the data needed or
13476: being set.
13477:
13478: =back
13479:
1.394 bowersj2 13480: =head1 OVERVIEW
1.191 harris41 13481:
1.394 bowersj2 13482: lonnet provides subroutines which interact with the
13483: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13484: about classes, users, and resources.
1.243 albertel 13485:
13486: For many of these objects you can also use this to store data about
13487: them or modify them in various ways.
1.191 harris41 13488:
1.394 bowersj2 13489: =head2 Symbs
1.191 harris41 13490:
1.394 bowersj2 13491: To identify a specific instance of a resource, LON-CAPA uses symbols
13492: or "symbs"X<symb>. These identifiers are built from the URL of the
13493: map, the resource number of the resource in the map, and the URL of
13494: the resource itself. The latter is somewhat redundant, but might help
13495: if maps change.
13496:
13497: An example is
13498:
13499: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13500:
13501: The respective map entry is
13502:
13503: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13504: title="Problem 2">
13505: </resource>
13506:
13507: Symbs are used by the random number generator, as well as to store and
13508: restore data specific to a certain instance of for example a problem.
13509:
13510: =head2 Storing And Retrieving Data
13511:
13512: X<store()>X<cstore()>X<restore()>Three of the most important functions
13513: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13514: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13515: is is the non-critical message twin of cstore. These functions are for
13516: handlers to store a perl hash to a user's permanent data space in an
13517: easy manner, and to retrieve it again on another call. It is expected
13518: that a handler would use this once at the beginning to retrieve data,
13519: and then again once at the end to send only the new data back.
13520:
13521: The data is stored in the user's data directory on the user's
13522: homeserver under the ID of the course.
13523:
13524: The hash that is returned by restore will have all of the previous
13525: value for all of the elements of the hash.
13526:
13527: Example:
13528:
13529: #creating a hash
13530: my %hash;
13531: $hash{'foo'}='bar';
13532:
13533: #storing it
13534: &Apache::lonnet::cstore(\%hash);
13535:
13536: #changing a value
13537: $hash{'foo'}='notbar';
13538:
13539: #adding a new value
13540: $hash{'bar'}='foo';
13541: &Apache::lonnet::cstore(\%hash);
13542:
13543: #retrieving the hash
13544: my %history=&Apache::lonnet::restore();
13545:
13546: #print the hash
13547: foreach my $key (sort(keys(%history))) {
13548: print("\%history{$key} = $history{$key}");
13549: }
13550:
13551: Will print out:
1.191 harris41 13552:
1.394 bowersj2 13553: %history{1:foo} = bar
13554: %history{1:keys} = foo:timestamp
13555: %history{1:timestamp} = 990455579
13556: %history{2:bar} = foo
13557: %history{2:foo} = notbar
13558: %history{2:keys} = foo:bar:timestamp
13559: %history{2:timestamp} = 990455580
13560: %history{bar} = foo
13561: %history{foo} = notbar
13562: %history{timestamp} = 990455580
13563: %history{version} = 2
13564:
13565: Note that the special hash entries C<keys>, C<version> and
13566: C<timestamp> were added to the hash. C<version> will be equal to the
13567: total number of versions of the data that have been stored. The
13568: C<timestamp> attribute will be the UNIX time the hash was
13569: stored. C<keys> is available in every historical section to list which
13570: keys were added or changed at a specific historical revision of a
13571: hash.
13572:
13573: B<Warning>: do not store the hash that restore returns directly. This
13574: will cause a mess since it will restore the historical keys as if the
13575: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13576:
1.394 bowersj2 13577: Calling convention:
1.191 harris41 13578:
1.1225 raeburn 13579: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 13580: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13581:
1.394 bowersj2 13582: For more detailed information, see lonnet specific documentation.
1.191 harris41 13583:
1.394 bowersj2 13584: =head1 RETURN MESSAGES
1.191 harris41 13585:
1.394 bowersj2 13586: =over 4
1.191 harris41 13587:
1.394 bowersj2 13588: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13589:
1.394 bowersj2 13590: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13591: when the connection is brought back up
1.191 harris41 13592:
1.394 bowersj2 13593: =item * B<con_failed>: unable to contact remote host and unable to save message
13594: for later delivery
1.191 harris41 13595:
1.967 bisitz 13596: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13597:
1.394 bowersj2 13598: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13599: that was requested
1.191 harris41 13600:
1.243 albertel 13601: =back
1.191 harris41 13602:
1.243 albertel 13603: =head1 PUBLIC SUBROUTINES
1.191 harris41 13604:
1.243 albertel 13605: =head2 Session Environment Functions
1.191 harris41 13606:
1.243 albertel 13607: =over 4
1.191 harris41 13608:
1.394 bowersj2 13609: =item *
13610: X<appenv()>
1.949 raeburn 13611: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13612: the user envirnoment file, and will be restored for each access this
1.620 albertel 13613: user makes during this session, also modifies the %env for the current
1.949 raeburn 13614: process. Optional rolesarrayref - if defined contains a reference to an array
13615: of roles which are exempt from the restriction on modifying user.role entries
13616: in the user's environment.db and in %env.
1.191 harris41 13617:
13618: =item *
1.394 bowersj2 13619: X<delenv()>
1.987 raeburn 13620: B<delenv($delthis,$regexp)>: removes all items from the session
13621: environment file that begin with $delthis. If the
13622: optional second arg - $regexp - is true, $delthis is treated as a
13623: regular expression, otherwise \Q$delthis\E is used.
13624: The values are also deleted from the current processes %env.
1.191 harris41 13625:
1.795 albertel 13626: =item * get_env_multiple($name)
13627:
13628: gets $name from the %env hash, it seemlessly handles the cases where multiple
13629: values may be defined and end up as an array ref.
13630:
13631: returns an array of values
13632:
1.243 albertel 13633: =back
13634:
13635: =head2 User Information
1.191 harris41 13636:
1.243 albertel 13637: =over 4
1.191 harris41 13638:
13639: =item *
1.394 bowersj2 13640: X<queryauthenticate()>
13641: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13642: authentication scheme
13643:
13644: =item *
1.394 bowersj2 13645: X<authenticate()>
1.1073 raeburn 13646: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13647: authenticate user from domain's lib servers (first use the current
13648: one). C<$upass> should be the users password.
1.1073 raeburn 13649: $checkdefauth is optional (value is 1 if a check should be made to
13650: authenticate user using default authentication method, and allow
13651: account creation if username does not have account in the domain).
13652: $clientcancheckhost is optional (value is 1 if checking whether the
13653: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13654:
13655: =item *
1.394 bowersj2 13656: X<homeserver()>
13657: B<homeserver($uname,$udom)>: find the server which has
13658: the user's directory and files (there must be only one), this caches
13659: the answer, and also caches if there is a borken connection.
1.191 harris41 13660:
13661: =item *
1.394 bowersj2 13662: X<idget()>
1.1300 raeburn 13663: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
13664: a list of student/employee IDs or clicker IDs
13665: (student/employee IDs are a unique resource in a domain, there must be
13666: only 1 ID per username, and only 1 username per ID in a specific domain).
13667: clickerIDs are not necessarily unique, as students might share clickers.
13668: (returns hash: id=>name,id=>name)
1.191 harris41 13669:
13670: =item *
1.394 bowersj2 13671: X<idrget()>
13672: B<idrget($udom,@unames)>: find the IDs behind a list of
13673: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13674:
13675: =item *
1.394 bowersj2 13676: X<idput()>
1.1300 raeburn 13677: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
13678: names and associated student/employee IDs or clicker IDs.
13679:
13680: =item *
13681: X<iddel()>
13682: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
13683: student/employee ID or clicker ID username look-ups from domain.
13684: The homeserver ($uhome) and namespace ($namespace) are optional.
13685: If no $uhome is provided, it will be determined usig &homeserver()
13686: for each user. If no $namespace is provided, the default is ids.
13687:
13688: =item *
13689: X<updateclickers()>
13690: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
13691: clicker ID-to-username look-ups in clickers.db on library server.
13692: Permitted actions are add or del (i.e., add or delete). The
13693: clickers.db contains clickerID as keys (escaped), and each corresponding
13694: value is an escaped comma-separated list of usernames (for whom the
13695: library server is the homeserver), who registered that particular ID.
13696: If $critical is true, the update will be sent via &critical, otherwise
13697: &reply() will be used.
1.191 harris41 13698:
13699: =item *
1.394 bowersj2 13700: X<rolesinit()>
1.1169 droeschl 13701: B<rolesinit($udom,$username)>: get user privileges.
13702: returns user role, first access and timer interval hashes
1.243 albertel 13703:
13704: =item *
1.1171 droeschl 13705: X<privileged()>
13706: B<privileged($username,$domain)>: returns a true if user has a
13707: privileged and active role (i.e. su or dc), false otherwise.
13708:
13709: =item *
1.551 albertel 13710: X<getsection()>
13711: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13712: course $cname, return section name/number or '' for "not in course"
13713: and '-1' for "no section"
13714:
13715: =item *
1.394 bowersj2 13716: X<userenvironment()>
13717: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13718: passed in @what from the requested user's environment, returns a hash
13719:
1.858 raeburn 13720: =item *
13721: X<userlog_query()>
1.859 albertel 13722: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13723: activity.log file. %filters defines filters applied when parsing the
13724: log file. These can be start or end timestamps, or the type of action
13725: - log to look for Login or Logout events, check for Checkin or
13726: Checkout, role for role selection. The response is in the form
13727: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13728: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13729:
1.243 albertel 13730: =back
13731:
13732: =head2 User Roles
13733:
13734: =over 4
13735:
13736: =item *
13737:
1.1284 raeburn 13738: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13739: returns codes for allowed actions.
13740:
13741: The first argument is required, all others are optional.
13742:
13743: $priv is the privilege being checked.
13744: $uri contains additional information about what is being checked for access (e.g.,
13745: URL, course ID etc.).
13746: $symb is the unique resource instance identifier in a course; if needed,
13747: but not provided, it will be retrieved via a call to &symbread().
13748: $role is the role for which a priv is being checked (only used if priv is evb).
13749: $clientip is the user's IP address (only used when checking for access to portfolio
13750: files).
13751: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13752: prevents recursive calls to &allowed.
13753:
1.243 albertel 13754: F: full access
13755: U,I,K: authentication modes (cxx only)
13756: '': forbidden
13757: 1: user needs to choose course
13758: 2: browse allowed
1.766 albertel 13759: A: passphrase authentication needed
1.1284 raeburn 13760: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13761:
13762: =item *
13763:
1.1192 raeburn 13764: constructaccess($url,$setpriv) : check for access to construction space URL
13765:
13766: See if the owner domain and name in the URL match those in the
13767: expected environment. If so, return three element list
13768: ($ownername,$ownerdomain,$ownerhome).
13769:
13770: Otherwise return the null string.
13771:
13772: If second argument 'setpriv' is true, it assigns the privileges,
13773: and returns the same three element list, unless the owner has
13774: blocked "ad hoc" Domain Coordinator access to the Author Space,
13775: in which case the null string is returned.
13776:
13777: =item *
13778:
1.1326 raeburn 13779: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
13780: define a custom role rolename set privileges in format of lonTabs/roles.tab
13781: for system, domain, and course level. $uname and $udom are optional (current
13782: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 13783:
13784: =item *
13785:
1.988 raeburn 13786: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13787: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13788: $type is Course (default) or Community.
1.988 raeburn 13789: If $forcedefault evaluates to true, text returned will be default
13790: text for $type. Otherwise, if this is a course, the text returned
13791: will be a custom name for the role (if defined in the course's
13792: environment). If no custom name is defined the default is returned.
13793:
1.832 raeburn 13794: =item *
13795:
1.1219 raeburn 13796: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13797: All arguments are optional. Returns a hash of a roles, either for
13798: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13799: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13800: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13801: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13802: For each key, value is set to colon-separated start and end times for
13803: the role. If no username and domain are specified, will default to
1.934 raeburn 13804: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13805: of role statuses (active, future or previous), roles
13806: (e.g., cc,in, st etc.) and domains of the roles which can be used
13807: to restrict the list of roles reported. If no array ref is
13808: provided for types, will default to return only active roles.
1.834 albertel 13809:
1.1195 raeburn 13810: =item *
13811:
13812: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 13813: user: $uname:$udom has a role in the course: $cdom_$cnum.
13814:
13815: Additional optional arguments are: $type (if role checking is to be restricted
13816: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 13817: available roles) or future (roles available in the future), and
13818: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 13819: have active Domain Coordinator role in course's domain or in additional
13820: domains (specified in 'Domains to check for privileged users' in course
13821: environment -- set via: Course Settings -> Classlists and staff listing).
13822:
13823: =item *
13824:
13825: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13826: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13827: $possdomains and $possroles are optional array refs -- to domains to check and
13828: roles to check. If $possdomains is not specified, a dump will be done of the
13829: users' roles.db to check for a dc or su role in any domain. This can be
13830: time consuming if &privileged is called repeatedly (e.g., when displaying a
13831: classlist), so in such cases, supplying a $possdomains array is preferred, as
13832: this then allows &privileged_by_domain() to be used, which caches the identity
13833: of privileged users, eliminating the need for repeated calls to &dump().
13834:
13835: =item *
13836:
13837: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13838: where the outer hash keys are domains specified in the $possdomains array ref,
13839: next inner hash keys are privileged roles specified in the $roles array ref,
13840: and the innermost hash contains key = value pairs for username:domain = end:start
13841: for active or future "privileged" users with that role in that domain. To avoid
13842: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13843: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 13844:
1.243 albertel 13845: =back
13846:
13847: =head2 User Modification
13848:
13849: =over 4
13850:
13851: =item *
13852:
1.957 raeburn 13853: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13854: user for the level given by URL. Optional start and end dates (leave empty
13855: string or zero for "no date")
1.191 harris41 13856:
13857: =item *
13858:
1.243 albertel 13859: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13860: change a users, password, possible return values are: ok,
13861: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13862: refused
1.191 harris41 13863:
13864: =item *
13865:
1.243 albertel 13866: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13867:
13868: =item *
13869:
1.1058 raeburn 13870: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13871: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13872:
13873: will update user information (firstname,middlename,lastname,generation,
13874: permanentemail), and if forceid is true, student/employee ID also.
13875: A user's institutional affiliation(s) can also be updated.
13876: User information fields will not be overwritten with empty entries
13877: unless the field is included in the $candelete array reference.
13878: This array is included when a single user is modified via "Manage Users",
13879: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13880:
13881: =item *
13882:
1.286 matthew 13883: modifystudent
13884:
1.957 raeburn 13885: modify a student's enrollment and identification information.
1.1235 raeburn 13886: The course id is resolved based on the current user's environment.
13887: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13888: associated with a course.
13889:
1.297 matthew 13890: This call is essentially a wrapper for lonnet::modifyuser and
13891: lonnet::modify_student_enrollment
1.286 matthew 13892:
13893: Inputs:
13894:
13895: =over 4
13896:
1.957 raeburn 13897: =item B<$udom> Student's loncapa domain
1.286 matthew 13898:
1.957 raeburn 13899: =item B<$uname> Student's loncapa login name
1.286 matthew 13900:
1.964 bisitz 13901: =item B<$uid> Student/Employee ID
1.286 matthew 13902:
1.957 raeburn 13903: =item B<$umode> Student's authentication mode
1.286 matthew 13904:
1.957 raeburn 13905: =item B<$upass> Student's password
1.286 matthew 13906:
1.957 raeburn 13907: =item B<$first> Student's first name
1.286 matthew 13908:
1.957 raeburn 13909: =item B<$middle> Student's middle name
1.286 matthew 13910:
1.957 raeburn 13911: =item B<$last> Student's last name
1.286 matthew 13912:
1.957 raeburn 13913: =item B<$gene> Student's generation
1.286 matthew 13914:
1.957 raeburn 13915: =item B<$usec> Student's section in course
1.286 matthew 13916:
13917: =item B<$end> Unix time of the roles expiration
13918:
13919: =item B<$start> Unix time of the roles start date
13920:
13921: =item B<$forceid> If defined, allow $uid to be changed
13922:
13923: =item B<$desiredhome> server to use as home server for student
13924:
1.957 raeburn 13925: =item B<$email> Student's permanent e-mail address
13926:
13927: =item B<$type> Type of enrollment (auto or manual)
13928:
1.963 raeburn 13929: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13930:
13931: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13932:
1.963 raeburn 13933: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13934:
1.963 raeburn 13935: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13936:
1.1216 raeburn 13937: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13938:
13939: =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 13940:
1.286 matthew 13941: =back
1.297 matthew 13942:
13943: =item *
13944:
13945: modify_student_enrollment
13946:
1.1235 raeburn 13947: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13948: 'role.request.course' must be defined for this function to proceed.
13949:
13950: Inputs:
13951:
13952: =over 4
13953:
1.1235 raeburn 13954: =item $udom, student's domain
1.297 matthew 13955:
1.1235 raeburn 13956: =item $uname, student's name
1.297 matthew 13957:
1.1235 raeburn 13958: =item $uid, student's user id
1.297 matthew 13959:
1.1235 raeburn 13960: =item $first, student's first name
1.297 matthew 13961:
13962: =item $middle
13963:
13964: =item $last
13965:
13966: =item $gene
13967:
13968: =item $usec
13969:
13970: =item $end
13971:
13972: =item $start
13973:
1.957 raeburn 13974: =item $type
13975:
13976: =item $locktype
13977:
13978: =item $cid
13979:
13980: =item $selfenroll
13981:
13982: =item $context
13983:
1.1216 raeburn 13984: =item $credits, number of credits student will earn from this class
13985:
1.1314 raeburn 13986: =item $instsec, institutional course section code for student
13987:
1.297 matthew 13988: =back
13989:
1.191 harris41 13990:
13991: =item *
13992:
1.243 albertel 13993: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13994: custom role; give a custom role to a user for the level given by URL. Specify
13995: name and domain of role author, and role name
1.191 harris41 13996:
13997: =item *
13998:
1.243 albertel 13999: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 14000:
14001: =item *
14002:
1.243 albertel 14003: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14004:
14005: =back
14006:
14007: =head2 Course Infomation
14008:
14009: =over 4
1.191 harris41 14010:
14011: =item *
14012:
1.1118 foxr 14013: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 14014: specified course id, including all environment settings for the
14015: course, the description of the course will be in the hash under the
14016: key 'description'
1.191 harris41 14017:
1.1118 foxr 14018: $options is an optional parameter that if supplied is a hash reference that controls
14019: what how this function works. It has the following key/values:
14020:
14021: =over 4
14022:
14023: =item freshen_cache
14024:
14025: If defined, and the environment cache for the course is valid, it is
14026: returned in the returned hash.
14027:
14028: =item one_time
14029:
14030: If defined, the last cache time is set to _now_
14031:
14032: =item user
14033:
14034: If defined, the supplied username is used instead of the current user.
14035:
14036:
14037: =back
14038:
1.191 harris41 14039: =item *
14040:
1.624 albertel 14041: resdata($name,$domain,$type,@which) : request for current parameter
14042: setting for a specific $type, where $type is either 'course' or 'user',
14043: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 14044: answers for 10 minutes.
1.243 albertel 14045:
1.877 foxr 14046: =item *
14047:
14048: get_courseresdata($courseid, $domain) : dump the entire course resource
14049: data base, returning a hash that is keyed by the resource name and has
14050: values that are the resource value. I believe that the timestamps and
14051: versions are also returned.
14052:
1.1236 raeburn 14053: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14054: supplemental content area. This routine caches the number of files for
14055: 10 minutes.
14056:
1.243 albertel 14057: =back
14058:
14059: =head2 Course Modification
14060:
14061: =over 4
1.191 harris41 14062:
14063: =item *
14064:
1.243 albertel 14065: writecoursepref($courseid,%prefs) : write preferences (environment
14066: database) for a course
1.191 harris41 14067:
14068: =item *
14069:
1.1011 raeburn 14070: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14071:
14072: =item *
14073:
1.1038 raeburn 14074: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14075:
1.1167 droeschl 14076: =item *
14077:
14078: is_course($courseid), is_course($cdom, $cnum)
14079:
14080: Accepts either a combined $courseid (in the form of domain_courseid) or the
14081: two component version $cdom, $cnum. It checks if the specified course exists.
14082:
14083: Returns:
14084: undef if the course doesn't exist, otherwise
14085: in scalar context the combined courseid.
14086: in list context the two components of the course identifier, domain and
14087: courseid.
14088:
1.243 albertel 14089: =back
14090:
14091: =head2 Resource Subroutines
14092:
14093: =over 4
1.191 harris41 14094:
14095: =item *
14096:
1.243 albertel 14097: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14098:
14099: =item *
14100:
1.243 albertel 14101: repcopy($filename) : subscribes to the requested file, and attempts to
14102: replicate from the owning library server, Might return
1.607 raeburn 14103: 'unavailable', 'not_found', 'forbidden', 'ok', or
14104: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14105: resource. Expects the local filesystem pathname
14106: (/home/httpd/html/res/....)
14107:
14108: =back
14109:
14110: =head2 Resource Information
14111:
14112: =over 4
1.191 harris41 14113:
14114: =item *
14115:
1.1228 raeburn 14116: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14117: and returns the value of a variety of different possible values,
14118: $varname should be a request string, and the other parameters can be
14119: used to specify who and what one is asking about. Ordinarily, $cid
14120: does not need to be specified, as it is retrived from
14121: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14122: within lonuserstate::loadmap() when initializing a course, before
14123: $env{'request.course.id'} has been set, so it needs to be provided
14124: in that one case.
1.243 albertel 14125:
14126: Possible values for $varname are environment.lastname (or other item
14127: from the envirnment hash), user.name (or someother aspect about the
14128: user), resource.0.maxtries (or some other part and parameter of a
14129: resource)
1.204 albertel 14130:
14131: =item *
14132:
1.243 albertel 14133: directcondval($number) : get current value of a condition; reads from a state
14134: string
1.204 albertel 14135:
14136: =item *
14137:
1.243 albertel 14138: condval($condidx) : value of condition index based on state
1.204 albertel 14139:
14140: =item *
14141:
1.243 albertel 14142: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14143: resource's metadata, $what should be either a specific key, or either
14144: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14145: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14146:
14147: this function automatically caches all requests
1.191 harris41 14148:
14149: =item *
14150:
1.243 albertel 14151: metadata_query($query,$custom,$customshow) : make a metadata query against the
14152: network of library servers; returns file handle of where SQL and regex results
14153: will be stored for query
1.191 harris41 14154:
14155: =item *
14156:
1.1282 raeburn 14157: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14158: return symbolic list entry (all arguments optional).
14159:
14160: Args: filename is the filename (including path) for the file for which a symb
14161: is required; donotrecurse, if true will prevent calls to allowed() being made
14162: to check access status if more than one resource was found in the bighash
14163: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14164: a randompick); ignorecachednull, if true will prevent a symb of '' being
14165: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14166: cause possible symbs to be checked to determine if they are subject to content
14167: blocking, if so they will not be included as possible symbs; possibles is a
14168: ref to a hash, which, as a side effect, will be populated with all possible
14169: symbs (content blocking not tested).
14170:
1.243 albertel 14171: returns the data handle
1.191 harris41 14172:
14173: =item *
14174:
1.1190 raeburn 14175: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14176: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14177: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 14178: on failure, user must be in a course, as it assumes the existence of
14179: the course initial hash, and uses $env('request.course.id'}. The third
14180: arg is an optional reference to a scalar. If this arg is passed in the
14181: call to symbverify, it will be set to 1 if the symb has been set to be
14182: encrypted; otherwise it will be null.
1.191 harris41 14183:
14184: =item *
14185:
1.243 albertel 14186: symbclean($symb) : removes versions numbers from a symb, returns the
14187: cleaned symb
1.191 harris41 14188:
14189: =item *
14190:
1.243 albertel 14191: is_on_map($uri) : checks if the $uri is somewhere on the current
14192: course map, user must be in a course for it to work.
1.191 harris41 14193:
14194: =item *
14195:
1.243 albertel 14196: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14197:
14198: =item *
14199:
1.243 albertel 14200: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14201: a random seed, all arguments are optional, if they aren't sent it uses the
14202: environment to derive them. Note: if symb isn't sent and it can't get one
14203: from &symbread it will use the current time as its return value
1.191 harris41 14204:
14205: =item *
14206:
1.243 albertel 14207: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14208: unfakeable, receipt
1.191 harris41 14209:
14210: =item *
14211:
1.620 albertel 14212: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14213:
14214: =item *
14215:
1.243 albertel 14216: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14217:
14218: =item *
14219:
1.243 albertel 14220: 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 14221:
14222: =item *
14223:
1.243 albertel 14224: 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 14225:
14226: =item *
14227:
1.243 albertel 14228: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14229:
14230: =item *
14231:
1.243 albertel 14232: devalidate($symb) : devalidate temporary spreadsheet calculations,
14233: forcing spreadsheet to reevaluate the resource scores next time.
14234:
1.1195 raeburn 14235: =item *
14236:
1.1196 raeburn 14237: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14238: when viewing in course context.
1.1195 raeburn 14239:
1.1196 raeburn 14240: input: six args -- filename (decluttered), course number, course domain,
14241: url, symb (if registered) and group (if this is a
14242: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 14243:
1.1196 raeburn 14244: output: array of five scalars --
1.1195 raeburn 14245: $cfile -- url for file editing if editable on current server
14246: $home -- homeserver of resource (i.e., for author if published,
14247: or course if uploaded.).
14248: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 14249: $forceedit -- 1 if icon/link should be to go to edit mode
14250: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 14251:
14252: =item *
14253:
14254: is_course_upload($file,$cnum,$cdom)
14255:
14256: Used in course context to determine if current file was uploaded to
14257: the course (i.e., would be found in /userfiles/docs on the course's
14258: homeserver.
14259:
14260: input: 3 args -- filename (decluttered), course number and course domain.
14261: output: boolean -- 1 if file was uploaded.
14262:
1.243 albertel 14263: =back
14264:
14265: =head2 Storing/Retreiving Data
14266:
14267: =over 4
1.191 harris41 14268:
14269: =item *
14270:
1.1269 raeburn 14271: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14272: permanently for this url; hashref needs to be given and should be a \%hashname;
14273: the remaining args aren't required and if they aren't passed or are '' they will
14274: be derived from the env (with the exception of $laststore, which is an
14275: optional arg used when a user's submission is stored in grading).
14276: $laststore is $version=$timestamp, where $version is the most recent version
14277: number retrieved for the corresponding $symb in the $namespace db file, and
14278: $timestamp is the timestamp for that transaction (UNIX time).
14279: $laststore is currently only passed when cstore() is called by
14280: structuretags::finalize_storage().
1.191 harris41 14281:
14282: =item *
14283:
1.1269 raeburn 14284: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14285: but uses critical subroutine
1.191 harris41 14286:
14287: =item *
14288:
1.243 albertel 14289: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14290: all args are optional
1.191 harris41 14291:
14292: =item *
14293:
1.717 albertel 14294: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14295: dumps the complete (or key matching regexp) namespace into a hash
14296: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14297: normally &store()ed into
14298:
14299: $range should be either an integer '100' (give me the first 100
14300: matching records)
14301: or be two integers sperated by a - with no spaces
14302: '30-50' (give me the 30th through the 50th matching
14303: records)
14304:
14305:
14306: =item *
14307:
1.1269 raeburn 14308: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14309: replaces a &store() version of data with a replacement set of data
14310: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 14311: reference. If $tolog is true, the transaction is logged in the courselog
14312: with an action=PUTSTORE.
1.717 albertel 14313:
14314: =item *
14315:
1.243 albertel 14316: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14317: works very similar to store/cstore, but all data is stored in a
14318: temporary location and can be reset using tmpreset, $storehash should
14319: be a hash reference, returns nothing on success
1.191 harris41 14320:
14321: =item *
14322:
1.243 albertel 14323: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14324: similar to restore, but all data is stored in a temporary location and
14325: can be reset using tmpreset. Returns a hash of values on success,
14326: error string otherwise.
1.191 harris41 14327:
14328: =item *
14329:
1.243 albertel 14330: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14331: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14332:
14333: =item *
14334:
1.243 albertel 14335: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14336: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14337:
14338: =item *
14339:
1.243 albertel 14340: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14341: namesp ($udom and $uname are optional)
1.191 harris41 14342:
14343: =item *
14344:
1.702 albertel 14345: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14346: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14347: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14348:
1.702 albertel 14349: $range should be either an integer '100' (give me the first 100
14350: matching records)
14351: or be two integers sperated by a - with no spaces
14352: '30-50' (give me the 30th through the 50th matching
14353: records)
1.449 matthew 14354: =item *
14355:
14356: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14357: $store can be a scalar, an array reference, or if the amount to be
14358: incremented is > 1, a hash reference.
14359:
14360: ($udom and $uname are optional)
1.191 harris41 14361:
14362: =item *
14363:
1.243 albertel 14364: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14365: ($udom and $uname are optional)
1.191 harris41 14366:
14367: =item *
14368:
1.243 albertel 14369: cput($namespace,$storehash,$udom,$uname) : critical put
14370: ($udom and $uname are optional)
1.191 harris41 14371:
14372: =item *
14373:
1.748 albertel 14374: newput($namespace,$storehash,$udom,$uname) :
14375:
14376: Attempts to store the items in the $storehash, but only if they don't
14377: currently exist, if this succeeds you can be certain that you have
14378: successfully created a new key value pair in the $namespace db.
14379:
14380:
14381: Args:
14382: $namespace: name of database to store values to
14383: $storehash: hashref to store to the db
14384: $udom: (optional) domain of user containing the db
14385: $uname: (optional) name of user caontaining the db
14386:
14387: Returns:
14388: 'ok' -> succeeded in storing all keys of $storehash
14389: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14390: least <key> already existed in the db (other
14391: requested keys may also already exist)
1.967 bisitz 14392: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14393: 'con_lost' -> unable to contact request server
14394: 'refused' -> action was not allowed by remote machine
14395:
14396:
14397: =item *
14398:
1.243 albertel 14399: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14400: reference filled in from namesp (encrypts the return communication)
14401: ($udom and $uname are optional)
1.191 harris41 14402:
14403: =item *
14404:
1.243 albertel 14405: log($udom,$name,$home,$message) : write to permanent log for user; use
14406: critical subroutine
14407:
1.806 raeburn 14408: =item *
14409:
1.860 raeburn 14410: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14411: array reference filled in from namespace found in domain level on either
14412: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14413:
14414: =item *
14415:
1.860 raeburn 14416: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14417: domain level either on specified domain server ($uhome) or primary domain
14418: server ($udom and $uhome are optional)
1.806 raeburn 14419:
1.943 raeburn 14420: =item *
14421:
1.1240 raeburn 14422: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14423: for: authentication, language, quotas, timezone, date locale, and portal URL in
14424: the target domain.
14425:
14426: May also include additional key => value pairs for the following groups:
14427:
14428: =over
14429:
14430: =item
14431: disk quotas (MB allocated by default to portfolios and authoring spaces).
14432:
14433: =over
14434:
14435: =item defaultquota, authorquota
14436:
14437: =back
14438:
14439: =item
14440: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14441: portfolio for users).
14442:
14443: =over
14444:
14445: =item
14446: aboutme, blog, webdav, portfolio
14447:
14448: =back
14449:
14450: =item
14451: requestcourses: ability to request courses, and how requests are processed.
14452:
14453: =over
14454:
14455: =item
1.1305 raeburn 14456: official, unofficial, community, textbook, placement
1.1240 raeburn 14457:
14458: =back
14459:
14460: =item
14461: inststatus: types of institutional affiliation, and order in which they are displayed.
14462:
14463: =over
14464:
14465: =item
1.1256 raeburn 14466: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 14467:
14468: =back
14469:
14470: =item
14471: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14472: for course's uploaded content.
14473:
14474: =over
14475:
14476: =item
1.1246 raeburn 14477: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 14478: communityquota, textbookquota, placementquota
1.1240 raeburn 14479:
14480: =back
14481:
14482: =item
14483: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14484: on your servers.
14485:
14486: =over
14487:
14488: =item
14489: remotesessions, hostedsessions
14490:
14491: =back
14492:
14493: =back
14494:
14495: In cases where a domain coordinator has never used the "Set Domain Configuration"
14496: utility to create a configuration.db file on a domain's primary library server
14497: only the following domain defaults: auth_def, auth_arg_def, lang_def
14498: -- corresponding values are authentication type (internal, krb4, krb5,
14499: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14500: will be available. Values are retrieved from cache (if current), unless the
14501: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14502: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14503:
14504: Typical usage:
1.943 raeburn 14505:
1.1240 raeburn 14506: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14507:
1.243 albertel 14508: =back
14509:
14510: =head2 Network Status Functions
14511:
14512: =over 4
1.191 harris41 14513:
14514: =item *
14515:
1.1137 raeburn 14516: dirlist() : return directory list based on URI (first arg).
14517:
14518: Inputs: 1 required, 5 optional.
14519:
14520: =over
14521:
14522: =item
14523: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14524:
14525: =item
14526: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14527:
14528: =item
14529: $username - username of user/course to be listed. Extracted from $uri if absent.
14530:
14531: =item
14532: $getpropath - boolean: 1 if prepend path using &propath().
14533:
14534: =item
14535: $getuserdir - boolean: 1 if prepend path for "userfiles".
14536:
14537: =item
14538: $alternateRoot - path to prepend in place of path from $uri.
14539:
14540: =back
14541:
14542: Returns: Array of up to two items.
14543:
14544: =over
14545:
14546: a reference to an array of files/subdirectories
14547:
14548: =over
14549:
14550: Each element in the array of files/subdirectories is a & separated list of
14551: item name and the result of running stat on the item. If dirlist was requested
14552: for a file instead of a directory, the item name will be ''. For a directory
14553: listing, if the item is a metadata file, the element will end &N&M
14554: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14555: default copyright set (1).
14556:
14557: =back
14558:
14559: a scalar containing error condition (if encountered).
14560:
14561: =over
14562:
14563: =item
14564: no_host (no homeserver identified for $username:$domain).
14565:
14566: =item
14567: no_such_host (server contacted for listing not identified as valid host).
14568:
14569: =item
14570: con_lost (connection to remote server failed).
14571:
14572: =item
14573: refused (invalid $username:$domain received on lond side).
14574:
14575: =item
14576: no_such_dir (directory at specified path on lond side does not exist).
14577:
14578: =item
14579: empty (directory at specified path on lond side is empty).
14580:
14581: =over
14582:
14583: This is currently not encountered because the &ls3, &ls2,
14584: &ls (_handler) routines on the lond side do not filter out
14585: . and .. from a directory listing.
14586:
14587: =back
14588:
14589: =back
14590:
14591: =back
1.191 harris41 14592:
14593: =item *
14594:
1.243 albertel 14595: spareserver() : find server with least workload from spare.tab
14596:
1.986 foxr 14597:
14598: =item *
14599:
14600: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14601: if there is no corresponding loncapa host.
14602:
1.243 albertel 14603: =back
14604:
1.986 foxr 14605:
1.243 albertel 14606: =head2 Apache Request
14607:
14608: =over 4
1.191 harris41 14609:
14610: =item *
14611:
1.243 albertel 14612: ssi($url,%hash) : server side include, does a complete request cycle on url to
14613: localhost, posts hash
14614:
14615: =back
14616:
14617: =head2 Data to String to Data
14618:
14619: =over 4
1.191 harris41 14620:
14621: =item *
14622:
1.243 albertel 14623: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14624: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14625:
14626: =item *
14627:
1.243 albertel 14628: hashref2str($hashref) : convert a hashref into a string complete with
14629: escaping and '=' and '&' separators, supports elements that are
14630: arrayrefs and hashrefs
1.191 harris41 14631:
14632: =item *
14633:
1.243 albertel 14634: arrayref2str($arrayref) : convert an arrayref into a string complete
14635: with escaping and '&' separators, supports elements that are arrayrefs
14636: and hashrefs
1.191 harris41 14637:
14638: =item *
14639:
1.243 albertel 14640: str2hash($string) : convert string to hash using unescaping and
14641: splitting on '=' and '&', supports elements that are arrayrefs and
14642: hashrefs
1.191 harris41 14643:
14644: =item *
14645:
1.243 albertel 14646: str2array($string) : convert string to hash using unescaping and
14647: splitting on '&', supports elements that are arrayrefs and hashrefs
14648:
14649: =back
14650:
14651: =head2 Logging Routines
14652:
14653:
14654: These routines allow one to make log messages in the lonnet.log and
14655: lonnet.perm logfiles.
1.191 harris41 14656:
1.1119 foxr 14657: =over 4
14658:
1.191 harris41 14659: =item *
14660:
1.243 albertel 14661: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14662:
14663: =item *
14664:
1.243 albertel 14665: logthis() : append message to the normal lonnet.log file, it gets
14666: preiodically rolled over and deleted.
1.191 harris41 14667:
14668: =item *
14669:
1.243 albertel 14670: logperm() : append a permanent message to lonnet.perm.log, this log
14671: file never gets deleted by any automated portion of the system, only
14672: messages of critical importance should go in here.
14673:
1.1119 foxr 14674:
1.243 albertel 14675: =back
14676:
14677: =head2 General File Helper Routines
14678:
14679: =over 4
1.191 harris41 14680:
14681: =item *
14682:
1.481 raeburn 14683: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14684: (a) files in /uploaded
14685: (i) If a local copy of the file exists -
14686: compares modification date of local copy with last-modified date for
14687: definitive version stored on home server for course. If local copy is
14688: stale, requests a new version from the home server and stores it.
14689: If the original has been removed from the home server, then local copy
14690: is unlinked.
14691: (ii) If local copy does not exist -
14692: requests the file from the home server and stores it.
14693:
14694: If $caller is 'uploadrep':
14695: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14696: for request for files originally uploaded via DOCS.
14697: - returns 'ok' if fresh local copy now available, -1 otherwise.
14698:
14699: Otherwise:
14700: This indicates a call from the content generation phase of the request.
14701: - returns the entire contents of the file or -1.
14702:
14703: (b) files in /res
14704: - returns the entire contents of a file or -1;
14705: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14706:
1.712 albertel 14707:
14708: =item *
14709:
14710: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14711: reference
14712:
14713: returns either a stat() list of data about the file or an empty list
14714: if the file doesn't exist or couldn't find out about it (connection
14715: problems or user unknown)
14716:
1.191 harris41 14717: =item *
14718:
1.243 albertel 14719: filelocation($dir,$file) : returns file system location of a file
14720: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14721: directory that relative $file lookups are to looked in ($dir of /a/dir
14722: and a file of ../bob will become /a/bob)
1.191 harris41 14723:
14724: =item *
14725:
14726: hreflocation($dir,$file) : returns file system location or a URL; same as
14727: filelocation except for hrefs
14728:
14729: =item *
14730:
1.1261 raeburn 14731: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14732: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14733:
1.243 albertel 14734: =back
14735:
1.608 albertel 14736: =head2 Usererfile file routines (/uploaded*)
14737:
14738: =over 4
14739:
14740: =item *
14741:
14742: userfileupload(): main rotine for putting a file in a user or course's
14743: filespace, arguments are,
14744:
1.620 albertel 14745: formname - required - this is the name of the element in $env where the
1.608 albertel 14746: filename, and the contents of the file to create/modifed exist
1.620 albertel 14747: the filename is in $env{'form.'.$formname.'.filename'} and the
14748: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14749: context - if coursedoc, store the file in the course of the active role
14750: of the current user;
14751: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14752: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14753: subdir - required - subdirectory to put the file in under ../userfiles/
14754: if undefined, it will be placed in "unknown"
14755:
14756: (This routine calls clean_filename() to remove any dangerous
14757: characters from the filename, and then calls finuserfileupload() to
14758: complete the transaction)
14759:
14760: returns either the url of the uploaded file (/uploaded/....) if successful
14761: and /adm/notfound.html if unsuccessful
14762:
14763: =item *
14764:
14765: clean_filename(): routine for cleaing a filename up for storage in
14766: userfile space, argument is:
14767:
14768: filename - proposed filename
14769:
14770: returns: the new clean filename
14771:
14772: =item *
14773:
1.1090 raeburn 14774: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14775: userspace, probably shouldn't be called directly
14776:
14777: docuname: username or courseid of destination for the file
14778: docudom: domain of user/course of destination for the file
14779: formname: same as for userfileupload()
1.1090 raeburn 14780: fname: filename (including subdirectories) for the file
14781: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14782: allfiles: reference to hash used to store objects found by parser
14783: codebase: reference to hash used for codebases of java objects found by parser
14784: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14785: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14786: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14787: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14788: context: if 'overwrite', will move the uploaded file from its temporary location to
14789: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14790: mimetype: reference to scalar to accommodate mime type determined
14791: from File::MMagic if $parser = parse.
1.608 albertel 14792:
14793: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14794: and /adm/notfound.html if unsuccessful (or an error message if context
14795: was 'overwrite').
14796:
1.608 albertel 14797:
14798: =item *
14799:
14800: renameuserfile(): renames an existing userfile to a new name
14801:
14802: Args:
14803: docuname: username or courseid of destination for the file
14804: docudom: domain of user/course of destination for the file
14805: old: current file name (including any subdirs under userfiles)
14806: new: desired file name (including any subdirs under userfiles)
14807:
14808: =item *
14809:
14810: mkdiruserfile(): creates a directory is a userfiles dir
14811:
14812: Args:
14813: docuname: username or courseid of destination for the file
14814: docudom: domain of user/course of destination for the file
14815: dir: dir to create (including any subdirs under userfiles)
14816:
14817: =item *
14818:
14819: removeuserfile(): removes a file that exists in userfiles
14820:
14821: Args:
14822: docuname: username or courseid of destination for the file
14823: docudom: domain of user/course of destination for the file
14824: fname: filname to delete (including any subdirs under userfiles)
14825:
14826: =item *
14827:
14828: removeuploadedurl(): convience function for removeuserfile()
14829:
14830: Args:
14831: url: a full /uploaded/... url to delete
14832:
1.747 albertel 14833: =item *
14834:
14835: get_portfile_permissions():
14836: Args:
14837: domain: domain of user or course contain the portfolio files
14838: user: name of user or num of course contain the portfolio files
14839: Returns:
14840: hashref of a dump of the proper file_permissions.db
14841:
14842:
14843: =item *
14844:
14845: get_access_controls():
14846:
14847: Args:
14848: current_permissions: the hash ref returned from get_portfile_permissions()
14849: group: (optional) the group you want the files associated with
14850: file: (optional) the file you want access info on
14851:
14852: Returns:
1.749 raeburn 14853: a hash (keys are file names) of hashes containing
14854: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14855: values are XML containing access control settings (see below)
1.747 albertel 14856:
14857: Internal notes:
14858:
1.749 raeburn 14859: access controls are stored in file_permissions.db as key=value pairs.
14860: key -> path to file/file_name\0uniqueID:scope_end_start
14861: where scope -> public,guest,course,group,domains or users.
14862: end -> UNIX time for end of access (0 -> no end date)
14863: start -> UNIX time for start of access
14864:
14865: value -> XML description of access control
14866: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14867: <start></start>
14868: <end></end>
14869:
14870: <password></password> for scope type = guest
14871:
14872: <domain></domain> for scope type = course or group
14873: <number></number>
14874: <roles id="">
14875: <role></role>
14876: <access></access>
14877: <section></section>
14878: <group></group>
14879: </roles>
14880:
14881: <dom></dom> for scope type = domains
14882:
14883: <users> for scope type = users
14884: <user>
14885: <uname></uname>
14886: <udom></udom>
14887: </user>
14888: </users>
14889: </scope>
14890:
14891: Access data is also aggregated for each file in an additional key=value pair:
14892: key -> path to file/file_name\0accesscontrol
14893: value -> reference to hash
14894: hash contains key = value pairs
14895: where key = uniqueID:scope_end_start
14896: value = UNIX time record was last updated
14897:
14898: Used to improve speed of look-ups of access controls for each file.
14899:
14900: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14901:
1.1198 raeburn 14902: =item *
14903:
1.749 raeburn 14904: modify_access_controls():
14905:
14906: Modifies access controls for a portfolio file
14907: Args
14908: 1. file name
14909: 2. reference to hash of required changes,
14910: 3. domain
14911: 4. username
14912: where domain,username are the domain of the portfolio owner
14913: (either a user or a course)
14914:
14915: Returns:
14916: 1. result of additions or updates ('ok' or 'error', with error message).
14917: 2. result of deletions ('ok' or 'error', with error message).
14918: 3. reference to hash of any new or updated access controls.
14919: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14920: key = integer (inbound ID)
1.1198 raeburn 14921: value = uniqueID
14922:
14923: =item *
14924:
14925: get_timebased_id():
14926:
14927: Attempts to get a unique timestamp-based suffix for use with items added to a
14928: course via the Course Editor (e.g., folders, composite pages,
14929: group bulletin boards).
14930:
14931: Args: (first three required; six others optional)
14932:
14933: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14934: docssequence, or name of group
14935:
14936: 2. keyid (alphanumeric): name of temporary locking key in hash,
14937: e.g., num, boardids
14938:
14939: 3. namespace: name of gdbm file used to store suffixes already assigned;
14940: file will be named nohist_namespace.db
14941:
14942: 4. cdom: domain of course; default is current course domain from %env
14943:
14944: 5. cnum: course number; default is current course number from %env
14945:
14946: 6. idtype: set to concat if an additional digit is to be appended to the
14947: unix timestamp to form the suffix, if the plain timestamp is already
14948: in use. Default is to not do this, but simply increment the unix
14949: timestamp by 1 until a unique key is obtained.
14950:
14951: 7. who: holder of locking key; defaults to user:domain for user.
14952:
14953: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14954: retrying); default is 3.
14955:
14956: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14957:
14958: Returns:
14959:
14960: 1. suffix obtained (numeric)
14961:
14962: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14963:
14964: 3. error: contains (localized) error message if an error occurred.
14965:
1.747 albertel 14966:
1.608 albertel 14967: =back
14968:
1.243 albertel 14969: =head2 HTTP Helper Routines
14970:
14971: =over 4
14972:
1.191 harris41 14973: =item *
14974:
14975: escape() : unpack non-word characters into CGI-compatible hex codes
14976:
14977: =item *
14978:
14979: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14980:
1.243 albertel 14981: =back
14982:
14983: =head1 PRIVATE SUBROUTINES
14984:
14985: =head2 Underlying communication routines (Shouldn't call)
14986:
14987: =over 4
14988:
14989: =item *
14990:
14991: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14992:
14993: =item *
14994:
14995: reply() : uses subreply to send a message to remote machine, logs all failures
14996:
14997: =item *
14998:
14999: critical() : passes a critical message to another server; if cannot
15000: get through then place message in connection buffer directory and
15001: returns con_delayed, if incapable of saving message, returns
15002: con_failed
15003:
15004: =item *
15005:
15006: reconlonc() : tries to reconnect lonc client processes.
15007:
15008: =back
15009:
15010: =head2 Resource Access Logging
15011:
15012: =over 4
15013:
15014: =item *
15015:
15016: flushcourselogs() : flush (save) buffer logs and access logs
15017:
15018: =item *
15019:
15020: courselog($what) : save message for course in hash
15021:
15022: =item *
15023:
15024: courseacclog($what) : save message for course using &courselog(). Perform
15025: special processing for specific resource types (problems, exams, quizzes, etc).
15026:
1.191 harris41 15027: =item *
15028:
15029: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15030: as a PerlChildExitHandler
1.243 albertel 15031:
15032: =back
15033:
15034: =head2 Other
15035:
15036: =over 4
15037:
15038: =item *
15039:
15040: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15041:
15042: =back
15043:
15044: =cut
1.877 foxr 15045:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>