Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1328
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1328 ! raeburn 4: # $Id: lonnet.pm,v 1.1327 2016/10/05 21:21:06 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.1104 raeburn 5837: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5838: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5839: my $setprivs;
1.994 raeburn 5840: if ($env{$cckey}) {
5841: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5842: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5843: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5844: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5845: $setprivs = 1;
1.994 raeburn 5846: }
5847: } else {
1.1088 raeburn 5848: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5849: $setprivs = 1;
1.994 raeburn 5850: }
1.1185 raeburn 5851: return $setprivs;
1.994 raeburn 5852: }
5853:
5854: sub set_adhoc_privileges {
1.1326 raeburn 5855: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1088 raeburn 5856: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5857: my $area = '/'.$dcdom.'/'.$pickedcourse;
5858: my $spec = $role.'.'.$area;
5859: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5860: $env{'user.name'},1);
1.1326 raeburn 5861: my %rolehash = ();
5862: if ($role =~ m{^cr/$dcdom/$dcdom\Q-domainconfig\E/}) {
5863: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
5864: } else {
5865: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
5866: }
5867: my ($author,$adv)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 5868: &appenv(\%userroles,[$role,'cm']);
5869: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5870: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5871: &appenv( {'request.role' => $spec,
5872: 'request.role.domain' => $dcdom,
5873: 'request.course.sec' => ''
5874: }
5875: );
5876: my $tadv=0;
5877: if (&allowed('adv') eq 'F') { $tadv=1; }
5878: &appenv({'request.role.adv' => $tadv});
5879: }
1.994 raeburn 5880: }
5881:
1.12 www 5882: # --------------------------------------------------------------- get interface
5883:
5884: sub get {
1.131 albertel 5885: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5886: my $items='';
1.800 albertel 5887: foreach my $item (@$storearr) {
5888: $items.=&escape($item).'&';
1.191 harris41 5889: }
1.12 www 5890: $items=~s/\&$//;
1.620 albertel 5891: if (!$udomain) { $udomain=$env{'user.domain'}; }
5892: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5893: my $uhome=&homeserver($uname,$udomain);
5894:
1.133 albertel 5895: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5896: my @pairs=split(/\&/,$rep);
1.273 albertel 5897: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5898: return @pairs;
5899: }
1.15 www 5900: my %returnhash=();
1.42 www 5901: my $i=0;
1.800 albertel 5902: foreach my $item (@$storearr) {
5903: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5904: $i++;
1.191 harris41 5905: }
1.15 www 5906: return %returnhash;
1.27 www 5907: }
5908:
5909: # --------------------------------------------------------------- del interface
5910:
5911: sub del {
1.133 albertel 5912: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5913: my $items='';
1.800 albertel 5914: foreach my $item (@$storearr) {
5915: $items.=&escape($item).'&';
1.191 harris41 5916: }
1.984 neumanie 5917:
1.27 www 5918: $items=~s/\&$//;
1.620 albertel 5919: if (!$udomain) { $udomain=$env{'user.domain'}; }
5920: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5921: my $uhome=&homeserver($uname,$udomain);
5922: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5923: }
5924:
5925: # -------------------------------------------------------------- dump interface
5926:
1.1180 droeschl 5927: sub unserialize {
5928: my ($rep, $escapedkeys) = @_;
5929:
5930: return {} if $rep =~ /^error/;
5931:
5932: my %returnhash=();
1.1252 raeburn 5933: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5934: my ($key, $value) = split(/=/, $item, 2);
5935: $key = unescape($key) unless $escapedkeys;
5936: next if $key =~ /^error: 2 /;
1.1252 raeburn 5937: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5938: }
5939: #return %returnhash;
5940: return \%returnhash;
5941: }
5942:
5943: # see Lond::dump_with_regexp
5944: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5945: sub dump {
1.1180 droeschl 5946: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5947: if (!$udomain) { $udomain=$env{'user.domain'}; }
5948: if (!$uname) { $uname=$env{'user.name'}; }
5949: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5950:
1.1266 raeburn 5951: if ($regexp) {
5952: $regexp=&escape($regexp);
5953: } else {
5954: $regexp='.';
5955: }
1.1180 droeschl 5956: if (grep { $_ eq $uhome } current_machine_ids()) {
5957: # user is hosted on this machine
1.1266 raeburn 5958: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5959: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5960: return %{unserialize($reply, $escapedkeys)};
5961: }
1.1166 raeburn 5962: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5963: my @pairs=split(/\&/,$rep);
5964: my %returnhash=();
1.1098 foxr 5965: if (!($rep =~ /^error/ )) {
5966: foreach my $item (@pairs) {
5967: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5968: $key = unescape($key) unless $escapedkeys;
5969: #$key = &unescape($key);
1.1098 foxr 5970: next if ($key =~ /^error: 2 /);
5971: $returnhash{$key}=&thaw_unescape($value);
5972: }
1.755 albertel 5973: }
5974: return %returnhash;
1.407 www 5975: }
5976:
1.1098 foxr 5977:
1.717 albertel 5978: # --------------------------------------------------------- dumpstore interface
5979:
5980: sub dumpstore {
5981: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5982: # same as dump but keys must be escaped. They may contain colon separated
5983: # lists of values that may themself contain colons (e.g. symbs).
5984: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5985: }
5986:
1.407 www 5987: # -------------------------------------------------------------- keys interface
5988:
5989: sub getkeys {
5990: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5991: if (!$udomain) { $udomain=$env{'user.domain'}; }
5992: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5993: my $uhome=&homeserver($uname,$udomain);
5994: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5995: my @keyarray=();
1.800 albertel 5996: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5997: next if ($key =~ /^error: 2 /);
1.800 albertel 5998: push(@keyarray,&unescape($key));
1.407 www 5999: }
6000: return @keyarray;
1.318 matthew 6001: }
6002:
1.319 matthew 6003: # --------------------------------------------------------------- currentdump
6004: sub currentdump {
1.328 matthew 6005: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6006: $courseid = $env{'request.course.id'} if (! defined($courseid));
6007: $sdom = $env{'user.domain'} if (! defined($sdom));
6008: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6009: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 6010: my $rep;
6011:
6012: if (grep { $_ eq $uhome } current_machine_ids()) {
6013: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6014: $courseid)));
6015: } else {
6016: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6017: }
6018:
1.318 matthew 6019: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6020: #
1.318 matthew 6021: my %returnhash=();
1.319 matthew 6022: #
6023: if ($rep eq "unknown_cmd") {
6024: # an old lond will not know currentdump
6025: # Do a dump and make it look like a currentdump
1.822 albertel 6026: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6027: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6028: my %hash = @tmp;
6029: @tmp=();
1.424 matthew 6030: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6031: } else {
6032: my @pairs=split(/\&/,$rep);
1.800 albertel 6033: foreach my $pair (@pairs) {
6034: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6035: my ($symb,$param) = split(/:/,$key);
6036: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6037: &thaw_unescape($value);
1.319 matthew 6038: }
1.191 harris41 6039: }
1.12 www 6040: return %returnhash;
1.424 matthew 6041: }
6042:
6043: sub convert_dump_to_currentdump{
6044: my %hash = %{shift()};
6045: my %returnhash;
6046: # Code ripped from lond, essentially. The only difference
6047: # here is the unescaping done by lonnet::dump(). Conceivably
6048: # we might run in to problems with parameter names =~ /^v\./
6049: while (my ($key,$value) = each(%hash)) {
6050: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6051: $symb = &unescape($symb);
6052: $param = &unescape($param);
1.424 matthew 6053: next if ($v eq 'version' || $symb eq 'keys');
6054: next if (exists($returnhash{$symb}) &&
6055: exists($returnhash{$symb}->{$param}) &&
6056: $returnhash{$symb}->{'v.'.$param} > $v);
6057: $returnhash{$symb}->{$param}=$value;
6058: $returnhash{$symb}->{'v.'.$param}=$v;
6059: }
6060: #
6061: # Remove all of the keys in the hashes which keep track of
6062: # the version of the parameter.
6063: while (my ($symb,$param_hash) = each(%returnhash)) {
6064: # use a foreach because we are going to delete from the hash.
6065: foreach my $key (keys(%$param_hash)) {
6066: delete($param_hash->{$key}) if ($key =~ /^v\./);
6067: }
6068: }
6069: return \%returnhash;
1.12 www 6070: }
6071:
1.627 albertel 6072: # ------------------------------------------------------ critical inc interface
6073:
6074: sub cinc {
6075: return &inc(@_,'critical');
6076: }
6077:
1.449 matthew 6078: # --------------------------------------------------------------- inc interface
6079:
6080: sub inc {
1.627 albertel 6081: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6082: if (!$udomain) { $udomain=$env{'user.domain'}; }
6083: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6084: my $uhome=&homeserver($uname,$udomain);
6085: my $items='';
6086: if (! ref($store)) {
6087: # got a single value, so use that instead
6088: $items = &escape($store).'=&';
6089: } elsif (ref($store) eq 'SCALAR') {
6090: $items = &escape($$store).'=&';
6091: } elsif (ref($store) eq 'ARRAY') {
6092: $items = join('=&',map {&escape($_);} @{$store});
6093: } elsif (ref($store) eq 'HASH') {
6094: while (my($key,$value) = each(%{$store})) {
6095: $items.= &escape($key).'='.&escape($value).'&';
6096: }
6097: }
6098: $items=~s/\&$//;
1.627 albertel 6099: if ($critical) {
6100: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6101: } else {
6102: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6103: }
1.449 matthew 6104: }
6105:
1.12 www 6106: # --------------------------------------------------------------- put interface
6107:
6108: sub put {
1.134 albertel 6109: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6110: if (!$udomain) { $udomain=$env{'user.domain'}; }
6111: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6112: my $uhome=&homeserver($uname,$udomain);
1.12 www 6113: my $items='';
1.800 albertel 6114: foreach my $item (keys(%$storehash)) {
6115: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6116: }
1.12 www 6117: $items=~s/\&$//;
1.134 albertel 6118: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6119: }
6120:
1.631 albertel 6121: # ------------------------------------------------------------ newput interface
6122:
6123: sub newput {
6124: my ($namespace,$storehash,$udomain,$uname)=@_;
6125: if (!$udomain) { $udomain=$env{'user.domain'}; }
6126: if (!$uname) { $uname=$env{'user.name'}; }
6127: my $uhome=&homeserver($uname,$udomain);
6128: my $items='';
6129: foreach my $key (keys(%$storehash)) {
6130: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6131: }
6132: $items=~s/\&$//;
6133: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6134: }
6135:
6136: # --------------------------------------------------------- putstore interface
6137:
1.524 raeburn 6138: sub putstore {
1.1269 raeburn 6139: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6140: if (!$udomain) { $udomain=$env{'user.domain'}; }
6141: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6142: my $uhome=&homeserver($uname,$udomain);
6143: my $items='';
1.715 albertel 6144: foreach my $key (keys(%$storehash)) {
6145: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6146: }
1.715 albertel 6147: $items=~s/\&$//;
1.716 albertel 6148: my $esc_symb=&escape($symb);
6149: my $esc_v=&escape($version);
1.715 albertel 6150: my $reply =
1.716 albertel 6151: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6152: $uhome);
1.1269 raeburn 6153: if (($tolog) && ($reply eq 'ok')) {
6154: my $namevalue='';
6155: foreach my $key (keys(%{$storehash})) {
6156: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6157: }
6158: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6159: '&host='.&escape($perlvar{'lonHostID'}).
6160: '&version='.$esc_v.
6161: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6162: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6163: }
1.715 albertel 6164: if ($reply eq 'unknown_cmd') {
1.716 albertel 6165: # gfall back to way things use to be done
1.715 albertel 6166: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6167: $uname);
1.524 raeburn 6168: }
1.715 albertel 6169: return $reply;
6170: }
6171:
6172: sub old_putstore {
1.716 albertel 6173: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6174: if (!$udomain) { $udomain=$env{'user.domain'}; }
6175: if (!$uname) { $uname=$env{'user.name'}; }
6176: my $uhome=&homeserver($uname,$udomain);
6177: my %newstorehash;
1.800 albertel 6178: foreach my $item (keys(%$storehash)) {
6179: my $key = $version.':'.&escape($symb).':'.$item;
6180: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6181: }
6182: my $items='';
6183: my %allitems = ();
1.800 albertel 6184: foreach my $item (keys(%newstorehash)) {
6185: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6186: my $key = $1.':keys:'.$2;
6187: $allitems{$key} .= $3.':';
6188: }
1.800 albertel 6189: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6190: }
1.800 albertel 6191: foreach my $item (keys(%allitems)) {
6192: $allitems{$item} =~ s/\:$//;
6193: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6194: }
6195: $items=~s/\&$//;
6196: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6197: }
6198:
1.47 www 6199: # ------------------------------------------------------ critical put interface
6200:
6201: sub cput {
1.134 albertel 6202: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6203: if (!$udomain) { $udomain=$env{'user.domain'}; }
6204: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6205: my $uhome=&homeserver($uname,$udomain);
1.47 www 6206: my $items='';
1.800 albertel 6207: foreach my $item (keys(%$storehash)) {
6208: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6209: }
1.47 www 6210: $items=~s/\&$//;
1.134 albertel 6211: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6212: }
6213:
6214: # -------------------------------------------------------------- eget interface
6215:
6216: sub eget {
1.133 albertel 6217: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6218: my $items='';
1.800 albertel 6219: foreach my $item (@$storearr) {
6220: $items.=&escape($item).'&';
1.191 harris41 6221: }
1.12 www 6222: $items=~s/\&$//;
1.620 albertel 6223: if (!$udomain) { $udomain=$env{'user.domain'}; }
6224: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6225: my $uhome=&homeserver($uname,$udomain);
6226: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6227: my @pairs=split(/\&/,$rep);
6228: my %returnhash=();
1.42 www 6229: my $i=0;
1.800 albertel 6230: foreach my $item (@$storearr) {
6231: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6232: $i++;
1.191 harris41 6233: }
1.12 www 6234: return %returnhash;
6235: }
6236:
1.667 albertel 6237: # ------------------------------------------------------------ tmpput interface
6238: sub tmpput {
1.802 raeburn 6239: my ($storehash,$server,$context)=@_;
1.667 albertel 6240: my $items='';
1.800 albertel 6241: foreach my $item (keys(%$storehash)) {
6242: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6243: }
6244: $items=~s/\&$//;
1.802 raeburn 6245: if (defined($context)) {
6246: $items .= ':'.&escape($context);
6247: }
1.667 albertel 6248: return &reply("tmpput:$items",$server);
6249: }
6250:
6251: # ------------------------------------------------------------ tmpget interface
6252: sub tmpget {
1.688 albertel 6253: my ($token,$server)=@_;
6254: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6255: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6256: my %returnhash;
1.1328 ! raeburn 6257: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
! 6258: return %returnhash;
! 6259: }
1.667 albertel 6260: foreach my $item (split(/\&/,$rep)) {
6261: my ($key,$value)=split(/=/,$item);
6262: $returnhash{&unescape($key)}=&thaw_unescape($value);
6263: }
6264: return %returnhash;
6265: }
6266:
1.1113 raeburn 6267: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6268: sub tmpdel {
6269: my ($token,$server)=@_;
6270: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6271: return &reply("tmpdel:$token",$server);
6272: }
6273:
1.1198 raeburn 6274: # ------------------------------------------------------------ get_timebased_id
6275:
6276: sub get_timebased_id {
6277: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6278: $maxtries) = @_;
6279: my ($newid,$error,$dellock);
6280: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6281: return ('','ok','invalid call to get suffix');
6282: }
6283:
6284: # set defaults for any optional args for which values were not supplied
6285: if ($who eq '') {
6286: $who = $env{'user.name'}.':'.$env{'user.domain'};
6287: }
6288: if (!$locktries) {
6289: $locktries = 3;
6290: }
6291: if (!$maxtries) {
6292: $maxtries = 10;
6293: }
6294:
6295: if (($cdom eq '') || ($cnum eq '')) {
6296: if ($env{'request.course.id'}) {
6297: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6298: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6299: }
6300: if (($cdom eq '') || ($cnum eq '')) {
6301: return ('','ok','call to get suffix not in course context');
6302: }
6303: }
6304:
6305: # construct locking item
6306: my $lockhash = {
6307: $prefix."\0".'locked_'.$keyid => $who,
6308: };
6309: my $tries = 0;
6310:
6311: # attempt to get lock on nohist_$namespace file
6312: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6313: while (($gotlock ne 'ok') && $tries <$locktries) {
6314: $tries ++;
6315: sleep 1;
6316: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6317: }
6318:
6319: # attempt to get unique identifier, based on current timestamp
6320: if ($gotlock eq 'ok') {
6321: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6322: my $id = time;
6323: $newid = $id;
1.1268 raeburn 6324: if ($idtype eq 'addcode') {
6325: $newid .= &sixnum_code();
6326: }
1.1198 raeburn 6327: my $idtries = 0;
6328: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6329: if ($idtype eq 'concat') {
6330: $newid = $id.$idtries;
1.1268 raeburn 6331: } elsif ($idtype eq 'addcode') {
6332: $newid = $newid.&sixnum_code();
1.1198 raeburn 6333: } else {
6334: $newid ++;
6335: }
6336: $idtries ++;
6337: }
6338: if (!exists($inuse{$prefix."\0".$newid})) {
6339: my %new_item = (
6340: $prefix."\0".$newid => $who,
6341: );
6342: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6343: $cdom,$cnum);
6344: if ($putresult ne 'ok') {
6345: undef($newid);
6346: $error = 'error saving new item: '.$putresult;
6347: }
6348: } else {
1.1268 raeburn 6349: undef($newid);
1.1198 raeburn 6350: $error = ('error: no unique suffix available for the new item ');
6351: }
6352: # remove lock
6353: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6354: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6355: } else {
6356: $error = "error: could not obtain lockfile\n";
6357: $dellock = 'ok';
1.1276 raeburn 6358: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6359: $dellock = 'nolock';
6360: }
1.1198 raeburn 6361: }
6362: return ($newid,$dellock,$error);
6363: }
6364:
1.1268 raeburn 6365: sub sixnum_code {
6366: my $code;
6367: for (0..6) {
6368: $code .= int( rand(9) );
6369: }
6370: return $code;
6371: }
6372:
1.765 albertel 6373: # -------------------------------------------------- portfolio access checking
6374:
6375: sub portfolio_access {
1.1270 raeburn 6376: my ($requrl,$clientip) = @_;
1.765 albertel 6377: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6378: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6379: if ($result) {
6380: my %setters;
6381: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6382: my ($startblock,$endblock) =
6383: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6384: if ($startblock && $endblock) {
6385: return 'B';
6386: }
6387: } else {
6388: my ($startblock,$endblock) =
6389: &Apache::loncommon::blockcheck(\%setters,'port');
6390: if ($startblock && $endblock) {
6391: return 'B';
6392: }
6393: }
6394: }
1.765 albertel 6395: if ($result eq 'ok') {
1.766 albertel 6396: return 'F';
1.765 albertel 6397: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6398: return 'A';
1.765 albertel 6399: }
1.766 albertel 6400: return '';
1.765 albertel 6401: }
6402:
6403: sub get_portfolio_access {
1.1270 raeburn 6404: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6405:
6406: if (!ref($access_hash)) {
6407: my $current_perms = &get_portfile_permissions($udom,$unum);
6408: my %access_controls = &get_access_controls($current_perms,$group,
6409: $file_name);
6410: $access_hash = $access_controls{$file_name};
6411: }
6412:
1.1270 raeburn 6413: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6414: my $now = time;
6415: if (ref($access_hash) eq 'HASH') {
6416: foreach my $key (keys(%{$access_hash})) {
6417: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6418: if ($start > $now) {
6419: next;
6420: }
6421: if ($end && $end<$now) {
6422: next;
6423: }
6424: if ($scope eq 'public') {
6425: $public = $key;
6426: last;
6427: } elsif ($scope eq 'guest') {
6428: $guest = $key;
6429: } elsif ($scope eq 'domains') {
6430: push(@domains,$key);
6431: } elsif ($scope eq 'users') {
6432: push(@users,$key);
6433: } elsif ($scope eq 'course') {
6434: push(@courses,$key);
6435: } elsif ($scope eq 'group') {
6436: push(@groups,$key);
1.1270 raeburn 6437: } elsif ($scope eq 'ip') {
6438: push(@ips,$key);
1.765 albertel 6439: }
6440: }
6441: if ($public) {
6442: return 'ok';
1.1270 raeburn 6443: } elsif (@ips > 0) {
6444: my $allowed;
6445: foreach my $ipkey (@ips) {
6446: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6447: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6448: $allowed = 1;
6449: last;
6450: }
6451: }
6452: }
6453: if ($allowed) {
6454: return 'ok';
6455: }
1.765 albertel 6456: }
6457: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6458: if ($guest) {
6459: return $guest;
6460: }
6461: } else {
6462: if (@domains > 0) {
6463: foreach my $domkey (@domains) {
6464: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6465: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6466: return 'ok';
6467: }
6468: }
6469: }
6470: }
6471: if (@users > 0) {
6472: foreach my $userkey (@users) {
1.865 raeburn 6473: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6474: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6475: if (ref($item) eq 'HASH') {
6476: if (($item->{'uname'} eq $env{'user.name'}) &&
6477: ($item->{'udom'} eq $env{'user.domain'})) {
6478: return 'ok';
6479: }
6480: }
6481: }
6482: }
1.765 albertel 6483: }
6484: }
6485: my %roleshash;
6486: my @courses_and_groups = @courses;
6487: push(@courses_and_groups,@groups);
6488: if (@courses_and_groups > 0) {
6489: my (%allgroups,%allroles);
6490: my ($start,$end,$role,$sec,$group);
6491: foreach my $envkey (%env) {
1.1060 raeburn 6492: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6493: my $cid = $2.'_'.$3;
6494: if ($1 eq 'gr') {
6495: $group = $4;
6496: $allgroups{$cid}{$group} = $env{$envkey};
6497: } else {
6498: if ($4 eq '') {
6499: $sec = 'none';
6500: } else {
6501: $sec = $4;
6502: }
6503: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6504: }
1.811 albertel 6505: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6506: my $cid = $2.'_'.$3;
6507: if ($4 eq '') {
6508: $sec = 'none';
6509: } else {
6510: $sec = $4;
6511: }
6512: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6513: }
6514: }
6515: if (keys(%allroles) == 0) {
6516: return;
6517: }
6518: foreach my $key (@courses_and_groups) {
6519: my %content = %{$$access_hash{$key}};
6520: my $cnum = $content{'number'};
6521: my $cdom = $content{'domain'};
6522: my $cid = $cdom.'_'.$cnum;
6523: if (!exists($allroles{$cid})) {
6524: next;
6525: }
6526: foreach my $role_id (keys(%{$content{'roles'}})) {
6527: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6528: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6529: my @status = @{$content{'roles'}{$role_id}{'access'}};
6530: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6531: foreach my $role (keys(%{$allroles{$cid}})) {
6532: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6533: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6534: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6535: if (grep/^all$/,@sections) {
6536: return 'ok';
6537: } else {
6538: if (grep/^$sec$/,@sections) {
6539: return 'ok';
6540: }
6541: }
6542: }
6543: }
6544: if (keys(%{$allgroups{$cid}}) == 0) {
6545: if (grep/^none$/,@groups) {
6546: return 'ok';
6547: }
6548: } else {
6549: if (grep/^all$/,@groups) {
6550: return 'ok';
6551: }
6552: foreach my $group (keys(%{$allgroups{$cid}})) {
6553: if (grep/^$group$/,@groups) {
6554: return 'ok';
6555: }
6556: }
6557: }
6558: }
6559: }
6560: }
6561: }
6562: }
6563: if ($guest) {
6564: return $guest;
6565: }
6566: }
6567: }
6568: return;
6569: }
6570:
6571: sub course_group_datechecker {
6572: my ($dates,$now,$status) = @_;
6573: my ($start,$end) = split(/\./,$dates);
6574: if (!$start && !$end) {
6575: return 'ok';
6576: }
6577: if (grep/^active$/,@{$status}) {
6578: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6579: return 'ok';
6580: }
6581: }
6582: if (grep/^previous$/,@{$status}) {
6583: if ($end > $now ) {
6584: return 'ok';
6585: }
6586: }
6587: if (grep/^future$/,@{$status}) {
6588: if ($start > $now) {
6589: return 'ok';
6590: }
6591: }
6592: return;
6593: }
6594:
6595: sub parse_portfolio_url {
6596: my ($url) = @_;
6597:
6598: my ($type,$udom,$unum,$group,$file_name);
6599:
1.823 albertel 6600: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6601: $type = 1;
6602: $udom = $1;
6603: $unum = $2;
6604: $file_name = $3;
1.823 albertel 6605: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6606: $type = 2;
6607: $udom = $1;
6608: $unum = $2;
6609: $group = $3;
6610: $file_name = $3.'/'.$4;
6611: }
6612: if (wantarray) {
6613: return ($type,$udom,$unum,$file_name,$group);
6614: }
6615: return $type;
6616: }
6617:
6618: sub is_portfolio_url {
6619: my ($url) = @_;
6620: return scalar(&parse_portfolio_url($url));
6621: }
6622:
1.798 raeburn 6623: sub is_portfolio_file {
6624: my ($file) = @_;
1.820 raeburn 6625: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6626: return 1;
6627: }
6628: return;
6629: }
6630:
1.976 raeburn 6631: sub usertools_access {
1.1084 raeburn 6632: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6633: my ($access,%tools);
6634: if ($context eq '') {
6635: $context = 'tools';
6636: }
6637: if ($context eq 'requestcourses') {
6638: %tools = (
6639: official => 1,
6640: unofficial => 1,
1.1006 raeburn 6641: community => 1,
1.1246 raeburn 6642: textbook => 1,
1.1305 raeburn 6643: placement => 1,
1.985 raeburn 6644: );
1.1183 raeburn 6645: } elsif ($context eq 'requestauthor') {
6646: %tools = (
6647: requestauthor => 1,
6648: );
1.985 raeburn 6649: } else {
6650: %tools = (
6651: aboutme => 1,
6652: blog => 1,
1.1177 raeburn 6653: webdav => 1,
1.985 raeburn 6654: portfolio => 1,
6655: );
6656: }
1.976 raeburn 6657: return if (!defined($tools{$tool}));
6658:
1.1242 raeburn 6659: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6660: $udom = $env{'user.domain'};
6661: $uname = $env{'user.name'};
6662: }
6663:
1.978 raeburn 6664: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6665: if ($action ne 'reload') {
1.985 raeburn 6666: if ($context eq 'requestcourses') {
6667: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6668: } elsif ($context eq 'requestauthor') {
6669: return $env{'environment.canrequest.author'};
1.985 raeburn 6670: } else {
6671: return $env{'environment.availabletools.'.$tool};
6672: }
6673: }
1.976 raeburn 6674: }
6675:
1.1183 raeburn 6676: my ($toolstatus,$inststatus,$envkey);
6677: if ($context eq 'requestauthor') {
6678: $envkey = $context;
6679: } else {
6680: $envkey = $context.'.'.$tool;
6681: }
1.976 raeburn 6682:
1.985 raeburn 6683: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6684: ($action ne 'reload')) {
1.1183 raeburn 6685: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6686: $inststatus = $env{'environment.inststatus'};
6687: } else {
1.1084 raeburn 6688: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6689: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6690: $inststatus = $userenvref->{'inststatus'};
6691: } else {
1.1183 raeburn 6692: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6693: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6694: $inststatus = $userenv{'inststatus'};
6695: }
1.976 raeburn 6696: }
6697:
6698: if ($toolstatus ne '') {
6699: if ($toolstatus) {
6700: $access = 1;
6701: } else {
6702: $access = 0;
6703: }
6704: return $access;
6705: }
6706:
1.1084 raeburn 6707: my ($is_adv,%domdef);
6708: if (ref($is_advref) eq 'HASH') {
6709: $is_adv = $is_advref->{'is_adv'};
6710: } else {
6711: $is_adv = &is_advanced_user($udom,$uname);
6712: }
6713: if (ref($domdefref) eq 'HASH') {
6714: %domdef = %{$domdefref};
6715: } else {
6716: %domdef = &get_domain_defaults($udom);
6717: }
1.976 raeburn 6718: if (ref($domdef{$tool}) eq 'HASH') {
6719: if ($is_adv) {
6720: if ($domdef{$tool}{'_LC_adv'} ne '') {
6721: if ($domdef{$tool}{'_LC_adv'}) {
6722: $access = 1;
6723: } else {
6724: $access = 0;
6725: }
6726: return $access;
6727: }
6728: }
6729: if ($inststatus ne '') {
6730: my ($hasaccess,$hasnoaccess);
6731: foreach my $affiliation (split(/:/,$inststatus)) {
6732: if ($domdef{$tool}{$affiliation} ne '') {
6733: if ($domdef{$tool}{$affiliation}) {
6734: $hasaccess = 1;
6735: } else {
6736: $hasnoaccess = 1;
6737: }
6738: }
6739: }
6740: if ($hasaccess || $hasnoaccess) {
6741: if ($hasaccess) {
6742: $access = 1;
6743: } elsif ($hasnoaccess) {
6744: $access = 0;
6745: }
6746: return $access;
6747: }
6748: } else {
6749: if ($domdef{$tool}{'default'} ne '') {
6750: if ($domdef{$tool}{'default'}) {
6751: $access = 1;
6752: } elsif ($domdef{$tool}{'default'} == 0) {
6753: $access = 0;
6754: }
6755: return $access;
6756: }
6757: }
6758: } else {
1.1177 raeburn 6759: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6760: $access = 1;
6761: } else {
6762: $access = 0;
6763: }
1.976 raeburn 6764: return $access;
6765: }
6766: }
6767:
1.1050 raeburn 6768: sub is_course_owner {
6769: my ($cdom,$cnum,$udom,$uname) = @_;
6770: if (($udom eq '') || ($uname eq '')) {
6771: $udom = $env{'user.domain'};
6772: $uname = $env{'user.name'};
6773: }
6774: unless (($udom eq '') || ($uname eq '')) {
6775: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6776: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6777: return 1;
6778: } else {
6779: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6780: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6781: return 1;
6782: }
6783: }
6784: }
6785: }
6786: return;
6787: }
6788:
1.976 raeburn 6789: sub is_advanced_user {
6790: my ($udom,$uname) = @_;
1.1085 raeburn 6791: if ($udom ne '' && $uname ne '') {
6792: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6793: if (wantarray) {
6794: return ($env{'user.adv'},$env{'user.author'});
6795: } else {
6796: return $env{'user.adv'};
6797: }
1.1085 raeburn 6798: }
6799: }
1.976 raeburn 6800: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6801: my %allroles;
1.1128 raeburn 6802: my ($is_adv,$is_author);
1.976 raeburn 6803: foreach my $role (keys(%roleshash)) {
6804: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6805: my $area = '/'.$tdomain.'/'.$trest;
6806: if ($sec ne '') {
6807: $area .= '/'.$sec;
6808: }
6809: if (($area ne '') && ($trole ne '')) {
6810: my $spec=$trole.'.'.$area;
6811: if ($trole =~ /^cr\//) {
6812: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6813: } elsif ($trole ne 'gr') {
6814: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6815: }
1.1128 raeburn 6816: if ($trole eq 'au') {
6817: $is_author = 1;
6818: }
1.976 raeburn 6819: }
6820: }
6821: foreach my $role (keys(%allroles)) {
6822: last if ($is_adv);
6823: foreach my $item (split(/:/,$allroles{$role})) {
6824: if ($item ne '') {
6825: my ($privilege,$restrictions)=split(/&/,$item);
6826: if ($privilege eq 'adv') {
6827: $is_adv = 1;
6828: last;
6829: }
6830: }
6831: }
6832: }
1.1128 raeburn 6833: if (wantarray) {
6834: return ($is_adv,$is_author);
6835: }
1.976 raeburn 6836: return $is_adv;
6837: }
1.798 raeburn 6838:
1.1035 raeburn 6839: sub check_can_request {
1.1036 raeburn 6840: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6841: my $canreq = 0;
6842: my ($types,$typename) = &Apache::loncommon::course_types();
6843: my @options = ('approval','validate','autolimit');
6844: my $optregex = join('|',@options);
6845: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6846: foreach my $type (@{$types}) {
6847: if (&usertools_access($env{'user.name'},
6848: $env{'user.domain'},
6849: $type,undef,'requestcourses')) {
6850: $canreq ++;
1.1036 raeburn 6851: if (ref($request_domains) eq 'HASH') {
6852: push(@{$request_domains->{$type}},$env{'user.domain'});
6853: }
1.1035 raeburn 6854: if ($dom eq $env{'user.domain'}) {
6855: $can_request->{$type} = 1;
6856: }
6857: }
6858: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6859: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6860: if (@curr > 0) {
1.1036 raeburn 6861: foreach my $item (@curr) {
6862: if (ref($request_domains) eq 'HASH') {
6863: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6864: if ($otherdom ne '') {
6865: if (ref($request_domains->{$type}) eq 'ARRAY') {
6866: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6867: push(@{$request_domains->{$type}},$otherdom);
6868: }
6869: } else {
6870: push(@{$request_domains->{$type}},$otherdom);
6871: }
6872: }
6873: }
6874: }
6875: unless($dom eq $env{'user.domain'}) {
6876: $canreq ++;
1.1035 raeburn 6877: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6878: $can_request->{$type} = 1;
6879: }
6880: }
6881: }
6882: }
6883: }
6884: }
6885: return $canreq;
6886: }
6887:
1.341 www 6888: # ---------------------------------------------- Custom access rule evaluation
6889:
6890: sub customaccess {
6891: my ($priv,$uri)=@_;
1.807 albertel 6892: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6893: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6894: $udom = &LONCAPA::clean_domain($udom);
6895: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6896: my $access=0;
1.800 albertel 6897: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6898: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6899: if ($type eq 'user') {
6900: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6901: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6902: if ($tdom) {
6903: if ($tdom ne $env{'user.domain'}) { next; }
6904: }
1.896 albertel 6905: if ($tuname) {
6906: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6907: }
6908: $access=($effect eq 'allow');
6909: last;
6910: }
6911: } else {
6912: if ($role) {
6913: if ($role ne $urole) { next; }
6914: }
6915: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6916: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6917: if ($tdom) {
6918: if ($tdom ne $udom) { next; }
6919: }
6920: if ($tcrs) {
6921: if ($tcrs ne $ucrs) { next; }
6922: }
6923: if ($tsec) {
6924: if ($tsec ne $usec) { next; }
6925: }
6926: $access=($effect eq 'allow');
6927: last;
6928: }
6929: if ($realm eq '' && $role eq '') {
6930: $access=($effect eq 'allow');
6931: }
1.402 bowersj2 6932: }
1.341 www 6933: }
6934: return $access;
6935: }
6936:
1.103 harris41 6937: # ------------------------------------------------- Check for a user privilege
1.12 www 6938:
6939: sub allowed {
1.1281 raeburn 6940: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6941: my $ver_orguri=$uri;
1.439 www 6942: $uri=&deversion($uri);
1.152 www 6943: my $orguri=$uri;
1.52 www 6944: $uri=&declutter($uri);
1.809 raeburn 6945:
1.810 raeburn 6946: if ($priv eq 'evb') {
6947: # Evade communication block restrictions for specified role in a course
6948: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6949: return $1;
6950: } else {
6951: return;
6952: }
6953: }
6954:
1.620 albertel 6955: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6956: # Free bre access to adm and meta resources
1.775 albertel 6957: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6958: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6959: && ($priv eq 'bre')) {
1.14 www 6960: return 'F';
1.159 www 6961: }
6962:
1.545 banghart 6963: # Free bre access to user's own portfolio contents
1.714 raeburn 6964: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6965: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6966: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6967: my %setters;
6968: my ($startblock,$endblock) =
6969: &Apache::loncommon::blockcheck(\%setters,'port');
6970: if ($startblock && $endblock) {
6971: return 'B';
6972: } else {
6973: return 'F';
6974: }
1.545 banghart 6975: }
6976:
1.762 raeburn 6977: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6978: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6979: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6980: if (exists($env{'request.course.id'})) {
6981: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6982: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6983: if (($domain eq $cdom) && ($name eq $cnum)) {
6984: my $courseprivid=$env{'request.course.id'};
6985: $courseprivid=~s/\_/\//;
6986: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6987: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6988: return $1;
1.762 raeburn 6989: } else {
6990: if ($env{'request.course.sec'}) {
6991: $courseprivid.='/'.$env{'request.course.sec'};
6992: }
6993: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6994: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6995: return $2;
6996: }
1.714 raeburn 6997: }
6998: }
6999: }
7000: }
7001:
1.159 www 7002: # Free bre to public access
7003:
7004: if ($priv eq 'bre') {
1.238 www 7005: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7006: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7007: return 'F';
7008: }
1.238 www 7009: if ($copyright eq 'priv') {
7010: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7011: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7012: return '';
7013: }
7014: }
7015: if ($copyright eq 'domain') {
7016: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7017: unless (($env{'user.domain'} eq $1) ||
7018: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7019: return '';
7020: }
1.262 matthew 7021: }
1.620 albertel 7022: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7023: # Library role, so allow browsing of resources in this domain.
7024: return 'F';
1.238 www 7025: }
1.341 www 7026: if ($copyright eq 'custom') {
7027: unless (&customaccess($priv,$uri)) { return ''; }
7028: }
1.14 www 7029: }
1.264 matthew 7030: # Domain coordinator is trying to create a course
1.620 albertel 7031: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7032: # uri is the requested domain in this case.
7033: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7034: # a role of dc for the domain in question.
1.620 albertel 7035: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7036: }
1.29 www 7037:
1.52 www 7038: my $thisallowed='';
7039: my $statecond=0;
7040: my $courseprivid='';
7041:
1.1039 raeburn 7042: my $ownaccess;
1.1043 raeburn 7043: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7044: if (($priv eq 'bro') && ($env{'user.author'})) {
7045: if ($uri eq '') {
7046: $ownaccess = 1;
7047: } else {
7048: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7049: my $udom = $env{'user.domain'};
7050: my $uname = $env{'user.name'};
7051: if ($uri =~ m{^\Q$udom\E/?$}) {
7052: $ownaccess = 1;
1.1040 raeburn 7053: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7054: unless ($uri =~ m{\.\./}) {
7055: $ownaccess = 1;
7056: }
7057: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7058: my $now = time;
7059: if ($uri =~ m{^([^/]+)/?$}) {
7060: my $adom = $1;
7061: foreach my $key (keys(%env)) {
1.1042 raeburn 7062: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7063: my ($start,$end) = split('.',$env{$key});
7064: if (($now >= $start) && (!$end || $end < $now)) {
7065: $ownaccess = 1;
7066: last;
7067: }
7068: }
7069: }
7070: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7071: my $adom = $1;
7072: my $aname = $2;
1.1042 raeburn 7073: foreach my $role ('ca','aa') {
7074: if ($env{"user.role.$role./$adom/$aname"}) {
7075: my ($start,$end) =
7076: split('.',$env{"user.role.$role./$adom/$aname"});
7077: if (($now >= $start) && (!$end || $end < $now)) {
7078: $ownaccess = 1;
7079: last;
7080: }
1.1039 raeburn 7081: }
7082: }
7083: }
7084: }
7085: }
7086: }
7087: }
7088:
1.52 www 7089: # Course
7090:
1.620 albertel 7091: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7092: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7093: $thisallowed.=$1;
7094: }
1.52 www 7095: }
1.29 www 7096:
1.52 www 7097: # Domain
7098:
1.620 albertel 7099: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7100: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7101: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7102: $thisallowed.=$1;
7103: }
1.12 www 7104: }
1.52 www 7105:
1.1141 raeburn 7106: # User who is not author or co-author might still be able to edit
7107: # resource of an author in the domain (e.g., if Domain Coordinator).
7108: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7109: (&allowed('mdc',$env{'request.course.id'}))) {
7110: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7111: $thisallowed.=$1;
7112: }
7113: }
7114:
1.52 www 7115: # Course: uri itself is a course
1.66 www 7116: my $courseuri=$uri;
7117: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7118: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7119:
1.620 albertel 7120: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7121: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7122: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7123: $thisallowed.=$1;
7124: }
1.12 www 7125: }
1.29 www 7126:
1.665 albertel 7127: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7128: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7129: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7130: $thisallowed='';
1.671 raeburn 7131: my ($match)=&is_on_map($uri);
7132: if ($match) {
7133: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7134: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 7135: my $value = $1;
7136: if ($noblockcheck) {
7137: $thisallowed.=$value;
1.1162 raeburn 7138: } else {
1.1281 raeburn 7139: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7140: if (@blockers > 0) {
7141: $thisallowed = 'B';
7142: } else {
7143: $thisallowed.=$value;
7144: }
1.1162 raeburn 7145: }
1.671 raeburn 7146: }
7147: } else {
1.705 albertel 7148: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7149: if ($refuri) {
7150: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7151: $thisallowed='F';
1.671 raeburn 7152: } else {
7153: $refuri=&declutter($refuri);
7154: my ($match) = &is_on_map($refuri);
7155: if ($match) {
1.1281 raeburn 7156: if ($noblockcheck) {
7157: $thisallowed='F';
1.1162 raeburn 7158: } else {
1.1281 raeburn 7159: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7160: if (@blockers > 0) {
7161: $thisallowed = 'B';
7162: } else {
7163: $thisallowed='F';
7164: }
1.1162 raeburn 7165: }
1.671 raeburn 7166: }
1.669 raeburn 7167: }
1.671 raeburn 7168: }
7169: }
1.314 www 7170: }
1.492 albertel 7171:
1.766 albertel 7172: if ($priv eq 'bre'
7173: && $thisallowed ne 'F'
7174: && $thisallowed ne '2'
7175: && &is_portfolio_url($uri)) {
1.1270 raeburn 7176: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7177: }
1.1250 raeburn 7178:
1.52 www 7179: # Full access at system, domain or course-wide level? Exit.
1.29 www 7180: if ($thisallowed=~/F/) {
7181: return 'F';
7182: }
7183:
1.52 www 7184: # If this is generating or modifying users, exit with special codes
1.29 www 7185:
1.643 www 7186: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7187: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7188: my ($audom,$auname)=split('/',$uri);
1.643 www 7189: # no author name given, so this just checks on the general right to make a co-author in this domain
7190: unless ($auname) { return $thisallowed; }
7191: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7192: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7193: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7194: ($audom ne $env{'request.role.domain'}))) { return ''; }
7195: }
1.52 www 7196: return $thisallowed;
7197: }
7198: #
1.103 harris41 7199: # Gathered so far: system, domain and course wide privileges
1.52 www 7200: #
7201: # Course: See if uri or referer is an individual resource that is part of
7202: # the course
7203:
1.620 albertel 7204: if ($env{'request.course.id'}) {
1.232 www 7205:
1.620 albertel 7206: $courseprivid=$env{'request.course.id'};
7207: if ($env{'request.course.sec'}) {
7208: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7209: }
7210: $courseprivid=~s/\_/\//;
7211: my $checkreferer=1;
1.232 www 7212: my ($match,$cond)=&is_on_map($uri);
7213: if ($match) {
7214: $statecond=$cond;
1.620 albertel 7215: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7216: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7217: my $value = $1;
7218: if ($priv eq 'bre') {
1.1281 raeburn 7219: if ($noblockcheck) {
7220: $thisallowed.=$value;
1.1162 raeburn 7221: } else {
1.1281 raeburn 7222: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7223: if (@blockers > 0) {
7224: $thisallowed = 'B';
7225: } else {
7226: $thisallowed.=$value;
7227: }
1.1162 raeburn 7228: }
7229: } else {
7230: $thisallowed.=$value;
7231: }
1.52 www 7232: $checkreferer=0;
7233: }
1.29 www 7234: }
1.83 www 7235:
1.148 www 7236: if ($checkreferer) {
1.620 albertel 7237: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7238: unless ($refuri) {
1.800 albertel 7239: foreach my $key (keys(%env)) {
7240: if ($key=~/^httpref\..*\*/) {
7241: my $pattern=$key;
1.156 www 7242: $pattern=~s/^httpref\.\/res\///;
1.148 www 7243: $pattern=~s/\*/\[\^\/\]\+/g;
7244: $pattern=~s/\//\\\//g;
1.152 www 7245: if ($orguri=~/$pattern/) {
1.800 albertel 7246: $refuri=$env{$key};
1.148 www 7247: }
7248: }
1.191 harris41 7249: }
1.148 www 7250: }
1.232 www 7251:
1.148 www 7252: if ($refuri) {
1.152 www 7253: $refuri=&declutter($refuri);
1.232 www 7254: my ($match,$cond)=&is_on_map($refuri);
7255: if ($match) {
7256: my $refstatecond=$cond;
1.620 albertel 7257: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7258: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7259: my $value = $1;
7260: if ($priv eq 'bre') {
1.1281 raeburn 7261: if ($noblockcheck) {
7262: $thisallowed.=$value;
1.1162 raeburn 7263: } else {
1.1281 raeburn 7264: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7265: if (@blockers > 0) {
7266: $thisallowed = 'B';
7267: } else {
7268: $thisallowed.=$value;
7269: }
1.1162 raeburn 7270: }
7271: } else {
7272: $thisallowed.=$value;
7273: }
1.53 www 7274: $uri=$refuri;
7275: $statecond=$refstatecond;
1.52 www 7276: }
7277: }
1.148 www 7278: }
1.29 www 7279: }
1.52 www 7280: }
1.29 www 7281:
1.52 www 7282: #
1.103 harris41 7283: # Gathered now: all privileges that could apply, and condition number
1.52 www 7284: #
7285: #
7286: # Full or no access?
7287: #
1.29 www 7288:
1.52 www 7289: if ($thisallowed=~/F/) {
7290: return 'F';
7291: }
1.29 www 7292:
1.52 www 7293: unless ($thisallowed) {
7294: return '';
7295: }
1.29 www 7296:
1.52 www 7297: # Restrictions exist, deal with them
7298: #
7299: # C:according to course preferences
7300: # R:according to resource settings
7301: # L:unless locked
7302: # X:according to user session state
7303: #
7304:
7305: # Possibly locked functionality, check all courses
1.54 www 7306: # Locks might take effect only after 10 minutes cache expiration for other
7307: # courses, and 2 minutes for current course
1.52 www 7308:
7309: my $envkey;
7310: if ($thisallowed=~/L/) {
1.1000 raeburn 7311: foreach $envkey (keys(%env)) {
1.54 www 7312: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7313: my $courseid=$2;
7314: my $roleid=$1.'.'.$2;
1.92 www 7315: $courseid=~s/^\///;
1.54 www 7316: my $expiretime=600;
1.620 albertel 7317: if ($env{'request.role'} eq $roleid) {
1.54 www 7318: $expiretime=120;
7319: }
7320: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7321: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7322: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7323: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7324: }
1.620 albertel 7325: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7326: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7327: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7328: &log($env{'user.domain'},$env{'user.name'},
7329: $env{'user.home'},
1.57 www 7330: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7331: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7332: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7333: return '';
7334: }
7335: }
1.620 albertel 7336: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7337: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7338: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7339: &log($env{'user.domain'},$env{'user.name'},
7340: $env{'user.home'},
1.57 www 7341: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7342: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7343: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7344: return '';
7345: }
7346: }
7347: }
1.29 www 7348: }
1.52 www 7349: }
7350:
7351: #
7352: # Rest of the restrictions depend on selected course
7353: #
7354:
1.620 albertel 7355: unless ($env{'request.course.id'}) {
1.766 albertel 7356: if ($thisallowed eq 'A') {
7357: return 'A';
1.814 raeburn 7358: } elsif ($thisallowed eq 'B') {
7359: return 'B';
1.766 albertel 7360: } else {
7361: return '1';
7362: }
1.52 www 7363: }
1.29 www 7364:
1.52 www 7365: #
7366: # Now user is definitely in a course
7367: #
1.53 www 7368:
7369:
7370: # Course preferences
7371:
7372: if ($thisallowed=~/C/) {
1.620 albertel 7373: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7374: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7375: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7376: =~/\Q$rolecode\E/) {
1.1304 raeburn 7377: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7378: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7379: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7380: $env{'request.course.id'});
7381: }
1.237 www 7382: return '';
7383: }
7384:
1.620 albertel 7385: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7386: =~/\Q$unamedom\E/) {
1.1304 raeburn 7387: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7388: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7389: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7390: $env{'request.course.id'});
7391: }
1.54 www 7392: return '';
7393: }
1.53 www 7394: }
7395:
7396: # Resource preferences
7397:
7398: if ($thisallowed=~/R/) {
1.620 albertel 7399: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7400: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7401: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7402: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7403: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7404: }
7405: return '';
1.54 www 7406: }
1.53 www 7407: }
1.30 www 7408:
1.246 www 7409: # Restricted by state or randomout?
1.30 www 7410:
1.52 www 7411: if ($thisallowed=~/X/) {
1.620 albertel 7412: if ($env{'acc.randomout'}) {
1.579 albertel 7413: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7414: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7415: return '';
7416: }
1.247 www 7417: }
7418: if (&condval($statecond)) {
1.52 www 7419: return '2';
7420: } else {
7421: return '';
7422: }
7423: }
1.30 www 7424:
1.766 albertel 7425: if ($thisallowed eq 'A') {
7426: return 'A';
1.814 raeburn 7427: } elsif ($thisallowed eq 'B') {
7428: return 'B';
1.766 albertel 7429: }
1.52 www 7430: return 'F';
1.232 www 7431: }
1.1162 raeburn 7432:
1.1192 raeburn 7433: # ------------------------------------------- Check construction space access
7434:
7435: sub constructaccess {
7436: my ($url,$setpriv)=@_;
7437:
7438: # We do not allow editing of previous versions of files
7439: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7440:
7441: # Get username and domain from URL
7442: my ($ownername,$ownerdomain,$ownerhome);
7443:
7444: ($ownerdomain,$ownername) =
1.1325 raeburn 7445: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 7446:
7447: # The URL does not really point to any authorspace, forget it
7448: unless (($ownername) && ($ownerdomain)) { return ''; }
7449:
7450: # Now we need to see if the user has access to the authorspace of
7451: # $ownername at $ownerdomain
7452:
7453: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7454: # Real author for this?
7455: $ownerhome = $env{'user.home'};
7456: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7457: return ($ownername,$ownerdomain,$ownerhome);
7458: }
7459: } else {
7460: # Co-author for this?
7461: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7462: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7463: $ownerhome = &homeserver($ownername,$ownerdomain);
7464: return ($ownername,$ownerdomain,$ownerhome);
7465: }
1.1312 raeburn 7466: if ($env{'request.course.id'}) {
7467: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
7468: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
7469: if (&allowed('mdc',$env{'request.course.id'})) {
7470: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
7471: return ($ownername,$ownerdomain,$ownerhome);
7472: }
7473: }
7474: }
1.1192 raeburn 7475: }
7476:
7477: # We don't have any access right now. If we are not possibly going to do anything about this,
7478: # we might as well leave
7479: unless ($setpriv) { return ''; }
7480:
7481: # Backdoor access?
7482: my $allowed=&allowed('eco',$ownerdomain);
7483: # Nope
7484: unless ($allowed) { return ''; }
7485: # Looks like we may have access, but could be locked by the owner of the construction space
7486: if ($allowed eq 'U') {
7487: my %blocked=&get('environment',['domcoord.author'],
7488: $ownerdomain,$ownername);
7489: # Is blocked by owner
7490: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7491: }
7492: if (($allowed eq 'F') || ($allowed eq 'U')) {
7493: # Grant temporary access
7494: my $then=$env{'user.login.time'};
1.1209 raeburn 7495: my $update=$env{'user.update.time'};
1.1192 raeburn 7496: if (!$update) { $update = $then; }
7497: my $refresh=$env{'user.refresh.time'};
7498: if (!$refresh) { $refresh = $update; }
7499: my $now = time;
7500: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7501: $now,'ca','constructaccess');
7502: $ownerhome = &homeserver($ownername,$ownerdomain);
7503: return($ownername,$ownerdomain,$ownerhome);
7504: }
7505: # No business here
7506: return '';
7507: }
7508:
1.1282 raeburn 7509: # ----------------------------------------------------------- Content Blocking
7510:
7511: {
7512: # Caches for faster Course Contents display where content blocking
7513: # is in operation (i.e., interval param set) for timed quiz.
7514: #
7515: # User for whom data are being temporarily cached.
7516: my $cacheduser='';
7517: # Cached blockers for this user (a hash of blocking items).
7518: my %cachedblockers=();
7519: # When the data were last cached.
7520: my $cachedlast='';
7521:
7522: sub load_all_blockers {
7523: my ($uname,$udom,$blocks)=@_;
7524: if (($uname ne '') && ($udom ne '')) {
7525: if (($cacheduser eq $uname.':'.$udom) &&
7526: (abs($cachedlast-time)<5)) {
7527: return;
7528: }
7529: }
7530: $cachedlast=time;
7531: $cacheduser=$uname.':'.$udom;
7532: %cachedblockers = &get_commblock_resources($blocks);
7533: }
7534:
1.1162 raeburn 7535: sub get_comm_blocks {
7536: my ($cdom,$cnum) = @_;
7537: if ($cdom eq '' || $cnum eq '') {
7538: return unless ($env{'request.course.id'});
7539: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7540: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7541: }
7542: my %commblocks;
7543: my $hashid=$cdom.'_'.$cnum;
7544: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7545: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7546: %commblocks = %{$blocksref};
7547: } else {
7548: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7549: my $cachetime = 600;
7550: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7551: }
7552: return %commblocks;
7553: }
7554:
1.1282 raeburn 7555: sub get_commblock_resources {
7556: my ($blocks) = @_;
7557: my %blockers = ();
7558: return %blockers unless ($env{'request.course.id'});
7559: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7560: my %commblocks;
7561: if (ref($blocks) eq 'HASH') {
7562: %commblocks = %{$blocks};
7563: } else {
7564: %commblocks = &get_comm_blocks();
7565: }
1.1282 raeburn 7566: return %blockers unless (keys(%commblocks) > 0);
7567: my $navmap = Apache::lonnavmaps::navmap->new();
7568: return %blockers unless (ref($navmap));
1.1162 raeburn 7569: my $now = time;
7570: foreach my $block (keys(%commblocks)) {
7571: if ($block =~ /^(\d+)____(\d+)$/) {
7572: my ($start,$end) = ($1,$2);
7573: if ($start <= $now && $end >= $now) {
7574: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7575: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7576: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 7577: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7578: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7579: }
7580: }
7581: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 7582: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7583: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7584: }
7585: }
7586: }
7587: }
7588: }
7589: } elsif ($block =~ /^firstaccess____(.+)$/) {
7590: my $item = $1;
1.1163 raeburn 7591: my @to_test;
1.1162 raeburn 7592: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7593: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 7594: my @interval;
7595: my $type = 'map';
7596: if ($item eq 'course') {
7597: $type = 'course';
7598: @interval=&EXT("resource.0.interval");
7599: } else {
7600: if ($item =~ /___\d+___/) {
7601: $type = 'resource';
7602: @interval=&EXT("resource.0.interval",$item);
7603: if (ref($navmap)) {
7604: my $res = $navmap->getBySymb($item);
7605: push(@to_test,$res);
7606: }
1.1162 raeburn 7607: } else {
1.1282 raeburn 7608: my $mapsymb = &symbread($item,1);
7609: if ($mapsymb) {
7610: if (ref($navmap)) {
7611: my $mapres = $navmap->getBySymb($mapsymb);
7612: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7613: foreach my $res (@to_test) {
7614: my $symb = $res->symb();
7615: next if ($symb eq $mapsymb);
7616: if ($symb ne '') {
7617: @interval=&EXT("resource.0.interval",$symb);
7618: if ($interval[1] eq 'map') {
7619: last;
1.1162 raeburn 7620: }
7621: }
7622: }
7623: }
7624: }
7625: }
1.1282 raeburn 7626: }
1.1310 raeburn 7627: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 7628: my $timelimit = $1;
1.1282 raeburn 7629: my $first_access;
7630: if ($type eq 'resource') {
7631: $first_access=&get_first_access($interval[1],$item);
7632: } elsif ($type eq 'map') {
7633: $first_access=&get_first_access($interval[1],undef,$item);
7634: } else {
7635: $first_access=&get_first_access($interval[1]);
7636: }
7637: if ($first_access) {
1.1292 raeburn 7638: my $timesup = $first_access+$timelimit;
1.1282 raeburn 7639: if ($timesup > $now) {
7640: my $activeblock;
7641: foreach my $res (@to_test) {
1.1283 raeburn 7642: if ($res->answerable()) {
1.1282 raeburn 7643: $activeblock = 1;
7644: last;
7645: }
7646: }
7647: if ($activeblock) {
7648: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7649: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7650: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7651: }
7652: }
7653: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7654: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7655: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7656: }
1.1162 raeburn 7657: }
7658: }
7659: }
7660: }
7661: }
7662: }
7663: }
7664: }
7665: }
1.1282 raeburn 7666: return %blockers;
1.1162 raeburn 7667: }
7668:
1.1282 raeburn 7669: sub has_comm_blocking {
7670: my ($priv,$symb,$uri,$blocks) = @_;
7671: my @blockers;
7672: return unless ($env{'request.course.id'});
7673: return unless ($priv eq 'bre');
7674: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7675: return if ($env{'request.state'} eq 'construct');
7676: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7677: return unless (keys(%cachedblockers) > 0);
7678: my (%possibles,@symbs);
7679: if (!$symb) {
7680: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7681: }
1.1282 raeburn 7682: if ($symb) {
7683: @symbs = ($symb);
7684: } elsif (keys(%possibles)) {
7685: @symbs = keys(%possibles);
7686: }
7687: my $noblock;
7688: foreach my $symb (@symbs) {
7689: last if ($noblock);
7690: my ($map,$resid,$resurl)=&decode_symb($symb);
7691: foreach my $block (keys(%cachedblockers)) {
7692: if ($block =~ /^firstaccess____(.+)$/) {
7693: my $item = $1;
7694: if (($item eq $map) || ($item eq $symb)) {
7695: $noblock = 1;
7696: last;
7697: }
7698: }
7699: if (ref($cachedblockers{$block}) eq 'HASH') {
7700: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7701: if ($cachedblockers{$block}{'resources'}{$symb}) {
7702: unless (grep(/^\Q$block\E$/,@blockers)) {
7703: push(@blockers,$block);
7704: }
7705: }
7706: }
1.1162 raeburn 7707: }
1.1282 raeburn 7708: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7709: if ($cachedblockers{$block}{'maps'}{$map}) {
7710: unless (grep(/^\Q$block\E$/,@blockers)) {
7711: push(@blockers,$block);
7712: }
7713: }
1.1162 raeburn 7714: }
7715: }
7716: }
1.1282 raeburn 7717: return if ($noblock);
7718: return @blockers;
7719: }
1.1162 raeburn 7720: }
7721:
1.1282 raeburn 7722: # -------------------------------- Deversion and split uri into path an filename
7723:
1.1133 foxr 7724: #
1.1282 raeburn 7725: # Removes the version from a URI and
1.1133 foxr 7726: # splits it in to its filename and path to the filename.
7727: # Seems like File::Basename could have done this more clearly.
7728: # Parameters:
7729: # $uri - input URI
7730: # Returns:
7731: # Two element list consisting of
7732: # $pathname - the URI up to and excluding the trailing /
7733: # $filename - The part of the URI following the last /
7734: # NOTE:
7735: # Another realization of this is simply:
7736: # use File::Basename;
7737: # ...
7738: # $uri = shift;
7739: # $filename = basename($uri);
7740: # $path = dirname($uri);
7741: # return ($filename, $path);
7742: #
7743: # The implementation below is probably faster however.
7744: #
1.710 albertel 7745: sub split_uri_for_cond {
7746: my $uri=&deversion(&declutter(shift));
7747: my @uriparts=split(/\//,$uri);
7748: my $filename=pop(@uriparts);
7749: my $pathname=join('/',@uriparts);
7750: return ($pathname,$filename);
7751: }
1.232 www 7752: # --------------------------------------------------- Is a resource on the map?
7753:
7754: sub is_on_map {
1.710 albertel 7755: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7756: #Trying to find the conditional for the file
1.620 albertel 7757: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7758: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7759: if ($match) {
1.289 bowersj2 7760: return (1,$1);
7761: } else {
1.434 www 7762: return (0,0);
1.289 bowersj2 7763: }
1.12 www 7764: }
7765:
1.427 www 7766: # --------------------------------------------------------- Get symb from alias
7767:
7768: sub get_symb_from_alias {
7769: my $symb=shift;
7770: my ($map,$resid,$url)=&decode_symb($symb);
7771: # Already is a symb
7772: if ($url) { return $symb; }
7773: # Must be an alias
7774: my $aliassymb='';
7775: my %bighash;
1.620 albertel 7776: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7777: &GDBM_READER(),0640)) {
7778: my $rid=$bighash{'mapalias_'.$symb};
7779: if ($rid) {
7780: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7781: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7782: $resid,$bighash{'src_'.$rid});
1.427 www 7783: }
7784: untie %bighash;
7785: }
7786: return $aliassymb;
7787: }
7788:
1.12 www 7789: # ----------------------------------------------------------------- Define Role
7790:
7791: sub definerole {
7792: if (allowed('mcr','/')) {
1.1326 raeburn 7793: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 7794: foreach my $role (split(':',$sysrole)) {
7795: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7796: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7797: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7798: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7799: return "refused:s:$crole&$cqual";
7800: }
7801: }
1.191 harris41 7802: }
1.800 albertel 7803: foreach my $role (split(':',$domrole)) {
7804: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7805: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7806: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7807: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7808: return "refused:d:$crole&$cqual";
7809: }
7810: }
1.191 harris41 7811: }
1.800 albertel 7812: foreach my $role (split(':',$courole)) {
7813: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7814: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7815: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7816: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7817: return "refused:c:$crole&$cqual";
7818: }
7819: }
1.191 harris41 7820: }
1.1326 raeburn 7821: my $uhome;
7822: if (($uname ne '') && ($udom ne '')) {
7823: $uhome = &homeserver($uname,$udom);
7824: return $uhome if ($uhome eq 'no_host');
7825: } else {
7826: $uname = $env{'user.name'};
7827: $udom = $env{'user.domain'};
7828: $uhome = $env{'user.home'};
7829: }
1.620 albertel 7830: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 7831: "$udom:$uname:rolesdef_$rolename=".
1.21 www 7832: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 7833: return reply($command,$uhome);
1.12 www 7834: } else {
7835: return 'refused';
7836: }
1.105 harris41 7837: }
7838:
7839: # ---------------- Make a metadata query against the network of library servers
7840:
7841: sub metadata_query {
1.1237 raeburn 7842: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7843: my %rhash;
1.845 albertel 7844: my %libserv = &all_library();
1.244 matthew 7845: my @server_list = (defined($server_array) ? @$server_array
7846: : keys(%libserv) );
7847: for my $server (@server_list) {
1.1237 raeburn 7848: my $domains = '';
7849: if (ref($domains_hash) eq 'HASH') {
7850: $domains = $domains_hash->{$server};
7851: }
1.118 harris41 7852: unless ($custom or $customshow) {
1.1237 raeburn 7853: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7854: $rhash{$server}=$reply;
7855: }
7856: else {
7857: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7858: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7859: $server);
7860: $rhash{$server}=$reply;
7861: }
1.112 harris41 7862: }
1.118 harris41 7863: return \%rhash;
1.240 www 7864: }
7865:
7866: # ----------------------------------------- Send log queries and wait for reply
7867:
7868: sub log_query {
7869: my ($uname,$udom,$query,%filters)=@_;
7870: my $uhome=&homeserver($uname,$udom);
7871: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7872: my $uhost=&hostname($uhome);
1.800 albertel 7873: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7874: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7875: $uhome);
1.479 albertel 7876: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7877: return get_query_reply($queryid);
7878: }
7879:
1.818 raeburn 7880: # -------------------------- Update MySQL table for portfolio file
7881:
7882: sub update_portfolio_table {
1.821 raeburn 7883: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7884: if ($group ne '') {
7885: $file_name =~s /^\Q$group\E//;
7886: }
1.818 raeburn 7887: my $homeserver = &homeserver($uname,$udom);
7888: my $queryid=
1.821 raeburn 7889: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7890: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7891: my $reply = &get_query_reply($queryid);
7892: return $reply;
7893: }
7894:
1.899 raeburn 7895: # -------------------------- Update MySQL allusers table
7896:
7897: sub update_allusers_table {
7898: my ($uname,$udom,$names) = @_;
7899: my $homeserver = &homeserver($uname,$udom);
7900: my $queryid=
7901: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7902: 'lastname='.&escape($names->{'lastname'}).'%%'.
7903: 'firstname='.&escape($names->{'firstname'}).'%%'.
7904: 'middlename='.&escape($names->{'middlename'}).'%%'.
7905: 'generation='.&escape($names->{'generation'}).'%%'.
7906: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7907: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7908: return;
1.899 raeburn 7909: }
7910:
1.508 raeburn 7911: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7912:
7913: sub fetch_enrollment_query {
1.511 raeburn 7914: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 7915: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 7916: my $maxtries = 1;
1.508 raeburn 7917: if ($context eq 'automated') {
7918: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 7919: $sleep = 2;
7920: $loopmax = 100;
1.547 raeburn 7921: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7922: } else {
7923: $homeserver = &homeserver($cnum,$dom);
7924: }
1.838 albertel 7925: my $host=&hostname($homeserver);
1.506 raeburn 7926: my $cmd = '';
1.1000 raeburn 7927: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7928: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7929: }
7930: $cmd =~ s/%%$//;
7931: $cmd = &escape($cmd);
7932: my $query = 'fetchenrollment';
1.620 albertel 7933: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7934: unless ($queryid=~/^\Q$host\E\_/) {
7935: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7936: return 'error: '.$queryid;
7937: }
1.1317 raeburn 7938: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 7939: my $tries = 1;
7940: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 7941: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 7942: $tries ++;
7943: }
1.526 raeburn 7944: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7945: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7946: } else {
1.901 albertel 7947: my @responses = split(/:/,$reply);
1.1322 raeburn 7948: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 7949: foreach my $line (@responses) {
7950: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7951: $$replyref{$key} = $value;
7952: }
7953: } else {
1.1117 foxr 7954: my $pathname = LONCAPA::tempdir();
1.800 albertel 7955: foreach my $line (@responses) {
7956: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7957: $$replyref{$key} = $value;
7958: if ($value > 0) {
1.800 albertel 7959: foreach my $item (@{$$affiliatesref{$key}}) {
7960: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7961: my $destname = $pathname.'/'.$filename;
7962: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7963: if ($xml_classlist =~ /^error/) {
7964: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7965: } else {
1.506 raeburn 7966: if ( open(FILE,">$destname") ) {
7967: print FILE &unescape($xml_classlist);
7968: close(FILE);
1.526 raeburn 7969: } else {
7970: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7971: }
7972: }
7973: }
7974: }
7975: }
7976: }
7977: return 'ok';
7978: }
7979: return 'error';
7980: }
7981:
1.242 www 7982: sub get_query_reply {
1.1317 raeburn 7983: my ($queryid,$sleep,$loopmax) = @_;;
7984: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
7985: $sleep = 0.2;
7986: }
7987: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
7988: $loopmax = 100;
7989: }
1.1117 foxr 7990: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7991: my $reply='';
1.1317 raeburn 7992: for (1..$loopmax) {
7993: sleep($sleep);
1.240 www 7994: if (-e $replyfile.'.end') {
1.448 albertel 7995: if (open(my $fh,$replyfile)) {
1.904 albertel 7996: $reply = join('',<$fh>);
7997: close($fh);
1.240 www 7998: } else { return 'error: reply_file_error'; }
1.242 www 7999: return &unescape($reply);
8000: }
1.240 www 8001: }
1.242 www 8002: return 'timeout:'.$queryid;
1.240 www 8003: }
8004:
8005: sub courselog_query {
1.241 www 8006: #
8007: # possible filters:
8008: # url: url or symb
8009: # username
8010: # domain
8011: # action: view, submit, grade
8012: # start: timestamp
8013: # end: timestamp
8014: #
1.240 www 8015: my (%filters)=@_;
1.620 albertel 8016: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8017: if ($filters{'url'}) {
8018: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8019: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8020: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8021: }
1.620 albertel 8022: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8023: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8024: return &log_query($cname,$cdom,'courselog',%filters);
8025: }
8026:
8027: sub userlog_query {
1.858 raeburn 8028: #
8029: # possible filters:
8030: # action: log check role
8031: # start: timestamp
8032: # end: timestamp
8033: #
1.240 www 8034: my ($uname,$udom,%filters)=@_;
8035: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8036: }
8037:
1.506 raeburn 8038: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8039:
8040: sub auto_run {
1.508 raeburn 8041: my ($cnum,$cdom) = @_;
1.876 raeburn 8042: my $response = 0;
8043: my $settings;
8044: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8045: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8046: $settings = $domconfig{'autoenroll'};
8047: if ($settings->{'run'} eq '1') {
8048: $response = 1;
8049: }
8050: } else {
1.934 raeburn 8051: my $homeserver;
8052: if (&is_course($cdom,$cnum)) {
8053: $homeserver = &homeserver($cnum,$cdom);
8054: } else {
8055: $homeserver = &domain($cdom,'primary');
8056: }
8057: if ($homeserver ne 'no_host') {
8058: $response = &reply('autorun:'.$cdom,$homeserver);
8059: }
1.876 raeburn 8060: }
1.506 raeburn 8061: return $response;
8062: }
1.776 albertel 8063:
1.506 raeburn 8064: sub auto_get_sections {
1.508 raeburn 8065: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8066: my $homeserver;
8067: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8068: $homeserver = &homeserver($cnum,$cdom);
8069: }
8070: if (!defined($homeserver)) {
8071: if ($cdom =~ /^$match_domain$/) {
8072: $homeserver = &domain($cdom,'primary');
8073: }
8074: }
8075: my @secs;
8076: if (defined($homeserver)) {
8077: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8078: unless ($response eq 'refused') {
8079: @secs = split(/:/,$response);
8080: }
1.506 raeburn 8081: }
8082: return @secs;
8083: }
1.776 albertel 8084:
1.506 raeburn 8085: sub auto_new_course {
1.1099 raeburn 8086: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8087: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8088: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8089: return $response;
8090: }
1.776 albertel 8091:
1.506 raeburn 8092: sub auto_validate_courseID {
1.508 raeburn 8093: my ($cnum,$cdom,$inst_course_id) = @_;
8094: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8095: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8096: return $response;
8097: }
1.776 albertel 8098:
1.1007 raeburn 8099: sub auto_validate_instcode {
1.1020 raeburn 8100: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8101: my ($homeserver,$response);
8102: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8103: $homeserver = &homeserver($cnum,$cdom);
8104: }
8105: if (!defined($homeserver)) {
8106: if ($cdom =~ /^$match_domain$/) {
8107: $homeserver = &domain($cdom,'primary');
8108: }
8109: }
1.1065 raeburn 8110: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8111: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 8112: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8113: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8114: }
8115:
1.506 raeburn 8116: sub auto_create_password {
1.873 raeburn 8117: my ($cnum,$cdom,$authparam,$udom) = @_;
8118: my ($homeserver,$response);
1.506 raeburn 8119: my $create_passwd = 0;
8120: my $authchk = '';
1.873 raeburn 8121: if ($udom =~ /^$match_domain$/) {
8122: $homeserver = &domain($udom,'primary');
8123: }
8124: if ($homeserver eq '') {
8125: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8126: $homeserver = &homeserver($cnum,$cdom);
8127: }
8128: }
8129: if ($homeserver eq '') {
8130: $authchk = 'nodomain';
1.506 raeburn 8131: } else {
1.873 raeburn 8132: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8133: if ($response eq 'refused') {
8134: $authchk = 'refused';
8135: } else {
1.901 albertel 8136: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8137: }
1.506 raeburn 8138: }
8139: return ($authparam,$create_passwd,$authchk);
8140: }
8141:
1.706 raeburn 8142: sub auto_photo_permission {
8143: my ($cnum,$cdom,$students) = @_;
8144: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8145: my ($outcome,$perm_reqd,$conditions) =
8146: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8147: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8148: return (undef,undef);
8149: }
1.706 raeburn 8150: return ($outcome,$perm_reqd,$conditions);
8151: }
8152:
8153: sub auto_checkphotos {
8154: my ($uname,$udom,$pid) = @_;
8155: my $homeserver = &homeserver($uname,$udom);
8156: my ($result,$resulttype);
8157: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8158: &escape($uname).':'.&escape($pid),
8159: $homeserver));
1.709 albertel 8160: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8161: return (undef,undef);
8162: }
1.706 raeburn 8163: if ($outcome) {
8164: ($result,$resulttype) = split(/:/,$outcome);
8165: }
8166: return ($result,$resulttype);
8167: }
8168:
8169: sub auto_photochoice {
8170: my ($cnum,$cdom) = @_;
8171: my $homeserver = &homeserver($cnum,$cdom);
8172: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8173: &escape($cdom),
8174: $homeserver)));
1.709 albertel 8175: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8176: return (undef,undef);
8177: }
1.706 raeburn 8178: return ($update,$comment);
8179: }
8180:
8181: sub auto_photoupdate {
8182: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8183: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8184: my $host=&hostname($homeserver);
1.706 raeburn 8185: my $cmd = '';
8186: my $maxtries = 1;
1.800 albertel 8187: foreach my $affiliate (keys(%{$affiliatesref})) {
8188: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8189: }
8190: $cmd =~ s/%%$//;
8191: $cmd = &escape($cmd);
8192: my $query = 'institutionalphotos';
8193: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8194: unless ($queryid=~/^\Q$host\E\_/) {
8195: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8196: return 'error: '.$queryid;
8197: }
8198: my $reply = &get_query_reply($queryid);
8199: my $tries = 1;
8200: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8201: $reply = &get_query_reply($queryid);
8202: $tries ++;
8203: }
8204: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8205: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8206: } else {
8207: my @responses = split(/:/,$reply);
8208: my $outcome = shift(@responses);
8209: foreach my $item (@responses) {
8210: my ($key,$value) = split(/=/,$item);
8211: $$photo{$key} = $value;
8212: }
8213: return $outcome;
8214: }
8215: return 'error';
8216: }
8217:
1.521 raeburn 8218: sub auto_instcode_format {
1.793 albertel 8219: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8220: $cat_order) = @_;
1.521 raeburn 8221: my $courses = '';
1.772 raeburn 8222: my @homeservers;
1.521 raeburn 8223: if ($caller eq 'global') {
1.841 albertel 8224: my %servers = &get_servers($codedom,'library');
8225: foreach my $tryserver (keys(%servers)) {
8226: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8227: push(@homeservers,$tryserver);
8228: }
1.584 raeburn 8229: }
1.1022 raeburn 8230: } elsif ($caller eq 'requests') {
8231: if ($codedom =~ /^$match_domain$/) {
8232: my $chome = &domain($codedom,'primary');
8233: unless ($chome eq 'no_host') {
8234: push(@homeservers,$chome);
8235: }
8236: }
1.521 raeburn 8237: } else {
1.772 raeburn 8238: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8239: }
1.793 albertel 8240: foreach my $code (keys(%{$instcodes})) {
8241: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8242: }
8243: chop($courses);
1.772 raeburn 8244: my $ok_response = 0;
8245: my $response;
8246: while (@homeservers > 0 && $ok_response == 0) {
8247: my $server = shift(@homeservers);
8248: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8249: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8250: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8251: split(/:/,$response);
1.772 raeburn 8252: %{$codes} = (%{$codes},&str2hash($codes_str));
8253: push(@{$codetitles},&str2array($codetitles_str));
8254: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8255: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8256: $ok_response = 1;
8257: }
8258: }
8259: if ($ok_response) {
1.521 raeburn 8260: return 'ok';
1.772 raeburn 8261: } else {
8262: return $response;
1.521 raeburn 8263: }
8264: }
8265:
1.792 raeburn 8266: sub auto_instcode_defaults {
8267: my ($domain,$returnhash,$code_order) = @_;
8268: my @homeservers;
1.841 albertel 8269:
8270: my %servers = &get_servers($domain,'library');
8271: foreach my $tryserver (keys(%servers)) {
8272: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8273: push(@homeservers,$tryserver);
8274: }
1.792 raeburn 8275: }
1.841 albertel 8276:
1.792 raeburn 8277: my $response;
1.841 albertel 8278: foreach my $server (@homeservers) {
1.792 raeburn 8279: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8280: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8281:
8282: foreach my $pair (split(/\&/,$response)) {
8283: my ($name,$value)=split(/\=/,$pair);
8284: if ($name eq 'code_order') {
8285: @{$code_order} = split(/\&/,&unescape($value));
8286: } else {
8287: $returnhash->{&unescape($name)}=&unescape($value);
8288: }
8289: }
8290: return 'ok';
1.792 raeburn 8291: }
1.841 albertel 8292:
8293: return $response;
1.1003 raeburn 8294: }
8295:
8296: sub auto_possible_instcodes {
1.1007 raeburn 8297: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8298: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8299: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8300: return;
8301: }
1.1003 raeburn 8302: my (@homeservers,$uhome);
8303: if (defined(&domain($domain,'primary'))) {
8304: $uhome=&domain($domain,'primary');
8305: push(@homeservers,&domain($domain,'primary'));
8306: } else {
8307: my %servers = &get_servers($domain,'library');
8308: foreach my $tryserver (keys(%servers)) {
8309: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8310: push(@homeservers,$tryserver);
8311: }
8312: }
8313: }
8314: my $response;
8315: foreach my $server (@homeservers) {
8316: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8317: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8318: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8319: split(':',$response);
8320: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8321: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8322: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8323: my ($name,$value)=split('=',$item);
8324: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8325: }
8326: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8327: my ($name,$value)=split('=',$item);
8328: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8329: }
8330: return 'ok';
8331: }
8332: return $response;
8333: }
1.792 raeburn 8334:
1.1010 raeburn 8335: sub auto_courserequest_checks {
8336: my ($dom) = @_;
1.1020 raeburn 8337: my ($homeserver,%validations);
8338: if ($dom =~ /^$match_domain$/) {
8339: $homeserver = &domain($dom,'primary');
8340: }
8341: unless ($homeserver eq 'no_host') {
8342: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8343: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8344: my @items = split(/&/,$response);
8345: foreach my $item (@items) {
8346: my ($key,$value) = split('=',$item);
8347: $validations{&unescape($key)} = &thaw_unescape($value);
8348: }
8349: }
8350: }
1.1010 raeburn 8351: return %validations;
8352: }
8353:
1.1020 raeburn 8354: sub auto_courserequest_validation {
1.1255 raeburn 8355: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8356: my ($homeserver,$response);
8357: if ($dom =~ /^$match_domain$/) {
8358: $homeserver = &domain($dom,'primary');
8359: }
1.1255 raeburn 8360: unless ($homeserver eq 'no_host') {
8361: my $customdata;
8362: if (ref($custominfo) eq 'HASH') {
8363: $customdata = &freeze_escape($custominfo);
8364: }
1.1020 raeburn 8365: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8366: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8367: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8368: $customdata,$homeserver));
1.1020 raeburn 8369: }
8370: return $response;
8371: }
8372:
1.777 albertel 8373: sub auto_validate_class_sec {
1.918 raeburn 8374: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8375: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8376: my $ownerlist;
8377: if (ref($owners) eq 'ARRAY') {
8378: $ownerlist = join(',',@{$owners});
8379: } else {
8380: $ownerlist = $owners;
8381: }
1.773 raeburn 8382: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8383: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8384: return $response;
8385: }
8386:
1.1248 raeburn 8387: sub auto_crsreq_update {
8388: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8389: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8390: my ($homeserver,%crsreqresponse);
8391: if ($cdom =~ /^$match_domain$/) {
8392: $homeserver = &domain($cdom,'primary');
8393: }
8394: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8395: my $info;
8396: if (ref($inbound) eq 'HASH') {
8397: $info = &freeze_escape($inbound);
8398: }
8399: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8400: ':'.&escape($action).':'.&escape($ownername).':'.
8401: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8402: &escape($title).':'.&escape($code).':'.
8403: &escape($accessstart).':'.&escape($accessend).':'.$info,
8404: $homeserver);
1.1248 raeburn 8405: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8406: my @items = split(/&/,$response);
8407: foreach my $item (@items) {
8408: my ($key,$value) = split('=',$item);
8409: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8410: }
8411: }
8412: }
8413: return \%crsreqresponse;
8414: }
8415:
1.1305 raeburn 8416: sub auto_export_grades {
1.1309 raeburn 8417: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8418: my ($homeserver,%exportresponse);
8419: if ($cdom =~ /^$match_domain$/) {
8420: $homeserver = &domain($cdom,'primary');
8421: }
8422: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8423: my $info;
8424: if (ref($inforef) eq 'HASH') {
8425: $info = &freeze_escape($inforef);
8426: }
8427: if (ref($gradesref) eq 'HASH') {
8428: my $grades = &freeze_escape($gradesref);
8429: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8430: $info.':'.$grades,$homeserver);
8431: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8432: my @items = split(/&/,$response);
8433: foreach my $item (@items) {
8434: my ($key,$value) = split('=',$item);
8435: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8436: }
8437: }
8438: }
8439: }
8440: return \%exportresponse;
1.1305 raeburn 8441: }
8442:
1.1287 raeburn 8443: sub check_instcode_cloning {
8444: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8445: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8446: return;
8447: }
8448: my $canclone;
8449: if (@{$code_order} > 0) {
8450: my $instcoderegexp ='^';
8451: my @clonecodes = split(/\&/,$cloner);
8452: foreach my $item (@{$code_order}) {
8453: if (grep(/^\Q$item\E=/,@clonecodes)) {
8454: foreach my $pair (@clonecodes) {
8455: my ($key,$val) = split(/\=/,$pair,2);
8456: $val = &unescape($val);
8457: if ($key eq $item) {
8458: $instcoderegexp .= '('.$val.')';
8459: last;
8460: }
8461: }
8462: } else {
8463: $instcoderegexp .= $codedefaults->{$item};
8464: }
8465: }
8466: $instcoderegexp .= '$';
8467: my (@from,@to);
8468: eval {
8469: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8470: (@to) = ($clonetocode =~ /$instcoderegexp/);
8471: };
8472: if ((@from > 0) && (@to > 0)) {
8473: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8474: if (!@diffs) {
8475: $canclone = 1;
8476: }
8477: }
8478: }
8479: return $canclone;
8480: }
8481:
8482: sub default_instcode_cloning {
8483: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8484: my (%codedefaults,@code_order,$canclone);
8485: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8486: %codedefaults = %{$codedefaultsref};
8487: @code_order = @{$codeorderref};
8488: } elsif ($clonedom) {
8489: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8490: }
8491: if (($domdefclone) && (@code_order)) {
8492: my @clonecodes = split(/\+/,$domdefclone);
8493: my $instcoderegexp ='^';
8494: foreach my $item (@code_order) {
8495: if (grep(/^\Q$item\E$/,@clonecodes)) {
8496: $instcoderegexp .= '('.$codedefaults{$item}.')';
8497: } else {
8498: $instcoderegexp .= $codedefaults{$item};
8499: }
8500: }
8501: $instcoderegexp .= '$';
8502: my (@from,@to);
8503: eval {
8504: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8505: (@to) = ($clonetocode =~ /$instcoderegexp/);
8506: };
8507: if ((@from > 0) && (@to > 0)) {
8508: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8509: if (!@diffs) {
8510: $canclone = 1;
8511: }
8512: }
8513: }
8514: return $canclone;
8515: }
8516:
1.679 raeburn 8517: # ------------------------------------------------------- Course Group routines
8518:
8519: sub get_coursegroups {
1.809 raeburn 8520: my ($cdom,$cnum,$group,$namespace) = @_;
8521: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8522: }
8523:
1.679 raeburn 8524: sub modify_coursegroup {
8525: my ($cdom,$cnum,$groupsettings) = @_;
8526: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8527: }
8528:
1.809 raeburn 8529: sub toggle_coursegroup_status {
8530: my ($cdom,$cnum,$group,$action) = @_;
8531: my ($from_namespace,$to_namespace);
8532: if ($action eq 'delete') {
8533: $from_namespace = 'coursegroups';
8534: $to_namespace = 'deleted_groups';
8535: } else {
8536: $from_namespace = 'deleted_groups';
8537: $to_namespace = 'coursegroups';
8538: }
8539: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8540: if (my $tmp = &error(%curr_group)) {
8541: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8542: return ('read error',$tmp);
8543: } else {
8544: my %savedsettings = %curr_group;
1.809 raeburn 8545: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8546: my $deloutcome;
8547: if ($result eq 'ok') {
1.809 raeburn 8548: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8549: } else {
8550: return ('write error',$result);
8551: }
8552: if ($deloutcome eq 'ok') {
8553: return 'ok';
8554: } else {
8555: return ('delete error',$deloutcome);
8556: }
8557: }
8558: }
8559:
1.679 raeburn 8560: sub modify_group_roles {
1.957 raeburn 8561: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8562: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8563: my $role = 'gr/'.&escape($userprivs);
8564: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8565: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8566: if ($result eq 'ok') {
8567: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8568: }
1.679 raeburn 8569: return $result;
8570: }
8571:
8572: sub modify_coursegroup_membership {
8573: my ($cdom,$cnum,$membership) = @_;
8574: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8575: return $result;
8576: }
8577:
1.682 raeburn 8578: sub get_active_groups {
8579: my ($udom,$uname,$cdom,$cnum) = @_;
8580: my $now = time;
8581: my %groups = ();
8582: foreach my $key (keys(%env)) {
1.811 albertel 8583: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8584: my ($start,$end) = split(/\./,$env{$key});
8585: if (($end!=0) && ($end<$now)) { next; }
8586: if (($start!=0) && ($start>$now)) { next; }
8587: if ($1 eq $cdom && $2 eq $cnum) {
8588: $groups{$3} = $env{$key} ;
8589: }
8590: }
8591: }
8592: return %groups;
8593: }
8594:
1.683 raeburn 8595: sub get_group_membership {
8596: my ($cdom,$cnum,$group) = @_;
8597: return(&dump('groupmembership',$cdom,$cnum,$group));
8598: }
8599:
8600: sub get_users_groups {
8601: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8602: my @usersgroups;
1.683 raeburn 8603: my $cachetime=1800;
8604:
8605: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8606: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8607: if (defined($cached)) {
1.734 albertel 8608: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8609: } else {
8610: $grouplist = '';
1.816 raeburn 8611: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8612: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8613: my $access_end = $env{'course.'.$courseid.
8614: '.default_enrollment_end_date'};
8615: my $now = time;
8616: foreach my $key (keys(%roleshash)) {
8617: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8618: my $group = $1;
8619: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8620: my $start = $2;
8621: my $end = $1;
8622: if ($start == -1) { next; } # deleted from group
8623: if (($start!=0) && ($start>$now)) { next; }
8624: if (($end!=0) && ($end<$now)) {
8625: if ($access_end && $access_end < $now) {
8626: if ($access_end - $end < 86400) {
8627: push(@usersgroups,$group);
1.733 raeburn 8628: }
8629: }
1.817 raeburn 8630: next;
1.733 raeburn 8631: }
1.817 raeburn 8632: push(@usersgroups,$group);
1.683 raeburn 8633: }
8634: }
8635: }
1.817 raeburn 8636: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8637: $grouplist = join(':',@usersgroups);
8638: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8639: }
1.733 raeburn 8640: return @usersgroups;
1.683 raeburn 8641: }
8642:
8643: sub devalidate_getgroups_cache {
8644: my ($udom,$uname,$cdom,$cnum)=@_;
8645: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8646:
1.683 raeburn 8647: my $hashid="$udom:$uname:$courseid";
8648: &devalidate_cache_new('getgroups',$hashid);
8649: }
8650:
1.12 www 8651: # ------------------------------------------------------------------ Plain Text
8652:
8653: sub plaintext {
1.988 raeburn 8654: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8655: if ($short =~ m{^cr/}) {
1.758 albertel 8656: return (split('/',$short))[-1];
8657: }
1.742 raeburn 8658: if (!defined($cid)) {
8659: $cid = $env{'request.course.id'};
8660: }
8661: my %rolenames = (
1.1008 raeburn 8662: Course => 'std',
8663: Community => 'alt1',
1.1305 raeburn 8664: Placement => 'std',
1.742 raeburn 8665: );
1.1037 raeburn 8666: if ($cid ne '') {
8667: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8668: unless ($forcedefault) {
8669: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8670: &Apache::lonlocal::mt_escape(\$roletext);
8671: return &Apache::lonlocal::mt($roletext);
8672: }
8673: }
8674: }
8675: if ((defined($type)) && (defined($rolenames{$type})) &&
8676: (defined($rolenames{$type})) &&
8677: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8678: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8679: } elsif ($cid ne '') {
8680: my $crstype = $env{'course.'.$cid.'.type'};
8681: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8682: (defined($prp{$short}{$rolenames{$crstype}}))) {
8683: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8684: }
1.742 raeburn 8685: }
1.1037 raeburn 8686: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8687: }
8688:
8689: # ----------------------------------------------------------------- Assign Role
8690:
8691: sub assignrole {
1.957 raeburn 8692: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8693: $context)=@_;
1.21 www 8694: my $mrole;
8695: if ($role =~ /^cr\//) {
1.393 www 8696: my $cwosec=$url;
1.811 albertel 8697: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8698: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8699: my $refused = 1;
8700: if ($context eq 'requestcourses') {
8701: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8702: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8703: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8704: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8705: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8706: if ($crsenv{'internal.courseowner'} eq
8707: $env{'user.name'}.':'.$env{'user.domain'}) {
8708: $refused = '';
8709: }
8710: }
8711: }
8712: }
8713: }
8714: if ($refused) {
8715: &logthis('Refused custom assignrole: '.
8716: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8717: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8718: return 'refused';
8719: }
1.104 www 8720: }
1.21 www 8721: $mrole='cr';
1.678 raeburn 8722: } elsif ($role =~ /^gr\//) {
8723: my $cwogrp=$url;
1.811 albertel 8724: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8725: unless (&allowed('mdg',$cwogrp)) {
8726: &logthis('Refused group assignrole: '.
8727: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8728: $env{'user.name'}.' at '.$env{'user.domain'});
8729: return 'refused';
8730: }
8731: $mrole='gr';
1.21 www 8732: } else {
1.82 www 8733: my $cwosec=$url;
1.811 albertel 8734: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8735: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8736: my $refused;
8737: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8738: if (!(&allowed('c'.$role,$url))) {
8739: $refused = 1;
8740: }
8741: } else {
8742: $refused = 1;
8743: }
1.947 raeburn 8744: if ($refused) {
1.1045 raeburn 8745: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8746: if (!$selfenroll && $context eq 'course') {
8747: my %crsenv;
8748: if ($role eq 'cc' || $role eq 'co') {
8749: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8750: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8751: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8752: if ($crsenv{'internal.courseowner'} eq
8753: $env{'user.name'}.':'.$env{'user.domain'}) {
8754: $refused = '';
8755: }
8756: }
8757: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8758: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8759: if ($crsenv{'internal.courseowner'} eq
8760: $env{'user.name'}.':'.$env{'user.domain'}) {
8761: $refused = '';
8762: }
8763: }
8764: }
8765: }
8766: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8767: $refused = '';
1.1017 raeburn 8768: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8769: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8770: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8771: my $wrongcc;
8772: if ($cnum =~ /^$match_community$/) {
8773: $wrongcc = 1 if ($role eq 'cc');
8774: } else {
8775: $wrongcc = 1 if ($role eq 'co');
8776: }
8777: unless ($wrongcc) {
8778: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8779: if ($crsenv{'internal.courseowner'} eq
8780: $env{'user.name'}.':'.$env{'user.domain'}) {
8781: $refused = '';
8782: }
1.1017 raeburn 8783: }
8784: }
1.1183 raeburn 8785: } elsif ($context eq 'requestauthor') {
8786: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8787: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8788: if ($env{'environment.requestauthor'} eq 'automatic') {
8789: $refused = '';
8790: } else {
8791: my %domdefaults = &get_domain_defaults($udom);
8792: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8793: my $checkbystatus;
8794: if ($env{'user.adv'}) {
8795: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8796: if ($disposition eq 'automatic') {
8797: $refused = '';
8798: } elsif ($disposition eq '') {
8799: $checkbystatus = 1;
8800: }
8801: } else {
8802: $checkbystatus = 1;
8803: }
8804: if ($checkbystatus) {
8805: if ($env{'environment.inststatus'}) {
8806: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8807: foreach my $type (@inststatuses) {
8808: if (($type ne '') &&
8809: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8810: $refused = '';
8811: }
8812: }
8813: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8814: $refused = '';
8815: }
8816: }
8817: }
8818: }
8819: }
1.1017 raeburn 8820: }
8821: if ($refused) {
1.947 raeburn 8822: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8823: ' '.$role.' '.$end.' '.$start.' by '.
8824: $env{'user.name'}.' at '.$env{'user.domain'});
8825: return 'refused';
8826: }
1.932 raeburn 8827: }
1.1131 raeburn 8828: } elsif ($role eq 'au') {
8829: if ($url ne '/'.$udom.'/') {
8830: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8831: ' to assign author role for '.$uname.':'.$udom.
8832: ' in domain: '.$url.' refused (wrong domain).');
8833: return 'refused';
8834: }
1.104 www 8835: }
1.21 www 8836: $mrole=$role;
8837: }
1.620 albertel 8838: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8839: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8840: if ($end) { $command.='_'.$end; }
1.21 www 8841: if ($start) {
8842: if ($end) {
1.81 www 8843: $command.='_'.$start;
1.21 www 8844: } else {
1.81 www 8845: $command.='_0_'.$start;
1.21 www 8846: }
8847: }
1.739 raeburn 8848: my $origstart = $start;
8849: my $origend = $end;
1.957 raeburn 8850: my $delflag;
1.357 www 8851: # actually delete
8852: if ($deleteflag) {
1.373 www 8853: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8854: # modify command to delete the role
1.620 albertel 8855: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8856: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8857: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8858: # set start and finish to negative values for userrolelog
8859: $start=-1;
8860: $end=-1;
1.957 raeburn 8861: $delflag = 1;
1.357 www 8862: }
8863: }
8864: # send command
1.349 www 8865: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8866: # log new user role if status is ok
1.349 www 8867: if ($answer eq 'ok') {
1.663 raeburn 8868: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8869: if (($role eq 'cc') || ($role eq 'in') ||
8870: ($role eq 'ep') || ($role eq 'ad') ||
8871: ($role eq 'ta') || ($role eq 'st') ||
8872: ($role=~/^cr/) || ($role eq 'gr') ||
8873: ($role eq 'co')) {
1.1200 raeburn 8874: # for course roles, perform group memberships changes triggered by role change.
8875: unless ($role =~ /^gr/) {
8876: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8877: $origstart,$selfenroll,$context);
8878: }
1.1184 raeburn 8879: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8880: $selfenroll,$context);
8881: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1327 raeburn 8882: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh')) {
1.1184 raeburn 8883: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8884: $context);
8885: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8886: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8887: $context);
8888: }
1.1053 raeburn 8889: if ($role eq 'cc') {
8890: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8891: }
1.349 www 8892: }
8893: return $answer;
1.169 harris41 8894: }
8895:
1.1053 raeburn 8896: sub autoupdate_coowners {
8897: my ($url,$end,$start,$uname,$udom) = @_;
8898: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8899: if (($cdom ne '') && ($cnum ne '')) {
8900: my $now = time;
8901: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8902: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8903: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8904: my $instcode = $coursehash{'internal.coursecode'};
8905: if ($instcode ne '') {
1.1056 raeburn 8906: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8907: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8908: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8909: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8910: if ($result eq 'valid') {
8911: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8912: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8913: push(@newcoowners,$coowner);
8914: }
8915: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8916: push(@newcoowners,$uname.':'.$udom);
8917: }
8918: @newcoowners = sort(@newcoowners);
8919: } else {
8920: push(@newcoowners,$uname.':'.$udom);
8921: }
8922: } else {
8923: if ($coursehash{'internal.co-owners'}) {
8924: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8925: unless ($coowner eq $uname.':'.$udom) {
8926: push(@newcoowners,$coowner);
8927: }
8928: }
8929: unless (@newcoowners > 0) {
8930: $delcoowners = 1;
8931: $coowners = '';
8932: }
8933: }
8934: }
8935: if (@newcoowners || $delcoowners) {
8936: &store_coowners($cdom,$cnum,$coursehash{'home'},
8937: $delcoowners,@newcoowners);
8938: }
8939: }
8940: }
8941: }
8942: }
8943: }
8944: }
8945:
8946: sub store_coowners {
8947: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8948: my $cid = $cdom.'_'.$cnum;
8949: my ($coowners,$delresult,$putresult);
8950: if (@newcoowners) {
8951: $coowners = join(',',@newcoowners);
8952: my %coownershash = (
8953: 'internal.co-owners' => $coowners,
8954: );
8955: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8956: if ($putresult eq 'ok') {
8957: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8958: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8959: }
8960: }
8961: }
8962: if ($delcoowners) {
8963: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8964: if ($delresult eq 'ok') {
8965: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8966: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8967: }
8968: }
8969: }
8970: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8971: my %crsinfo =
8972: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8973: if (ref($crsinfo{$cid}) eq 'HASH') {
8974: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8975: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8976: }
8977: }
8978: }
8979:
1.169 harris41 8980: # -------------------------------------------------- Modify user authentication
1.197 www 8981: # Overrides without validation
8982:
1.169 harris41 8983: sub modifyuserauth {
8984: my ($udom,$uname,$umode,$upass)=@_;
8985: my $uhome=&homeserver($uname,$udom);
1.197 www 8986: unless (&allowed('mau',$udom)) { return 'refused'; }
8987: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8988: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8989: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8990: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8991: &escape($upass),$uhome);
1.620 albertel 8992: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8993: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8994: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8995: &log($udom,,$uname,$uhome,
1.620 albertel 8996: 'Authentication changed by '.$env{'user.domain'}.', '.
8997: $env{'user.name'}.', '.$umode.
1.197 www 8998: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8999: unless ($reply eq 'ok') {
1.197 www 9000: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9001: return 'error: '.$reply;
9002: }
1.170 harris41 9003: return 'ok';
1.80 www 9004: }
9005:
1.81 www 9006: # --------------------------------------------------------------- Modify a user
1.80 www 9007:
1.81 www 9008: sub modifyuser {
1.206 matthew 9009: my ($udom, $uname, $uid,
9010: $umode, $upass, $first,
9011: $middle, $last, $gene,
1.1058 raeburn 9012: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9013: $udom= &LONCAPA::clean_domain($udom);
9014: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9015: my $showcandelete = 'none';
9016: if (ref($candelete) eq 'ARRAY') {
9017: if (@{$candelete} > 0) {
9018: $showcandelete = join(', ',@{$candelete});
9019: }
9020: }
1.81 www 9021: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9022: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9023: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9024: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9025: ' desiredhome not specified').
1.620 albertel 9026: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9027: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9028: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9029: my $newuser;
9030: if ($uhome eq 'no_host') {
9031: $newuser = 1;
9032: }
1.80 www 9033: # ----------------------------------------------------------------- Create User
1.406 albertel 9034: if (($uhome eq 'no_host') &&
9035: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9036: my $unhome='';
1.844 albertel 9037: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9038: $unhome = $desiredhome;
1.620 albertel 9039: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9040: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9041: } else { # load balancing routine for determining $unhome
1.81 www 9042: my $loadm=10000000;
1.841 albertel 9043: my %servers = &get_servers($udom,'library');
9044: foreach my $tryserver (keys(%servers)) {
9045: my $answer=reply('load',$tryserver);
9046: if (($answer=~/\d+/) && ($answer<$loadm)) {
9047: $loadm=$answer;
9048: $unhome=$tryserver;
9049: }
1.80 www 9050: }
9051: }
9052: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9053: return 'error: unable to find a home server for '.$uname.
9054: ' in domain '.$udom;
1.80 www 9055: }
9056: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9057: &escape($upass),$unhome);
9058: unless ($reply eq 'ok') {
9059: return 'error: '.$reply;
9060: }
1.230 stredwic 9061: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9062: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9063: return 'error: unable verify users home machine.';
1.80 www 9064: }
1.209 matthew 9065: } # End of creation of new user
1.80 www 9066: # ---------------------------------------------------------------------- Add ID
9067: if ($uid) {
9068: $uid=~tr/A-Z/a-z/;
9069: my %uidhash=&idrget($udom,$uname);
1.196 www 9070: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9071: && (!$forceid)) {
1.80 www 9072: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9073: return 'error: user id "'.$uid.'" does not match '.
9074: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9075: }
9076: } else {
1.1300 raeburn 9077: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 9078: }
9079: }
9080: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9081: my @tmp=&get('environment',
1.899 raeburn 9082: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9083: 'permanentemail','inststatus'],
1.134 albertel 9084: $udom,$uname);
1.1075 raeburn 9085: my (%names,%oldnames);
1.313 matthew 9086: if ($tmp[0] =~ m/^error:.*/) {
9087: %names=();
9088: } else {
9089: %names = @tmp;
1.1075 raeburn 9090: %oldnames = %names;
1.313 matthew 9091: }
1.388 www 9092: #
1.1058 raeburn 9093: # If name, email and/or uid are blank (e.g., because an uploaded file
9094: # of users did not contain them), do not overwrite existing values
9095: # unless field is in $candelete array ref.
9096: #
9097:
9098: my @fields = ('firstname','middlename','lastname','generation',
9099: 'permanentemail','id');
9100: my %newvalues;
9101: if (ref($candelete) eq 'ARRAY') {
9102: foreach my $field (@fields) {
9103: if (grep(/^\Q$field\E$/,@{$candelete})) {
9104: if ($field eq 'firstname') {
9105: $names{$field} = $first;
9106: } elsif ($field eq 'middlename') {
9107: $names{$field} = $middle;
9108: } elsif ($field eq 'lastname') {
9109: $names{$field} = $last;
9110: } elsif ($field eq 'generation') {
9111: $names{$field} = $gene;
9112: } elsif ($field eq 'permanentemail') {
9113: $names{$field} = $email;
9114: } elsif ($field eq 'id') {
9115: $names{$field} = $uid;
9116: }
9117: }
9118: }
9119: }
1.388 www 9120: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9121: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9122: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9123: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9124: if ($email) {
9125: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9126: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9127: }
1.899 raeburn 9128: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9129: if (defined($inststatus)) {
9130: $names{'inststatus'} = '';
9131: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9132: if (ref($usertypes) eq 'HASH') {
9133: my @okstatuses;
9134: foreach my $item (split(/:/,$inststatus)) {
9135: if (defined($usertypes->{$item})) {
9136: push(@okstatuses,$item);
9137: }
9138: }
9139: if (@okstatuses) {
9140: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9141: }
9142: }
9143: }
1.1075 raeburn 9144: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9145: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9146: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9147: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9148: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9149: } else {
9150: $logmsg .= ' during self creation';
9151: }
1.1075 raeburn 9152: my $changed;
9153: if ($newuser) {
9154: $changed = 1;
9155: } else {
9156: foreach my $field (@fields) {
9157: if ($names{$field} ne $oldnames{$field}) {
9158: $changed = 1;
9159: last;
9160: }
9161: }
9162: }
9163: unless ($changed) {
9164: $logmsg = 'No changes in user information needed for: '.$logmsg;
9165: &logthis($logmsg);
9166: return 'ok';
9167: }
9168: my $reply = &put('environment', \%names, $udom,$uname);
9169: if ($reply ne 'ok') {
9170: return 'error: '.$reply;
9171: }
1.1087 raeburn 9172: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9173: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9174: }
1.1075 raeburn 9175: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9176: &devalidate_cache_new('namescache',$uname.':'.$udom);
9177: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9178: &logthis($logmsg);
1.134 albertel 9179: return 'ok';
1.80 www 9180: }
9181:
1.81 www 9182: # -------------------------------------------------------------- Modify student
1.80 www 9183:
1.81 www 9184: sub modifystudent {
9185: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9186: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 9187: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9188: if (!$cid) {
1.620 albertel 9189: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9190: return 'not_in_class';
9191: }
1.80 www 9192: }
9193: # --------------------------------------------------------------- Make the user
1.81 www 9194: my $reply=&modifyuser
1.209 matthew 9195: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9196: $desiredhome,$email,$inststatus);
1.80 www 9197: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9198: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 9199: # student's environment
1.297 matthew 9200: $uid = undef if (!$forceid);
1.455 albertel 9201: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 9202: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 9203: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9204: return $reply;
9205: }
9206:
9207: sub modify_student_enrollment {
1.1216 raeburn 9208: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 9209: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9210: my ($cdom,$cnum,$chome);
9211: if (!$cid) {
1.620 albertel 9212: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9213: return 'not_in_class';
9214: }
1.620 albertel 9215: $cdom=$env{'course.'.$cid.'.domain'};
9216: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9217: } else {
9218: ($cdom,$cnum)=split(/_/,$cid);
9219: }
1.620 albertel 9220: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9221: if (!$chome) {
1.457 raeburn 9222: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9223: }
1.455 albertel 9224: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9225: # Make sure the user exists
1.81 www 9226: my $uhome=&homeserver($uname,$udom);
9227: if (($uhome eq '') || ($uhome eq 'no_host')) {
9228: return 'error: no such user';
9229: }
1.297 matthew 9230: # Get student data if we were not given enough information
9231: if (!defined($first) || $first eq '' ||
9232: !defined($last) || $last eq '' ||
9233: !defined($uid) || $uid eq '' ||
9234: !defined($middle) || $middle eq '' ||
9235: !defined($gene) || $gene eq '') {
1.294 matthew 9236: # They did not supply us with enough data to enroll the student, so
9237: # we need to pick up more information.
1.297 matthew 9238: my %tmp = &get('environment',
1.294 matthew 9239: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9240: ,$udom,$uname);
9241:
1.800 albertel 9242: #foreach my $key (keys(%tmp)) {
9243: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9244: #}
1.294 matthew 9245: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9246: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9247: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9248: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9249: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9250: }
1.556 albertel 9251: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9252: my $user = "$uname:$udom";
9253: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9254: my $reply=cput('classlist',
1.1148 raeburn 9255: {$user =>
1.1314 raeburn 9256: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9257: $cdom,$cnum);
1.1148 raeburn 9258: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9259: &devalidate_getsection_cache($udom,$uname,$cid);
9260: } else {
1.81 www 9261: return 'error: '.$reply;
9262: }
1.297 matthew 9263: # Add student role to user
1.83 www 9264: my $uurl='/'.$cid;
1.81 www 9265: $uurl=~s/\_/\//g;
9266: if ($usec) {
9267: $uurl.='/'.$usec;
9268: }
1.1148 raeburn 9269: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9270: $selfenroll,$context);
9271: if ($result ne 'ok') {
9272: if ($old_entry{$user} ne '') {
9273: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9274: } else {
9275: $reply = &del('classlist',[$user],$cdom,$cnum);
9276: }
9277: }
9278: return $result;
1.21 www 9279: }
9280:
1.556 albertel 9281: sub format_name {
9282: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9283: my $name;
9284: if ($first ne 'lastname') {
9285: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9286: } else {
9287: if ($lastname=~/\S/) {
9288: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9289: $name=~s/\s+,/,/;
9290: } else {
9291: $name.= $firstname.' '.$middlename.' '.$generation;
9292: }
9293: }
9294: $name=~s/^\s+//;
9295: $name=~s/\s+$//;
9296: $name=~s/\s+/ /g;
9297: return $name;
9298: }
9299:
1.84 www 9300: # ------------------------------------------------- Write to course preferences
9301:
9302: sub writecoursepref {
9303: my ($courseid,%prefs)=@_;
9304: $courseid=~s/^\///;
9305: $courseid=~s/\_/\//g;
9306: my ($cdomain,$cnum)=split(/\//,$courseid);
9307: my $chome=homeserver($cnum,$cdomain);
9308: if (($chome eq '') || ($chome eq 'no_host')) {
9309: return 'error: no such course';
9310: }
9311: my $cstring='';
1.800 albertel 9312: foreach my $pref (keys(%prefs)) {
9313: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9314: }
1.84 www 9315: $cstring=~s/\&$//;
9316: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9317: }
9318:
9319: # ---------------------------------------------------------- Make/modify course
9320:
9321: sub createcourse {
1.741 raeburn 9322: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9323: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9324: $url=&declutter($url);
9325: my $cid='';
1.1028 raeburn 9326: if ($context eq 'requestcourses') {
9327: my $can_create = 0;
9328: my ($ownername,$ownerdom) = split(':',$course_owner);
9329: if ($udom eq $ownerdom) {
9330: if (&usertools_access($ownername,$ownerdom,$category,undef,
9331: $context)) {
9332: $can_create = 1;
9333: }
9334: } else {
9335: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9336: $category);
9337: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9338: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9339: if (@curr > 0) {
9340: my @options = qw(approval validate autolimit);
9341: my $optregex = join('|',@options);
9342: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9343: $can_create = 1;
9344: }
9345: }
9346: }
9347: }
9348: if ($can_create) {
9349: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9350: unless (&allowed('ccc',$udom)) {
9351: return 'refused';
9352: }
1.1017 raeburn 9353: }
9354: } else {
9355: return 'refused';
9356: }
1.1028 raeburn 9357: } elsif (!&allowed('ccc',$udom)) {
9358: return 'refused';
1.84 www 9359: }
1.1011 raeburn 9360: # --------------------------------------------------------------- Get Unique ID
9361: my $uname;
9362: if ($cnum =~ /^$match_courseid$/) {
9363: my $chome=&homeserver($cnum,$udom,'true');
9364: if (($chome eq '') || ($chome eq 'no_host')) {
9365: $uname = $cnum;
9366: } else {
1.1038 raeburn 9367: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9368: }
9369: } else {
1.1038 raeburn 9370: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9371: }
9372: return $uname if ($uname =~ /^error/);
9373: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9374: if (!defined($course_server)) {
9375: if (defined(&domain($udom,'primary'))) {
9376: $course_server = &domain($udom,'primary');
9377: } else {
9378: $course_server = $env{'user.home'};
9379: }
9380: }
9381: my %host_servers =
9382: &Apache::lonnet::get_servers($udom,'library');
9383: unless ($host_servers{$course_server}) {
9384: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9385: }
1.84 www 9386: # ------------------------------------------------------------- Make the course
9387: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9388: $course_server);
1.84 www 9389: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9390: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9391: if (($uhome eq '') || ($uhome eq 'no_host')) {
9392: return 'error: no such course';
9393: }
1.271 www 9394: # ----------------------------------------------------------------- Course made
1.516 raeburn 9395: # log existence
1.1029 raeburn 9396: my $now = time;
1.918 raeburn 9397: my $newcourse = {
9398: $udom.'_'.$uname => {
1.921 raeburn 9399: description => $description,
9400: inst_code => $inst_code,
9401: owner => $course_owner,
9402: type => $crstype,
1.1029 raeburn 9403: creator => $env{'user.name'}.':'.
9404: $env{'user.domain'},
9405: created => $now,
9406: context => $context,
1.918 raeburn 9407: },
9408: };
1.921 raeburn 9409: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9410: # set toplevel url
1.271 www 9411: my $topurl=$url;
9412: unless ($nonstandard) {
9413: # ------------------------------------------ For standard courses, make top url
9414: my $mapurl=&clutter($url);
1.278 www 9415: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9416: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9417: <map>
9418: <resource id="1" type="start"></resource>
9419: <resource id="2" src="$mapurl"></resource>
9420: <resource id="3" type="finish"></resource>
9421: <link index="1" from="1" to="2"></link>
9422: <link index="2" from="2" to="3"></link>
9423: </map>
9424: ENDINITMAP
9425: $topurl=&declutter(
1.638 albertel 9426: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9427: );
9428: }
9429: # ----------------------------------------------------------- Write preferences
1.84 www 9430: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9431: ('description' => $description,
9432: 'url' => $topurl,
9433: 'internal.creator' => $env{'user.name'}.':'.
9434: $env{'user.domain'},
9435: 'internal.created' => $now,
9436: 'internal.creationcontext' => $context)
9437: );
1.84 www 9438: return '/'.$udom.'/'.$uname;
9439: }
9440:
1.1011 raeburn 9441: # ------------------------------------------------------------------- Create ID
9442: sub generate_coursenum {
1.1038 raeburn 9443: my ($udom,$crstype) = @_;
1.1011 raeburn 9444: my $domdesc = &domain($udom);
9445: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9446: my $first;
9447: if ($crstype eq 'Community') {
9448: $first = '0';
9449: } else {
9450: $first = int(1+rand(9));
9451: }
9452: my $uname=$first.
1.1011 raeburn 9453: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9454: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9455: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9456: # ----------------------------------------------- Make sure that does not exist
9457: my $uhome=&homeserver($uname,$udom,'true');
9458: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9459: if ($crstype eq 'Community') {
9460: $first = '0';
9461: } else {
9462: $first = int(1+rand(9));
9463: }
9464: $uname=$first.
1.1011 raeburn 9465: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9466: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9467: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9468: $uhome=&homeserver($uname,$udom,'true');
9469: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9470: return 'error: unable to generate unique course-ID';
9471: }
9472: }
9473: return $uname;
9474: }
9475:
1.813 albertel 9476: sub is_course {
1.1167 droeschl 9477: my ($cdom, $cnum) = scalar(@_) == 1 ?
9478: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9479:
9480: return unless $cdom and $cnum;
9481:
9482: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9483: '.');
9484:
1.1219 raeburn 9485: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9486: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9487: }
9488:
1.1015 raeburn 9489: sub store_userdata {
9490: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9491: my $result;
1.1016 raeburn 9492: if ($datakey ne '') {
1.1013 raeburn 9493: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9494: if ($udom eq '' || $uname eq '') {
9495: $udom = $env{'user.domain'};
9496: $uname = $env{'user.name'};
9497: }
9498: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9499: if (($uhome eq '') || ($uhome eq 'no_host')) {
9500: $result = 'error: no_host';
9501: } else {
9502: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9503: $storehash->{'host'} = $perlvar{'lonHostID'};
9504:
9505: my $namevalue='';
9506: foreach my $key (keys(%{$storehash})) {
9507: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9508: }
9509: $namevalue=~s/\&$//;
1.1224 raeburn 9510: unless ($namespace eq 'courserequests') {
9511: $datakey = &escape($datakey);
9512: }
1.1105 raeburn 9513: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9514: $namevalue,$uhome);
1.1013 raeburn 9515: }
9516: } else {
9517: $result = 'error: data to store was not a hash reference';
9518: }
9519: } else {
9520: $result= 'error: invalid requestkey';
9521: }
9522: return $result;
9523: }
9524:
1.21 www 9525: # ---------------------------------------------------------- Assign Custom Role
9526:
9527: sub assigncustomrole {
1.957 raeburn 9528: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9529: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9530: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9531: }
9532:
9533: # ----------------------------------------------------------------- Revoke Role
9534:
9535: sub revokerole {
1.957 raeburn 9536: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9537: my $now=time;
1.965 raeburn 9538: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9539: }
9540:
9541: # ---------------------------------------------------------- Revoke Custom Role
9542:
9543: sub revokecustomrole {
1.957 raeburn 9544: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9545: my $now=time;
1.357 www 9546: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9547: $deleteflag,$selfenroll,$context);
1.17 www 9548: }
9549:
1.533 banghart 9550: # ------------------------------------------------------------ Disk usage
1.535 albertel 9551: sub diskusage {
1.955 raeburn 9552: my ($udom,$uname,$directorypath,$getpropath)=@_;
9553: $directorypath =~ s/\/$//;
9554: my $listing=&reply('du2:'.&escape($directorypath).':'
9555: .&escape($getpropath).':'.&escape($uname).':'
9556: .&escape($udom),homeserver($uname,$udom));
9557: if ($listing eq 'unknown_cmd') {
9558: if ($getpropath) {
9559: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9560: }
9561: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9562: }
1.514 albertel 9563: return $listing;
1.512 banghart 9564: }
9565:
1.566 banghart 9566: sub is_locked {
1.1096 raeburn 9567: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9568: my @check;
9569: my $is_locked;
1.1093 raeburn 9570: push (@check,$file_name);
1.613 albertel 9571: my %locked = &get('file_permissions',\@check,
1.620 albertel 9572: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9573: my ($tmp)=keys(%locked);
9574: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9575:
1.566 banghart 9576: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9577: $is_locked = 'false';
9578: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9579: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9580: $is_locked = 'true';
1.1096 raeburn 9581: if (ref($which) eq 'ARRAY') {
9582: push(@{$which},$entry);
9583: } else {
9584: last;
9585: }
1.745 raeburn 9586: }
9587: }
1.566 banghart 9588: } else {
9589: $is_locked = 'false';
9590: }
1.1093 raeburn 9591: return $is_locked;
1.566 banghart 9592: }
9593:
1.759 albertel 9594: sub declutter_portfile {
9595: my ($file) = @_;
1.833 albertel 9596: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9597: return $file;
9598: }
9599:
1.559 banghart 9600: # ------------------------------------------------------------- Mark as Read Only
9601:
9602: sub mark_as_readonly {
9603: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9604: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9605: my ($tmp)=keys(%current_permissions);
9606: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9607: foreach my $file (@{$files}) {
1.759 albertel 9608: $file = &declutter_portfile($file);
1.561 banghart 9609: push(@{$current_permissions{$file}},$what);
1.559 banghart 9610: }
1.613 albertel 9611: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9612: return;
9613: }
9614:
1.572 banghart 9615: # ------------------------------------------------------------Save Selected Files
9616:
9617: sub save_selected_files {
9618: my ($user, $path, @files) = @_;
9619: my $filename = $user."savedfiles";
1.573 banghart 9620: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9621: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9622: foreach my $file (@files) {
1.620 albertel 9623: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9624: }
9625: foreach my $file (@other_files) {
1.574 banghart 9626: print (OUT $file."\n");
1.572 banghart 9627: }
1.574 banghart 9628: close (OUT);
1.572 banghart 9629: return 'ok';
9630: }
9631:
1.574 banghart 9632: sub clear_selected_files {
9633: my ($user) = @_;
9634: my $filename = $user."savedfiles";
1.1117 foxr 9635: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9636: print (OUT undef);
9637: close (OUT);
9638: return ("ok");
9639: }
9640:
1.572 banghart 9641: sub files_in_path {
9642: my ($user, $path) = @_;
9643: my $filename = $user."savedfiles";
9644: my %return_files;
1.1117 foxr 9645: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9646: while (my $line_in = <IN>) {
1.574 banghart 9647: chomp ($line_in);
9648: my @paths_and_file = split (m!/!, $line_in);
9649: my $file_part = pop (@paths_and_file);
9650: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9651: $path_part.='/';
9652: my $path_and_file = $path_part.$file_part;
9653: if ($path_part eq $path) {
9654: $return_files{$file_part}= 'selected';
9655: }
9656: }
1.574 banghart 9657: close (IN);
9658: return (\%return_files);
1.572 banghart 9659: }
9660:
9661: # called in portfolio select mode, to show files selected NOT in current directory
9662: sub files_not_in_path {
9663: my ($user, $path) = @_;
9664: my $filename = $user."savedfiles";
9665: my @return_files;
9666: my $path_part;
1.1117 foxr 9667: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9668: while (my $line = <IN>) {
1.572 banghart 9669: #ok, I know it's clunky, but I want it to work
1.800 albertel 9670: my @paths_and_file = split(m|/|, $line);
9671: my $file_part = pop(@paths_and_file);
9672: chomp($file_part);
9673: my $path_part = join('/', @paths_and_file);
1.572 banghart 9674: $path_part .= '/';
9675: my $path_and_file = $path_part.$file_part;
9676: if ($path_part ne $path) {
1.800 albertel 9677: push(@return_files, ($path_and_file));
1.572 banghart 9678: }
9679: }
1.800 albertel 9680: close(OUT);
1.574 banghart 9681: return (@return_files);
1.572 banghart 9682: }
9683:
1.1273 raeburn 9684: #------------------------------Submitted/Handedback Portfolio Files Versioning
9685:
9686: sub portfiles_versioning {
9687: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9688: my $portfolio_root = '/userfiles/portfolio';
9689: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9690: foreach my $file (@{$portfiles}) {
9691: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9692: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9693: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9694: my $getpropath = 1;
9695: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9696: $stu_name,$getpropath);
9697: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9698: my $new_answer =
9699: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9700: if ($new_answer ne 'problem getting file') {
9701: push(@{$versioned_portfiles}, $directory.$new_answer);
9702: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9703: [$symb,$env{'request.course.id'},'graded']);
9704: }
9705: }
9706: }
9707:
9708: sub get_next_version {
9709: my ($answer_name, $answer_ext, $dir_list) = @_;
9710: my $version;
9711: if (ref($dir_list) eq 'ARRAY') {
9712: foreach my $row (@{$dir_list}) {
9713: my ($file) = split(/\&/,$row,2);
9714: my ($file_name,$file_version,$file_ext) =
9715: &file_name_version_ext($file);
9716: if (($file_name eq $answer_name) &&
9717: ($file_ext eq $answer_ext)) {
9718: # gets here if filename and extension match,
9719: # regardless of version
9720: if ($file_version ne '') {
9721: # a versioned file is found so save it for later
9722: if ($file_version > $version) {
9723: $version = $file_version;
9724: }
9725: }
9726: }
9727: }
9728: }
9729: $version ++;
9730: return($version);
9731: }
9732:
9733: sub version_selected_portfile {
9734: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
9735: my ($answer_name,$answer_ver,$answer_ext) =
9736: &file_name_version_ext($file_name);
9737: my $new_answer;
9738: $env{'form.copy'} =
9739: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
9740: if($env{'form.copy'} eq '-1') {
9741: $new_answer = 'problem getting file';
9742: } else {
9743: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
9744: my $copy_result =
9745: &finishuserfileupload($stu_name,$domain,'copy',
9746: '/portfolio'.$directory.$new_answer);
9747: }
9748: undef($env{'form.copy'});
9749: return ($new_answer);
9750: }
9751:
9752: sub file_name_version_ext {
9753: my ($file)=@_;
9754: my @file_parts = split(/\./, $file);
9755: my ($name,$version,$ext);
9756: if (@file_parts > 1) {
9757: $ext=pop(@file_parts);
9758: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
9759: $version=pop(@file_parts);
9760: }
9761: $name=join('.',@file_parts);
9762: } else {
9763: $name=join('.',@file_parts);
9764: }
9765: return($name,$version,$ext);
9766: }
9767:
1.745 raeburn 9768: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9769:
1.745 raeburn 9770: sub get_portfile_permissions {
9771: my ($domain,$user) = @_;
1.613 albertel 9772: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9773: my ($tmp)=keys(%current_permissions);
9774: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9775: return \%current_permissions;
9776: }
9777:
9778: #---------------------------------------------Get portfolio file access controls
9779:
1.749 raeburn 9780: sub get_access_controls {
1.745 raeburn 9781: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9782: my %access;
9783: my $real_file = $file;
9784: $file =~ s/\.meta$//;
1.745 raeburn 9785: if (defined($file)) {
1.749 raeburn 9786: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9787: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9788: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9789: }
9790: }
1.745 raeburn 9791: } else {
1.749 raeburn 9792: foreach my $key (keys(%{$current_permissions})) {
9793: if ($key =~ /\0accesscontrol$/) {
9794: if (defined($group)) {
9795: if ($key !~ m-^\Q$group\E/-) {
9796: next;
9797: }
9798: }
9799: my ($fullpath) = split(/\0/,$key);
9800: if (ref($$current_permissions{$key}) eq 'HASH') {
9801: foreach my $control (keys(%{$$current_permissions{$key}})) {
9802: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9803: }
9804: }
9805: }
9806: }
9807: }
9808: return %access;
9809: }
9810:
9811: sub modify_access_controls {
9812: my ($file_name,$changes,$domain,$user)=@_;
9813: my ($outcome,$deloutcome);
9814: my %store_permissions;
9815: my %new_values;
9816: my %new_control;
9817: my %translation;
9818: my @deletions = ();
9819: my $now = time;
9820: if (exists($$changes{'activate'})) {
9821: if (ref($$changes{'activate'}) eq 'HASH') {
9822: my @newitems = sort(keys(%{$$changes{'activate'}}));
9823: my $numnew = scalar(@newitems);
9824: for (my $i=0; $i<$numnew; $i++) {
9825: my $newkey = $newitems[$i];
9826: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9827: if ($newkey =~ /^\d+:/) {
9828: $newkey =~ s/^(\d+)/$newid/;
9829: $translation{$1} = $newid;
9830: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9831: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9832: $translation{$1} = $newid;
9833: }
1.749 raeburn 9834: $new_values{$file_name."\0".$newkey} =
9835: $$changes{'activate'}{$newitems[$i]};
9836: $new_control{$newkey} = $now;
9837: }
9838: }
9839: }
9840: my %todelete;
9841: my %changed_items;
9842: foreach my $action ('delete','update') {
9843: if (exists($$changes{$action})) {
9844: if (ref($$changes{$action}) eq 'HASH') {
9845: foreach my $key (keys(%{$$changes{$action}})) {
9846: my ($itemnum) = ($key =~ /^([^:]+):/);
9847: if ($action eq 'delete') {
9848: $todelete{$itemnum} = 1;
9849: } else {
9850: $changed_items{$itemnum} = $key;
9851: }
9852: }
1.745 raeburn 9853: }
9854: }
1.749 raeburn 9855: }
9856: # get lock on access controls for file.
9857: my $lockhash = {
9858: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9859: ':'.$env{'user.domain'},
9860: };
9861: my $tries = 0;
9862: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9863:
1.1288 damieng 9864: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 9865: $tries ++;
1.1289 damieng 9866: sleep(0.1);
1.749 raeburn 9867: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9868: }
9869: if ($gotlock eq 'ok') {
9870: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9871: my ($tmp)=keys(%curr_permissions);
9872: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9873: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9874: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9875: if (ref($curr_controls) eq 'HASH') {
9876: foreach my $control_item (keys(%{$curr_controls})) {
9877: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9878: if (defined($todelete{$itemnum})) {
9879: push(@deletions,$file_name."\0".$control_item);
9880: } else {
9881: if (defined($changed_items{$itemnum})) {
9882: $new_control{$changed_items{$itemnum}} = $now;
9883: push(@deletions,$file_name."\0".$control_item);
9884: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9885: } else {
9886: $new_control{$control_item} = $$curr_controls{$control_item};
9887: }
9888: }
1.745 raeburn 9889: }
9890: }
9891: }
1.970 raeburn 9892: my ($group);
9893: if (&is_course($domain,$user)) {
9894: ($group,my $file) = split(/\//,$file_name,2);
9895: }
1.749 raeburn 9896: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9897: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9898: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9899: # remove lock
9900: my @del_lock = ($file_name."\0".'locked_access_records');
9901: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9902: my $sqlresult =
1.970 raeburn 9903: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9904: $group);
1.749 raeburn 9905: } else {
9906: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9907: }
1.749 raeburn 9908: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9909: }
9910:
1.827 raeburn 9911: sub make_public_indefinitely {
1.1271 raeburn 9912: my (@requrl) = @_;
9913: return &automated_portfile_access('public',\@requrl);
9914: }
9915:
9916: sub automated_portfile_access {
9917: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 9918: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
9919: return 'invalid';
9920: }
1.1271 raeburn 9921: my %urls;
9922: if (ref($addsref) eq 'ARRAY') {
9923: foreach my $requrl (@{$addsref}) {
9924: if (&is_portfolio_url($requrl)) {
9925: unless (exists($urls{$requrl})) {
9926: $urls{$requrl} = 'add';
9927: }
9928: }
9929: }
9930: }
9931: if (ref($delsref) eq 'ARRAY') {
9932: foreach my $requrl (@{$delsref}) {
9933: if (&is_portfolio_url($requrl)) {
9934: unless (exists($urls{$requrl})) {
9935: $urls{$requrl} = 'delete';
9936: }
9937: }
9938: }
9939: }
9940: unless (keys(%urls)) {
9941: return 'invalid';
9942: }
9943: my $ip;
9944: if ($accesstype eq 'ip') {
9945: if (ref($info) eq 'HASH') {
9946: if ($info->{'ip'} ne '') {
9947: $ip = $info->{'ip'};
9948: }
9949: }
9950: if ($ip eq '') {
9951: return 'invalid';
9952: }
9953: }
9954: my $errors;
1.827 raeburn 9955: my $now = time;
1.1271 raeburn 9956: my %current_perms;
9957: foreach my $requrl (sort(keys(%urls))) {
9958: my $action;
9959: if ($urls{$requrl} eq 'add') {
9960: $action = 'activate';
9961: } else {
9962: $action = 'none';
9963: }
9964: my $aclnum = 0;
1.827 raeburn 9965: my (undef,$udom,$unum,$file_name,$group) =
9966: &parse_portfolio_url($requrl);
1.1271 raeburn 9967: unless (exists($current_perms{$unum.':'.$udom})) {
9968: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
9969: }
9970: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 9971: $group,$file_name);
9972: foreach my $key (keys(%{$access_controls{$file_name}})) {
9973: my ($num,$scope,$end,$start) =
9974: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 9975: if ($scope eq $accesstype) {
9976: if (($start <= $now) && ($end == 0)) {
9977: if ($accesstype eq 'ip') {
9978: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
9979: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
9980: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
9981: if ($urls{$requrl} eq 'add') {
9982: $action = 'none';
9983: last;
9984: } else {
9985: $action = 'delete';
9986: $aclnum = $num;
9987: last;
9988: }
9989: }
9990: }
9991: }
9992: } elsif ($accesstype eq 'public') {
9993: if ($urls{$requrl} eq 'add') {
9994: $action = 'none';
9995: last;
9996: } else {
9997: $action = 'delete';
9998: $aclnum = $num;
9999: last;
10000: }
10001: }
10002: } elsif ($accesstype eq 'public') {
1.827 raeburn 10003: $action = 'update';
10004: $aclnum = $num;
1.1271 raeburn 10005: last;
1.827 raeburn 10006: }
10007: }
10008: }
10009: if ($action eq 'none') {
1.1271 raeburn 10010: next;
1.827 raeburn 10011: } else {
10012: my %changes;
10013: my $newend = 0;
10014: my $newstart = $now;
1.1271 raeburn 10015: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 10016: $changes{$action}{$newkey} = {
1.1271 raeburn 10017: type => $accesstype,
1.827 raeburn 10018: time => {
10019: start => $newstart,
10020: end => $newend,
10021: },
10022: };
1.1271 raeburn 10023: if ($accesstype eq 'ip') {
10024: $changes{$action}{$newkey}{'ip'} = [$ip];
10025: }
1.827 raeburn 10026: my ($outcome,$deloutcome,$new_values,$translation) =
10027: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 10028: unless ($outcome eq 'ok') {
10029: $errors .= $outcome.' ';
10030: }
1.827 raeburn 10031: }
1.1271 raeburn 10032: }
10033: if ($errors) {
10034: $errors =~ s/\s$//;
10035: return $errors;
1.827 raeburn 10036: } else {
1.1271 raeburn 10037: return 'ok';
1.827 raeburn 10038: }
10039: }
10040:
1.745 raeburn 10041: #------------------------------------------------------Get Marked as Read Only
10042:
10043: sub get_marked_as_readonly {
10044: my ($domain,$user,$what,$group) = @_;
10045: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10046: my @readonly_files;
1.629 banghart 10047: my $cmp1=$what;
10048: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10049: while (my ($file_name,$value) = each(%{$current_permissions})) {
10050: if (defined($group)) {
10051: if ($file_name !~ m-^\Q$group\E/-) {
10052: next;
10053: }
10054: }
1.561 banghart 10055: if (ref($value) eq "ARRAY"){
10056: foreach my $stored_what (@{$value}) {
1.629 banghart 10057: my $cmp2=$stored_what;
1.759 albertel 10058: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10059: $cmp2=join('',@{$stored_what});
1.745 raeburn 10060: }
1.629 banghart 10061: if ($cmp1 eq $cmp2) {
1.561 banghart 10062: push(@readonly_files, $file_name);
1.745 raeburn 10063: last;
1.563 banghart 10064: } elsif (!defined($what)) {
10065: push(@readonly_files, $file_name);
1.745 raeburn 10066: last;
1.561 banghart 10067: }
10068: }
1.745 raeburn 10069: }
1.561 banghart 10070: }
10071: return @readonly_files;
10072: }
1.577 banghart 10073: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10074:
1.577 banghart 10075: sub get_marked_as_readonly_hash {
1.745 raeburn 10076: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10077: my %readonly_files;
1.745 raeburn 10078: while (my ($file_name,$value) = each(%{$current_permissions})) {
10079: if (defined($group)) {
10080: if ($file_name !~ m-^\Q$group\E/-) {
10081: next;
10082: }
10083: }
1.577 banghart 10084: if (ref($value) eq "ARRAY"){
10085: foreach my $stored_what (@{$value}) {
1.745 raeburn 10086: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10087: foreach my $lock_descriptor(@{$stored_what}) {
10088: if ($lock_descriptor eq 'graded') {
10089: $readonly_files{$file_name} = 'graded';
10090: } elsif ($lock_descriptor eq 'handback') {
10091: $readonly_files{$file_name} = 'handback';
10092: } else {
10093: if (!exists($readonly_files{$file_name})) {
10094: $readonly_files{$file_name} = 'locked';
10095: }
10096: }
1.745 raeburn 10097: }
1.750 banghart 10098: }
1.577 banghart 10099: }
10100: }
10101: }
10102: return %readonly_files;
10103: }
1.559 banghart 10104: # ------------------------------------------------------------ Unmark as Read Only
10105:
10106: sub unmark_as_readonly {
1.629 banghart 10107: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10108: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10109: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10110: $file_name = &declutter_portfile($file_name);
1.634 albertel 10111: my $symb_crs = $what;
10112: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10113: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10114: my ($tmp)=keys(%current_permissions);
10115: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10116: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10117: foreach my $file (@readonly_files) {
1.759 albertel 10118: my $clean_file = &declutter_portfile($file);
10119: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10120: my $current_locks = $current_permissions{$file};
1.563 banghart 10121: my @new_locks;
10122: my @del_keys;
10123: if (ref($current_locks) eq "ARRAY"){
10124: foreach my $locker (@{$current_locks}) {
1.632 albertel 10125: my $compare=$locker;
1.749 raeburn 10126: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10127: $compare=join('',@{$locker});
1.746 raeburn 10128: if ($compare ne $symb_crs) {
10129: push(@new_locks, $locker);
10130: }
1.563 banghart 10131: }
10132: }
1.650 albertel 10133: if (scalar(@new_locks) > 0) {
1.563 banghart 10134: $current_permissions{$file} = \@new_locks;
10135: } else {
10136: push(@del_keys, $file);
1.613 albertel 10137: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10138: delete($current_permissions{$file});
1.563 banghart 10139: }
10140: }
1.561 banghart 10141: }
1.613 albertel 10142: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10143: return;
10144: }
1.512 banghart 10145:
1.17 www 10146: # ------------------------------------------------------------ Directory lister
10147:
10148: sub dirlist {
1.955 raeburn 10149: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10150: $uri=~s/^\///;
10151: $uri=~s/\/$//;
1.253 stredwic 10152: my ($udom, $uname);
1.955 raeburn 10153: if ($getuserdir) {
1.253 stredwic 10154: $udom = $userdomain;
10155: $uname = $username;
1.955 raeburn 10156: } else {
10157: (undef,$udom,$uname)=split(/\//,$uri);
10158: if(defined($userdomain)) {
10159: $udom = $userdomain;
10160: }
10161: if(defined($username)) {
10162: $uname = $username;
10163: }
1.253 stredwic 10164: }
1.955 raeburn 10165: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10166:
1.955 raeburn 10167: $dirRoot = $perlvar{'lonDocRoot'};
10168: if (defined($getpropath)) {
10169: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10170: $dirRoot =~ s/\/$//;
1.955 raeburn 10171: } elsif (defined($getuserdir)) {
10172: my $subdir=$uname.'__';
10173: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10174: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10175: ."/$udom/$subdir/$uname";
10176: } elsif (defined($alternateRoot)) {
10177: $dirRoot = $alternateRoot;
1.751 banghart 10178: }
1.253 stredwic 10179:
10180: if($udom) {
10181: if($uname) {
1.1135 raeburn 10182: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10183: if ($uhome eq 'no_host') {
10184: return ([],'no_host');
10185: }
1.955 raeburn 10186: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10187: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10188: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10189: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10190: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10191: } else {
10192: @listing_results = map { &unescape($_); } split(/:/,$listing);
10193: }
1.605 matthew 10194: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10195: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10196: @listing_results = split(/:/,$listing);
10197: } else {
10198: @listing_results = map { &unescape($_); } split(/:/,$listing);
10199: }
1.1135 raeburn 10200: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10201: ($listing eq 'rejected') || ($listing eq 'refused') ||
10202: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10203: return ([],$listing);
10204: } else {
10205: return (\@listing_results);
1.1135 raeburn 10206: }
1.955 raeburn 10207: } elsif(!$alternateRoot) {
1.1136 raeburn 10208: my (%allusers,%listerror);
1.841 albertel 10209: my %servers = &get_servers($udom,'library');
1.955 raeburn 10210: foreach my $tryserver (keys(%servers)) {
10211: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10212: &escape($udom),$tryserver);
10213: if ($listing eq 'unknown_cmd') {
10214: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10215: $udom, $tryserver);
10216: } else {
10217: @listing_results = map { &unescape($_); } split(/:/,$listing);
10218: }
1.841 albertel 10219: if ($listing eq 'unknown_cmd') {
10220: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10221: $udom, $tryserver);
10222: @listing_results = split(/:/,$listing);
10223: } else {
10224: @listing_results =
10225: map { &unescape($_); } split(/:/,$listing);
10226: }
1.1136 raeburn 10227: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10228: ($listing eq 'rejected') || ($listing eq 'refused') ||
10229: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10230: $listerror{$tryserver} = $listing;
10231: } else {
1.841 albertel 10232: foreach my $line (@listing_results) {
10233: my ($entry) = split(/&/,$line,2);
10234: $allusers{$entry} = 1;
10235: }
10236: }
1.253 stredwic 10237: }
1.1136 raeburn 10238: my @alluserslist=();
1.800 albertel 10239: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10240: push(@alluserslist,$user.'&user');
1.253 stredwic 10241: }
1.1318 droeschl 10242:
10243: if (!%listerror) {
10244: # no errors
10245: return (\@alluserslist);
10246: } elsif (scalar(keys(%servers)) == 1) {
10247: # one library server, one error
10248: my ($key) = keys(%listerror);
10249: return (\@alluserslist, $listerror{$key});
10250: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10251: # con_lost indicates that we might miss data from at least one
10252: # library server
10253: return (\@alluserslist, 'con_lost');
10254: } else {
10255: # multiple library servers and no con_lost -> data should be
10256: # complete.
10257: return (\@alluserslist);
10258: }
10259:
1.253 stredwic 10260: } else {
1.1136 raeburn 10261: return ([],'missing username');
1.253 stredwic 10262: }
1.955 raeburn 10263: } elsif(!defined($getpropath)) {
1.1136 raeburn 10264: my $path = $perlvar{'lonDocRoot'}.'/res/';
10265: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10266: return (\@all_domains);
1.955 raeburn 10267: } else {
1.1136 raeburn 10268: return ([],'missing domain');
1.275 stredwic 10269: }
10270: }
10271:
10272: # --------------------------------------------- GetFileTimestamp
10273: # This function utilizes dirlist and returns the date stamp for
10274: # when it was last modified. It will also return an error of -1
10275: # if an error occurs
10276:
10277: sub GetFileTimestamp {
1.955 raeburn 10278: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10279: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10280: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10281: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10282: undef,$getuserdir);
10283: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10284: return -1;
10285: }
10286: if (ref($fileref) eq 'ARRAY') {
10287: my @stats = split('&',$fileref->[0]);
1.375 matthew 10288: # @stats contains first the filename, then the stat output
10289: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10290: } else {
10291: return -1;
1.253 stredwic 10292: }
1.26 www 10293: }
10294:
1.712 albertel 10295: sub stat_file {
10296: my ($uri) = @_;
1.787 albertel 10297: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10298:
1.955 raeburn 10299: my ($udom,$uname,$file);
1.712 albertel 10300: if ($uri =~ m-^/(uploaded|editupload)/-) {
10301: ($udom,$uname,$file) =
1.811 albertel 10302: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10303: $file = 'userfiles/'.$file;
10304: }
10305: if ($uri =~ m-^/res/-) {
10306: ($udom,$uname) =
1.807 albertel 10307: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10308: $file = $uri;
10309: }
10310:
10311: if (!$udom || !$uname || !$file) {
10312: # unable to handle the uri
10313: return ();
10314: }
1.956 raeburn 10315: my $getpropath;
10316: if ($file =~ /^userfiles\//) {
10317: $getpropath = 1;
10318: }
1.1136 raeburn 10319: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10320: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10321: return ();
10322: } else {
10323: if (ref($listref) eq 'ARRAY') {
10324: my @stats = split('&',$listref->[0]);
10325: shift(@stats); #filename is first
10326: return @stats;
10327: }
1.712 albertel 10328: }
10329: return ();
10330: }
10331:
1.1313 raeburn 10332: # --------------------------------------------------------- recursedirs
10333: # Recursive function to traverse either a specific user's Authoring Space
10334: # or corresponding Published Resource Space, and populate the hash ref:
10335: # $dirhashref with URLs of all directories, and if $filehashref hash
10336: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10337: # or .rights files in resource space, and .meta, .save, .log, and .bak
10338: # files in Authoring Space.
10339: #
10340: # Inputs:
10341: #
10342: # $is_home - true if current server is home server for user's space
10343: # $context - either: priv, or res respectively for Authoring or Resource Space.
10344: # $docroot - Document root (i.e., /home/httpd/html
10345: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10346: # $relpath - Current path (relative to top level).
10347: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10348: # $filehashref - reference to hash to populate with URLs of files (Optional)
10349: #
10350: # Returns: nothing
10351: #
10352: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10353: #
10354: # Currently used by interface/londocs.pm to create linked select boxes for
10355: # directory and filename to import a Course "Author" resource into a course, and
10356: # also to create linked select boxes for Authoring Space and Directory to choose
10357: # save location for creation of a new "standard" problem from the Course Editor.
10358: #
10359:
10360: sub recursedirs {
10361: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10362: return unless (ref($dirhashref) eq 'HASH');
10363: my $currpath = $docroot.$toppath;
10364: if ($relpath) {
10365: $currpath .= "/$relpath";
10366: }
10367: my $savefile;
10368: if (ref($filehashref)) {
10369: $savefile = 1;
10370: }
10371: if ($is_home) {
10372: if (opendir(my $dirh,$currpath)) {
10373: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10374: next if ($item eq '');
10375: if (-d "$currpath/$item") {
10376: my $newpath;
10377: if ($relpath) {
10378: $newpath = "$relpath/$item";
10379: } else {
10380: $newpath = $item;
10381: }
10382: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10383: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10384: } elsif ($savefile) {
10385: if ($context eq 'priv') {
10386: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10387: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10388: }
10389: } else {
10390: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10391: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10392: }
10393: }
10394: }
10395: }
10396: closedir($dirh);
10397: }
10398: } else {
10399: my ($dirlistref,$listerror) =
10400: &dirlist($toppath.$relpath);
10401: my @dir_lines;
10402: my $dirptr=16384;
10403: if (ref($dirlistref) eq 'ARRAY') {
10404: foreach my $dir_line (sort
10405: {
10406: my ($afile)=split('&',$a,2);
10407: my ($bfile)=split('&',$b,2);
10408: return (lc($afile) cmp lc($bfile));
10409: } (@{$dirlistref})) {
10410: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10411: split(/\&/,$dir_line,16);
10412: $item =~ s/\s+$//;
10413: next if (($item =~ /^\.\.?$/) || ($obs));
10414: if ($dirptr&$testdir) {
10415: my $newpath;
10416: if ($relpath) {
10417: $newpath = "$relpath/$item";
10418: } else {
10419: $relpath = '/';
10420: $newpath = $item;
10421: }
10422: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10423: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10424: } elsif ($savefile) {
10425: if ($context eq 'priv') {
10426: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10427: $filehashref->{$relpath}{$item} = 1;
10428: }
10429: } else {
10430: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10431: $filehashref->{$relpath}{$item} = 1;
10432: }
10433: }
10434: }
10435: }
10436: }
10437: }
10438: return;
10439: }
10440:
1.26 www 10441: # -------------------------------------------------------- Value of a Condition
10442:
1.713 albertel 10443: # gets the value of a specific preevaluated condition
10444: # stored in the string $env{user.state.<cid>}
10445: # or looks up a condition reference in the bighash and if if hasn't
10446: # already been evaluated recurses into docondval to get the value of
10447: # the condition, then memoizing it to
10448: # $env{user.state.<cid>.<condition>}
1.40 www 10449: sub directcondval {
10450: my $number=shift;
1.620 albertel 10451: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10452: &Apache::lonuserstate::evalstate();
10453: }
1.713 albertel 10454: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10455: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10456: } elsif ($number =~ /^_/) {
10457: my $sub_condition;
10458: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10459: &GDBM_READER(),0640)) {
10460: $sub_condition=$bighash{'conditions'.$number};
10461: untie(%bighash);
10462: }
10463: my $value = &docondval($sub_condition);
1.949 raeburn 10464: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10465: return $value;
10466: }
1.620 albertel 10467: if ($env{'user.state.'.$env{'request.course.id'}}) {
10468: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10469: } else {
10470: return 2;
10471: }
10472: }
10473:
1.713 albertel 10474: # get the collection of conditions for this resource
1.26 www 10475: sub condval {
10476: my $condidx=shift;
1.54 www 10477: my $allpathcond='';
1.713 albertel 10478: foreach my $cond (split(/\|/,$condidx)) {
10479: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10480: $allpathcond.=
10481: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10482: }
1.191 harris41 10483: }
1.54 www 10484: $allpathcond=~s/\|$//;
1.713 albertel 10485: return &docondval($allpathcond);
10486: }
10487:
10488: #evaluates an expression of conditions
10489: sub docondval {
10490: my ($allpathcond) = @_;
10491: my $result=0;
10492: if ($env{'request.course.id'}
10493: && defined($allpathcond)) {
10494: my $operand='|';
10495: my @stack;
10496: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10497: if ($chunk eq '(') {
10498: push @stack,($operand,$result);
10499: } elsif ($chunk eq ')') {
10500: my $before=pop @stack;
10501: if (pop @stack eq '&') {
10502: $result=$result>$before?$before:$result;
10503: } else {
10504: $result=$result>$before?$result:$before;
10505: }
10506: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10507: $operand=$chunk;
10508: } else {
10509: my $new=directcondval($chunk);
10510: if ($operand eq '&') {
10511: $result=$result>$new?$new:$result;
10512: } else {
10513: $result=$result>$new?$result:$new;
10514: }
10515: }
10516: }
1.26 www 10517: }
10518: return $result;
1.421 albertel 10519: }
10520:
10521: # ---------------------------------------------------- Devalidate courseresdata
10522:
10523: sub devalidatecourseresdata {
10524: my ($coursenum,$coursedomain)=@_;
10525: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10526: &devalidate_cache_new('courseres',$hashid);
1.28 www 10527: }
10528:
1.763 www 10529:
1.200 www 10530: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10531: #
10532: # Parameters:
10533: # $coursenum - Number of the course.
10534: # $coursedomain - Domain at which the course was created.
10535: # Returns:
10536: # A hash of the course parameters along (I think) with timestamps
10537: # and version info.
1.877 foxr 10538:
1.624 albertel 10539: sub get_courseresdata {
10540: my ($coursenum,$coursedomain)=@_;
1.200 www 10541: my $coursehom=&homeserver($coursenum,$coursedomain);
10542: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10543: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10544: my %dumpreply;
1.417 albertel 10545: unless (defined($cached)) {
1.624 albertel 10546: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10547: $result=\%dumpreply;
1.251 albertel 10548: my ($tmp) = keys(%dumpreply);
10549: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10550: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10551: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10552: return $tmp;
1.416 albertel 10553: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10554: $result=undef;
1.599 albertel 10555: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10556: }
10557: }
1.624 albertel 10558: return $result;
10559: }
10560:
1.633 albertel 10561: sub devalidateuserresdata {
10562: my ($uname,$udom)=@_;
10563: my $hashid="$udom:$uname";
10564: &devalidate_cache_new('userres',$hashid);
10565: }
10566:
1.624 albertel 10567: sub get_userresdata {
10568: my ($uname,$udom)=@_;
10569: #most student don\'t have any data set, check if there is some data
10570: if (&EXT_cache_status($udom,$uname)) { return undef; }
10571:
10572: my $hashid="$udom:$uname";
10573: my ($result,$cached)=&is_cached_new('userres',$hashid);
10574: if (!defined($cached)) {
10575: my %resourcedata=&dump('resourcedata',$udom,$uname);
10576: $result=\%resourcedata;
10577: &do_cache_new('userres',$hashid,$result,600);
10578: }
10579: my ($tmp)=keys(%$result);
10580: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10581: return $result;
10582: }
10583: #error 2 occurs when the .db doesn't exist
10584: if ($tmp!~/error: 2 /) {
1.1294 raeburn 10585: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10586: &logthis("<font color=\"blue\">WARNING:".
10587: " Trying to get resource data for ".
10588: $uname." at ".$udom.": ".
10589: $tmp."</font>");
10590: }
1.624 albertel 10591: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10592: #&EXT_cache_set($udom,$uname);
10593: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10594: undef($tmp); # not really an error so don't send it back
1.624 albertel 10595: }
10596: return $tmp;
10597: }
1.879 foxr 10598: #----------------------------------------------- resdata - return resource data
10599: # Purpose:
10600: # Return resource data for either users or for a course.
10601: # Parameters:
10602: # $name - Course/user name.
10603: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 10604: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 10605: # $mapp - decluttered URL of enclosing map
10606: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
10607: # $recurseup - Ref to array of map URLs, starting with map containing
10608: # $mapp up through hierarchy of nested maps to top level map.
10609: # $courseid - CourseID (first part of param identifier).
10610: # $modifier - Middle part of param identifier.
10611: # $what - Last part of param identifier.
1.879 foxr 10612: # @which - Array of names of resources desired.
10613: # Returns:
10614: # The value of the first reasource in @which that is found in the
10615: # resource hash.
10616: # Exceptional Conditions:
10617: # If the $type passed in is not valid (not the string 'course' or
10618: # 'user', an undefined reference is returned.
10619: # If none of the resources are found, an undef is returned
1.624 albertel 10620: sub resdata {
1.1301 raeburn 10621: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
10622: $modifier,$what,@which)=@_;
1.624 albertel 10623: my $result;
10624: if ($type eq 'course') {
10625: $result=&get_courseresdata($name,$domain);
10626: } elsif ($type eq 'user') {
10627: $result=&get_userresdata($name,$domain);
10628: }
10629: if (!ref($result)) { return $result; }
1.251 albertel 10630: foreach my $item (@which) {
1.1301 raeburn 10631: if ($item->[1] eq 'course') {
10632: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
10633: unless ($$recursed) {
1.1302 raeburn 10634: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 10635: $$recursed = 1;
10636: }
10637: foreach my $item (@${recurseup}) {
10638: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
10639: last if (defined($result->{$norecursechk}));
10640: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
10641: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
10642: }
10643: }
10644: }
10645: if (defined($result->{$item->[0]})) {
1.927 albertel 10646: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10647: }
1.250 albertel 10648: }
1.291 albertel 10649: return undef;
1.200 www 10650: }
10651:
1.1298 raeburn 10652: sub get_domain_ltitools {
10653: my ($cdom) = @_;
10654: my %ltitools;
10655: my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10656: if (defined($cached)) {
10657: if (ref($result) eq 'HASH') {
10658: %ltitools = %{$result};
10659: }
10660: } else {
10661: my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10662: if (ref($domconfig{'ltitools'}) eq 'HASH') {
10663: %ltitools = %{$domconfig{'ltitools'}};
10664: }
10665: my $cachetime = 24*60*60;
10666: &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10667: }
10668: return %ltitools;
10669: }
10670:
1.1236 raeburn 10671: sub get_numsuppfiles {
10672: my ($cnum,$cdom,$ignorecache)=@_;
10673: my $hashid=$cnum.':'.$cdom;
10674: my ($suppcount,$cached);
10675: unless ($ignorecache) {
10676: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10677: }
10678: unless (defined($cached)) {
10679: my $chome=&homeserver($cnum,$cdom);
10680: unless ($chome eq 'no_host') {
10681: ($suppcount,my $errors) = (0,0);
10682: my $suppmap = 'supplemental.sequence';
10683: ($suppcount,$errors) =
10684: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10685: }
10686: &do_cache_new('suppcount',$hashid,$suppcount,600);
10687: }
10688: return $suppcount;
10689: }
10690:
1.379 matthew 10691: #
10692: # EXT resource caching routines
10693: #
10694:
1.1302 raeburn 10695: {
10696: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
10697: #
10698: # The course for which we cache
10699: my $cachedmapkey='';
10700: # The cached recursive maps for this course
10701: my %cachedmaps=();
10702: # When this was last done
10703: my $cachedmaptime='';
10704:
1.379 matthew 10705: sub clear_EXT_cache_status {
1.383 albertel 10706: &delenv('cache.EXT.');
1.379 matthew 10707: }
10708:
10709: sub EXT_cache_status {
10710: my ($target_domain,$target_user) = @_;
1.383 albertel 10711: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10712: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10713: # We know already the user has no data
10714: return 1;
10715: } else {
10716: return 0;
10717: }
10718: }
10719:
10720: sub EXT_cache_set {
10721: my ($target_domain,$target_user) = @_;
1.383 albertel 10722: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10723: #&appenv({$cachename => time});
1.379 matthew 10724: }
10725:
1.28 www 10726: # --------------------------------------------------------- Value of a Variable
1.58 www 10727: sub EXT {
1.715 albertel 10728:
1.1228 raeburn 10729: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10730: unless ($varname) { return ''; }
1.218 albertel 10731: #get real user name/domain, courseid and symb
10732: my $courseid;
1.359 albertel 10733: my $publicuser;
1.427 www 10734: if ($symbparm) {
10735: $symbparm=&get_symb_from_alias($symbparm);
10736: }
1.218 albertel 10737: if (!($uname && $udom)) {
1.790 albertel 10738: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10739: if (!$symbparm) { $symbparm=$cursymb; }
10740: } else {
1.620 albertel 10741: $courseid=$env{'request.course.id'};
1.218 albertel 10742: }
1.48 www 10743: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10744: my $rest;
1.320 albertel 10745: if (defined($therest[0])) {
1.48 www 10746: $rest=join('.',@therest);
10747: } else {
10748: $rest='';
10749: }
1.320 albertel 10750:
1.57 www 10751: my $qualifierrest=$qualifier;
10752: if ($rest) { $qualifierrest.='.'.$rest; }
10753: my $spacequalifierrest=$space;
10754: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10755: if ($realm eq 'user') {
1.48 www 10756: # --------------------------------------------------------------- user.resource
10757: if ($space eq 'resource') {
1.651 albertel 10758: if ( (defined($Apache::lonhomework::parsing_a_problem)
10759: || defined($Apache::lonhomework::parsing_a_task))
10760: &&
1.744 albertel 10761: ($symbparm eq &symbread()) ) {
10762: # if we are in the middle of processing the resource the
10763: # get the value we are planning on committing
10764: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10765: return $Apache::lonhomework::results{$qualifierrest};
10766: } else {
10767: return $Apache::lonhomework::history{$qualifierrest};
10768: }
1.335 albertel 10769: } else {
1.359 albertel 10770: my %restored;
1.620 albertel 10771: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10772: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10773: } else {
10774: %restored=&restore($symbparm,$courseid,$udom,$uname);
10775: }
1.335 albertel 10776: return $restored{$qualifierrest};
10777: }
1.48 www 10778: # ----------------------------------------------------------------- user.access
10779: } elsif ($space eq 'access') {
1.218 albertel 10780: # FIXME - not supporting calls for a specific user
1.48 www 10781: return &allowed($qualifier,$rest);
10782: # ------------------------------------------ user.preferences, user.environment
10783: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10784: if (($uname eq $env{'user.name'}) &&
10785: ($udom eq $env{'user.domain'})) {
10786: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10787: } else {
1.359 albertel 10788: my %returnhash;
10789: if (!$publicuser) {
10790: %returnhash=&userenvironment($udom,$uname,
10791: $qualifierrest);
10792: }
1.218 albertel 10793: return $returnhash{$qualifierrest};
10794: }
1.48 www 10795: # ----------------------------------------------------------------- user.course
10796: } elsif ($space eq 'course') {
1.218 albertel 10797: # FIXME - not supporting calls for a specific user
1.620 albertel 10798: return $env{join('.',('request.course',$qualifier))};
1.48 www 10799: # ------------------------------------------------------------------- user.role
10800: } elsif ($space eq 'role') {
1.218 albertel 10801: # FIXME - not supporting calls for a specific user
1.620 albertel 10802: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10803: if ($qualifier eq 'value') {
10804: return $role;
10805: } elsif ($qualifier eq 'extent') {
10806: return $where;
10807: }
10808: # ----------------------------------------------------------------- user.domain
10809: } elsif ($space eq 'domain') {
1.218 albertel 10810: return $udom;
1.48 www 10811: # ------------------------------------------------------------------- user.name
10812: } elsif ($space eq 'name') {
1.218 albertel 10813: return $uname;
1.48 www 10814: # ---------------------------------------------------- Any other user namespace
1.29 www 10815: } else {
1.359 albertel 10816: my %reply;
10817: if (!$publicuser) {
10818: %reply=&get($space,[$qualifierrest],$udom,$uname);
10819: }
10820: return $reply{$qualifierrest};
1.48 www 10821: }
1.236 www 10822: } elsif ($realm eq 'query') {
10823: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10824: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10825: [$spacequalifierrest]);
1.620 albertel 10826: return $env{'form.'.$spacequalifierrest};
1.236 www 10827: } elsif ($realm eq 'request') {
1.48 www 10828: # ------------------------------------------------------------- request.browser
10829: if ($space eq 'browser') {
1.1145 bisitz 10830: return $env{'browser.'.$qualifier};
1.57 www 10831: # ------------------------------------------------------------ request.filename
10832: } else {
1.620 albertel 10833: return $env{'request.'.$spacequalifierrest};
1.29 www 10834: }
1.28 www 10835: } elsif ($realm eq 'course') {
1.48 www 10836: # ---------------------------------------------------------- course.description
1.620 albertel 10837: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10838: } elsif ($realm eq 'resource') {
1.165 www 10839:
1.620 albertel 10840: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10841: if (!$symbparm) { $symbparm=&symbread(); }
10842: }
1.693 albertel 10843:
1.1232 raeburn 10844: if ($qualifier eq '') {
10845: if ($space eq 'title') {
10846: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10847: return &gettitle($symbparm);
10848: }
1.693 albertel 10849:
1.1232 raeburn 10850: if ($space eq 'map') {
10851: my ($map) = &decode_symb($symbparm);
10852: return &symbread($map);
10853: }
10854: if ($space eq 'maptitle') {
10855: my ($map) = &decode_symb($symbparm);
10856: return &gettitle($map);
10857: }
10858: if ($space eq 'filename') {
10859: if ($symbparm) {
10860: return &clutter((&decode_symb($symbparm))[2]);
10861: }
10862: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10863: }
1.1232 raeburn 10864:
1.1233 raeburn 10865: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10866: if ($space eq 'visibleparts') {
10867: my $navmap = Apache::lonnavmaps::navmap->new();
10868: my $item;
10869: if (ref($navmap)) {
10870: my $res = $navmap->getBySymb($symbparm);
10871: my $parts = $res->parts();
10872: if (ref($parts) eq 'ARRAY') {
10873: $item = join(',',@{$parts});
10874: }
10875: undef($navmap);
1.1232 raeburn 10876: }
1.1233 raeburn 10877: return $item;
1.1232 raeburn 10878: }
10879: }
10880: }
1.693 albertel 10881:
1.1301 raeburn 10882: my ($section, $group, @groups, @recurseup, $recursed);
10883: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 10884: if (($courseid eq '') && ($cid)) {
10885: $courseid = $cid;
10886: }
10887: if (($symbparm && $courseid) &&
10888: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10889:
1.218 albertel 10890: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10891:
1.60 www 10892: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10893: my $symbp=$symbparm;
1.1301 raeburn 10894: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10895: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 10896: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 10897: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 10898: if (($env{'user.name'} eq $uname) &&
10899: ($env{'user.domain'} eq $udom)) {
10900: $section=$env{'request.course.sec'};
1.733 raeburn 10901: @groups = split(/:/,$env{'request.course.groups'});
10902: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10903: } else {
1.539 albertel 10904: if (! defined($usection)) {
1.551 albertel 10905: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10906: } else {
10907: $section = $usection;
10908: }
1.733 raeburn 10909: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10910: }
10911:
10912: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10913: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 10914: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 10915: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10916:
1.593 albertel 10917: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10918: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 10919: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 10920: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10921:
1.60 www 10922: # ----------------------------------------------------------- first, check user
1.624 albertel 10923:
1.1301 raeburn 10924: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
10925: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 10926: ([$courselevelr,'resource'],
10927: [$courselevelm,'map' ],
1.1301 raeburn 10928: [$courseleveli,'map' ],
1.927 albertel 10929: [$courselevel, 'course' ]));
1.931 albertel 10930: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10931:
1.594 albertel 10932: # ------------------------------------------------ second, check some of course
1.684 raeburn 10933: my $coursereply;
1.691 raeburn 10934: if (@groups > 0) {
10935: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 10936: $recurseparm,$mapparm,$spacequalifierrest,
10937: $mapp,\$recursed,\@recurseup);
10938: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10939: }
1.96 www 10940:
1.684 raeburn 10941: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10942: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 10943: 'course',$mapp,\$recursed,\@recurseup,
10944: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 10945: ([$seclevelr, 'resource'],
10946: [$seclevelm, 'map' ],
1.1301 raeburn 10947: [$secleveli, 'map' ],
1.927 albertel 10948: [$seclevel, 'course' ],
10949: [$courselevelr,'resource']));
10950: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10951:
1.60 www 10952: # ------------------------------------------------------ third, check map parms
1.218 albertel 10953: my %parmhash=();
10954: my $thisparm='';
10955: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10956: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10957: &GDBM_READER(),0640)) {
1.218 albertel 10958: $thisparm=$parmhash{$symbparm};
10959: untie(%parmhash);
10960: }
1.927 albertel 10961: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10962: }
1.594 albertel 10963: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 10964:
10965: my $what = $spacequalifierrest;
10966: $what=~s/\./\_/;
1.282 albertel 10967: my $filename;
10968: if (!$symbparm) { $symbparm=&symbread(); }
10969: if ($symbparm) {
1.409 www 10970: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10971: } else {
1.620 albertel 10972: $filename=$env{'request.filename'};
1.282 albertel 10973: }
1.1301 raeburn 10974: my $metadata=&metadata($filename,$what);
1.927 albertel 10975: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301 raeburn 10976: $metadata=&metadata($filename,'parameter_'.$what);
1.927 albertel 10977: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10978:
1.1301 raeburn 10979: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 10980: if ($symbparm && defined($courseid) &&
1.620 albertel 10981: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10982: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10983: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 10984: 'course',$mapp,\$recursed,\@recurseup,
10985: $courseid,'.',$spacequalifierrest,
1.927 albertel 10986: ([$courselevelm,'map' ],
1.1301 raeburn 10987: [$courseleveli,'map' ],
1.927 albertel 10988: [$courselevel, 'course']));
10989: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10990: }
1.145 www 10991: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10992: unless ($space eq '0') {
1.336 albertel 10993: my @parts=split(/_/,$space);
10994: my $id=pop(@parts);
10995: my $part=join('_',@parts);
10996: if ($part eq '') { $part='0'; }
1.927 albertel 10997: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10998: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10999: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11000: }
1.395 albertel 11001: if ($recurse) { return undef; }
11002: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11003: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11004: # ---------------------------------------------------- Any other user namespace
11005: } elsif ($realm eq 'environment') {
11006: # ----------------------------------------------------------------- environment
1.620 albertel 11007: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11008: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11009: } else {
1.770 albertel 11010: if ($uname eq 'anonymous' && $udom eq '') {
11011: return '';
11012: }
1.219 albertel 11013: my %returnhash=&userenvironment($udom,$uname,
11014: $spacequalifierrest);
11015: return $returnhash{$spacequalifierrest};
11016: }
1.28 www 11017: } elsif ($realm eq 'system') {
1.48 www 11018: # ----------------------------------------------------------------- system.time
11019: if ($space eq 'time') {
11020: return time;
11021: }
1.696 albertel 11022: } elsif ($realm eq 'server') {
11023: # ----------------------------------------------------------------- system.time
11024: if ($space eq 'name') {
11025: return $ENV{'SERVER_NAME'};
11026: }
1.28 www 11027: }
1.48 www 11028: return '';
1.61 www 11029: }
11030:
1.927 albertel 11031: sub get_reply {
11032: my ($reply_value) = @_;
1.940 raeburn 11033: if (ref($reply_value) eq 'ARRAY') {
11034: if (wantarray) {
11035: return @$reply_value;
11036: }
11037: return $reply_value->[0];
11038: } else {
11039: return $reply_value;
1.927 albertel 11040: }
11041: }
11042:
1.691 raeburn 11043: sub check_group_parms {
1.1301 raeburn 11044: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11045: $recursed,$recurseupref) = @_;
11046: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11047: [$what,'course']);
11048: my $coursereply;
1.691 raeburn 11049: foreach my $group (@{$groups}) {
1.1301 raeburn 11050: my @groupitems = ();
1.691 raeburn 11051: foreach my $level (@levels) {
1.927 albertel 11052: my $item = $courseid.'.['.$group.'].'.$level->[0];
11053: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11054: }
1.1301 raeburn 11055: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11056: $env{'course.'.$courseid.'.domain'},
11057: 'course',$mapp,$recursed,$recurseupref,
11058: $courseid,'.['.$group.'].',$what,
11059: @groupitems);
11060: last if (defined($coursereply));
1.691 raeburn 11061: }
11062: return $coursereply;
11063: }
11064:
1.1301 raeburn 11065: sub get_map_hierarchy {
1.1302 raeburn 11066: my ($mapname,$courseid) = @_;
11067: my @recurseup = ();
1.1301 raeburn 11068: if ($mapname) {
1.1302 raeburn 11069: if (($cachedmapkey eq $courseid) &&
11070: (abs($cachedmaptime-time)<5)) {
11071: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11072: return @{$cachedmaps{$mapname}};
11073: }
11074: }
1.1301 raeburn 11075: my $navmap = Apache::lonnavmaps::navmap->new();
11076: if (ref($navmap)) {
11077: @recurseup = $navmap->recurseup_maps($mapname);
11078: undef($navmap);
1.1302 raeburn 11079: $cachedmaps{$mapname} = \@recurseup;
11080: $cachedmaptime=time;
11081: $cachedmapkey=$courseid;
1.1301 raeburn 11082: }
11083: }
11084: return @recurseup;
11085: }
11086:
1.1302 raeburn 11087: }
11088:
1.691 raeburn 11089: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11090: my ($courseid,@groups) = @_;
11091: @groups = sort(@groups);
1.691 raeburn 11092: return @groups;
11093: }
11094:
1.395 albertel 11095: sub packages_tab_default {
11096: my ($uri,$varname)=@_;
11097: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11098:
11099: my (@extension,@specifics,$do_default);
11100: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11101: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11102: if ($pack_type eq 'default') {
11103: $do_default=1;
11104: } elsif ($pack_type eq 'extension') {
11105: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11106: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11107: # only look at packages defaults for packages that this id is
1.738 albertel 11108: push(@specifics,[$package,$pack_type,$pack_part]);
11109: }
11110: }
11111: # first look for a package that matches the requested part id
11112: foreach my $package (@specifics) {
11113: my (undef,$pack_type,$pack_part)=@{$package};
11114: next if ($pack_part ne $part);
11115: if (defined($packagetab{"$pack_type&$name&default"})) {
11116: return $packagetab{"$pack_type&$name&default"};
11117: }
11118: }
11119: # look for any possible matching non extension_ package
11120: foreach my $package (@specifics) {
11121: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11122: if (defined($packagetab{"$pack_type&$name&default"})) {
11123: return $packagetab{"$pack_type&$name&default"};
11124: }
1.585 albertel 11125: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11126: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11127: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11128: }
11129: }
1.738 albertel 11130: # look for any posible extension_ match
11131: foreach my $package (@extension) {
11132: my ($package,$pack_type)=@{$package};
11133: if (defined($packagetab{"$pack_type&$name&default"})) {
11134: return $packagetab{"$pack_type&$name&default"};
11135: }
11136: if (defined($packagetab{$package."&$name&default"})) {
11137: return $packagetab{$package."&$name&default"};
11138: }
11139: }
11140: # look for a global default setting
11141: if ($do_default && defined($packagetab{"default&$name&default"})) {
11142: return $packagetab{"default&$name&default"};
11143: }
1.395 albertel 11144: return undef;
11145: }
11146:
1.334 albertel 11147: sub add_prefix_and_part {
11148: my ($prefix,$part)=@_;
11149: my $keyroot;
11150: if (defined($prefix) && $prefix !~ /^__/) {
11151: # prefix that has a part already
11152: $keyroot=$prefix;
11153: } elsif (defined($prefix)) {
11154: # prefix that is missing a part
11155: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11156: } else {
11157: # no prefix at all
11158: if (defined($part)) { $keyroot='_'.$part; }
11159: }
11160: return $keyroot;
11161: }
11162:
1.71 www 11163: # ---------------------------------------------------------------- Get metadata
11164:
1.599 albertel 11165: my %metaentry;
1.1070 www 11166: my %importedpartids;
1.71 www 11167: sub metadata {
1.176 www 11168: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11169: $uri=&declutter($uri);
1.288 albertel 11170: # if it is a non metadata possible uri return quickly
1.529 albertel 11171: if (($uri eq '') ||
11172: (($uri =~ m|^/*adm/|) &&
1.1298 raeburn 11173: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108 raeburn 11174: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11175: return undef;
11176: }
1.1261 raeburn 11177: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11178: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11179: return undef;
1.288 albertel 11180: }
1.73 www 11181: my $filename=$uri;
11182: $uri=~s/\.meta$//;
1.172 www 11183: #
11184: # Is the metadata already cached?
1.177 www 11185: # Look at timestamp of caching
1.172 www 11186: # Everything is cached by the main uri, libraries are never directly cached
11187: #
1.428 albertel 11188: if (!defined($liburi)) {
1.599 albertel 11189: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11190: if (defined($cached)) { return $result->{':'.$what}; }
11191: }
11192: {
1.1069 www 11193: # Imported parts would go here
1.1070 www 11194: my %importedids=();
11195: my @origfileimportpartids=();
1.1069 www 11196: my $importedparts=0;
1.172 www 11197: #
11198: # Is this a recursive call for a library?
11199: #
1.599 albertel 11200: # if (! exists($metacache{$uri})) {
11201: # $metacache{$uri}={};
11202: # }
1.924 albertel 11203: my $cachetime = 60*60;
1.171 www 11204: if ($liburi) {
11205: $liburi=&declutter($liburi);
11206: $filename=$liburi;
1.401 bowersj2 11207: } else {
1.599 albertel 11208: &devalidate_cache_new('meta',$uri);
11209: undef(%metaentry);
1.401 bowersj2 11210: }
1.140 www 11211: my %metathesekeys=();
1.73 www 11212: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11213: my $metastring;
1.1140 www 11214: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11215: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11216: $metastring =
1.929 albertel 11217: &Apache::lonnet::ssi_body($which,
1.924 albertel 11218: ('grade_target' => 'meta'));
11219: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11220: } elsif (($uri !~ m -^(editupload)/-) &&
11221: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11222: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11223: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11224: $metastring=&getfile($file);
1.489 albertel 11225: }
1.208 albertel 11226: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11227: my $token;
1.140 www 11228: undef %metathesekeys;
1.71 www 11229: while ($token=$parser->get_token) {
1.339 albertel 11230: if ($token->[0] eq 'S') {
11231: if (defined($token->[2]->{'package'})) {
1.172 www 11232: #
11233: # This is a package - get package info
11234: #
1.339 albertel 11235: my $package=$token->[2]->{'package'};
11236: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11237: if (defined($token->[2]->{'id'})) {
11238: $keyroot.='_'.$token->[2]->{'id'};
11239: }
1.599 albertel 11240: if ($metaentry{':packages'}) {
11241: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11242: } else {
1.599 albertel 11243: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11244: }
1.736 albertel 11245: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11246: my $part=$keyroot;
11247: $part=~s/^\_//;
1.736 albertel 11248: if ($pack_entry=~/^\Q$package\E\&/ ||
11249: $pack_entry=~/^\Q$package\E_0\&/) {
11250: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11251: # ignore package.tab specified default values
11252: # here &package_tab_default() will fetch those
11253: if ($subp eq 'default') { next; }
1.736 albertel 11254: my $value=$packagetab{$pack_entry};
1.432 albertel 11255: my $unikey;
11256: if ($pack =~ /_0$/) {
11257: $unikey='parameter_0_'.$name;
11258: $part=0;
11259: } else {
11260: $unikey='parameter'.$keyroot.'_'.$name;
11261: }
1.339 albertel 11262: if ($subp eq 'display') {
11263: $value.=' [Part: '.$part.']';
11264: }
1.599 albertel 11265: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11266: $metathesekeys{$unikey}=1;
1.599 albertel 11267: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11268: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11269: }
1.599 albertel 11270: if (defined($metaentry{':'.$unikey.'.default'})) {
11271: $metaentry{':'.$unikey}=
11272: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11273: }
1.339 albertel 11274: }
11275: }
11276: } else {
1.172 www 11277: #
11278: # This is not a package - some other kind of start tag
1.339 albertel 11279: #
11280: my $entry=$token->[1];
1.1068 www 11281: my $unikey='';
1.175 www 11282:
1.339 albertel 11283: if ($entry eq 'import') {
1.175 www 11284: #
11285: # Importing a library here
1.339 albertel 11286: #
1.1067 www 11287: my $location=$parser->get_text('/import');
11288: my $dir=$filename;
11289: $dir=~s|[^/]*$||;
11290: $location=&filelocation($dir,$location);
1.1069 www 11291:
1.1068 www 11292: my $importmode=$token->[2]->{'importmode'};
11293: if ($importmode eq 'problem') {
1.1069 www 11294: # Import as problem/response
1.1068 www 11295: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11296: } elsif ($importmode eq 'part') {
11297: # Import as part(s)
1.1069 www 11298: $importedparts=1;
11299: # We need to get the original file and the imported file to get the part order correct
11300: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11301: # Load and inspect original file
1.1070 www 11302: if ($#origfileimportpartids<0) {
11303: undef(%importedpartids);
11304: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11305: my $origfile=&getfile($origfilelocation);
11306: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11307: }
11308:
1.1069 www 11309: # Load and inspect imported file
11310: my $impfile=&getfile($location);
11311: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11312: if ($#impfilepartids>=0) {
11313: # This problem had parts
1.1070 www 11314: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11315: } else {
11316: # Importing by turning a single problem into a problem part
11317: # It gets the import-tags ID as part-ID
11318: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11319: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11320: }
1.1068 www 11321: } else {
11322: # Normal import
11323: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11324: if (defined($token->[2]->{'id'})) {
11325: $unikey.='_'.$token->[2]->{'id'};
11326: }
1.1067 www 11327: }
11328:
1.339 albertel 11329: if ($depthcount<20) {
1.736 albertel 11330: my $metadata =
11331: &metadata($uri,'keys', $location,$unikey,
11332: $depthcount+1);
11333: foreach my $meta (split(',',$metadata)) {
11334: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11335: $metathesekeys{$meta}=1;
1.339 albertel 11336: }
1.1068 www 11337:
11338: }
1.1067 www 11339: } else {
11340: #
11341: # Not importing, some other kind of non-package, non-library start tag
11342: #
11343: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11344: if (defined($token->[2]->{'id'})) {
11345: $unikey.='_'.$token->[2]->{'id'};
11346: }
1.339 albertel 11347: if (defined($token->[2]->{'name'})) {
11348: $unikey.='_'.$token->[2]->{'name'};
11349: }
11350: $metathesekeys{$unikey}=1;
1.736 albertel 11351: foreach my $param (@{$token->[3]}) {
11352: $metaentry{':'.$unikey.'.'.$param} =
11353: $token->[2]->{$param};
1.339 albertel 11354: }
11355: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11356: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11357: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11358: # only ws inside the tag, and not in default, so use default
11359: # as value
1.599 albertel 11360: $metaentry{':'.$unikey}=$default;
1.908 albertel 11361: } elsif ( $internaltext =~ /\S/ ) {
11362: # something interesting inside the tag
11363: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11364: } else {
1.908 albertel 11365: # no interesting values, don't set a default
1.339 albertel 11366: }
1.172 www 11367: # end of not-a-package not-a-library import
1.339 albertel 11368: }
1.172 www 11369: # end of not-a-package start tag
1.339 albertel 11370: }
1.172 www 11371: # the next is the end of "start tag"
1.339 albertel 11372: }
11373: }
1.483 albertel 11374: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11375: $extension = lc($extension);
11376: if ($extension eq 'htm') { $extension='html'; }
11377:
1.737 albertel 11378: foreach my $key (keys(%packagetab)) {
1.483 albertel 11379: #no specific packages #how's our extension
11380: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11381: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11382: \%metathesekeys);
11383: }
1.883 albertel 11384:
11385: if (!exists($metaentry{':packages'})
11386: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11387: foreach my $key (keys(%packagetab)) {
1.483 albertel 11388: #no specific packages well let's get default then
11389: if ($key!~/^default&/) { next; }
1.488 albertel 11390: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11391: \%metathesekeys);
11392: }
11393: }
1.338 www 11394: # are there custom rights to evaluate
1.599 albertel 11395: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11396:
1.338 www 11397: #
11398: # Importing a rights file here
1.339 albertel 11399: #
11400: unless ($depthcount) {
1.599 albertel 11401: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11402: my $dir=$filename;
11403: $dir=~s|[^/]*$||;
11404: $location=&filelocation($dir,$location);
1.736 albertel 11405: my $rights_metadata =
11406: &metadata($uri,'keys',$location,'_rights',
11407: $depthcount+1);
11408: foreach my $rights (split(',',$rights_metadata)) {
11409: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11410: $metathesekeys{$rights}=1;
1.339 albertel 11411: }
11412: }
11413: }
1.737 albertel 11414: # uniqifiy package listing
11415: my %seen;
11416: my @uniq_packages =
11417: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11418: $metaentry{':packages'} = join(',',@uniq_packages);
11419:
1.1070 www 11420: if ($importedparts) {
11421: # We had imported parts and need to rebuild partorder
11422: $metaentry{':partorder'}='';
11423: $metathesekeys{'partorder'}=1;
11424: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11425: if ($origfileimportpartids[$index] eq 'part') {
11426: # original part, part of the problem
11427: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11428: } else {
11429: # we have imported parts at this position
11430: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11431: }
11432: }
11433: $metaentry{':partorder'}=~s/^\,//;
11434: }
11435:
1.737 albertel 11436: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11437: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 11438: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11439: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11440: # this is the end of "was not already recently cached
1.71 www 11441: }
1.599 albertel 11442: return $metaentry{':'.$what};
1.261 albertel 11443: }
11444:
1.488 albertel 11445: sub metadata_create_package_def {
1.483 albertel 11446: my ($uri,$key,$package,$metathesekeys)=@_;
11447: my ($pack,$name,$subp)=split(/\&/,$key);
11448: if ($subp eq 'default') { next; }
11449:
1.599 albertel 11450: if (defined($metaentry{':packages'})) {
11451: $metaentry{':packages'}.=','.$package;
1.483 albertel 11452: } else {
1.599 albertel 11453: $metaentry{':packages'}=$package;
1.483 albertel 11454: }
11455: my $value=$packagetab{$key};
11456: my $unikey;
11457: $unikey='parameter_0_'.$name;
1.599 albertel 11458: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11459: $$metathesekeys{$unikey}=1;
1.599 albertel 11460: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11461: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11462: }
1.599 albertel 11463: if (defined($metaentry{':'.$unikey.'.default'})) {
11464: $metaentry{':'.$unikey}=
11465: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11466: }
11467: }
11468:
1.261 albertel 11469: sub metadata_generate_part0 {
11470: my ($metadata,$metacache,$uri) = @_;
11471: my %allnames;
1.737 albertel 11472: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11473: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11474: my $part=$$metacache{':'.$metakey.'.part'};
11475: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11476: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11477: $allnames{$name}=$part;
11478: }
11479: }
11480: }
11481: foreach my $name (keys(%allnames)) {
11482: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11483: my $key=":parameter_0_$name";
1.261 albertel 11484: $$metacache{"$key.part"}='0';
11485: $$metacache{"$key.name"}=$name;
1.428 albertel 11486: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11487: $allnames{$name}.'_'.$name.
11488: '.type'};
1.428 albertel 11489: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11490: '.display'};
1.644 www 11491: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11492: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11493: $$metacache{"$key.display"}=$olddis;
11494: }
1.71 www 11495: }
11496:
1.764 albertel 11497: # ------------------------------------------------------ Devalidate title cache
11498:
11499: sub devalidate_title_cache {
11500: my ($url)=@_;
11501: if (!$env{'request.course.id'}) { return; }
11502: my $symb=&symbread($url);
11503: if (!$symb) { return; }
11504: my $key=$env{'request.course.id'}."\0".$symb;
11505: &devalidate_cache_new('title',$key);
11506: }
11507:
1.1014 droeschl 11508: # ------------------------------------------------- Get the title of a course
11509:
11510: sub current_course_title {
11511: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11512: }
1.301 www 11513: # ------------------------------------------------- Get the title of a resource
11514:
11515: sub gettitle {
11516: my $urlsymb=shift;
11517: my $symb=&symbread($urlsymb);
1.534 albertel 11518: if ($symb) {
1.620 albertel 11519: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11520: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11521: if (defined($cached)) {
11522: return $result;
11523: }
1.534 albertel 11524: my ($map,$resid,$url)=&decode_symb($symb);
11525: my $title='';
1.907 albertel 11526: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11527: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11528: } else {
11529: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11530: &GDBM_READER(),0640)) {
11531: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11532: $title=$bighash{'title_'.$mapid.'.'.$resid};
11533: untie(%bighash);
11534: }
1.534 albertel 11535: }
11536: $title=~s/\&colon\;/\:/gs;
11537: if ($title) {
1.1159 www 11538: # Remember both $symb and $title for dynamic metadata
11539: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11540: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11541: # Cache this title and then return it
1.599 albertel 11542: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11543: }
11544: $urlsymb=$url;
11545: }
11546: my $title=&metadata($urlsymb,'title');
11547: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11548: return $title;
1.301 www 11549: }
1.613 albertel 11550:
1.614 albertel 11551: sub get_slot {
11552: my ($which,$cnum,$cdom)=@_;
11553: if (!$cnum || !$cdom) {
1.790 albertel 11554: (undef,my $courseid)=&whichuser();
1.620 albertel 11555: $cdom=$env{'course.'.$courseid.'.domain'};
11556: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11557: }
1.703 albertel 11558: my $key=join("\0",'slots',$cdom,$cnum,$which);
11559: my %slotinfo;
11560: if (exists($remembered{$key})) {
11561: $slotinfo{$which} = $remembered{$key};
11562: } else {
11563: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11564: &Apache::lonhomework::showhash(%slotinfo);
11565: my ($tmp)=keys(%slotinfo);
11566: if ($tmp=~/^error:/) { return (); }
11567: $remembered{$key} = $slotinfo{$which};
11568: }
1.616 albertel 11569: if (ref($slotinfo{$which}) eq 'HASH') {
11570: return %{$slotinfo{$which}};
11571: }
11572: return $slotinfo{$which};
1.614 albertel 11573: }
1.1150 raeburn 11574:
11575: sub get_reservable_slots {
11576: my ($cnum,$cdom,$uname,$udom) = @_;
11577: my $now = time;
11578: my $reservable_info;
11579: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11580: if (exists($remembered{$key})) {
11581: $reservable_info = $remembered{$key};
11582: } else {
11583: my %resv;
11584: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11585: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11586: $reservable_info = \%resv;
11587: $remembered{$key} = $reservable_info;
11588: }
11589: return $reservable_info;
11590: }
11591:
11592: sub get_course_slots {
11593: my ($cnum,$cdom) = @_;
11594: my $hashid=$cnum.':'.$cdom;
11595: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11596: if (defined($cached)) {
11597: if (ref($result) eq 'HASH') {
11598: return %{$result};
11599: }
11600: } else {
11601: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11602: my ($tmp) = keys(%slots);
11603: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 11604: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11605: return %slots;
11606: }
11607: }
11608: return;
11609: }
11610:
11611: sub devalidate_slots_cache {
11612: my ($cnum,$cdom)=@_;
11613: my $hashid=$cnum.':'.$cdom;
11614: &devalidate_cache_new('allslots',$hashid);
11615: }
11616:
1.1181 raeburn 11617: sub get_coursechange {
11618: my ($cdom,$cnum) = @_;
11619: if ($cdom eq '' || $cnum eq '') {
11620: return unless ($env{'request.course.id'});
11621: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11622: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11623: }
11624: my $hashid=$cdom.'_'.$cnum;
11625: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11626: if ((defined($cached)) && ($change ne '')) {
11627: return $change;
11628: } else {
11629: my %crshash;
11630: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11631: if ($crshash{'internal.contentchange'} eq '') {
11632: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11633: if ($change eq '') {
11634: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11635: $change = $crshash{'internal.created'};
11636: }
11637: } else {
11638: $change = $crshash{'internal.contentchange'};
11639: }
11640: my $cachetime = 600;
11641: &do_cache_new('crschange',$hashid,$change,$cachetime);
11642: }
11643: return $change;
11644: }
11645:
11646: sub devalidate_coursechange_cache {
11647: my ($cnum,$cdom)=@_;
11648: my $hashid=$cnum.':'.$cdom;
11649: &devalidate_cache_new('crschange',$hashid);
11650: }
11651:
1.31 www 11652: # ------------------------------------------------- Update symbolic store links
11653:
11654: sub symblist {
11655: my ($mapname,%newhash)=@_;
1.438 www 11656: $mapname=&deversion(&declutter($mapname));
1.31 www 11657: my %hash;
1.620 albertel 11658: if (($env{'request.course.fn'}) && (%newhash)) {
11659: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11660: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11661: foreach my $url (keys(%newhash)) {
1.711 albertel 11662: next if ($url eq 'last_known'
11663: && $env{'form.no_update_last_known'});
11664: $hash{declutter($url)}=&encode_symb($mapname,
11665: $newhash{$url}->[1],
11666: $newhash{$url}->[0]);
1.191 harris41 11667: }
1.31 www 11668: if (untie(%hash)) {
11669: return 'ok';
11670: }
11671: }
11672: }
11673: return 'error';
1.212 www 11674: }
11675:
11676: # --------------------------------------------------------------- Verify a symb
11677:
11678: sub symbverify {
1.1190 raeburn 11679: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11680: my $thisfn=$thisurl;
1.439 www 11681: $thisfn=&declutter($thisfn);
1.215 www 11682: # direct jump to resource in page or to a sequence - will construct own symbs
11683: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11684: # check URL part
1.409 www 11685: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11686:
1.431 www 11687: unless ($url eq $thisfn) { return 0; }
1.213 www 11688:
1.216 www 11689: $symb=&symbclean($symb);
1.510 www 11690: $thisurl=&deversion($thisurl);
1.439 www 11691: $thisfn=&deversion($thisfn);
1.213 www 11692:
11693: my %bighash;
11694: my $okay=0;
1.431 www 11695:
1.620 albertel 11696: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11697: &GDBM_READER(),0640)) {
1.1204 raeburn 11698: my $noclutter;
1.1032 raeburn 11699: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11700: $thisurl =~ s/\?.+$//;
1.1204 raeburn 11701: if ($map =~ m{^uploaded/.+\.page$}) {
11702: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11703: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11704: $noclutter = 1;
11705: }
11706: }
11707: my $ids;
11708: if ($noclutter) {
11709: $ids=$bighash{'ids_'.$thisurl};
11710: } else {
11711: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11712: }
1.1102 raeburn 11713: unless ($ids) {
11714: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
11715: $ids=$bighash{$idkey};
1.216 www 11716: }
11717: if ($ids) {
11718: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 11719: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 11720: $symb =~ s/\?.+$//;
1.1202 raeburn 11721: }
1.800 albertel 11722: foreach my $id (split(/\,/,$ids)) {
11723: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11724: if (
11725: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 11726: eq $symb) {
11727: if (ref($encstate)) {
11728: $$encstate = $bighash{'encrypted_'.$id};
11729: }
1.620 albertel 11730: if (($env{'request.role.adv'}) ||
1.1101 raeburn 11731: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11732: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 11733: $okay=1;
1.1202 raeburn 11734: last;
1.582 albertel 11735: }
11736: }
1.216 www 11737: }
11738: }
1.213 www 11739: untie(%bighash);
11740: }
11741: return $okay;
1.31 www 11742: }
11743:
1.210 www 11744: # --------------------------------------------------------------- Clean-up symb
11745:
11746: sub symbclean {
11747: my $symb=shift;
1.568 albertel 11748: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11749: # remove version from map
11750: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11751:
1.210 www 11752: # remove version from URL
11753: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11754:
1.507 www 11755: # remove wrapper
11756:
1.510 www 11757: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11758: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11759: return $symb;
1.409 www 11760: }
11761:
11762: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11763:
11764: sub encode_symb {
11765: my ($map,$resid,$url)=@_;
11766: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11767: }
1.409 www 11768:
11769: sub decode_symb {
1.568 albertel 11770: my $symb=shift;
11771: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11772: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11773: return (&fixversion($map),$resid,&fixversion($url));
11774: }
11775:
11776: sub fixversion {
11777: my $fn=shift;
1.609 banghart 11778: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11779: my %bighash;
11780: my $uri=&clutter($fn);
1.620 albertel 11781: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11782: # is this cached?
1.599 albertel 11783: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11784: if (defined($cached)) { return $result; }
11785: # unfortunately not cached, or expired
1.620 albertel 11786: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11787: &GDBM_READER(),0640)) {
11788: if ($bighash{'version_'.$uri}) {
11789: my $version=$bighash{'version_'.$uri};
1.444 www 11790: unless (($version eq 'mostrecent') ||
11791: ($version==&getversion($uri))) {
1.440 www 11792: $uri=~s/\.(\w+)$/\.$version\.$1/;
11793: }
11794: }
11795: untie %bighash;
1.413 www 11796: }
1.599 albertel 11797: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11798: }
11799:
11800: sub deversion {
11801: my $url=shift;
11802: $url=~s/\.\d+\.(\w+)$/\.$1/;
11803: return $url;
1.210 www 11804: }
11805:
1.31 www 11806: # ------------------------------------------------------ Return symb list entry
11807:
11808: sub symbread {
1.1282 raeburn 11809: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 11810: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 11811: if (defined($env{$cache_str})) {
11812: if ($ignorecachednull) {
11813: return $env{$cache_str} unless ($env{$cache_str} eq '');
11814: } else {
11815: return $env{$cache_str};
11816: }
11817: }
1.242 www 11818: # no filename provided? try from environment
1.1265 raeburn 11819: unless ($thisfn) {
1.620 albertel 11820: if ($env{'request.symb'}) {
11821: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 11822: }
1.620 albertel 11823: $thisfn=$env{'request.filename'};
1.44 www 11824: }
1.569 albertel 11825: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11826: # is that filename actually a symb? Verify, clean, and return
11827: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11828: if (&symbverify($thisfn,$1)) {
1.620 albertel 11829: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11830: }
1.242 www 11831: }
1.44 www 11832: $thisfn=declutter($thisfn);
1.31 www 11833: my %hash;
1.37 www 11834: my %bighash;
11835: my $syval='';
1.620 albertel 11836: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11837: my $targetfn = $thisfn;
1.609 banghart 11838: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11839: $targetfn = 'adm/wrapper/'.$thisfn;
11840: }
1.687 albertel 11841: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11842: $targetfn=$1;
11843: }
1.620 albertel 11844: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11845: &GDBM_READER(),0640)) {
1.481 raeburn 11846: $syval=$hash{$targetfn};
1.37 www 11847: untie(%hash);
11848: }
11849: # ---------------------------------------------------------- There was an entry
11850: if ($syval) {
1.601 albertel 11851: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11852: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11853: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11854: #return $env{$cache_str}='';
1.601 albertel 11855: #}
11856: #$syval.=$1;
11857: #}
1.37 www 11858: } else {
11859: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11860: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11861: &GDBM_READER(),0640)) {
1.37 www 11862: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11863: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11864: unless ($ids) {
11865: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11866: }
11867: unless ($ids) {
11868: # alias?
11869: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11870: }
1.37 www 11871: if ($ids) {
11872: # ------------------------------------------------------------------- Has ID(s)
11873: my @possibilities=split(/\,/,$ids);
1.39 www 11874: if ($#possibilities==0) {
11875: # ----------------------------------------------- There is only one possibility
1.37 www 11876: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11877: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11878: $resid,$thisfn);
1.1282 raeburn 11879: if (ref($possibles) eq 'HASH') {
11880: $possibles->{$syval} = 1;
11881: }
11882: if ($checkforblock) {
11883: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11884: if (@blockers) {
11885: $syval = '';
11886: return;
11887: }
11888: }
11889: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11890: # ------------------------------------------ There is more than one possibility
11891: my $realpossible=0;
1.800 albertel 11892: foreach my $id (@possibilities) {
11893: my $file=$bighash{'src_'.$id};
1.1282 raeburn 11894: my $canaccess;
11895: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11896: $canaccess = 1;
11897: } else {
11898: $canaccess = &allowed('bre',$file);
11899: }
11900: if ($canaccess) {
11901: my ($mapid,$resid)=split(/\./,$id);
11902: if ($bighash{'map_type_'.$mapid} ne 'page') {
11903: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11904: $resid,$thisfn);
11905: if (ref($possibles) eq 'HASH') {
11906: $possibles->{$syval} = 1;
11907: }
11908: if ($checkforblock) {
11909: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11910: unless (@blockers > 0) {
11911: $syval = $poss_syval;
11912: $realpossible++;
11913: }
11914: } else {
11915: $syval = $poss_syval;
11916: $realpossible++;
11917: }
11918: }
1.39 www 11919: }
1.191 harris41 11920: }
1.39 www 11921: if ($realpossible!=1) { $syval=''; }
1.249 www 11922: } else {
11923: $syval='';
1.37 www 11924: }
11925: }
1.1282 raeburn 11926: untie(%bighash);
1.481 raeburn 11927: }
1.31 www 11928: }
1.62 www 11929: if ($syval) {
1.620 albertel 11930: return $env{$cache_str}=$syval;
1.62 www 11931: }
1.31 www 11932: }
1.949 raeburn 11933: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11934: return $env{$cache_str}='';
1.31 www 11935: }
11936:
11937: # ---------------------------------------------------------- Return random seed
11938:
1.32 www 11939: sub numval {
11940: my $txt=shift;
11941: $txt=~tr/A-J/0-9/;
11942: $txt=~tr/a-j/0-9/;
11943: $txt=~tr/K-T/0-9/;
11944: $txt=~tr/k-t/0-9/;
11945: $txt=~tr/U-Z/0-5/;
11946: $txt=~tr/u-z/0-5/;
11947: $txt=~s/\D//g;
1.564 albertel 11948: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11949: return int($txt);
1.368 albertel 11950: }
11951:
1.484 albertel 11952: sub numval2 {
11953: my $txt=shift;
11954: $txt=~tr/A-J/0-9/;
11955: $txt=~tr/a-j/0-9/;
11956: $txt=~tr/K-T/0-9/;
11957: $txt=~tr/k-t/0-9/;
11958: $txt=~tr/U-Z/0-5/;
11959: $txt=~tr/u-z/0-5/;
11960: $txt=~s/\D//g;
11961: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11962: my $total;
11963: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11964: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11965: return int($total);
11966: }
11967:
1.575 albertel 11968: sub numval3 {
11969: use integer;
11970: my $txt=shift;
11971: $txt=~tr/A-J/0-9/;
11972: $txt=~tr/a-j/0-9/;
11973: $txt=~tr/K-T/0-9/;
11974: $txt=~tr/k-t/0-9/;
11975: $txt=~tr/U-Z/0-5/;
11976: $txt=~tr/u-z/0-5/;
11977: $txt=~s/\D//g;
11978: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11979: my $total;
11980: foreach my $val (@txts) { $total+=$val; }
11981: if ($_64bit) { $total=(($total<<32)>>32); }
11982: return $total;
11983: }
11984:
1.675 albertel 11985: sub digest {
11986: my ($data)=@_;
11987: my $digest=&Digest::MD5::md5($data);
11988: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11989: my ($e,$f);
11990: {
11991: use integer;
11992: $e=($a+$b);
11993: $f=($c+$d);
11994: if ($_64bit) {
11995: $e=(($e<<32)>>32);
11996: $f=(($f<<32)>>32);
11997: }
11998: }
11999: if (wantarray) {
12000: return ($e,$f);
12001: } else {
12002: my $g;
12003: {
12004: use integer;
12005: $g=($e+$f);
12006: if ($_64bit) {
12007: $g=(($g<<32)>>32);
12008: }
12009: }
12010: return $g;
12011: }
12012: }
12013:
1.368 albertel 12014: sub latest_rnd_algorithm_id {
1.675 albertel 12015: return '64bit5';
1.366 albertel 12016: }
1.32 www 12017:
1.503 albertel 12018: sub get_rand_alg {
12019: my ($courseid)=@_;
1.790 albertel 12020: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12021: if ($courseid) {
1.620 albertel 12022: return $env{"course.$courseid.rndseed"};
1.503 albertel 12023: }
12024: return &latest_rnd_algorithm_id();
12025: }
12026:
1.562 albertel 12027: sub validCODE {
12028: my ($CODE)=@_;
12029: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12030: return 0;
12031: }
12032:
1.491 albertel 12033: sub getCODE {
1.620 albertel 12034: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12035: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12036: defined($Apache::lonhomework::parsing_a_task) ) &&
12037: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12038: return $Apache::lonhomework::history{'resource.CODE'};
12039: }
12040: return undef;
12041: }
1.1133 foxr 12042: #
12043: # Determines the random seed for a specific context:
12044: #
12045: # parameters:
12046: # symb - in course context the symb for the seed.
12047: # course_id - The course id of the form domain_coursenum.
12048: # domain - Domain for the user.
12049: # course - Course for the user.
12050: # cenv - environment of the course.
12051: #
12052: # NOTE:
12053: # All parameters are picked out of the environment if missing
12054: # or not defined.
12055: # If a symb cannot be determined the current time is used instead.
12056: #
12057: # For a given well defined symb, courside, domain, username,
12058: # and course environment, the seed is reproducible.
12059: #
1.31 www 12060: sub rndseed {
1.1133 foxr 12061: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12062: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12063: if (!defined($symb)) {
1.366 albertel 12064: unless ($symb=$wsymb) { return time; }
12065: }
1.1146 foxr 12066: if (!defined $courseid) {
12067: $courseid=$wcourseid;
12068: }
12069: if (!defined $domain) { $domain=$wdomain; }
12070: if (!defined $username) { $username=$wusername }
1.1133 foxr 12071:
12072: my $which;
12073: if (defined($cenv->{'rndseed'})) {
12074: $which = $cenv->{'rndseed'};
12075: } else {
12076: $which =&get_rand_alg($courseid);
12077: }
1.491 albertel 12078: if (defined(&getCODE())) {
1.1133 foxr 12079:
1.675 albertel 12080: if ($which eq '64bit5') {
12081: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12082: } elsif ($which eq '64bit4') {
1.575 albertel 12083: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12084: } else {
12085: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12086: }
1.675 albertel 12087: } elsif ($which eq '64bit5') {
12088: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12089: } elsif ($which eq '64bit4') {
12090: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12091: } elsif ($which eq '64bit3') {
12092: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12093: } elsif ($which eq '64bit2') {
12094: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12095: } elsif ($which eq '64bit') {
12096: return &rndseed_64bit($symb,$courseid,$domain,$username);
12097: }
12098: return &rndseed_32bit($symb,$courseid,$domain,$username);
12099: }
12100:
12101: sub rndseed_32bit {
12102: my ($symb,$courseid,$domain,$username)=@_;
12103: {
12104: use integer;
12105: my $symbchck=unpack("%32C*",$symb) << 27;
12106: my $symbseed=numval($symb) << 22;
12107: my $namechck=unpack("%32C*",$username) << 17;
12108: my $nameseed=numval($username) << 12;
12109: my $domainseed=unpack("%32C*",$domain) << 7;
12110: my $courseseed=unpack("%32C*",$courseid);
12111: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12112: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12113: #&logthis("rndseed :$num:$symb");
1.564 albertel 12114: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12115: return $num;
12116: }
12117: }
12118:
12119: sub rndseed_64bit {
12120: my ($symb,$courseid,$domain,$username)=@_;
12121: {
12122: use integer;
12123: my $symbchck=unpack("%32S*",$symb) << 21;
12124: my $symbseed=numval($symb) << 10;
12125: my $namechck=unpack("%32S*",$username);
12126:
12127: my $nameseed=numval($username) << 21;
12128: my $domainseed=unpack("%32S*",$domain) << 10;
12129: my $courseseed=unpack("%32S*",$courseid);
12130:
12131: my $num1=$symbchck+$symbseed+$namechck;
12132: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12133: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12134: #&logthis("rndseed :$num:$symb");
1.564 albertel 12135: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12136: return "$num1,$num2";
1.155 albertel 12137: }
1.366 albertel 12138: }
12139:
1.443 albertel 12140: sub rndseed_64bit2 {
12141: my ($symb,$courseid,$domain,$username)=@_;
12142: {
12143: use integer;
12144: # strings need to be an even # of cahracters long, it it is odd the
12145: # last characters gets thrown away
12146: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12147: my $symbseed=numval($symb) << 10;
12148: my $namechck=unpack("%32S*",$username.' ');
12149:
12150: my $nameseed=numval($username) << 21;
1.501 albertel 12151: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12152: my $courseseed=unpack("%32S*",$courseid.' ');
12153:
12154: my $num1=$symbchck+$symbseed+$namechck;
12155: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12156: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12157: #&logthis("rndseed :$num:$symb");
1.803 albertel 12158: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12159: return "$num1,$num2";
12160: }
12161: }
12162:
12163: sub rndseed_64bit3 {
12164: my ($symb,$courseid,$domain,$username)=@_;
12165: {
12166: use integer;
12167: # strings need to be an even # of cahracters long, it it is odd the
12168: # last characters gets thrown away
12169: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12170: my $symbseed=numval2($symb) << 10;
12171: my $namechck=unpack("%32S*",$username.' ');
12172:
12173: my $nameseed=numval2($username) << 21;
1.443 albertel 12174: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12175: my $courseseed=unpack("%32S*",$courseid.' ');
12176:
12177: my $num1=$symbchck+$symbseed+$namechck;
12178: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12179: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12180: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12181: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12182:
1.503 albertel 12183: return "$num1:$num2";
1.443 albertel 12184: }
12185: }
12186:
1.575 albertel 12187: sub rndseed_64bit4 {
12188: my ($symb,$courseid,$domain,$username)=@_;
12189: {
12190: use integer;
12191: # strings need to be an even # of cahracters long, it it is odd the
12192: # last characters gets thrown away
12193: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12194: my $symbseed=numval3($symb) << 10;
12195: my $namechck=unpack("%32S*",$username.' ');
12196:
12197: my $nameseed=numval3($username) << 21;
12198: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12199: my $courseseed=unpack("%32S*",$courseid.' ');
12200:
12201: my $num1=$symbchck+$symbseed+$namechck;
12202: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12203: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12204: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12205: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12206:
1.575 albertel 12207: return "$num1:$num2";
12208: }
12209: }
12210:
1.675 albertel 12211: sub rndseed_64bit5 {
12212: my ($symb,$courseid,$domain,$username)=@_;
12213: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12214: return "$num1:$num2";
12215: }
12216:
1.366 albertel 12217: sub rndseed_CODE_64bit {
12218: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12219: {
1.366 albertel 12220: use integer;
1.443 albertel 12221: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12222: my $symbseed=numval2($symb);
1.491 albertel 12223: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12224: my $CODEseed=numval(&getCODE());
1.443 albertel 12225: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12226: my $num1=$symbseed+$CODEchck;
12227: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12228: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12229: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12230: if ($_64bit) { $num1=(($num1<<32)>>32); }
12231: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12232: return "$num1:$num2";
1.366 albertel 12233: }
12234: }
12235:
1.575 albertel 12236: sub rndseed_CODE_64bit4 {
12237: my ($symb,$courseid,$domain,$username)=@_;
12238: {
12239: use integer;
12240: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12241: my $symbseed=numval3($symb);
12242: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12243: my $CODEseed=numval3(&getCODE());
12244: my $courseseed=unpack("%32S*",$courseid.' ');
12245: my $num1=$symbseed+$CODEchck;
12246: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12247: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12248: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12249: if ($_64bit) { $num1=(($num1<<32)>>32); }
12250: if ($_64bit) { $num2=(($num2<<32)>>32); }
12251: return "$num1:$num2";
12252: }
12253: }
12254:
1.675 albertel 12255: sub rndseed_CODE_64bit5 {
12256: my ($symb,$courseid,$domain,$username)=@_;
12257: my $code = &getCODE();
12258: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12259: return "$num1:$num2";
12260: }
12261:
1.366 albertel 12262: sub setup_random_from_rndseed {
12263: my ($rndseed)=@_;
1.503 albertel 12264: if ($rndseed =~/([,:])/) {
1.1262 raeburn 12265: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12266: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12267: &Math::Random::random_set_seed_from_phrase($rndseed);
12268: } else {
12269: &Math::Random::random_set_seed($num1,$num2);
12270: }
1.366 albertel 12271: } else {
12272: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12273: }
1.36 albertel 12274: }
12275:
1.474 albertel 12276: sub latest_receipt_algorithm_id {
1.835 albertel 12277: return 'receipt3';
1.474 albertel 12278: }
12279:
1.480 www 12280: sub recunique {
12281: my $fucourseid=shift;
12282: my $unique;
1.835 albertel 12283: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12284: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12285: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12286: } else {
12287: $unique=$perlvar{'lonReceipt'};
12288: }
12289: return unpack("%32C*",$unique);
12290: }
12291:
12292: sub recprefix {
12293: my $fucourseid=shift;
12294: my $prefix;
1.835 albertel 12295: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12296: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12297: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12298: } else {
12299: $prefix=$perlvar{'lonHostID'};
12300: }
12301: return unpack("%32C*",$prefix);
12302: }
12303:
1.76 www 12304: sub ireceipt {
1.474 albertel 12305: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12306:
12307: my $return =&recprefix($fucourseid).'-';
12308:
12309: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12310: $env{'request.state'} eq 'construct') {
12311: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12312: return $return;
12313: }
12314:
1.76 www 12315: my $cuname=unpack("%32C*",$funame);
12316: my $cudom=unpack("%32C*",$fudom);
12317: my $cucourseid=unpack("%32C*",$fucourseid);
12318: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12319: my $cunique=&recunique($fucourseid);
1.474 albertel 12320: my $cpart=unpack("%32S*",$part);
1.835 albertel 12321: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12322:
1.790 albertel 12323: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12324:
12325: $return.= ($cunique%$cuname+
12326: $cunique%$cudom+
12327: $cusymb%$cuname+
12328: $cusymb%$cudom+
12329: $cucourseid%$cuname+
12330: $cucourseid%$cudom+
12331: $cpart%$cuname+
12332: $cpart%$cudom);
12333: } else {
12334: $return.= ($cunique%$cuname+
12335: $cunique%$cudom+
12336: $cusymb%$cuname+
12337: $cusymb%$cudom+
12338: $cucourseid%$cuname+
12339: $cucourseid%$cudom);
12340: }
12341: return $return;
1.76 www 12342: }
12343:
12344: sub receipt {
1.474 albertel 12345: my ($part)=@_;
1.790 albertel 12346: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12347: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12348: }
1.260 ng 12349:
1.790 albertel 12350: sub whichuser {
12351: my ($passedsymb)=@_;
12352: my ($symb,$courseid,$domain,$name,$publicuser);
12353: if (defined($env{'form.grade_symb'})) {
12354: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12355: my $allowed=&allowed('vgr',$tmp_courseid);
12356: if (!$allowed &&
12357: exists($env{'request.course.sec'}) &&
12358: $env{'request.course.sec'} !~ /^\s*$/) {
12359: $allowed=&allowed('vgr',$tmp_courseid.
12360: '/'.$env{'request.course.sec'});
12361: }
12362: if ($allowed) {
12363: ($symb)=&get_env_multiple('form.grade_symb');
12364: $courseid=$tmp_courseid;
12365: ($domain)=&get_env_multiple('form.grade_domain');
12366: ($name)=&get_env_multiple('form.grade_username');
12367: return ($symb,$courseid,$domain,$name,$publicuser);
12368: }
12369: }
12370: if (!$passedsymb) {
12371: $symb=&symbread();
12372: } else {
12373: $symb=$passedsymb;
12374: }
12375: $courseid=$env{'request.course.id'};
12376: $domain=$env{'user.domain'};
12377: $name=$env{'user.name'};
12378: if ($name eq 'public' && $domain eq 'public') {
12379: if (!defined($env{'form.username'})) {
12380: $env{'form.username'}.=time.rand(10000000);
12381: }
12382: $name.=$env{'form.username'};
12383: }
12384: return ($symb,$courseid,$domain,$name,$publicuser);
12385:
12386: }
12387:
1.36 albertel 12388: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12389: # returns either the contents of the file or
12390: # -1 if the file doesn't exist
1.481 raeburn 12391: #
12392: # if the target is a file that was uploaded via DOCS,
12393: # a check will be made to see if a current copy exists on the local server,
12394: # if it does this will be served, otherwise a copy will be retrieved from
12395: # the home server for the course and stored in /home/httpd/html/userfiles on
12396: # the local server.
1.472 albertel 12397:
1.36 albertel 12398: sub getfile {
1.538 albertel 12399: my ($file) = @_;
1.609 banghart 12400: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12401: &repcopy($file);
12402: return &readfile($file);
12403: }
12404:
12405: sub repcopy_userfile {
12406: my ($file)=@_;
1.1142 raeburn 12407: my $londocroot = $perlvar{'lonDocRoot'};
12408: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12409: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12410: my ($cdom,$cnum,$filename) =
1.811 albertel 12411: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12412: my $uri="/uploaded/$cdom/$cnum/$filename";
12413: if (-e "$file") {
1.828 www 12414: # we already have a local copy, check it out
1.538 albertel 12415: my @fileinfo = stat($file);
1.828 www 12416: my $rtncode;
12417: my $info;
1.538 albertel 12418: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12419: if ($lwpresp ne 'ok') {
1.828 www 12420: # there is no such file anymore, even though we had a local copy
1.482 albertel 12421: if ($rtncode eq '404') {
1.538 albertel 12422: unlink($file);
1.482 albertel 12423: }
12424: return -1;
12425: }
12426: if ($info < $fileinfo[9]) {
1.828 www 12427: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12428: return 'ok';
1.828 www 12429: } else {
12430: # the file is outdated, get rid of it
12431: unlink($file);
1.482 albertel 12432: }
1.828 www 12433: }
12434: # one way or the other, at this point, we don't have the file
12435: # construct the correct path for the file
12436: my @parts = ($cdom,$cnum);
12437: if ($filename =~ m|^(.+)/[^/]+$|) {
12438: push @parts, split(/\//,$1);
12439: }
12440: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12441: foreach my $part (@parts) {
12442: $path .= '/'.$part;
12443: if (!-e $path) {
12444: mkdir($path,0770);
1.482 albertel 12445: }
12446: }
1.828 www 12447: # now the path exists for sure
12448: # get a user agent
12449: my $ua=new LWP::UserAgent;
12450: my $transferfile=$file.'.in.transfer';
12451: # FIXME: this should flock
12452: if (-e $transferfile) { return 'ok'; }
12453: my $request;
12454: $uri=~s/^\///;
1.980 raeburn 12455: my $homeserver = &homeserver($cnum,$cdom);
12456: my $protocol = $protocol{$homeserver};
12457: $protocol = 'http' if ($protocol ne 'https');
12458: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12459: my $response=$ua->request($request,$transferfile);
12460: # did it work?
12461: if ($response->is_error()) {
12462: unlink($transferfile);
12463: &logthis("Userfile repcopy failed for $uri");
12464: return -1;
12465: }
12466: # worked, rename the transfer file
12467: rename($transferfile,$file);
1.607 raeburn 12468: return 'ok';
1.481 raeburn 12469: }
12470:
1.517 albertel 12471: sub tokenwrapper {
12472: my $uri=shift;
1.980 raeburn 12473: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12474: $uri=~s|^/||;
1.620 albertel 12475: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12476: my $token=$1;
1.552 albertel 12477: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12478: if ($udom && $uname && $file) {
12479: $file=~s|(\?\.*)*$||;
1.949 raeburn 12480: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12481: my $homeserver = &homeserver($uname,$udom);
12482: my $protocol = $protocol{$homeserver};
12483: $protocol = 'http' if ($protocol ne 'https');
12484: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12485: (($uri=~/\?/)?'&':'?').'token='.$token.
12486: '&tokenissued='.$perlvar{'lonHostID'};
12487: } else {
12488: return '/adm/notfound.html';
12489: }
12490: }
12491:
1.828 www 12492: # call with reqtype HEAD: get last modification time
12493: # call with reqtype GET: get the file contents
12494: # Do not call this with reqtype GET for large files! It loads everything into memory
12495: #
1.481 raeburn 12496: sub getuploaded {
12497: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12498: $uri=~s/^\///;
1.980 raeburn 12499: my $homeserver = &homeserver($cnum,$cdom);
12500: my $protocol = $protocol{$homeserver};
12501: $protocol = 'http' if ($protocol ne 'https');
12502: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12503: my $ua=new LWP::UserAgent;
12504: my $request=new HTTP::Request($reqtype,$uri);
12505: my $response=$ua->request($request);
12506: $$rtncode = $response->code;
1.482 albertel 12507: if (! $response->is_success()) {
12508: return 'failed';
12509: }
12510: if ($reqtype eq 'HEAD') {
1.486 www 12511: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12512: } elsif ($reqtype eq 'GET') {
12513: $$info = $response->content;
1.472 albertel 12514: }
1.482 albertel 12515: return 'ok';
1.36 albertel 12516: }
12517:
1.481 raeburn 12518: sub readfile {
12519: my $file = shift;
12520: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12521: my $fh;
12522: open($fh,"<$file");
12523: my $a='';
1.800 albertel 12524: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12525: return $a;
12526: }
12527:
1.36 albertel 12528: sub filelocation {
1.590 banghart 12529: my ($dir,$file) = @_;
12530: my $location;
12531: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12532:
12533: if ($file =~ m-^/adm/-) {
12534: $file=~s-^/adm/wrapper/-/-;
12535: $file=~s-^/adm/coursedocs/showdoc/-/-;
12536: }
1.882 albertel 12537:
1.1139 www 12538: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12539: $location = $file;
1.609 banghart 12540: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12541: my ($udom,$uname,$filename)=
1.811 albertel 12542: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12543: my $home=&homeserver($uname,$udom);
12544: my $is_me=0;
12545: my @ids=¤t_machine_ids();
12546: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12547: if ($is_me) {
1.1117 foxr 12548: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12549: } else {
12550: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12551: $udom.'/'.$uname.'/'.$filename;
12552: }
1.882 albertel 12553: } elsif ($file =~ m-^/adm/-) {
12554: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12555: } else {
12556: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12557: $file=~s:^/(res|priv)/:/:;
12558: my $space=$1;
1.590 banghart 12559: if ( !( $file =~ m:^/:) ) {
12560: $location = $dir. '/'.$file;
12561: } else {
1.1142 raeburn 12562: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12563: }
1.59 albertel 12564: }
1.590 banghart 12565: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12566: while ($location=~m{/\.\./}) {
12567: if ($location =~ m{/[^/]+/\.\./}) {
12568: $location=~ s{/[^/]+/\.\./}{/}g;
12569: } else {
12570: $location=~ s{/\.\./}{/}g;
12571: }
12572: } #remove dir/..
1.590 banghart 12573: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12574: return $location;
1.46 www 12575: }
1.36 albertel 12576:
1.46 www 12577: sub hreflocation {
12578: my ($dir,$file)=@_;
1.980 raeburn 12579: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12580: $file=filelocation($dir,$file);
1.700 albertel 12581: } elsif ($file=~m-^/adm/-) {
12582: $file=~s-^/adm/wrapper/-/-;
12583: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12584: }
12585: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12586: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12587: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12588: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12589: {/uploaded/$1/$2/}x;
1.46 www 12590: }
1.913 albertel 12591: if ($file=~ m{^/userfiles/}) {
12592: $file =~ s{^/userfiles/}{/uploaded/};
12593: }
1.462 albertel 12594: return $file;
1.465 albertel 12595: }
12596:
1.1139 www 12597:
12598:
12599:
12600:
1.465 albertel 12601: sub current_machine_domains {
1.853 albertel 12602: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12603: }
12604:
12605: sub machine_domains {
12606: my ($hostname) = @_;
1.465 albertel 12607: my @domains;
1.838 albertel 12608: my %hostname = &all_hostnames();
1.465 albertel 12609: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12610: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12611: if ($hostname eq $name) {
1.844 albertel 12612: push(@domains,&host_domain($id));
1.465 albertel 12613: }
12614: }
12615: return @domains;
12616: }
12617:
12618: sub current_machine_ids {
1.853 albertel 12619: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12620: }
12621:
12622: sub machine_ids {
12623: my ($hostname) = @_;
12624: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12625: my @ids;
1.888 albertel 12626: my %name_to_host = &all_names();
1.889 albertel 12627: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12628: return @{ $name_to_host{$hostname} };
12629: }
12630: return;
1.31 www 12631: }
12632:
1.824 raeburn 12633: sub additional_machine_domains {
12634: my @domains;
12635: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12636: while( my $line = <$fh>) {
12637: $line =~ s/\s//g;
12638: push(@domains,$line);
12639: }
12640: return @domains;
12641: }
12642:
12643: sub default_login_domain {
12644: my $domain = $perlvar{'lonDefDomain'};
12645: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12646: foreach my $posdom (¤t_machine_domains(),
12647: &additional_machine_domains()) {
12648: if (lc($posdom) eq lc($testdomain)) {
12649: $domain=$posdom;
12650: last;
12651: }
12652: }
12653: return $domain;
12654: }
12655:
1.31 www 12656: # ------------------------------------------------------------- Declutters URLs
12657:
12658: sub declutter {
12659: my $thisfn=shift;
1.569 albertel 12660: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 12661: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12662: $thisfn=~s{^/home/httpd/html}{};
12663: }
1.31 www 12664: $thisfn=~s/^\///;
1.697 albertel 12665: $thisfn=~s|^adm/wrapper/||;
12666: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12667: $thisfn=~s/^res\///;
1.1172 bisitz 12668: $thisfn=~s/^priv\///;
1.1032 raeburn 12669: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12670: $thisfn=~s/\?.+$//;
12671: }
1.268 www 12672: return $thisfn;
12673: }
12674:
12675: # ------------------------------------------------------------- Clutter up URLs
12676:
12677: sub clutter {
12678: my $thisfn='/'.&declutter(shift);
1.887 albertel 12679: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12680: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12681: $thisfn='/res'.$thisfn;
12682: }
1.1031 raeburn 12683: if ($thisfn !~m|^/adm|) {
12684: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12685: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12686: } else {
12687: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12688: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12689: if ($embstyle eq 'ssi'
12690: || ($embstyle eq 'hdn')
12691: || ($embstyle eq 'rat')
12692: || ($embstyle eq 'prv')
12693: || ($embstyle eq 'ign')) {
12694: #do nothing with these
12695: } elsif (($embstyle eq 'img')
1.695 albertel 12696: || ($embstyle eq 'emb')
12697: || ($embstyle eq 'wrp')) {
12698: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12699: } elsif ($embstyle eq 'unk'
12700: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12701: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12702: } else {
1.718 www 12703: # &logthis("Got a blank emb style");
1.695 albertel 12704: }
1.694 albertel 12705: }
1.1298 raeburn 12706: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
12707: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 12708: }
1.31 www 12709: return $thisfn;
1.12 www 12710: }
12711:
1.787 albertel 12712: sub clutter_with_no_wrapper {
12713: my $uri = &clutter(shift);
12714: if ($uri =~ m-^/adm/-) {
12715: $uri =~ s-^/adm/wrapper/-/-;
12716: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12717: }
12718: return $uri;
12719: }
12720:
1.557 albertel 12721: sub freeze_escape {
12722: my ($value)=@_;
12723: if (ref($value)) {
12724: $value=&nfreeze($value);
12725: return '__FROZEN__'.&escape($value);
12726: }
12727: return &escape($value);
12728: }
12729:
1.11 www 12730:
1.557 albertel 12731: sub thaw_unescape {
12732: my ($value)=@_;
12733: if ($value =~ /^__FROZEN__/) {
12734: substr($value,0,10,undef);
12735: $value=&unescape($value);
12736: return &thaw($value);
12737: }
12738: return &unescape($value);
12739: }
12740:
1.436 albertel 12741: sub correct_line_ends {
12742: my ($result)=@_;
12743: $$result =~s/\r\n/\n/mg;
12744: $$result =~s/\r/\n/mg;
1.415 albertel 12745: }
1.1 albertel 12746: # ================================================================ Main Program
12747:
1.184 www 12748: sub goodbye {
1.204 albertel 12749: &logthis("Starting Shut down");
1.443 albertel 12750: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12751: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12752: #converted
1.599 albertel 12753: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12754: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12755: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12756: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12757: #1.1 only
1.870 albertel 12758: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12759: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12760: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12761: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12762: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12763: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12764: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12765: &flushcourselogs();
12766: &logthis("Shutting down");
12767: }
12768:
1.852 albertel 12769: sub get_dns {
1.1210 raeburn 12770: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12771: if (!$ignore_cache) {
12772: my ($content,$cached)=
12773: &Apache::lonnet::is_cached_new('dns',$url);
12774: if ($cached) {
1.1210 raeburn 12775: &$func($content,$hashref);
1.869 albertel 12776: return;
12777: }
12778: }
12779:
12780: my %alldns;
1.852 albertel 12781: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12782: foreach my $dns (<$config>) {
12783: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12784: my $line = $1;
12785: my ($host,$protocol) = split(/:/,$line);
12786: if ($protocol ne 'https') {
12787: $protocol = 'http';
12788: }
12789: $alldns{$host} = $protocol;
1.869 albertel 12790: }
12791: while (%alldns) {
1.1263 raeburn 12792: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12793: my $ua=new LWP::UserAgent;
1.1134 raeburn 12794: $ua->timeout(30);
1.979 raeburn 12795: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12796: my $response=$ua->request($request);
1.979 raeburn 12797: delete($alldns{$dns});
1.852 albertel 12798: next if ($response->is_error());
12799: my @content = split("\n",$response->content);
1.1210 raeburn 12800: unless ($nocache) {
1.1219 raeburn 12801: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 12802: }
12803: &$func(\@content,$hashref);
1.869 albertel 12804: return;
1.852 albertel 12805: }
12806: close($config);
1.871 albertel 12807: my $which = (split('/',$url))[3];
12808: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12809: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12810: my @content = <$config>;
1.1210 raeburn 12811: &$func(\@content,$hashref);
12812: return;
12813: }
12814:
12815: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 12816: sub parse_dns_checksums_tab {
1.1210 raeburn 12817: my ($lines,$hashref) = @_;
1.1264 raeburn 12818: my $lonhost = $perlvar{'lonHostID'};
12819: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 12820: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 12821: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12822: my $webconfdir = '/etc/httpd/conf';
12823: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12824: $webconfdir = '/etc/apache2';
12825: } elsif ($distro =~ /^sles(\d+)$/) {
12826: if ($1 >= 10) {
12827: $webconfdir = '/etc/apache2';
12828: }
12829: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12830: if ($1 >= 10.0) {
12831: $webconfdir = '/etc/apache2';
12832: }
12833: }
1.1210 raeburn 12834: my ($release,$timestamp) = split(/\-/,$loncaparev);
12835: my (%chksum,%revnum);
12836: if (ref($lines) eq 'ARRAY') {
12837: chomp(@{$lines});
1.1238 raeburn 12838: my $version = shift(@{$lines});
12839: if ($version eq $release) {
1.1210 raeburn 12840: foreach my $line (@{$lines}) {
1.1238 raeburn 12841: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 12842: if ($file =~ m{^/etc/httpd/conf}) {
12843: if ($webconfdir eq '/etc/apache2') {
12844: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12845: }
12846: }
1.1238 raeburn 12847: $chksum{$file} = $shasum;
12848: $revnum{$file} = $version;
1.1210 raeburn 12849: }
12850: if (ref($hashref) eq 'HASH') {
12851: %{$hashref} = (
12852: sums => \%chksum,
12853: versions => \%revnum,
12854: );
12855: }
12856: }
12857: }
1.869 albertel 12858: return;
1.852 albertel 12859: }
1.1210 raeburn 12860:
12861: sub fetch_dns_checksums {
1.1238 raeburn 12862: my %checksums;
12863: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 12864: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 12865: my ($release,$timestamp) = split(/\-/,$loncaparev);
12866: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 12867: \%checksums);
1.1210 raeburn 12868: return \%checksums;
12869: }
12870:
1.327 albertel 12871: # ------------------------------------------------------------ Read domain file
12872: {
1.852 albertel 12873: my $loaded;
1.846 albertel 12874: my %domain;
12875:
1.852 albertel 12876: sub parse_domain_tab {
12877: my ($lines) = @_;
12878: foreach my $line (@$lines) {
12879: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12880:
1.846 albertel 12881: chomp($line);
1.852 albertel 12882: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12883: my %this_domain;
12884: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12885: 'lang_def', 'city', 'longi', 'lati',
12886: 'primary') {
12887: $this_domain{$field} = shift(@elements);
12888: }
12889: $domain{$name} = \%this_domain;
1.852 albertel 12890: }
12891: }
1.864 albertel 12892:
12893: sub reset_domain_info {
12894: undef($loaded);
12895: undef(%domain);
12896: }
12897:
1.852 albertel 12898: sub load_domain_tab {
1.1293 raeburn 12899: my ($ignore_cache,$nocache) = @_;
12900: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12901: my $fh;
12902: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12903: my @lines = <$fh>;
12904: &parse_domain_tab(\@lines);
1.448 albertel 12905: }
1.852 albertel 12906: close($fh);
12907: $loaded = 1;
1.327 albertel 12908: }
1.846 albertel 12909:
12910: sub domain {
1.852 albertel 12911: &load_domain_tab() if (!$loaded);
12912:
1.846 albertel 12913: my ($name,$what) = @_;
12914: return if ( !exists($domain{$name}) );
12915:
12916: if (!$what) {
12917: return $domain{$name}{'description'};
12918: }
12919: return $domain{$name}{$what};
12920: }
1.974 raeburn 12921:
12922: sub domain_info {
12923: &load_domain_tab() if (!$loaded);
12924: return %domain;
12925: }
12926:
1.327 albertel 12927: }
12928:
12929:
1.1 albertel 12930: # ------------------------------------------------------------- Read hosts file
12931: {
1.838 albertel 12932: my %hostname;
1.844 albertel 12933: my %hostdom;
1.845 albertel 12934: my %libserv;
1.852 albertel 12935: my $loaded;
1.888 albertel 12936: my %name_to_host;
1.1074 raeburn 12937: my %internetdom;
1.1107 raeburn 12938: my %LC_dns_serv;
1.852 albertel 12939:
12940: sub parse_hosts_tab {
12941: my ($file) = @_;
12942: foreach my $configline (@$file) {
12943: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12944: chomp($configline);
12945: if ($configline =~ /^\^/) {
12946: if ($configline =~ /^\^([\w.\-]+)/) {
12947: $LC_dns_serv{$1} = 1;
12948: }
12949: next;
12950: }
1.1074 raeburn 12951: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12952: $name=~s/\s//g;
12953: if ($id && $domain && $role && $name) {
12954: $hostname{$id}=$name;
1.888 albertel 12955: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12956: $hostdom{$id}=$domain;
12957: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12958: if (defined($protocol)) {
12959: if ($protocol eq 'https') {
12960: $protocol{$id} = $protocol;
12961: } else {
12962: $protocol{$id} = 'http';
12963: }
1.968 raeburn 12964: } else {
1.969 raeburn 12965: $protocol{$id} = 'http';
1.968 raeburn 12966: }
1.1074 raeburn 12967: if (defined($intdom)) {
12968: $internetdom{$id} = $intdom;
12969: }
1.852 albertel 12970: }
12971: }
12972: }
1.864 albertel 12973:
12974: sub reset_hosts_info {
1.897 albertel 12975: &purge_remembered();
1.864 albertel 12976: &reset_domain_info();
12977: &reset_hosts_ip_info();
1.892 albertel 12978: undef(%name_to_host);
1.864 albertel 12979: undef(%hostname);
12980: undef(%hostdom);
12981: undef(%libserv);
12982: undef($loaded);
12983: }
1.1 albertel 12984:
1.852 albertel 12985: sub load_hosts_tab {
1.1293 raeburn 12986: my ($ignore_cache,$nocache) = @_;
12987: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12988: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12989: my @config = <$config>;
12990: &parse_hosts_tab(\@config);
12991: close($config);
12992: $loaded=1;
1.1 albertel 12993: }
1.852 albertel 12994:
1.838 albertel 12995: sub hostname {
1.852 albertel 12996: &load_hosts_tab() if (!$loaded);
12997:
1.838 albertel 12998: my ($lonid) = @_;
12999: return $hostname{$lonid};
13000: }
1.845 albertel 13001:
1.838 albertel 13002: sub all_hostnames {
1.852 albertel 13003: &load_hosts_tab() if (!$loaded);
13004:
1.838 albertel 13005: return %hostname;
13006: }
1.845 albertel 13007:
1.888 albertel 13008: sub all_names {
1.1293 raeburn 13009: my ($ignore_cache,$nocache) = @_;
13010: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13011:
13012: return %name_to_host;
13013: }
13014:
1.974 raeburn 13015: sub all_host_domain {
13016: &load_hosts_tab() if (!$loaded);
13017: return %hostdom;
13018: }
13019:
1.845 albertel 13020: sub is_library {
1.852 albertel 13021: &load_hosts_tab() if (!$loaded);
13022:
1.845 albertel 13023: return exists($libserv{$_[0]});
13024: }
13025:
13026: sub all_library {
1.852 albertel 13027: &load_hosts_tab() if (!$loaded);
13028:
1.845 albertel 13029: return %libserv;
13030: }
13031:
1.1062 droeschl 13032: sub unique_library {
13033: #2x reverse removes all hostnames that appear more than once
13034: my %unique = reverse &all_library();
13035: return reverse %unique;
13036: }
13037:
1.841 albertel 13038: sub get_servers {
1.852 albertel 13039: &load_hosts_tab() if (!$loaded);
13040:
1.841 albertel 13041: my ($domain,$type) = @_;
13042: my %possible_hosts = ($type eq 'library') ? %libserv
13043: : %hostname;
13044: my %result;
1.842 albertel 13045: if (ref($domain) eq 'ARRAY') {
13046: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13047: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13048: $result{$host} = $hostname;
13049: }
13050: }
13051: } else {
13052: while ( my ($host,$hostname) = each(%possible_hosts)) {
13053: if ($hostdom{$host} eq $domain) {
13054: $result{$host} = $hostname;
13055: }
1.841 albertel 13056: }
13057: }
13058: return %result;
13059: }
1.845 albertel 13060:
1.1062 droeschl 13061: sub get_unique_servers {
13062: my %unique = reverse &get_servers(@_);
13063: return reverse %unique;
13064: }
13065:
1.844 albertel 13066: sub host_domain {
1.852 albertel 13067: &load_hosts_tab() if (!$loaded);
13068:
1.844 albertel 13069: my ($lonid) = @_;
13070: return $hostdom{$lonid};
13071: }
13072:
1.841 albertel 13073: sub all_domains {
1.852 albertel 13074: &load_hosts_tab() if (!$loaded);
13075:
1.841 albertel 13076: my %seen;
13077: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13078: return @uniq;
13079: }
1.1074 raeburn 13080:
13081: sub internet_dom {
13082: &load_hosts_tab() if (!$loaded);
13083:
13084: my ($lonid) = @_;
13085: return $internetdom{$lonid};
13086: }
1.1107 raeburn 13087:
13088: sub is_LC_dns {
13089: &load_hosts_tab() if (!$loaded);
13090:
13091: my ($hostname) = @_;
13092: return exists($LC_dns_serv{$hostname});
13093: }
13094:
1.1 albertel 13095: }
13096:
1.847 albertel 13097: {
13098: my %iphost;
1.856 albertel 13099: my %name_to_ip;
13100: my %lonid_to_ip;
1.869 albertel 13101:
1.847 albertel 13102: sub get_hosts_from_ip {
13103: my ($ip) = @_;
13104: my %iphosts = &get_iphost();
13105: if (ref($iphosts{$ip})) {
13106: return @{$iphosts{$ip}};
13107: }
13108: return;
1.839 albertel 13109: }
1.864 albertel 13110:
13111: sub reset_hosts_ip_info {
13112: undef(%iphost);
13113: undef(%name_to_ip);
13114: undef(%lonid_to_ip);
13115: }
1.856 albertel 13116:
13117: sub get_host_ip {
13118: my ($lonid) = @_;
13119: if (exists($lonid_to_ip{$lonid})) {
13120: return $lonid_to_ip{$lonid};
13121: }
13122: my $name=&hostname($lonid);
13123: my $ip = gethostbyname($name);
13124: return if (!$ip || length($ip) ne 4);
13125: $ip=inet_ntoa($ip);
13126: $name_to_ip{$name} = $ip;
13127: $lonid_to_ip{$lonid} = $ip;
13128: return $ip;
13129: }
1.847 albertel 13130:
13131: sub get_iphost {
1.1293 raeburn 13132: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13133:
1.869 albertel 13134: if (!$ignore_cache) {
13135: if (%iphost) {
13136: return %iphost;
13137: }
13138: my ($ip_info,$cached)=
13139: &Apache::lonnet::is_cached_new('iphost','iphost');
13140: if ($cached) {
13141: %iphost = %{$ip_info->[0]};
13142: %name_to_ip = %{$ip_info->[1]};
13143: %lonid_to_ip = %{$ip_info->[2]};
13144: return %iphost;
13145: }
13146: }
1.894 albertel 13147:
13148: # get yesterday's info for fallback
13149: my %old_name_to_ip;
13150: my ($ip_info,$cached)=
13151: &Apache::lonnet::is_cached_new('iphost','iphost');
13152: if ($cached) {
13153: %old_name_to_ip = %{$ip_info->[1]};
13154: }
13155:
1.1293 raeburn 13156: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13157: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13158: my $ip;
13159: if (!exists($name_to_ip{$name})) {
13160: $ip = gethostbyname($name);
13161: if (!$ip || length($ip) ne 4) {
1.894 albertel 13162: if (defined($old_name_to_ip{$name})) {
13163: $ip = $old_name_to_ip{$name};
13164: &logthis("Can't find $name defaulting to old $ip");
13165: } else {
13166: &logthis("Name $name no IP found");
13167: next;
13168: }
13169: } else {
13170: $ip=inet_ntoa($ip);
1.847 albertel 13171: }
13172: $name_to_ip{$name} = $ip;
13173: } else {
13174: $ip = $name_to_ip{$name};
1.653 albertel 13175: }
1.888 albertel 13176: foreach my $id (@{ $name_to_host{$name} }) {
13177: $lonid_to_ip{$id} = $ip;
13178: }
13179: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13180: }
1.1293 raeburn 13181: unless ($nocache) {
13182: &do_cache_new('iphost','iphost',
13183: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13184: 48*60*60);
13185: }
1.869 albertel 13186:
1.847 albertel 13187: return %iphost;
1.598 albertel 13188: }
13189:
1.992 raeburn 13190: #
13191: # Given a DNS returns the loncapa host name for that DNS
13192: #
13193: sub host_from_dns {
13194: my ($dns) = @_;
13195: my @hosts;
13196: my $ip;
13197:
1.993 raeburn 13198: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13199: $ip = $name_to_ip{$dns};
13200: }
13201: if (!$ip) {
13202: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13203: if (length($ip) == 4) {
13204: $ip = &IO::Socket::inet_ntoa($ip);
13205: }
13206: }
13207: if ($ip) {
13208: @hosts = get_hosts_from_ip($ip);
13209: return $hosts[0];
13210: }
13211: return undef;
1.986 foxr 13212: }
1.992 raeburn 13213:
1.1074 raeburn 13214: sub get_internet_names {
13215: my ($lonid) = @_;
13216: return if ($lonid eq '');
13217: my ($idnref,$cached)=
13218: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13219: if ($cached) {
13220: return $idnref;
13221: }
13222: my $ip = &get_host_ip($lonid);
13223: my @hosts = &get_hosts_from_ip($ip);
13224: my %iphost = &get_iphost();
13225: my (@idns,%seen);
13226: foreach my $id (@hosts) {
13227: my $dom = &host_domain($id);
13228: my $prim_id = &domain($dom,'primary');
13229: my $prim_ip = &get_host_ip($prim_id);
13230: next if ($seen{$prim_ip});
13231: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13232: foreach my $id (@{$iphost{$prim_ip}}) {
13233: my $intdom = &internet_dom($id);
13234: unless (grep(/^\Q$intdom\E$/,@idns)) {
13235: push(@idns,$intdom);
13236: }
13237: }
13238: }
13239: $seen{$prim_ip} = 1;
13240: }
1.1219 raeburn 13241: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13242: }
13243:
1.986 foxr 13244: }
13245:
1.1079 raeburn 13246: sub all_loncaparevs {
1.1249 raeburn 13247: 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 13248: }
13249:
1.1227 raeburn 13250: # ---------------------------------------------------------- Read loncaparev table
13251: {
13252: sub load_loncaparevs {
13253: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13254: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13255: while (my $configline=<$config>) {
13256: chomp($configline);
13257: my ($hostid,$loncaparev)=split(/:/,$configline);
13258: $loncaparevs{$hostid}=$loncaparev;
13259: }
13260: close($config);
13261: }
13262: }
13263: }
13264: }
13265:
13266: # ---------------------------------------------------------- Read serverhostID table
13267: {
13268: sub load_serverhomeIDs {
13269: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13270: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13271: while (my $configline=<$config>) {
13272: chomp($configline);
13273: my ($name,$id)=split(/:/,$configline);
13274: $serverhomeIDs{$name}=$id;
13275: }
13276: close($config);
13277: }
13278: }
13279: }
13280: }
13281:
13282:
1.862 albertel 13283: BEGIN {
13284:
13285: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13286: unless ($readit) {
13287: {
13288: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13289: %perlvar = (%perlvar,%{$configvars});
13290: }
13291:
13292:
1.1 albertel 13293: # ------------------------------------------------------ Read spare server file
13294: {
1.448 albertel 13295: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13296:
13297: while (my $configline=<$config>) {
13298: chomp($configline);
1.284 matthew 13299: if ($configline) {
1.784 albertel 13300: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13301: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13302: push(@{ $spareid{$type} }, $host);
1.1 albertel 13303: }
13304: }
1.448 albertel 13305: close($config);
1.1 albertel 13306: }
1.11 www 13307: # ------------------------------------------------------------ Read permissions
13308: {
1.448 albertel 13309: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13310:
13311: while (my $configline=<$config>) {
1.448 albertel 13312: chomp($configline);
13313: if ($configline) {
13314: my ($role,$perm)=split(/ /,$configline);
13315: if ($perm ne '') { $pr{$role}=$perm; }
13316: }
1.11 www 13317: }
1.448 albertel 13318: close($config);
1.11 www 13319: }
13320:
13321: # -------------------------------------------- Read plain texts for permissions
13322: {
1.448 albertel 13323: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13324:
13325: while (my $configline=<$config>) {
1.448 albertel 13326: chomp($configline);
13327: if ($configline) {
1.742 raeburn 13328: my ($short,@plain)=split(/:/,$configline);
13329: %{$prp{$short}} = ();
13330: if (@plain > 0) {
13331: $prp{$short}{'std'} = $plain[0];
13332: for (my $i=1; $i<@plain; $i++) {
13333: $prp{$short}{'alt'.$i} = $plain[$i];
13334: }
13335: }
1.448 albertel 13336: }
1.135 www 13337: }
1.448 albertel 13338: close($config);
1.135 www 13339: }
13340:
13341: # ---------------------------------------------------------- Read package table
13342: {
1.448 albertel 13343: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13344:
13345: while (my $configline=<$config>) {
1.483 albertel 13346: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13347: chomp($configline);
13348: my ($short,$plain)=split(/:/,$configline);
13349: my ($pack,$name)=split(/\&/,$short);
13350: if ($plain ne '') {
13351: $packagetab{$pack.'&'.$name.'&name'}=$name;
13352: $packagetab{$short}=$plain;
13353: }
1.11 www 13354: }
1.448 albertel 13355: close($config);
1.329 matthew 13356: }
13357:
1.1073 raeburn 13358: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 13359:
13360: &load_loncaparevs();
1.1073 raeburn 13361:
1.1074 raeburn 13362: # ---------------------------------------------------------- Read serverhostID table
13363:
1.1227 raeburn 13364: &load_serverhomeIDs();
13365:
13366: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13367: {
13368: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13369: if (-e $file) {
13370: my $parser = HTML::LCParser->new($file);
13371: while (my $token = $parser->get_token()) {
13372: if ($token->[0] eq 'S') {
13373: my $item = $token->[1];
13374: my $name = $token->[2]{'name'};
13375: my $value = $token->[2]{'value'};
1.1285 raeburn 13376: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 13377: my $namematch = $token->[2]{'namematch'};
13378: if ($item eq 'parameter') {
13379: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13380: my $release = $parser->get_text();
13381: $release =~ s/(^\s*|\s*$ )//gx;
13382: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13383: }
13384: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 13385: my $release = $parser->get_text();
13386: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 13387: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 13388: }
13389: }
13390: }
13391: }
1.1073 raeburn 13392: }
13393:
1.1138 raeburn 13394: # ---------------------------------------------------------- Read managers table
13395: {
13396: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13397: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13398: while (my $configline=<$config>) {
13399: chomp($configline);
13400: next if ($configline =~ /^\#/);
13401: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13402: $managerstab{$configline} = 1;
13403: }
13404: }
13405: close($config);
13406: }
13407: }
13408: }
13409:
1.329 matthew 13410: # ------------- set up temporary directory
13411: {
1.1117 foxr 13412: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13413:
1.11 www 13414: }
13415:
1.794 albertel 13416: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13417: 'compress_threshold'=> 20_000,
13418: });
1.185 www 13419:
1.281 www 13420: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13421: $dumpcount=0;
1.958 www 13422: $locknum=0;
1.22 www 13423:
1.163 harris41 13424: &logtouch();
1.672 albertel 13425: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13426: $readit=1;
1.564 albertel 13427: {
13428: use integer;
13429: my $test=(2**32)+1;
1.568 albertel 13430: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13431: &logthis(" Detected 64bit platform ($_64bit)");
13432: }
1.195 www 13433: }
1.1 albertel 13434: }
1.179 www 13435:
1.1 albertel 13436: 1;
1.191 harris41 13437: __END__
13438:
1.243 albertel 13439: =pod
13440:
1.191 harris41 13441: =head1 NAME
13442:
1.243 albertel 13443: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13444:
13445: =head1 SYNOPSIS
13446:
1.243 albertel 13447: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13448:
13449: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13450:
1.243 albertel 13451: Common parameters:
13452:
13453: =over 4
13454:
13455: =item *
13456:
13457: $uname : an internal username (if $cname expecting a course Id specifically)
13458:
13459: =item *
13460:
13461: $udom : a domain (if $cdom expecting a course's domain specifically)
13462:
13463: =item *
13464:
13465: $symb : a resource instance identifier
13466:
13467: =item *
13468:
13469: $namespace : the name of a .db file that contains the data needed or
13470: being set.
13471:
13472: =back
13473:
1.394 bowersj2 13474: =head1 OVERVIEW
1.191 harris41 13475:
1.394 bowersj2 13476: lonnet provides subroutines which interact with the
13477: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13478: about classes, users, and resources.
1.243 albertel 13479:
13480: For many of these objects you can also use this to store data about
13481: them or modify them in various ways.
1.191 harris41 13482:
1.394 bowersj2 13483: =head2 Symbs
1.191 harris41 13484:
1.394 bowersj2 13485: To identify a specific instance of a resource, LON-CAPA uses symbols
13486: or "symbs"X<symb>. These identifiers are built from the URL of the
13487: map, the resource number of the resource in the map, and the URL of
13488: the resource itself. The latter is somewhat redundant, but might help
13489: if maps change.
13490:
13491: An example is
13492:
13493: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13494:
13495: The respective map entry is
13496:
13497: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13498: title="Problem 2">
13499: </resource>
13500:
13501: Symbs are used by the random number generator, as well as to store and
13502: restore data specific to a certain instance of for example a problem.
13503:
13504: =head2 Storing And Retrieving Data
13505:
13506: X<store()>X<cstore()>X<restore()>Three of the most important functions
13507: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13508: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13509: is is the non-critical message twin of cstore. These functions are for
13510: handlers to store a perl hash to a user's permanent data space in an
13511: easy manner, and to retrieve it again on another call. It is expected
13512: that a handler would use this once at the beginning to retrieve data,
13513: and then again once at the end to send only the new data back.
13514:
13515: The data is stored in the user's data directory on the user's
13516: homeserver under the ID of the course.
13517:
13518: The hash that is returned by restore will have all of the previous
13519: value for all of the elements of the hash.
13520:
13521: Example:
13522:
13523: #creating a hash
13524: my %hash;
13525: $hash{'foo'}='bar';
13526:
13527: #storing it
13528: &Apache::lonnet::cstore(\%hash);
13529:
13530: #changing a value
13531: $hash{'foo'}='notbar';
13532:
13533: #adding a new value
13534: $hash{'bar'}='foo';
13535: &Apache::lonnet::cstore(\%hash);
13536:
13537: #retrieving the hash
13538: my %history=&Apache::lonnet::restore();
13539:
13540: #print the hash
13541: foreach my $key (sort(keys(%history))) {
13542: print("\%history{$key} = $history{$key}");
13543: }
13544:
13545: Will print out:
1.191 harris41 13546:
1.394 bowersj2 13547: %history{1:foo} = bar
13548: %history{1:keys} = foo:timestamp
13549: %history{1:timestamp} = 990455579
13550: %history{2:bar} = foo
13551: %history{2:foo} = notbar
13552: %history{2:keys} = foo:bar:timestamp
13553: %history{2:timestamp} = 990455580
13554: %history{bar} = foo
13555: %history{foo} = notbar
13556: %history{timestamp} = 990455580
13557: %history{version} = 2
13558:
13559: Note that the special hash entries C<keys>, C<version> and
13560: C<timestamp> were added to the hash. C<version> will be equal to the
13561: total number of versions of the data that have been stored. The
13562: C<timestamp> attribute will be the UNIX time the hash was
13563: stored. C<keys> is available in every historical section to list which
13564: keys were added or changed at a specific historical revision of a
13565: hash.
13566:
13567: B<Warning>: do not store the hash that restore returns directly. This
13568: will cause a mess since it will restore the historical keys as if the
13569: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13570:
1.394 bowersj2 13571: Calling convention:
1.191 harris41 13572:
1.1225 raeburn 13573: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 13574: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13575:
1.394 bowersj2 13576: For more detailed information, see lonnet specific documentation.
1.191 harris41 13577:
1.394 bowersj2 13578: =head1 RETURN MESSAGES
1.191 harris41 13579:
1.394 bowersj2 13580: =over 4
1.191 harris41 13581:
1.394 bowersj2 13582: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13583:
1.394 bowersj2 13584: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13585: when the connection is brought back up
1.191 harris41 13586:
1.394 bowersj2 13587: =item * B<con_failed>: unable to contact remote host and unable to save message
13588: for later delivery
1.191 harris41 13589:
1.967 bisitz 13590: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13591:
1.394 bowersj2 13592: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13593: that was requested
1.191 harris41 13594:
1.243 albertel 13595: =back
1.191 harris41 13596:
1.243 albertel 13597: =head1 PUBLIC SUBROUTINES
1.191 harris41 13598:
1.243 albertel 13599: =head2 Session Environment Functions
1.191 harris41 13600:
1.243 albertel 13601: =over 4
1.191 harris41 13602:
1.394 bowersj2 13603: =item *
13604: X<appenv()>
1.949 raeburn 13605: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13606: the user envirnoment file, and will be restored for each access this
1.620 albertel 13607: user makes during this session, also modifies the %env for the current
1.949 raeburn 13608: process. Optional rolesarrayref - if defined contains a reference to an array
13609: of roles which are exempt from the restriction on modifying user.role entries
13610: in the user's environment.db and in %env.
1.191 harris41 13611:
13612: =item *
1.394 bowersj2 13613: X<delenv()>
1.987 raeburn 13614: B<delenv($delthis,$regexp)>: removes all items from the session
13615: environment file that begin with $delthis. If the
13616: optional second arg - $regexp - is true, $delthis is treated as a
13617: regular expression, otherwise \Q$delthis\E is used.
13618: The values are also deleted from the current processes %env.
1.191 harris41 13619:
1.795 albertel 13620: =item * get_env_multiple($name)
13621:
13622: gets $name from the %env hash, it seemlessly handles the cases where multiple
13623: values may be defined and end up as an array ref.
13624:
13625: returns an array of values
13626:
1.243 albertel 13627: =back
13628:
13629: =head2 User Information
1.191 harris41 13630:
1.243 albertel 13631: =over 4
1.191 harris41 13632:
13633: =item *
1.394 bowersj2 13634: X<queryauthenticate()>
13635: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13636: authentication scheme
13637:
13638: =item *
1.394 bowersj2 13639: X<authenticate()>
1.1073 raeburn 13640: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13641: authenticate user from domain's lib servers (first use the current
13642: one). C<$upass> should be the users password.
1.1073 raeburn 13643: $checkdefauth is optional (value is 1 if a check should be made to
13644: authenticate user using default authentication method, and allow
13645: account creation if username does not have account in the domain).
13646: $clientcancheckhost is optional (value is 1 if checking whether the
13647: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13648:
13649: =item *
1.394 bowersj2 13650: X<homeserver()>
13651: B<homeserver($uname,$udom)>: find the server which has
13652: the user's directory and files (there must be only one), this caches
13653: the answer, and also caches if there is a borken connection.
1.191 harris41 13654:
13655: =item *
1.394 bowersj2 13656: X<idget()>
1.1300 raeburn 13657: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
13658: a list of student/employee IDs or clicker IDs
13659: (student/employee IDs are a unique resource in a domain, there must be
13660: only 1 ID per username, and only 1 username per ID in a specific domain).
13661: clickerIDs are not necessarily unique, as students might share clickers.
13662: (returns hash: id=>name,id=>name)
1.191 harris41 13663:
13664: =item *
1.394 bowersj2 13665: X<idrget()>
13666: B<idrget($udom,@unames)>: find the IDs behind a list of
13667: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13668:
13669: =item *
1.394 bowersj2 13670: X<idput()>
1.1300 raeburn 13671: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
13672: names and associated student/employee IDs or clicker IDs.
13673:
13674: =item *
13675: X<iddel()>
13676: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
13677: student/employee ID or clicker ID username look-ups from domain.
13678: The homeserver ($uhome) and namespace ($namespace) are optional.
13679: If no $uhome is provided, it will be determined usig &homeserver()
13680: for each user. If no $namespace is provided, the default is ids.
13681:
13682: =item *
13683: X<updateclickers()>
13684: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
13685: clicker ID-to-username look-ups in clickers.db on library server.
13686: Permitted actions are add or del (i.e., add or delete). The
13687: clickers.db contains clickerID as keys (escaped), and each corresponding
13688: value is an escaped comma-separated list of usernames (for whom the
13689: library server is the homeserver), who registered that particular ID.
13690: If $critical is true, the update will be sent via &critical, otherwise
13691: &reply() will be used.
1.191 harris41 13692:
13693: =item *
1.394 bowersj2 13694: X<rolesinit()>
1.1169 droeschl 13695: B<rolesinit($udom,$username)>: get user privileges.
13696: returns user role, first access and timer interval hashes
1.243 albertel 13697:
13698: =item *
1.1171 droeschl 13699: X<privileged()>
13700: B<privileged($username,$domain)>: returns a true if user has a
13701: privileged and active role (i.e. su or dc), false otherwise.
13702:
13703: =item *
1.551 albertel 13704: X<getsection()>
13705: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13706: course $cname, return section name/number or '' for "not in course"
13707: and '-1' for "no section"
13708:
13709: =item *
1.394 bowersj2 13710: X<userenvironment()>
13711: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13712: passed in @what from the requested user's environment, returns a hash
13713:
1.858 raeburn 13714: =item *
13715: X<userlog_query()>
1.859 albertel 13716: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13717: activity.log file. %filters defines filters applied when parsing the
13718: log file. These can be start or end timestamps, or the type of action
13719: - log to look for Login or Logout events, check for Checkin or
13720: Checkout, role for role selection. The response is in the form
13721: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13722: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13723:
1.243 albertel 13724: =back
13725:
13726: =head2 User Roles
13727:
13728: =over 4
13729:
13730: =item *
13731:
1.1284 raeburn 13732: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13733: returns codes for allowed actions.
13734:
13735: The first argument is required, all others are optional.
13736:
13737: $priv is the privilege being checked.
13738: $uri contains additional information about what is being checked for access (e.g.,
13739: URL, course ID etc.).
13740: $symb is the unique resource instance identifier in a course; if needed,
13741: but not provided, it will be retrieved via a call to &symbread().
13742: $role is the role for which a priv is being checked (only used if priv is evb).
13743: $clientip is the user's IP address (only used when checking for access to portfolio
13744: files).
13745: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13746: prevents recursive calls to &allowed.
13747:
1.243 albertel 13748: F: full access
13749: U,I,K: authentication modes (cxx only)
13750: '': forbidden
13751: 1: user needs to choose course
13752: 2: browse allowed
1.766 albertel 13753: A: passphrase authentication needed
1.1284 raeburn 13754: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13755:
13756: =item *
13757:
1.1192 raeburn 13758: constructaccess($url,$setpriv) : check for access to construction space URL
13759:
13760: See if the owner domain and name in the URL match those in the
13761: expected environment. If so, return three element list
13762: ($ownername,$ownerdomain,$ownerhome).
13763:
13764: Otherwise return the null string.
13765:
13766: If second argument 'setpriv' is true, it assigns the privileges,
13767: and returns the same three element list, unless the owner has
13768: blocked "ad hoc" Domain Coordinator access to the Author Space,
13769: in which case the null string is returned.
13770:
13771: =item *
13772:
1.1326 raeburn 13773: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
13774: define a custom role rolename set privileges in format of lonTabs/roles.tab
13775: for system, domain, and course level. $uname and $udom are optional (current
13776: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 13777:
13778: =item *
13779:
1.988 raeburn 13780: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13781: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13782: $type is Course (default) or Community.
1.988 raeburn 13783: If $forcedefault evaluates to true, text returned will be default
13784: text for $type. Otherwise, if this is a course, the text returned
13785: will be a custom name for the role (if defined in the course's
13786: environment). If no custom name is defined the default is returned.
13787:
1.832 raeburn 13788: =item *
13789:
1.1219 raeburn 13790: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13791: All arguments are optional. Returns a hash of a roles, either for
13792: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13793: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13794: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13795: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13796: For each key, value is set to colon-separated start and end times for
13797: the role. If no username and domain are specified, will default to
1.934 raeburn 13798: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13799: of role statuses (active, future or previous), roles
13800: (e.g., cc,in, st etc.) and domains of the roles which can be used
13801: to restrict the list of roles reported. If no array ref is
13802: provided for types, will default to return only active roles.
1.834 albertel 13803:
1.1195 raeburn 13804: =item *
13805:
13806: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 13807: user: $uname:$udom has a role in the course: $cdom_$cnum.
13808:
13809: Additional optional arguments are: $type (if role checking is to be restricted
13810: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 13811: available roles) or future (roles available in the future), and
13812: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 13813: have active Domain Coordinator role in course's domain or in additional
13814: domains (specified in 'Domains to check for privileged users' in course
13815: environment -- set via: Course Settings -> Classlists and staff listing).
13816:
13817: =item *
13818:
13819: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13820: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13821: $possdomains and $possroles are optional array refs -- to domains to check and
13822: roles to check. If $possdomains is not specified, a dump will be done of the
13823: users' roles.db to check for a dc or su role in any domain. This can be
13824: time consuming if &privileged is called repeatedly (e.g., when displaying a
13825: classlist), so in such cases, supplying a $possdomains array is preferred, as
13826: this then allows &privileged_by_domain() to be used, which caches the identity
13827: of privileged users, eliminating the need for repeated calls to &dump().
13828:
13829: =item *
13830:
13831: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13832: where the outer hash keys are domains specified in the $possdomains array ref,
13833: next inner hash keys are privileged roles specified in the $roles array ref,
13834: and the innermost hash contains key = value pairs for username:domain = end:start
13835: for active or future "privileged" users with that role in that domain. To avoid
13836: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13837: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 13838:
1.243 albertel 13839: =back
13840:
13841: =head2 User Modification
13842:
13843: =over 4
13844:
13845: =item *
13846:
1.957 raeburn 13847: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13848: user for the level given by URL. Optional start and end dates (leave empty
13849: string or zero for "no date")
1.191 harris41 13850:
13851: =item *
13852:
1.243 albertel 13853: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13854: change a users, password, possible return values are: ok,
13855: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13856: refused
1.191 harris41 13857:
13858: =item *
13859:
1.243 albertel 13860: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13861:
13862: =item *
13863:
1.1058 raeburn 13864: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13865: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13866:
13867: will update user information (firstname,middlename,lastname,generation,
13868: permanentemail), and if forceid is true, student/employee ID also.
13869: A user's institutional affiliation(s) can also be updated.
13870: User information fields will not be overwritten with empty entries
13871: unless the field is included in the $candelete array reference.
13872: This array is included when a single user is modified via "Manage Users",
13873: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13874:
13875: =item *
13876:
1.286 matthew 13877: modifystudent
13878:
1.957 raeburn 13879: modify a student's enrollment and identification information.
1.1235 raeburn 13880: The course id is resolved based on the current user's environment.
13881: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13882: associated with a course.
13883:
1.297 matthew 13884: This call is essentially a wrapper for lonnet::modifyuser and
13885: lonnet::modify_student_enrollment
1.286 matthew 13886:
13887: Inputs:
13888:
13889: =over 4
13890:
1.957 raeburn 13891: =item B<$udom> Student's loncapa domain
1.286 matthew 13892:
1.957 raeburn 13893: =item B<$uname> Student's loncapa login name
1.286 matthew 13894:
1.964 bisitz 13895: =item B<$uid> Student/Employee ID
1.286 matthew 13896:
1.957 raeburn 13897: =item B<$umode> Student's authentication mode
1.286 matthew 13898:
1.957 raeburn 13899: =item B<$upass> Student's password
1.286 matthew 13900:
1.957 raeburn 13901: =item B<$first> Student's first name
1.286 matthew 13902:
1.957 raeburn 13903: =item B<$middle> Student's middle name
1.286 matthew 13904:
1.957 raeburn 13905: =item B<$last> Student's last name
1.286 matthew 13906:
1.957 raeburn 13907: =item B<$gene> Student's generation
1.286 matthew 13908:
1.957 raeburn 13909: =item B<$usec> Student's section in course
1.286 matthew 13910:
13911: =item B<$end> Unix time of the roles expiration
13912:
13913: =item B<$start> Unix time of the roles start date
13914:
13915: =item B<$forceid> If defined, allow $uid to be changed
13916:
13917: =item B<$desiredhome> server to use as home server for student
13918:
1.957 raeburn 13919: =item B<$email> Student's permanent e-mail address
13920:
13921: =item B<$type> Type of enrollment (auto or manual)
13922:
1.963 raeburn 13923: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13924:
13925: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13926:
1.963 raeburn 13927: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13928:
1.963 raeburn 13929: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13930:
1.1216 raeburn 13931: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13932:
13933: =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 13934:
1.286 matthew 13935: =back
1.297 matthew 13936:
13937: =item *
13938:
13939: modify_student_enrollment
13940:
1.1235 raeburn 13941: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13942: 'role.request.course' must be defined for this function to proceed.
13943:
13944: Inputs:
13945:
13946: =over 4
13947:
1.1235 raeburn 13948: =item $udom, student's domain
1.297 matthew 13949:
1.1235 raeburn 13950: =item $uname, student's name
1.297 matthew 13951:
1.1235 raeburn 13952: =item $uid, student's user id
1.297 matthew 13953:
1.1235 raeburn 13954: =item $first, student's first name
1.297 matthew 13955:
13956: =item $middle
13957:
13958: =item $last
13959:
13960: =item $gene
13961:
13962: =item $usec
13963:
13964: =item $end
13965:
13966: =item $start
13967:
1.957 raeburn 13968: =item $type
13969:
13970: =item $locktype
13971:
13972: =item $cid
13973:
13974: =item $selfenroll
13975:
13976: =item $context
13977:
1.1216 raeburn 13978: =item $credits, number of credits student will earn from this class
13979:
1.1314 raeburn 13980: =item $instsec, institutional course section code for student
13981:
1.297 matthew 13982: =back
13983:
1.191 harris41 13984:
13985: =item *
13986:
1.243 albertel 13987: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13988: custom role; give a custom role to a user for the level given by URL. Specify
13989: name and domain of role author, and role name
1.191 harris41 13990:
13991: =item *
13992:
1.243 albertel 13993: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13994:
13995: =item *
13996:
1.243 albertel 13997: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13998:
13999: =back
14000:
14001: =head2 Course Infomation
14002:
14003: =over 4
1.191 harris41 14004:
14005: =item *
14006:
1.1118 foxr 14007: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 14008: specified course id, including all environment settings for the
14009: course, the description of the course will be in the hash under the
14010: key 'description'
1.191 harris41 14011:
1.1118 foxr 14012: $options is an optional parameter that if supplied is a hash reference that controls
14013: what how this function works. It has the following key/values:
14014:
14015: =over 4
14016:
14017: =item freshen_cache
14018:
14019: If defined, and the environment cache for the course is valid, it is
14020: returned in the returned hash.
14021:
14022: =item one_time
14023:
14024: If defined, the last cache time is set to _now_
14025:
14026: =item user
14027:
14028: If defined, the supplied username is used instead of the current user.
14029:
14030:
14031: =back
14032:
1.191 harris41 14033: =item *
14034:
1.624 albertel 14035: resdata($name,$domain,$type,@which) : request for current parameter
14036: setting for a specific $type, where $type is either 'course' or 'user',
14037: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 14038: answers for 10 minutes.
1.243 albertel 14039:
1.877 foxr 14040: =item *
14041:
14042: get_courseresdata($courseid, $domain) : dump the entire course resource
14043: data base, returning a hash that is keyed by the resource name and has
14044: values that are the resource value. I believe that the timestamps and
14045: versions are also returned.
14046:
1.1236 raeburn 14047: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14048: supplemental content area. This routine caches the number of files for
14049: 10 minutes.
14050:
1.243 albertel 14051: =back
14052:
14053: =head2 Course Modification
14054:
14055: =over 4
1.191 harris41 14056:
14057: =item *
14058:
1.243 albertel 14059: writecoursepref($courseid,%prefs) : write preferences (environment
14060: database) for a course
1.191 harris41 14061:
14062: =item *
14063:
1.1011 raeburn 14064: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14065:
14066: =item *
14067:
1.1038 raeburn 14068: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14069:
1.1167 droeschl 14070: =item *
14071:
14072: is_course($courseid), is_course($cdom, $cnum)
14073:
14074: Accepts either a combined $courseid (in the form of domain_courseid) or the
14075: two component version $cdom, $cnum. It checks if the specified course exists.
14076:
14077: Returns:
14078: undef if the course doesn't exist, otherwise
14079: in scalar context the combined courseid.
14080: in list context the two components of the course identifier, domain and
14081: courseid.
14082:
1.243 albertel 14083: =back
14084:
14085: =head2 Resource Subroutines
14086:
14087: =over 4
1.191 harris41 14088:
14089: =item *
14090:
1.243 albertel 14091: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14092:
14093: =item *
14094:
1.243 albertel 14095: repcopy($filename) : subscribes to the requested file, and attempts to
14096: replicate from the owning library server, Might return
1.607 raeburn 14097: 'unavailable', 'not_found', 'forbidden', 'ok', or
14098: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14099: resource. Expects the local filesystem pathname
14100: (/home/httpd/html/res/....)
14101:
14102: =back
14103:
14104: =head2 Resource Information
14105:
14106: =over 4
1.191 harris41 14107:
14108: =item *
14109:
1.1228 raeburn 14110: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14111: and returns the value of a variety of different possible values,
14112: $varname should be a request string, and the other parameters can be
14113: used to specify who and what one is asking about. Ordinarily, $cid
14114: does not need to be specified, as it is retrived from
14115: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14116: within lonuserstate::loadmap() when initializing a course, before
14117: $env{'request.course.id'} has been set, so it needs to be provided
14118: in that one case.
1.243 albertel 14119:
14120: Possible values for $varname are environment.lastname (or other item
14121: from the envirnment hash), user.name (or someother aspect about the
14122: user), resource.0.maxtries (or some other part and parameter of a
14123: resource)
1.204 albertel 14124:
14125: =item *
14126:
1.243 albertel 14127: directcondval($number) : get current value of a condition; reads from a state
14128: string
1.204 albertel 14129:
14130: =item *
14131:
1.243 albertel 14132: condval($condidx) : value of condition index based on state
1.204 albertel 14133:
14134: =item *
14135:
1.243 albertel 14136: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14137: resource's metadata, $what should be either a specific key, or either
14138: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14139: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14140:
14141: this function automatically caches all requests
1.191 harris41 14142:
14143: =item *
14144:
1.243 albertel 14145: metadata_query($query,$custom,$customshow) : make a metadata query against the
14146: network of library servers; returns file handle of where SQL and regex results
14147: will be stored for query
1.191 harris41 14148:
14149: =item *
14150:
1.1282 raeburn 14151: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14152: return symbolic list entry (all arguments optional).
14153:
14154: Args: filename is the filename (including path) for the file for which a symb
14155: is required; donotrecurse, if true will prevent calls to allowed() being made
14156: to check access status if more than one resource was found in the bighash
14157: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14158: a randompick); ignorecachednull, if true will prevent a symb of '' being
14159: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14160: cause possible symbs to be checked to determine if they are subject to content
14161: blocking, if so they will not be included as possible symbs; possibles is a
14162: ref to a hash, which, as a side effect, will be populated with all possible
14163: symbs (content blocking not tested).
14164:
1.243 albertel 14165: returns the data handle
1.191 harris41 14166:
14167: =item *
14168:
1.1190 raeburn 14169: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14170: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14171: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 14172: on failure, user must be in a course, as it assumes the existence of
14173: the course initial hash, and uses $env('request.course.id'}. The third
14174: arg is an optional reference to a scalar. If this arg is passed in the
14175: call to symbverify, it will be set to 1 if the symb has been set to be
14176: encrypted; otherwise it will be null.
1.191 harris41 14177:
14178: =item *
14179:
1.243 albertel 14180: symbclean($symb) : removes versions numbers from a symb, returns the
14181: cleaned symb
1.191 harris41 14182:
14183: =item *
14184:
1.243 albertel 14185: is_on_map($uri) : checks if the $uri is somewhere on the current
14186: course map, user must be in a course for it to work.
1.191 harris41 14187:
14188: =item *
14189:
1.243 albertel 14190: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14191:
14192: =item *
14193:
1.243 albertel 14194: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14195: a random seed, all arguments are optional, if they aren't sent it uses the
14196: environment to derive them. Note: if symb isn't sent and it can't get one
14197: from &symbread it will use the current time as its return value
1.191 harris41 14198:
14199: =item *
14200:
1.243 albertel 14201: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14202: unfakeable, receipt
1.191 harris41 14203:
14204: =item *
14205:
1.620 albertel 14206: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14207:
14208: =item *
14209:
1.243 albertel 14210: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14211:
14212: =item *
14213:
1.243 albertel 14214: 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 14215:
14216: =item *
14217:
1.243 albertel 14218: 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 14219:
14220: =item *
14221:
1.243 albertel 14222: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14223:
14224: =item *
14225:
1.243 albertel 14226: devalidate($symb) : devalidate temporary spreadsheet calculations,
14227: forcing spreadsheet to reevaluate the resource scores next time.
14228:
1.1195 raeburn 14229: =item *
14230:
1.1196 raeburn 14231: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14232: when viewing in course context.
1.1195 raeburn 14233:
1.1196 raeburn 14234: input: six args -- filename (decluttered), course number, course domain,
14235: url, symb (if registered) and group (if this is a
14236: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 14237:
1.1196 raeburn 14238: output: array of five scalars --
1.1195 raeburn 14239: $cfile -- url for file editing if editable on current server
14240: $home -- homeserver of resource (i.e., for author if published,
14241: or course if uploaded.).
14242: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 14243: $forceedit -- 1 if icon/link should be to go to edit mode
14244: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 14245:
14246: =item *
14247:
14248: is_course_upload($file,$cnum,$cdom)
14249:
14250: Used in course context to determine if current file was uploaded to
14251: the course (i.e., would be found in /userfiles/docs on the course's
14252: homeserver.
14253:
14254: input: 3 args -- filename (decluttered), course number and course domain.
14255: output: boolean -- 1 if file was uploaded.
14256:
1.243 albertel 14257: =back
14258:
14259: =head2 Storing/Retreiving Data
14260:
14261: =over 4
1.191 harris41 14262:
14263: =item *
14264:
1.1269 raeburn 14265: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14266: permanently for this url; hashref needs to be given and should be a \%hashname;
14267: the remaining args aren't required and if they aren't passed or are '' they will
14268: be derived from the env (with the exception of $laststore, which is an
14269: optional arg used when a user's submission is stored in grading).
14270: $laststore is $version=$timestamp, where $version is the most recent version
14271: number retrieved for the corresponding $symb in the $namespace db file, and
14272: $timestamp is the timestamp for that transaction (UNIX time).
14273: $laststore is currently only passed when cstore() is called by
14274: structuretags::finalize_storage().
1.191 harris41 14275:
14276: =item *
14277:
1.1269 raeburn 14278: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14279: but uses critical subroutine
1.191 harris41 14280:
14281: =item *
14282:
1.243 albertel 14283: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14284: all args are optional
1.191 harris41 14285:
14286: =item *
14287:
1.717 albertel 14288: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14289: dumps the complete (or key matching regexp) namespace into a hash
14290: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14291: normally &store()ed into
14292:
14293: $range should be either an integer '100' (give me the first 100
14294: matching records)
14295: or be two integers sperated by a - with no spaces
14296: '30-50' (give me the 30th through the 50th matching
14297: records)
14298:
14299:
14300: =item *
14301:
1.1269 raeburn 14302: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14303: replaces a &store() version of data with a replacement set of data
14304: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 14305: reference. If $tolog is true, the transaction is logged in the courselog
14306: with an action=PUTSTORE.
1.717 albertel 14307:
14308: =item *
14309:
1.243 albertel 14310: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14311: works very similar to store/cstore, but all data is stored in a
14312: temporary location and can be reset using tmpreset, $storehash should
14313: be a hash reference, returns nothing on success
1.191 harris41 14314:
14315: =item *
14316:
1.243 albertel 14317: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14318: similar to restore, but all data is stored in a temporary location and
14319: can be reset using tmpreset. Returns a hash of values on success,
14320: error string otherwise.
1.191 harris41 14321:
14322: =item *
14323:
1.243 albertel 14324: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14325: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14326:
14327: =item *
14328:
1.243 albertel 14329: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14330: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14331:
14332: =item *
14333:
1.243 albertel 14334: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14335: namesp ($udom and $uname are optional)
1.191 harris41 14336:
14337: =item *
14338:
1.702 albertel 14339: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14340: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14341: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14342:
1.702 albertel 14343: $range should be either an integer '100' (give me the first 100
14344: matching records)
14345: or be two integers sperated by a - with no spaces
14346: '30-50' (give me the 30th through the 50th matching
14347: records)
1.449 matthew 14348: =item *
14349:
14350: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14351: $store can be a scalar, an array reference, or if the amount to be
14352: incremented is > 1, a hash reference.
14353:
14354: ($udom and $uname are optional)
1.191 harris41 14355:
14356: =item *
14357:
1.243 albertel 14358: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14359: ($udom and $uname are optional)
1.191 harris41 14360:
14361: =item *
14362:
1.243 albertel 14363: cput($namespace,$storehash,$udom,$uname) : critical put
14364: ($udom and $uname are optional)
1.191 harris41 14365:
14366: =item *
14367:
1.748 albertel 14368: newput($namespace,$storehash,$udom,$uname) :
14369:
14370: Attempts to store the items in the $storehash, but only if they don't
14371: currently exist, if this succeeds you can be certain that you have
14372: successfully created a new key value pair in the $namespace db.
14373:
14374:
14375: Args:
14376: $namespace: name of database to store values to
14377: $storehash: hashref to store to the db
14378: $udom: (optional) domain of user containing the db
14379: $uname: (optional) name of user caontaining the db
14380:
14381: Returns:
14382: 'ok' -> succeeded in storing all keys of $storehash
14383: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14384: least <key> already existed in the db (other
14385: requested keys may also already exist)
1.967 bisitz 14386: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14387: 'con_lost' -> unable to contact request server
14388: 'refused' -> action was not allowed by remote machine
14389:
14390:
14391: =item *
14392:
1.243 albertel 14393: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14394: reference filled in from namesp (encrypts the return communication)
14395: ($udom and $uname are optional)
1.191 harris41 14396:
14397: =item *
14398:
1.243 albertel 14399: log($udom,$name,$home,$message) : write to permanent log for user; use
14400: critical subroutine
14401:
1.806 raeburn 14402: =item *
14403:
1.860 raeburn 14404: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14405: array reference filled in from namespace found in domain level on either
14406: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14407:
14408: =item *
14409:
1.860 raeburn 14410: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14411: domain level either on specified domain server ($uhome) or primary domain
14412: server ($udom and $uhome are optional)
1.806 raeburn 14413:
1.943 raeburn 14414: =item *
14415:
1.1240 raeburn 14416: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14417: for: authentication, language, quotas, timezone, date locale, and portal URL in
14418: the target domain.
14419:
14420: May also include additional key => value pairs for the following groups:
14421:
14422: =over
14423:
14424: =item
14425: disk quotas (MB allocated by default to portfolios and authoring spaces).
14426:
14427: =over
14428:
14429: =item defaultquota, authorquota
14430:
14431: =back
14432:
14433: =item
14434: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14435: portfolio for users).
14436:
14437: =over
14438:
14439: =item
14440: aboutme, blog, webdav, portfolio
14441:
14442: =back
14443:
14444: =item
14445: requestcourses: ability to request courses, and how requests are processed.
14446:
14447: =over
14448:
14449: =item
1.1305 raeburn 14450: official, unofficial, community, textbook, placement
1.1240 raeburn 14451:
14452: =back
14453:
14454: =item
14455: inststatus: types of institutional affiliation, and order in which they are displayed.
14456:
14457: =over
14458:
14459: =item
1.1256 raeburn 14460: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 14461:
14462: =back
14463:
14464: =item
14465: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14466: for course's uploaded content.
14467:
14468: =over
14469:
14470: =item
1.1246 raeburn 14471: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 14472: communityquota, textbookquota, placementquota
1.1240 raeburn 14473:
14474: =back
14475:
14476: =item
14477: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14478: on your servers.
14479:
14480: =over
14481:
14482: =item
14483: remotesessions, hostedsessions
14484:
14485: =back
14486:
14487: =back
14488:
14489: In cases where a domain coordinator has never used the "Set Domain Configuration"
14490: utility to create a configuration.db file on a domain's primary library server
14491: only the following domain defaults: auth_def, auth_arg_def, lang_def
14492: -- corresponding values are authentication type (internal, krb4, krb5,
14493: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14494: will be available. Values are retrieved from cache (if current), unless the
14495: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14496: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14497:
14498: Typical usage:
1.943 raeburn 14499:
1.1240 raeburn 14500: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14501:
1.243 albertel 14502: =back
14503:
14504: =head2 Network Status Functions
14505:
14506: =over 4
1.191 harris41 14507:
14508: =item *
14509:
1.1137 raeburn 14510: dirlist() : return directory list based on URI (first arg).
14511:
14512: Inputs: 1 required, 5 optional.
14513:
14514: =over
14515:
14516: =item
14517: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14518:
14519: =item
14520: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14521:
14522: =item
14523: $username - username of user/course to be listed. Extracted from $uri if absent.
14524:
14525: =item
14526: $getpropath - boolean: 1 if prepend path using &propath().
14527:
14528: =item
14529: $getuserdir - boolean: 1 if prepend path for "userfiles".
14530:
14531: =item
14532: $alternateRoot - path to prepend in place of path from $uri.
14533:
14534: =back
14535:
14536: Returns: Array of up to two items.
14537:
14538: =over
14539:
14540: a reference to an array of files/subdirectories
14541:
14542: =over
14543:
14544: Each element in the array of files/subdirectories is a & separated list of
14545: item name and the result of running stat on the item. If dirlist was requested
14546: for a file instead of a directory, the item name will be ''. For a directory
14547: listing, if the item is a metadata file, the element will end &N&M
14548: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14549: default copyright set (1).
14550:
14551: =back
14552:
14553: a scalar containing error condition (if encountered).
14554:
14555: =over
14556:
14557: =item
14558: no_host (no homeserver identified for $username:$domain).
14559:
14560: =item
14561: no_such_host (server contacted for listing not identified as valid host).
14562:
14563: =item
14564: con_lost (connection to remote server failed).
14565:
14566: =item
14567: refused (invalid $username:$domain received on lond side).
14568:
14569: =item
14570: no_such_dir (directory at specified path on lond side does not exist).
14571:
14572: =item
14573: empty (directory at specified path on lond side is empty).
14574:
14575: =over
14576:
14577: This is currently not encountered because the &ls3, &ls2,
14578: &ls (_handler) routines on the lond side do not filter out
14579: . and .. from a directory listing.
14580:
14581: =back
14582:
14583: =back
14584:
14585: =back
1.191 harris41 14586:
14587: =item *
14588:
1.243 albertel 14589: spareserver() : find server with least workload from spare.tab
14590:
1.986 foxr 14591:
14592: =item *
14593:
14594: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14595: if there is no corresponding loncapa host.
14596:
1.243 albertel 14597: =back
14598:
1.986 foxr 14599:
1.243 albertel 14600: =head2 Apache Request
14601:
14602: =over 4
1.191 harris41 14603:
14604: =item *
14605:
1.243 albertel 14606: ssi($url,%hash) : server side include, does a complete request cycle on url to
14607: localhost, posts hash
14608:
14609: =back
14610:
14611: =head2 Data to String to Data
14612:
14613: =over 4
1.191 harris41 14614:
14615: =item *
14616:
1.243 albertel 14617: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14618: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14619:
14620: =item *
14621:
1.243 albertel 14622: hashref2str($hashref) : convert a hashref into a string complete with
14623: escaping and '=' and '&' separators, supports elements that are
14624: arrayrefs and hashrefs
1.191 harris41 14625:
14626: =item *
14627:
1.243 albertel 14628: arrayref2str($arrayref) : convert an arrayref into a string complete
14629: with escaping and '&' separators, supports elements that are arrayrefs
14630: and hashrefs
1.191 harris41 14631:
14632: =item *
14633:
1.243 albertel 14634: str2hash($string) : convert string to hash using unescaping and
14635: splitting on '=' and '&', supports elements that are arrayrefs and
14636: hashrefs
1.191 harris41 14637:
14638: =item *
14639:
1.243 albertel 14640: str2array($string) : convert string to hash using unescaping and
14641: splitting on '&', supports elements that are arrayrefs and hashrefs
14642:
14643: =back
14644:
14645: =head2 Logging Routines
14646:
14647:
14648: These routines allow one to make log messages in the lonnet.log and
14649: lonnet.perm logfiles.
1.191 harris41 14650:
1.1119 foxr 14651: =over 4
14652:
1.191 harris41 14653: =item *
14654:
1.243 albertel 14655: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14656:
14657: =item *
14658:
1.243 albertel 14659: logthis() : append message to the normal lonnet.log file, it gets
14660: preiodically rolled over and deleted.
1.191 harris41 14661:
14662: =item *
14663:
1.243 albertel 14664: logperm() : append a permanent message to lonnet.perm.log, this log
14665: file never gets deleted by any automated portion of the system, only
14666: messages of critical importance should go in here.
14667:
1.1119 foxr 14668:
1.243 albertel 14669: =back
14670:
14671: =head2 General File Helper Routines
14672:
14673: =over 4
1.191 harris41 14674:
14675: =item *
14676:
1.481 raeburn 14677: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14678: (a) files in /uploaded
14679: (i) If a local copy of the file exists -
14680: compares modification date of local copy with last-modified date for
14681: definitive version stored on home server for course. If local copy is
14682: stale, requests a new version from the home server and stores it.
14683: If the original has been removed from the home server, then local copy
14684: is unlinked.
14685: (ii) If local copy does not exist -
14686: requests the file from the home server and stores it.
14687:
14688: If $caller is 'uploadrep':
14689: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14690: for request for files originally uploaded via DOCS.
14691: - returns 'ok' if fresh local copy now available, -1 otherwise.
14692:
14693: Otherwise:
14694: This indicates a call from the content generation phase of the request.
14695: - returns the entire contents of the file or -1.
14696:
14697: (b) files in /res
14698: - returns the entire contents of a file or -1;
14699: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14700:
1.712 albertel 14701:
14702: =item *
14703:
14704: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14705: reference
14706:
14707: returns either a stat() list of data about the file or an empty list
14708: if the file doesn't exist or couldn't find out about it (connection
14709: problems or user unknown)
14710:
1.191 harris41 14711: =item *
14712:
1.243 albertel 14713: filelocation($dir,$file) : returns file system location of a file
14714: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14715: directory that relative $file lookups are to looked in ($dir of /a/dir
14716: and a file of ../bob will become /a/bob)
1.191 harris41 14717:
14718: =item *
14719:
14720: hreflocation($dir,$file) : returns file system location or a URL; same as
14721: filelocation except for hrefs
14722:
14723: =item *
14724:
1.1261 raeburn 14725: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14726: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14727:
1.243 albertel 14728: =back
14729:
1.608 albertel 14730: =head2 Usererfile file routines (/uploaded*)
14731:
14732: =over 4
14733:
14734: =item *
14735:
14736: userfileupload(): main rotine for putting a file in a user or course's
14737: filespace, arguments are,
14738:
1.620 albertel 14739: formname - required - this is the name of the element in $env where the
1.608 albertel 14740: filename, and the contents of the file to create/modifed exist
1.620 albertel 14741: the filename is in $env{'form.'.$formname.'.filename'} and the
14742: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14743: context - if coursedoc, store the file in the course of the active role
14744: of the current user;
14745: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14746: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14747: subdir - required - subdirectory to put the file in under ../userfiles/
14748: if undefined, it will be placed in "unknown"
14749:
14750: (This routine calls clean_filename() to remove any dangerous
14751: characters from the filename, and then calls finuserfileupload() to
14752: complete the transaction)
14753:
14754: returns either the url of the uploaded file (/uploaded/....) if successful
14755: and /adm/notfound.html if unsuccessful
14756:
14757: =item *
14758:
14759: clean_filename(): routine for cleaing a filename up for storage in
14760: userfile space, argument is:
14761:
14762: filename - proposed filename
14763:
14764: returns: the new clean filename
14765:
14766: =item *
14767:
1.1090 raeburn 14768: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14769: userspace, probably shouldn't be called directly
14770:
14771: docuname: username or courseid of destination for the file
14772: docudom: domain of user/course of destination for the file
14773: formname: same as for userfileupload()
1.1090 raeburn 14774: fname: filename (including subdirectories) for the file
14775: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14776: allfiles: reference to hash used to store objects found by parser
14777: codebase: reference to hash used for codebases of java objects found by parser
14778: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14779: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14780: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14781: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14782: context: if 'overwrite', will move the uploaded file from its temporary location to
14783: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14784: mimetype: reference to scalar to accommodate mime type determined
14785: from File::MMagic if $parser = parse.
1.608 albertel 14786:
14787: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14788: and /adm/notfound.html if unsuccessful (or an error message if context
14789: was 'overwrite').
14790:
1.608 albertel 14791:
14792: =item *
14793:
14794: renameuserfile(): renames an existing userfile to a new name
14795:
14796: Args:
14797: docuname: username or courseid of destination for the file
14798: docudom: domain of user/course of destination for the file
14799: old: current file name (including any subdirs under userfiles)
14800: new: desired file name (including any subdirs under userfiles)
14801:
14802: =item *
14803:
14804: mkdiruserfile(): creates a directory is a userfiles dir
14805:
14806: Args:
14807: docuname: username or courseid of destination for the file
14808: docudom: domain of user/course of destination for the file
14809: dir: dir to create (including any subdirs under userfiles)
14810:
14811: =item *
14812:
14813: removeuserfile(): removes a file that exists in userfiles
14814:
14815: Args:
14816: docuname: username or courseid of destination for the file
14817: docudom: domain of user/course of destination for the file
14818: fname: filname to delete (including any subdirs under userfiles)
14819:
14820: =item *
14821:
14822: removeuploadedurl(): convience function for removeuserfile()
14823:
14824: Args:
14825: url: a full /uploaded/... url to delete
14826:
1.747 albertel 14827: =item *
14828:
14829: get_portfile_permissions():
14830: Args:
14831: domain: domain of user or course contain the portfolio files
14832: user: name of user or num of course contain the portfolio files
14833: Returns:
14834: hashref of a dump of the proper file_permissions.db
14835:
14836:
14837: =item *
14838:
14839: get_access_controls():
14840:
14841: Args:
14842: current_permissions: the hash ref returned from get_portfile_permissions()
14843: group: (optional) the group you want the files associated with
14844: file: (optional) the file you want access info on
14845:
14846: Returns:
1.749 raeburn 14847: a hash (keys are file names) of hashes containing
14848: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14849: values are XML containing access control settings (see below)
1.747 albertel 14850:
14851: Internal notes:
14852:
1.749 raeburn 14853: access controls are stored in file_permissions.db as key=value pairs.
14854: key -> path to file/file_name\0uniqueID:scope_end_start
14855: where scope -> public,guest,course,group,domains or users.
14856: end -> UNIX time for end of access (0 -> no end date)
14857: start -> UNIX time for start of access
14858:
14859: value -> XML description of access control
14860: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14861: <start></start>
14862: <end></end>
14863:
14864: <password></password> for scope type = guest
14865:
14866: <domain></domain> for scope type = course or group
14867: <number></number>
14868: <roles id="">
14869: <role></role>
14870: <access></access>
14871: <section></section>
14872: <group></group>
14873: </roles>
14874:
14875: <dom></dom> for scope type = domains
14876:
14877: <users> for scope type = users
14878: <user>
14879: <uname></uname>
14880: <udom></udom>
14881: </user>
14882: </users>
14883: </scope>
14884:
14885: Access data is also aggregated for each file in an additional key=value pair:
14886: key -> path to file/file_name\0accesscontrol
14887: value -> reference to hash
14888: hash contains key = value pairs
14889: where key = uniqueID:scope_end_start
14890: value = UNIX time record was last updated
14891:
14892: Used to improve speed of look-ups of access controls for each file.
14893:
14894: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14895:
1.1198 raeburn 14896: =item *
14897:
1.749 raeburn 14898: modify_access_controls():
14899:
14900: Modifies access controls for a portfolio file
14901: Args
14902: 1. file name
14903: 2. reference to hash of required changes,
14904: 3. domain
14905: 4. username
14906: where domain,username are the domain of the portfolio owner
14907: (either a user or a course)
14908:
14909: Returns:
14910: 1. result of additions or updates ('ok' or 'error', with error message).
14911: 2. result of deletions ('ok' or 'error', with error message).
14912: 3. reference to hash of any new or updated access controls.
14913: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14914: key = integer (inbound ID)
1.1198 raeburn 14915: value = uniqueID
14916:
14917: =item *
14918:
14919: get_timebased_id():
14920:
14921: Attempts to get a unique timestamp-based suffix for use with items added to a
14922: course via the Course Editor (e.g., folders, composite pages,
14923: group bulletin boards).
14924:
14925: Args: (first three required; six others optional)
14926:
14927: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14928: docssequence, or name of group
14929:
14930: 2. keyid (alphanumeric): name of temporary locking key in hash,
14931: e.g., num, boardids
14932:
14933: 3. namespace: name of gdbm file used to store suffixes already assigned;
14934: file will be named nohist_namespace.db
14935:
14936: 4. cdom: domain of course; default is current course domain from %env
14937:
14938: 5. cnum: course number; default is current course number from %env
14939:
14940: 6. idtype: set to concat if an additional digit is to be appended to the
14941: unix timestamp to form the suffix, if the plain timestamp is already
14942: in use. Default is to not do this, but simply increment the unix
14943: timestamp by 1 until a unique key is obtained.
14944:
14945: 7. who: holder of locking key; defaults to user:domain for user.
14946:
14947: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14948: retrying); default is 3.
14949:
14950: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14951:
14952: Returns:
14953:
14954: 1. suffix obtained (numeric)
14955:
14956: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14957:
14958: 3. error: contains (localized) error message if an error occurred.
14959:
1.747 albertel 14960:
1.608 albertel 14961: =back
14962:
1.243 albertel 14963: =head2 HTTP Helper Routines
14964:
14965: =over 4
14966:
1.191 harris41 14967: =item *
14968:
14969: escape() : unpack non-word characters into CGI-compatible hex codes
14970:
14971: =item *
14972:
14973: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14974:
1.243 albertel 14975: =back
14976:
14977: =head1 PRIVATE SUBROUTINES
14978:
14979: =head2 Underlying communication routines (Shouldn't call)
14980:
14981: =over 4
14982:
14983: =item *
14984:
14985: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14986:
14987: =item *
14988:
14989: reply() : uses subreply to send a message to remote machine, logs all failures
14990:
14991: =item *
14992:
14993: critical() : passes a critical message to another server; if cannot
14994: get through then place message in connection buffer directory and
14995: returns con_delayed, if incapable of saving message, returns
14996: con_failed
14997:
14998: =item *
14999:
15000: reconlonc() : tries to reconnect lonc client processes.
15001:
15002: =back
15003:
15004: =head2 Resource Access Logging
15005:
15006: =over 4
15007:
15008: =item *
15009:
15010: flushcourselogs() : flush (save) buffer logs and access logs
15011:
15012: =item *
15013:
15014: courselog($what) : save message for course in hash
15015:
15016: =item *
15017:
15018: courseacclog($what) : save message for course using &courselog(). Perform
15019: special processing for specific resource types (problems, exams, quizzes, etc).
15020:
1.191 harris41 15021: =item *
15022:
15023: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15024: as a PerlChildExitHandler
1.243 albertel 15025:
15026: =back
15027:
15028: =head2 Other
15029:
15030: =over 4
15031:
15032: =item *
15033:
15034: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15035:
15036: =back
15037:
15038: =cut
1.877 foxr 15039:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>