Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1337
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1337 ! raeburn 4: # $Id: lonnet.pm,v 1.1336 2017/01/28 23:26:51 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.1337 ! raeburn 653: my ($linkname,$pubname);
1.1155 raeburn 654: if ($name eq '') {
655: $name = 'lonID';
1.1337 ! raeburn 656: $linkname = 'lonLinkID';
! 657: $pubname = 'lonPubID';
1.1155 raeburn 658: }
659: my $lonid=$cookies{$name};
1.1337 ! raeburn 660: if (!$lonid) {
! 661: if (($name eq 'lonID') && ($ENV{'SERVER_PORT'} != 443) && ($linkname)) {
! 662: $lonid=$cookies{$linkname};
! 663: }
! 664: if (!$lonid) {
! 665: if (($name eq 'lonID') && ($pubname)) {
! 666: $lonid=$cookies{$pubname};
! 667: }
! 668: }
! 669: }
1.916 albertel 670: return undef if (!$lonid);
671:
672: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 673: my $lonidsdir;
674: if ($name eq 'lonDAV') {
675: $lonidsdir=$r->dir_config('lonDAVsessDir');
676: } else {
677: $lonidsdir=$r->dir_config('lonIDsDir');
678: }
1.916 albertel 679: return undef if (!-e "$lonidsdir/$handle.id");
680:
1.917 albertel 681: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
682: return undef if (!$opened);
1.916 albertel 683:
684: flock($idf,LOCK_SH);
685: my %disk_env;
686: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
687: &GDBM_READER(),0640)) {
688: return undef;
689: }
690:
691: if (!defined($disk_env{'user.name'})
692: || !defined($disk_env{'user.domain'})) {
693: return undef;
694: }
1.1245 raeburn 695:
696: if (ref($userhashref) eq 'HASH') {
697: $userhashref->{'name'} = $disk_env{'user.name'};
698: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 699: }
1.1245 raeburn 700:
1.916 albertel 701: return $handle;
702: }
703:
1.830 albertel 704: sub timed_flock {
705: my ($file,$lock_type) = @_;
706: my $failed=0;
707: eval {
708: local $SIG{__DIE__}='DEFAULT';
709: local $SIG{ALRM}=sub {
710: $failed=1;
711: die("failed lock");
712: };
713: alarm(13);
714: flock($file,$lock_type);
715: alarm(0);
716: };
717: if ($failed) {
718: return undef;
719: } else {
720: return 1;
721: }
722: }
723:
1.5 www 724: # ---------------------------------------------------------- Append Environment
725:
726: sub appenv {
1.949 raeburn 727: my ($newenv,$roles) = @_;
728: if (ref($newenv) eq 'HASH') {
729: foreach my $key (keys(%{$newenv})) {
730: my $refused = 0;
731: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
732: $refused = 1;
733: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 734: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 735: if (grep(/^\Q$role\E$/,@{$roles})) {
736: $refused = 0;
737: }
738: }
739: }
740: if ($refused) {
741: &logthis("<font color=\"blue\">WARNING: ".
742: "Attempt to modify environment ".$key." to ".$newenv->{$key}
743: .'</font>');
744: delete($newenv->{$key});
745: } else {
746: $env{$key}=$newenv->{$key};
747: }
748: }
749: my $opened = open(my $env_file,'+<',$env{'user.environment'});
750: if ($opened
751: && &timed_flock($env_file,LOCK_EX)
752: &&
753: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
754: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
755: while (my ($key,$value) = each(%{$newenv})) {
756: $disk_env{$key} = $value;
757: }
758: untie(%disk_env);
1.35 www 759: }
1.191 harris41 760: }
1.56 www 761: return 'ok';
762: }
763: # ----------------------------------------------------- Delete from Environment
764:
765: sub delenv {
1.1104 raeburn 766: my ($delthis,$regexp,$roles) = @_;
767: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
768: my $refused = 1;
769: if (ref($roles) eq 'ARRAY') {
770: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
771: if (grep(/^\Q$role\E$/,@{$roles})) {
772: $refused = 0;
773: }
774: }
775: if ($refused) {
776: &logthis("<font color=\"blue\">WARNING: ".
777: "Attempt to delete from environment ".$delthis);
778: return 'error';
779: }
1.56 www 780: }
1.917 albertel 781: my $opened = open(my $env_file,'+<',$env{'user.environment'});
782: if ($opened
1.915 albertel 783: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 784: &&
785: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
786: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 787: foreach my $key (keys(%disk_env)) {
1.987 raeburn 788: if ($regexp) {
789: if ($key=~/^$delthis/) {
790: delete($env{$key});
791: delete($disk_env{$key});
792: }
793: } else {
794: if ($key=~/^\Q$delthis\E/) {
795: delete($env{$key});
796: delete($disk_env{$key});
797: }
798: }
1.448 albertel 799: }
1.783 albertel 800: untie(%disk_env);
1.5 www 801: }
802: return 'ok';
1.369 albertel 803: }
804:
1.790 albertel 805: sub get_env_multiple {
806: my ($name) = @_;
807: my @values;
808: if (defined($env{$name})) {
809: # exists is it an array
810: if (ref($env{$name})) {
811: @values=@{ $env{$name} };
812: } else {
813: $values[0]=$env{$name};
814: }
815: }
816: return(@values);
817: }
818:
1.958 www 819: # ------------------------------------------------------------------- Locking
820:
821: sub set_lock {
822: my ($text)=@_;
823: $locknum++;
824: my $id=$$.'-'.$locknum;
825: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
826: 'session.lock.'.$id => $text});
827: return $id;
828: }
829:
830: sub get_locks {
831: my $num=0;
832: my %texts=();
833: foreach my $lock (split(/\,/,$env{'session.locks'})) {
834: if ($lock=~/\w/) {
835: $num++;
836: $texts{$lock}=$env{'session.lock.'.$lock};
837: }
838: }
839: return ($num,%texts);
840: }
841:
842: sub remove_lock {
843: my ($id)=@_;
844: my $newlocks='';
845: foreach my $lock (split(/\,/,$env{'session.locks'})) {
846: if (($lock=~/\w/) && ($lock ne $id)) {
847: $newlocks.=','.$lock;
848: }
849: }
850: &appenv({'session.locks' => $newlocks});
851: &delenv('session.lock.'.$id);
852: }
853:
854: sub remove_all_locks {
855: my $activelocks=$env{'session.locks'};
856: foreach my $lock (split(/\,/,$env{'session.locks'})) {
857: if ($lock=~/\w/) {
858: &remove_lock($lock);
859: }
860: }
861: }
862:
863:
1.369 albertel 864: # ------------------------------------------ Find out current server userload
865: sub userload {
866: my $numusers=0;
867: {
868: opendir(LONIDS,$perlvar{'lonIDsDir'});
869: my $filename;
870: my $curtime=time;
871: while ($filename=readdir(LONIDS)) {
1.925 albertel 872: next if ($filename eq '.' || $filename eq '..');
873: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 874: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 875: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 876: }
877: closedir(LONIDS);
878: }
879: my $userloadpercent=0;
880: my $maxuserload=$perlvar{'lonUserLoadLim'};
881: if ($maxuserload) {
1.371 albertel 882: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 883: }
1.372 albertel 884: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 885: return $userloadpercent;
1.283 www 886: }
887:
1.1 albertel 888: # ------------------------------ Find server with least workload from spare.tab
1.11 www 889:
1.1 albertel 890: sub spareserver {
1.1083 raeburn 891: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 892: my $spare_server;
1.370 albertel 893: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 894: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
895: : $userloadpercent;
1.1083 raeburn 896: my ($uint_dom,$remotesessions);
897: if (($udom ne '') && (&domain($udom) ne '')) {
898: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
899: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
900: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
901: $remotesessions = $udomdefaults{'remotesessions'};
902: }
1.1123 raeburn 903: my $spareshash = &this_host_spares($udom);
904: if (ref($spareshash) eq 'HASH') {
905: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
906: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 907: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
908: $try_server));
1.1123 raeburn 909: ($spare_server, $lowest_load) =
910: &compare_server_load($try_server, $spare_server, $lowest_load);
911: }
1.1083 raeburn 912: }
1.784 albertel 913:
1.1123 raeburn 914: my $found_server = ($spare_server ne '' && $lowest_load < 100);
915:
916: if (!$found_server) {
917: if (ref($spareshash->{'default'}) eq 'ARRAY') {
918: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 919: next unless (&spare_can_host($udom,$uint_dom,
920: $remotesessions,$try_server));
1.1123 raeburn 921: ($spare_server, $lowest_load) =
922: &compare_server_load($try_server, $spare_server, $lowest_load);
923: }
924: }
925: }
1.784 albertel 926: }
927:
928: if (!$want_server_name) {
1.968 raeburn 929: my $protocol = 'http';
930: if ($protocol{$spare_server} eq 'https') {
931: $protocol = $protocol{$spare_server};
932: }
1.1001 raeburn 933: if (defined($spare_server)) {
934: my $hostname = &hostname($spare_server);
1.1083 raeburn 935: if (defined($hostname)) {
1.1001 raeburn 936: $spare_server = $protocol.'://'.$hostname;
937: }
938: }
1.784 albertel 939: }
940: return $spare_server;
941: }
942:
943: sub compare_server_load {
1.1253 raeburn 944: my ($try_server, $spare_server, $lowest_load, $required) = @_;
945:
946: if ($required) {
947: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
948: my $remoterev = &get_server_loncaparev(undef,$try_server);
949: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
950: if (($major eq '' && $minor eq '') ||
951: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
952: return ($spare_server,$lowest_load);
953: }
954: }
1.784 albertel 955:
956: my $loadans = &reply('load', $try_server);
957: my $userloadans = &reply('userload',$try_server);
958:
959: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 960: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 961: }
962:
963: my $load;
964: if ($loadans =~ /\d/) {
965: if ($userloadans =~ /\d/) {
966: #both are numbers, pick the bigger one
967: $load = ($loadans > $userloadans) ? $loadans
968: : $userloadans;
1.411 albertel 969: } else {
1.784 albertel 970: $load = $loadans;
1.411 albertel 971: }
1.784 albertel 972: } else {
973: $load = $userloadans;
974: }
975:
976: if (($load =~ /\d/) && ($load < $lowest_load)) {
977: $spare_server = $try_server;
978: $lowest_load = $load;
1.370 albertel 979: }
1.784 albertel 980: return ($spare_server,$lowest_load);
1.202 matthew 981: }
1.914 albertel 982:
983: # --------------------------- ask offload servers if user already has a session
984: sub find_existing_session {
985: my ($udom,$uname) = @_;
1.1123 raeburn 986: my $spareshash = &this_host_spares($udom);
987: if (ref($spareshash) eq 'HASH') {
988: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
989: foreach my $try_server (@{ $spareshash->{'primary'} }) {
990: return $try_server if (&has_user_session($try_server, $udom, $uname));
991: }
992: }
993: if (ref($spareshash->{'default'}) eq 'ARRAY') {
994: foreach my $try_server (@{ $spareshash->{'default'} }) {
995: return $try_server if (&has_user_session($try_server, $udom, $uname));
996: }
997: }
1.914 albertel 998: }
999: return;
1000: }
1001:
1002: # -------------------------------- ask if server already has a session for user
1003: sub has_user_session {
1004: my ($lonid,$udom,$uname) = @_;
1005: my $result = &reply(join(':','userhassession',
1006: map {&escape($_)} ($udom,$uname)),$lonid);
1007: return 1 if ($result eq 'ok');
1008:
1009: return 0;
1010: }
1011:
1.1076 raeburn 1012: # --------- determine least loaded server in a user's domain which allows login
1013:
1014: sub choose_server {
1.1259 raeburn 1015: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1016: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1017: my %servers = &get_servers($udom);
1.1076 raeburn 1018: my $lowest_load = 30000;
1.1259 raeburn 1019: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1020: if ($skiploadbal) {
1021: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1022: unless (defined($cached)) {
1023: my $cachetime = 60*60*24;
1024: my %domconfig =
1025: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1026: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1027: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1028: $cachetime);
1029: }
1030: }
1031: }
1.1076 raeburn 1032: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1033: if ($skiploadbal) {
1034: if (ref($balancers) eq 'HASH') {
1035: next if (exists($balancers->{$lonhost}));
1036: }
1037: }
1.1115 raeburn 1038: my $loginvia;
1039: if ($checkloginvia) {
1040: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1041: if ($loginvia) {
1042: my ($server,$path) = split(/:/,$loginvia);
1043: ($login_host, $lowest_load) =
1.1253 raeburn 1044: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1045: if ($login_host eq $server) {
1046: $portal_path = $path;
1.1151 raeburn 1047: $isredirect = 1;
1.1116 raeburn 1048: }
1049: } else {
1050: ($login_host, $lowest_load) =
1.1253 raeburn 1051: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1052: if ($login_host eq $lonhost) {
1053: $portal_path = '';
1.1151 raeburn 1054: $isredirect = '';
1.1116 raeburn 1055: }
1056: }
1057: } else {
1.1076 raeburn 1058: ($login_host, $lowest_load) =
1.1253 raeburn 1059: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1060: }
1061: }
1062: if ($login_host ne '') {
1.1116 raeburn 1063: $hostname = &hostname($login_host);
1.1076 raeburn 1064: }
1.1331 raeburn 1065: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1066: }
1067:
1.202 matthew 1068: # --------------------------------------------- Try to change a user's password
1069:
1070: sub changepass {
1.799 raeburn 1071: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1072: $currentpass = &escape($currentpass);
1073: $newpass = &escape($newpass);
1.1030 raeburn 1074: my $lonhost = $perlvar{'lonHostID'};
1075: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1076: $server);
1077: if (! $answer) {
1078: &logthis("No reply on password change request to $server ".
1079: "by $uname in domain $udom.");
1080: } elsif ($answer =~ "^ok") {
1081: &logthis("$uname in $udom successfully changed their password ".
1082: "on $server.");
1083: } elsif ($answer =~ "^pwchange_failure") {
1084: &logthis("$uname in $udom was unable to change their password ".
1085: "on $server. The action was blocked by either lcpasswd ".
1086: "or pwchange");
1087: } elsif ($answer =~ "^non_authorized") {
1088: &logthis("$uname in $udom did not get their password correct when ".
1089: "attempting to change it on $server.");
1090: } elsif ($answer =~ "^auth_mode_error") {
1091: &logthis("$uname in $udom attempted to change their password despite ".
1092: "not being locally or internally authenticated on $server.");
1093: } elsif ($answer =~ "^unknown_user") {
1094: &logthis("$uname in $udom attempted to change their password ".
1095: "on $server but were unable to because $server is not ".
1096: "their home server.");
1097: } elsif ($answer =~ "^refused") {
1098: &logthis("$server refused to change $uname in $udom password because ".
1099: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1100: } elsif ($answer =~ "invalid_client") {
1101: &logthis("$server refused to change $uname in $udom password because ".
1102: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1103: }
1104: return $answer;
1.1 albertel 1105: }
1106:
1.169 harris41 1107: # ----------------------- Try to determine user's current authentication scheme
1108:
1109: sub queryauthenticate {
1110: my ($uname,$udom)=@_;
1.456 albertel 1111: my $uhome=&homeserver($uname,$udom);
1112: if (!$uhome) {
1113: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1114: return 'no_host';
1115: }
1116: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1117: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1118: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1119: }
1.456 albertel 1120: return $answer;
1.169 harris41 1121: }
1122:
1.1 albertel 1123: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1124:
1.1 albertel 1125: sub authenticate {
1.1073 raeburn 1126: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1127: $upass=&escape($upass);
1128: $uname= &LONCAPA::clean_username($uname);
1.836 www 1129: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1130: my $newhome;
1.836 www 1131: if ((!$uhome) || ($uhome eq 'no_host')) {
1132: # Maybe the machine was offline and only re-appeared again recently?
1133: &reconlonc();
1134: # One more
1.952 raeburn 1135: $uhome=&homeserver($uname,$udom,1);
1136: if (($uhome eq 'no_host') && $checkdefauth) {
1137: if (defined(&domain($udom,'primary'))) {
1138: $newhome=&domain($udom,'primary');
1139: }
1140: if ($newhome ne '') {
1141: $uhome = $newhome;
1142: }
1143: }
1.836 www 1144: if ((!$uhome) || ($uhome eq 'no_host')) {
1145: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1146: return 'no_host';
1147: }
1.1 albertel 1148: }
1.1073 raeburn 1149: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1150: if ($answer eq 'authorized') {
1.952 raeburn 1151: if ($newhome) {
1152: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1153: return 'no_account_on_host';
1154: } else {
1155: &logthis("User $uname at $udom authorized by $uhome");
1156: return $uhome;
1157: }
1.471 albertel 1158: }
1159: if ($answer eq 'non_authorized') {
1160: &logthis("User $uname at $udom rejected by $uhome");
1161: return 'no_host';
1.9 www 1162: }
1.471 albertel 1163: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1164: return 'no_host';
1165: }
1166:
1.1073 raeburn 1167: sub can_host_session {
1.1074 raeburn 1168: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1169: my $canhost = 1;
1.1074 raeburn 1170: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1171: if (ref($remotesessions) eq 'HASH') {
1172: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1173: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1174: $canhost = 0;
1175: } else {
1176: $canhost = 1;
1177: }
1178: }
1179: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1180: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1181: $canhost = 1;
1182: } else {
1183: $canhost = 0;
1184: }
1185: }
1186: if ($canhost) {
1187: if ($remotesessions->{'version'} ne '') {
1188: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1189: if ($reqmajor ne '' && $reqminor ne '') {
1190: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1191: my $major = $1;
1192: my $minor = $2;
1193: if (($major < $reqmajor ) ||
1194: (($major == $reqmajor) && ($minor < $reqminor))) {
1195: $canhost = 0;
1196: }
1197: } else {
1198: $canhost = 0;
1199: }
1200: }
1201: }
1202: }
1203: }
1204: if ($canhost) {
1205: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1206: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1207: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1208: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1209: if (($uint_dom ne '') &&
1210: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1211: $canhost = 0;
1212: } else {
1213: $canhost = 1;
1214: }
1215: }
1216: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1217: if (($uint_dom ne '') &&
1218: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1219: $canhost = 1;
1220: } else {
1221: $canhost = 0;
1222: }
1223: }
1224: }
1225: }
1226: return $canhost;
1227: }
1228:
1.1083 raeburn 1229: sub spare_can_host {
1230: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1231: my $canhost=1;
1.1279 raeburn 1232: my $try_server_hostname = &hostname($try_server);
1233: my $serverhomeID = &get_server_homeID($try_server_hostname);
1234: my $serverhomedom = &host_domain($serverhomeID);
1235: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1236: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1237: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1238: $canhost = 0;
1239: }
1240: }
1241: if (($canhost) && ($uint_dom)) {
1242: my @intdoms;
1243: my $internet_names = &get_internet_names($try_server);
1244: if (ref($internet_names) eq 'ARRAY') {
1245: @intdoms = @{$internet_names};
1246: }
1247: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1248: my $remoterev = &get_server_loncaparev(undef,$try_server);
1249: $canhost = &can_host_session($udom,$try_server,$remoterev,
1250: $remotesessions,
1251: $defdomdefaults{'hostedsessions'});
1252: }
1.1083 raeburn 1253: }
1254: return $canhost;
1255: }
1256:
1.1123 raeburn 1257: sub this_host_spares {
1258: my ($dom) = @_;
1.1126 raeburn 1259: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1260: my @hosts = ¤t_machine_ids();
1261: foreach my $lonhost (@hosts) {
1262: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1263: $dom_in_use = $dom;
1264: $lonhost_in_use = $lonhost;
1.1123 raeburn 1265: last;
1266: }
1267: }
1.1126 raeburn 1268: if ($dom_in_use ne '') {
1269: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1270: }
1271: if (ref($result) ne 'HASH') {
1272: $lonhost_in_use = $perlvar{'lonHostID'};
1273: $dom_in_use = &host_domain($lonhost_in_use);
1274: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1275: if (ref($result) ne 'HASH') {
1276: $result = \%spareid;
1277: }
1278: }
1279: return $result;
1280: }
1281:
1282: sub spares_for_offload {
1283: my ($dom_in_use,$lonhost_in_use) = @_;
1284: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1285: if (defined($cached)) {
1286: return $result;
1287: } else {
1.1126 raeburn 1288: my $cachetime = 60*60*24;
1289: my %domconfig =
1290: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1291: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1292: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1293: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1294: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1295: }
1296: }
1297: }
1298: }
1.1126 raeburn 1299: return;
1.1123 raeburn 1300: }
1301:
1.1129 raeburn 1302: sub get_lonbalancer_config {
1303: my ($servers) = @_;
1304: my ($currbalancer,$currtargets);
1305: if (ref($servers) eq 'HASH') {
1306: foreach my $server (keys(%{$servers})) {
1307: my %what = (
1308: spareid => 1,
1309: perlvar => 1,
1310: );
1311: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1312: if ($result eq 'ok') {
1313: if (ref($returnhash) eq 'HASH') {
1314: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1315: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1316: $currbalancer = $server;
1317: $currtargets = {};
1318: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1319: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1320: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1321: }
1322: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1323: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1324: }
1325: }
1326: last;
1327: }
1328: }
1329: }
1330: }
1331: }
1332: }
1333: return ($currbalancer,$currtargets);
1334: }
1335:
1336: sub check_loadbalancing {
1.1331 raeburn 1337: my ($uname,$udom,$caller) = @_;
1.1191 raeburn 1338: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1339: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1340: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1341: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1342: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1343: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1344: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1345: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1346: my $domneedscache;
1.1129 raeburn 1347: my $cachetime = 60*60*24;
1348:
1349: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1350: $dom_in_use = $udom;
1351: $homeintdom = 1;
1352: } else {
1353: $dom_in_use = $serverhomedom;
1354: }
1355: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1356: unless (defined($cached)) {
1357: my %domconfig =
1358: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1359: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1360: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1361: } else {
1362: $domneedscache = $dom_in_use;
1.1129 raeburn 1363: }
1364: }
1365: if (ref($result) eq 'HASH') {
1.1191 raeburn 1366: ($is_balancer,$currtargets,$currrules) =
1367: &check_balancer_result($result,@hosts);
1.1129 raeburn 1368: if ($is_balancer) {
1369: if (ref($currrules) eq 'HASH') {
1370: if ($homeintdom) {
1371: if ($uname ne '') {
1372: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1373: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1374: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1375: $rule_in_effect = $currrules->{'_LC_author'};
1376: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1377: $rule_in_effect = $currrules->{'_LC_adv'}
1378: }
1379: }
1380: if ($rule_in_effect eq '') {
1381: my %userenv = &userenvironment($udom,$uname,'inststatus');
1382: if ($userenv{'inststatus'} ne '') {
1383: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1384: my ($othertitle,$usertypes,$types) =
1385: &Apache::loncommon::sorted_inst_types($udom);
1386: if (ref($types) eq 'ARRAY') {
1387: foreach my $type (@{$types}) {
1388: if (grep(/^\Q$type\E$/,@statuses)) {
1389: if (exists($currrules->{$type})) {
1390: $rule_in_effect = $currrules->{$type};
1391: }
1392: }
1393: }
1394: }
1395: } else {
1396: if (exists($currrules->{'default'})) {
1397: $rule_in_effect = $currrules->{'default'};
1398: }
1399: }
1400: }
1401: } else {
1402: if (exists($currrules->{'default'})) {
1403: $rule_in_effect = $currrules->{'default'};
1404: }
1405: }
1406: } else {
1407: if ($currrules->{'_LC_external'} ne '') {
1408: $rule_in_effect = $currrules->{'_LC_external'};
1409: }
1410: }
1411: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1412: $uname,$udom);
1413: }
1414: }
1415: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1416: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1417: unless (defined($cached)) {
1418: my %domconfig =
1419: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1420: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1421: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1422: } else {
1423: $domneedscache = $serverhomedom;
1.1129 raeburn 1424: }
1425: }
1426: if (ref($result) eq 'HASH') {
1.1191 raeburn 1427: ($is_balancer,$currtargets,$currrules) =
1428: &check_balancer_result($result,@hosts);
1429: if ($is_balancer) {
1.1129 raeburn 1430: if (ref($currrules) eq 'HASH') {
1431: if ($currrules->{'_LC_internetdom'} ne '') {
1432: $rule_in_effect = $currrules->{'_LC_internetdom'};
1433: }
1434: }
1435: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1436: $uname,$udom);
1437: }
1438: } else {
1439: if ($perlvar{'lonBalancer'} eq 'yes') {
1440: $is_balancer = 1;
1441: $offloadto = &this_host_spares($dom_in_use);
1442: }
1.1307 raeburn 1443: unless (defined($cached)) {
1444: $domneedscache = $serverhomedom;
1445: }
1.1129 raeburn 1446: }
1447: } else {
1448: if ($perlvar{'lonBalancer'} eq 'yes') {
1449: $is_balancer = 1;
1450: $offloadto = &this_host_spares($dom_in_use);
1451: }
1.1307 raeburn 1452: unless (defined($cached)) {
1453: $domneedscache = $serverhomedom;
1454: }
1455: }
1456: if ($domneedscache) {
1457: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1458: }
1.1176 raeburn 1459: if ($is_balancer) {
1460: my $lowest_load = 30000;
1461: if (ref($offloadto) eq 'HASH') {
1462: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1463: foreach my $try_server (@{$offloadto->{'primary'}}) {
1464: ($otherserver,$lowest_load) =
1465: &compare_server_load($try_server,$otherserver,$lowest_load);
1466: }
1.1129 raeburn 1467: }
1.1176 raeburn 1468: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1469:
1.1176 raeburn 1470: if (!$found_server) {
1471: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1472: foreach my $try_server (@{$offloadto->{'default'}}) {
1473: ($otherserver,$lowest_load) =
1474: &compare_server_load($try_server,$otherserver,$lowest_load);
1475: }
1476: }
1477: }
1478: } elsif (ref($offloadto) eq 'ARRAY') {
1479: if (@{$offloadto} == 1) {
1480: $otherserver = $offloadto->[0];
1481: } elsif (@{$offloadto} > 1) {
1482: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1483: ($otherserver,$lowest_load) =
1484: &compare_server_load($try_server,$otherserver,$lowest_load);
1485: }
1486: }
1487: }
1.1331 raeburn 1488: unless ($caller eq 'login') {
1489: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1490: $is_balancer = 0;
1491: if ($uname ne '' && $udom ne '') {
1492: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1176 raeburn 1493:
1.1331 raeburn 1494: &appenv({'user.loadbalexempt' => $lonhost,
1495: 'user.loadbalcheck.time' => time});
1496: }
1.1176 raeburn 1497: }
1.1129 raeburn 1498: }
1499: }
1500: }
1501: return ($is_balancer,$otherserver);
1502: }
1503:
1.1191 raeburn 1504: sub check_balancer_result {
1505: my ($result,@hosts) = @_;
1506: my ($is_balancer,$currtargets,$currrules);
1507: if (ref($result) eq 'HASH') {
1508: if ($result->{'lonhost'} ne '') {
1509: my $currbalancer = $result->{'lonhost'};
1510: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1511: $is_balancer = 1;
1512: $currtargets = $result->{'targets'};
1513: $currrules = $result->{'rules'};
1514: }
1515: } else {
1516: foreach my $key (keys(%{$result})) {
1517: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1518: (ref($result->{$key}) eq 'HASH')) {
1519: $is_balancer = 1;
1520: $currrules = $result->{$key}{'rules'};
1521: $currtargets = $result->{$key}{'targets'};
1522: last;
1523: }
1524: }
1525: }
1526: }
1527: return ($is_balancer,$currtargets,$currrules);
1528: }
1529:
1.1129 raeburn 1530: sub get_loadbalancer_targets {
1531: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1532: my $offloadto;
1.1175 raeburn 1533: if ($rule_in_effect eq 'none') {
1534: return [$perlvar{'lonHostID'}];
1535: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1536: $offloadto = $currtargets;
1537: } else {
1538: if ($rule_in_effect eq 'homeserver') {
1539: my $homeserver = &homeserver($uname,$udom);
1540: if ($homeserver ne 'no_host') {
1541: $offloadto = [$homeserver];
1542: }
1543: } elsif ($rule_in_effect eq 'externalbalancer') {
1544: my %domconfig =
1545: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1546: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1547: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1548: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1549: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1550: }
1551: }
1552: } else {
1.1178 raeburn 1553: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1554: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1555: if (&hostname($remotebalancer) ne '') {
1556: $offloadto = [$remotebalancer];
1557: }
1558: }
1559: } elsif (&hostname($rule_in_effect) ne '') {
1560: $offloadto = [$rule_in_effect];
1561: }
1562: }
1563: return $offloadto;
1564: }
1565:
1.1127 raeburn 1566: sub internet_dom_servers {
1567: my ($dom) = @_;
1568: my (%uniqservers,%servers);
1569: my $primaryserver = &hostname(&domain($dom,'primary'));
1570: my @machinedoms = &machine_domains($primaryserver);
1571: foreach my $mdom (@machinedoms) {
1572: my %currservers = %servers;
1573: my %server = &get_servers($mdom);
1574: %servers = (%currservers,%server);
1575: }
1576: my %by_hostname;
1577: foreach my $id (keys(%servers)) {
1578: push(@{$by_hostname{$servers{$id}}},$id);
1579: }
1580: foreach my $hostname (sort(keys(%by_hostname))) {
1581: if (@{$by_hostname{$hostname}} > 1) {
1582: my $match = 0;
1583: foreach my $id (@{$by_hostname{$hostname}}) {
1584: if (&host_domain($id) eq $dom) {
1585: $uniqservers{$id} = $hostname;
1586: $match = 1;
1587: }
1588: }
1589: unless ($match) {
1590: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1591: }
1592: } else {
1593: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1594: }
1595: }
1596: return %uniqservers;
1597: }
1598:
1.1 albertel 1599: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1600:
1.599 albertel 1601: my %homecache;
1.1 albertel 1602: sub homeserver {
1.230 stredwic 1603: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1604: my $index="$uname:$udom";
1.426 albertel 1605:
1.599 albertel 1606: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1607:
1608: my %servers = &get_servers($udom,'library');
1609: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1610: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1611: exists($badServerCache{$tryserver}));
1.841 albertel 1612:
1613: my $answer=reply("home:$udom:$uname",$tryserver);
1614: if ($answer eq 'found') {
1615: delete($badServerCache{$tryserver});
1616: return $homecache{$index}=$tryserver;
1617: } elsif ($answer eq 'no_host') {
1618: $badServerCache{$tryserver}=1;
1619: }
1.1 albertel 1620: }
1621: return 'no_host';
1.70 www 1622: }
1623:
1.1300 raeburn 1624: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1625:
1626: sub idget {
1.1300 raeburn 1627: my ($udom,$idsref,$namespace)=@_;
1.70 www 1628: my %returnhash=();
1.1300 raeburn 1629: my @ids=();
1630: if (ref($idsref) eq 'ARRAY') {
1631: @ids = @{$idsref};
1632: } else {
1633: return %returnhash;
1634: }
1635: if ($namespace eq '') {
1636: $namespace = 'ids';
1637: }
1.70 www 1638:
1.841 albertel 1639: my %servers = &get_servers($udom,'library');
1640: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1641: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1642: if ($namespace eq 'ids') {
1643: $idlist=~tr/A-Z/a-z/;
1644: }
1645: my $reply;
1646: if ($namespace eq 'ids') {
1647: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1648: } else {
1649: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1650: }
1.841 albertel 1651: my @answer=();
1652: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1653: @answer=split(/\&/,$reply);
1654: } ;
1655: my $i;
1656: for ($i=0;$i<=$#ids;$i++) {
1657: if ($answer[$i]) {
1.1299 raeburn 1658: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1659: }
1.841 albertel 1660: }
1.1300 raeburn 1661: }
1.70 www 1662: return %returnhash;
1663: }
1664:
1665: # ------------------------------------- Find the IDs behind a list of usernames
1666:
1667: sub idrget {
1668: my ($udom,@unames)=@_;
1669: my %returnhash=();
1.800 albertel 1670: foreach my $uname (@unames) {
1671: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1672: }
1.70 www 1673: return %returnhash;
1674: }
1675:
1.1300 raeburn 1676: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 1677:
1678: sub idput {
1.1300 raeburn 1679: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 1680: my %servers=();
1.1300 raeburn 1681: my %ids=();
1682: my %byid = ();
1683: if (ref($idsref) eq 'HASH') {
1684: %ids=%{$idsref};
1685: }
1686: if ($namespace eq '') {
1687: $namespace = 'ids';
1688: }
1.800 albertel 1689: foreach my $uname (keys(%ids)) {
1690: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 1691: if ($uhom eq '') {
1692: $uhom=&homeserver($uname,$udom);
1693: }
1.70 www 1694: if ($uhom ne 'no_host') {
1.800 albertel 1695: my $esc_unam=&escape($uname);
1.1300 raeburn 1696: if ($namespace eq 'ids') {
1697: my $id=&escape($ids{$uname});
1698: $id=~tr/A-Z/a-z/;
1699: my $esc_unam=&escape($uname);
1700: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 1701: } else {
1.1300 raeburn 1702: my @currids = split(/,/,$ids{$uname});
1703: foreach my $id (@currids) {
1704: $byid{$uhom}{$id} .= $uname.',';
1705: }
1706: }
1707: }
1708: }
1709: if ($namespace eq 'clickers') {
1710: foreach my $server (keys(%byid)) {
1711: if (ref($byid{$server}) eq 'HASH') {
1712: foreach my $id (keys(%{$byid{$server}})) {
1713: $byid{$server} =~ s/,$//;
1714: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
1715: }
1.70 www 1716: }
1717: }
1.191 harris41 1718: }
1.800 albertel 1719: foreach my $server (keys(%servers)) {
1.1300 raeburn 1720: $servers{$server} =~ s/\&$//;
1721: if ($namespace eq 'ids') {
1722: &critical('idput:'.$udom.':'.$servers{$server},$server);
1723: } else {
1724: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
1725: }
1.191 harris41 1726: }
1.344 www 1727: }
1728:
1.1300 raeburn 1729: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 1730:
1731: sub iddel {
1.1300 raeburn 1732: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 1733: my %result=();
1.1300 raeburn 1734: my %ids=();
1735: my %byid = ();
1736: if (ref($idshashref) eq 'HASH') {
1737: %ids=%{$idshashref};
1738: } else {
1.1231 raeburn 1739: return %result;
1740: }
1.1300 raeburn 1741: if ($namespace eq '') {
1742: $namespace = 'ids';
1743: }
1.1231 raeburn 1744: my %servers=();
1.1300 raeburn 1745: while (my ($id,$unamestr) = each(%ids)) {
1746: if ($namespace eq 'ids') {
1747: my $uhom = $uhome;
1748: if ($uhom eq '') {
1749: $uhom=&homeserver($unamestr,$udom);
1750: }
1751: if ($uhom ne 'no_host') {
1752: $servers{$uhom}.='&'.&escape($id);
1753: }
1754: } else {
1755: my @curritems = split(/,/,$ids{$id});
1756: foreach my $uname (@curritems) {
1757: my $uhom = $uhome;
1758: if ($uhom eq '') {
1759: $uhom=&homeserver($uname,$udom);
1760: }
1761: if ($uhom ne 'no_host') {
1762: $byid{$uhom}{$id} .= $uname.',';
1763: }
1764: }
1.1231 raeburn 1765: }
1.1300 raeburn 1766: }
1767: if ($namespace eq 'clickers') {
1768: foreach my $server (keys(%byid)) {
1769: if (ref($byid{$server}) eq 'HASH') {
1770: foreach my $id (keys(%{$byid{$server}})) {
1771: $byid{$server}{$id} =~ s/,$//;
1772: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
1773: }
1.1231 raeburn 1774: }
1775: }
1776: }
1777: foreach my $server (keys(%servers)) {
1.1300 raeburn 1778: $servers{$server} =~ s/\&$//;
1779: if ($namespace eq 'ids') {
1780: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1781: } elsif ($namespace eq 'clickers') {
1782: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
1783: }
1.1231 raeburn 1784: }
1785: return %result;
1786: }
1787:
1.1300 raeburn 1788: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
1789:
1790: sub updateclickers {
1791: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
1792: my %clickers;
1793: if (ref($idshashref) eq 'HASH') {
1794: %clickers=%{$idshashref};
1795: } else {
1796: return;
1797: }
1798: my $items='';
1799: foreach my $item (keys(%clickers)) {
1800: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
1801: }
1802: $items=~s/\&$//;
1803: my $request = "updateclickers:$udom:$action:$items";
1804: if ($critical) {
1805: return &critical($request,$uhome);
1806: } else {
1807: return &reply($request,$uhome);
1808: }
1809: }
1810:
1.1023 raeburn 1811: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1812: sub dump_dom {
1.1165 droeschl 1813: my ($namespace, $udom, $regexp) = @_;
1814:
1815: $udom ||= $env{'user.domain'};
1816:
1817: return () unless $udom;
1818:
1819: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1820: }
1821:
1.1023 raeburn 1822: # ------------------------------------------ get items from domain db files
1.806 raeburn 1823:
1824: sub get_dom {
1.860 raeburn 1825: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1826: return if ($udom eq 'public');
1.806 raeburn 1827: my $items='';
1828: foreach my $item (@$storearr) {
1829: $items.=&escape($item).'&';
1830: }
1831: $items=~s/\&$//;
1.860 raeburn 1832: if (!$udom) {
1833: $udom=$env{'user.domain'};
1.1267 raeburn 1834: return if ($udom eq 'public');
1.860 raeburn 1835: if (defined(&domain($udom,'primary'))) {
1836: $uhome=&domain($udom,'primary');
1837: } else {
1.874 albertel 1838: undef($uhome);
1.860 raeburn 1839: }
1840: } else {
1841: if (!$uhome) {
1842: if (defined(&domain($udom,'primary'))) {
1843: $uhome=&domain($udom,'primary');
1844: }
1845: }
1846: }
1847: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1848: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1849: my %returnhash;
1.875 albertel 1850: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1851: return %returnhash;
1852: }
1.806 raeburn 1853: my @pairs=split(/\&/,$rep);
1854: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1855: return @pairs;
1856: }
1857: my $i=0;
1858: foreach my $item (@$storearr) {
1859: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1860: $i++;
1861: }
1862: return %returnhash;
1863: } else {
1.880 banghart 1864: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1865: }
1866: }
1867:
1868: # -------------------------------------------- put items in domain db files
1869:
1870: sub put_dom {
1.860 raeburn 1871: my ($namespace,$storehash,$udom,$uhome)=@_;
1872: if (!$udom) {
1873: $udom=$env{'user.domain'};
1874: if (defined(&domain($udom,'primary'))) {
1875: $uhome=&domain($udom,'primary');
1876: } else {
1.874 albertel 1877: undef($uhome);
1.860 raeburn 1878: }
1879: } else {
1880: if (!$uhome) {
1881: if (defined(&domain($udom,'primary'))) {
1882: $uhome=&domain($udom,'primary');
1883: }
1884: }
1885: }
1886: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1887: my $items='';
1888: foreach my $item (keys(%$storehash)) {
1889: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1890: }
1891: $items=~s/\&$//;
1892: return &reply("putdom:$udom:$namespace:$items",$uhome);
1893: } else {
1.860 raeburn 1894: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1895: }
1896: }
1897:
1.1023 raeburn 1898: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1899: sub newput_dom {
1.1023 raeburn 1900: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1901: my $result;
1902: if (!$udom) {
1903: $udom=$env{'user.domain'};
1904: }
1.1023 raeburn 1905: if ($udom) {
1906: my $uname = &get_domainconfiguser($udom);
1907: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1908: }
1909: return $result;
1910: }
1911:
1.1023 raeburn 1912: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1913: sub del_dom {
1.1023 raeburn 1914: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1915: if (ref($storearr) eq 'ARRAY') {
1916: if (!$udom) {
1917: $udom=$env{'user.domain'};
1918: }
1.1023 raeburn 1919: if ($udom) {
1920: my $uname = &get_domainconfiguser($udom);
1921: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1922: }
1923: }
1924: }
1925:
1.1023 raeburn 1926: # ----------------------------------construct domainconfig user for a domain
1927: sub get_domainconfiguser {
1928: my ($udom) = @_;
1929: return $udom.'-domainconfig';
1930: }
1931:
1.837 raeburn 1932: sub retrieve_inst_usertypes {
1933: my ($udom) = @_;
1934: my (%returnhash,@order);
1.989 raeburn 1935: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1936: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1937: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1938: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1939: } else {
1940: if (defined(&domain($udom,'primary'))) {
1941: my $uhome=&domain($udom,'primary');
1942: my $rep=&reply("inst_usertypes:$udom",$uhome);
1943: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1944: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1945: return (\%returnhash,\@order);
1946: }
1947: my ($hashitems,$orderitems) = split(/:/,$rep);
1948: my @pairs=split(/\&/,$hashitems);
1949: foreach my $item (@pairs) {
1950: my ($key,$value)=split(/=/,$item,2);
1951: $key = &unescape($key);
1952: next if ($key =~ /^error: 2 /);
1953: $returnhash{$key}=&thaw_unescape($value);
1954: }
1955: my @esc_order = split(/\&/,$orderitems);
1956: foreach my $item (@esc_order) {
1957: push(@order,&unescape($item));
1958: }
1959: } else {
1.1256 raeburn 1960: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1961: }
1.1256 raeburn 1962: return (\%returnhash,\@order);
1.837 raeburn 1963: }
1964: }
1965:
1.868 raeburn 1966: sub is_domainimage {
1967: my ($url) = @_;
1.1306 raeburn 1968: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1969: if (&domain($1) ne '') {
1970: return '1';
1971: }
1972: }
1973: return;
1974: }
1975:
1.899 raeburn 1976: sub inst_directory_query {
1977: my ($srch) = @_;
1978: my $udom = $srch->{'srchdomain'};
1979: my %results;
1980: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1981: my $outcome;
1.899 raeburn 1982: if ($homeserver ne '') {
1.904 albertel 1983: my $queryid=&reply("querysend:instdirsearch:".
1984: &escape($srch->{'srchby'}).':'.
1985: &escape($srch->{'srchterm'}).':'.
1986: &escape($srch->{'srchtype'}),$homeserver);
1987: my $host=&hostname($homeserver);
1988: if ($queryid !~/^\Q$host\E\_/) {
1989: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1990: return;
1991: }
1992: my $response = &get_query_reply($queryid);
1993: my $maxtries = 5;
1994: my $tries = 1;
1995: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1996: $response = &get_query_reply($queryid);
1997: $tries ++;
1998: }
1999:
2000: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2001: if ($response eq 'unavailable') {
2002: $outcome = $response;
2003: } else {
2004: $outcome = 'ok';
2005: my @matches = split(/\n/,$response);
2006: foreach my $match (@matches) {
2007: my ($key,$value) = split(/=/,$match);
2008: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2009: }
1.899 raeburn 2010: }
2011: }
2012: }
1.909 raeburn 2013: return ($outcome,%results);
1.899 raeburn 2014: }
2015:
2016: sub usersearch {
2017: my ($srch) = @_;
2018: my $dom = $srch->{'srchdomain'};
2019: my %results;
2020: my %libserv = &all_library();
2021: my $query = 'usersearch';
2022: foreach my $tryserver (keys(%libserv)) {
2023: if (&host_domain($tryserver) eq $dom) {
2024: my $host=&hostname($tryserver);
2025: my $queryid=
1.911 raeburn 2026: &reply("querysend:".&escape($query).':'.
2027: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2028: &escape($srch->{'srchtype'}).':'.
2029: &escape($srch->{'srchterm'}),$tryserver);
2030: if ($queryid !~/^\Q$host\E\_/) {
2031: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2032: next;
1.899 raeburn 2033: }
2034: my $reply = &get_query_reply($queryid);
2035: my $maxtries = 1;
2036: my $tries = 1;
2037: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2038: $reply = &get_query_reply($queryid);
2039: $tries ++;
2040: }
2041: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2042: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2043: } else {
1.911 raeburn 2044: my @matches;
2045: if ($reply =~ /\n/) {
2046: @matches = split(/\n/,$reply);
2047: } else {
2048: @matches = split(/\&/,$reply);
2049: }
1.899 raeburn 2050: foreach my $match (@matches) {
2051: my ($uname,$udom,%userhash);
1.911 raeburn 2052: foreach my $entry (split(/:/,$match)) {
2053: my ($key,$value) =
2054: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2055: $userhash{$key} = $value;
2056: if ($key eq 'username') {
2057: $uname = $value;
2058: } elsif ($key eq 'domain') {
2059: $udom = $value;
1.911 raeburn 2060: }
1.899 raeburn 2061: }
2062: $results{$uname.':'.$udom} = \%userhash;
2063: }
2064: }
2065: }
2066: }
2067: return %results;
2068: }
2069:
1.912 raeburn 2070: sub get_instuser {
2071: my ($udom,$uname,$id) = @_;
2072: my $homeserver = &domain($udom,'primary');
2073: my ($outcome,%results);
2074: if ($homeserver ne '') {
2075: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2076: &escape($id).':'.&escape($udom),$homeserver);
2077: my $host=&hostname($homeserver);
2078: if ($queryid !~/^\Q$host\E\_/) {
2079: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2080: return;
2081: }
2082: my $response = &get_query_reply($queryid);
2083: my $maxtries = 5;
2084: my $tries = 1;
2085: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2086: $response = &get_query_reply($queryid);
2087: $tries ++;
2088: }
2089: if (!&error($response) && $response ne 'refused') {
2090: if ($response eq 'unavailable') {
2091: $outcome = $response;
2092: } else {
2093: $outcome = 'ok';
2094: my @matches = split(/\n/,$response);
2095: foreach my $match (@matches) {
2096: my ($key,$value) = split(/=/,$match);
2097: $results{&unescape($key)} = &thaw_unescape($value);
2098: }
2099: }
2100: }
2101: }
2102: my %userinfo;
2103: if (ref($results{$uname}) eq 'HASH') {
2104: %userinfo = %{$results{$uname}};
2105: }
2106: return ($outcome,%userinfo);
2107: }
2108:
1.1290 raeburn 2109: sub get_multiple_instusers {
2110: my ($udom,$users,$caller) = @_;
2111: my ($outcome,$results);
2112: if (ref($users) eq 'HASH') {
2113: my $count = keys(%{$users});
2114: my $requested = &freeze_escape($users);
2115: my $homeserver = &domain($udom,'primary');
2116: if ($homeserver ne '') {
2117: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2118: my $host=&hostname($homeserver);
2119: if ($queryid !~/^\Q$host\E\_/) {
2120: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2121: ' for host: '.$homeserver.'in domain '.$udom);
2122: return ($outcome,$results);
2123: }
2124: my $response = &get_query_reply($queryid);
2125: my $maxtries = 5;
2126: if ($count > 100) {
2127: $maxtries = 1+int($count/20);
2128: }
2129: my $tries = 1;
2130: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2131: $response = &get_query_reply($queryid);
2132: $tries ++;
2133: }
2134: if ($response eq '') {
2135: $results = {};
2136: foreach my $key (keys(%{$users})) {
2137: my ($uname,$id);
2138: if ($caller eq 'id') {
2139: $id = $key;
2140: } else {
2141: $uname = $key;
2142: }
2143: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2144: $outcome = $resp;
1.1290 raeburn 2145: if ($resp eq 'ok') {
2146: %{$results} = (%{$results}, %info);
2147: } else {
2148: last;
2149: }
2150: }
2151: } elsif(!&error($response) && ($response ne 'refused')) {
2152: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2153: $outcome = $response;
2154: } else {
1.1291 raeburn 2155: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2156: if ($outcome eq 'ok') {
2157: $results = &thaw_unescape($userdata);
2158: }
2159: }
2160: }
2161: }
2162: }
2163: return ($outcome,$results);
2164: }
2165:
1.912 raeburn 2166: sub inst_rulecheck {
1.923 raeburn 2167: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2168: my %returnhash;
2169: if ($udom ne '') {
2170: if (ref($rules) eq 'ARRAY') {
2171: @{$rules} = map {&escape($_);} (@{$rules});
2172: my $rulestr = join(':',@{$rules});
2173: my $homeserver=&domain($udom,'primary');
2174: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2175: my $response;
2176: if ($item eq 'username') {
2177: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2178: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2179: $homeserver));
1.923 raeburn 2180: } elsif ($item eq 'id') {
2181: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2182: ':'.&escape($id).':'.$rulestr,
2183: $homeserver));
1.945 raeburn 2184: } elsif ($item eq 'selfcreate') {
2185: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2186: &escape($udom).':'.&escape($uname).
2187: ':'.$rulestr,$homeserver));
1.923 raeburn 2188: }
1.912 raeburn 2189: if ($response ne 'refused') {
2190: my @pairs=split(/\&/,$response);
2191: foreach my $item (@pairs) {
2192: my ($key,$value)=split(/=/,$item,2);
2193: $key = &unescape($key);
2194: next if ($key =~ /^error: 2 /);
2195: $returnhash{$key}=&thaw_unescape($value);
2196: }
2197: }
2198: }
2199: }
2200: }
2201: return %returnhash;
2202: }
2203:
2204: sub inst_userrules {
1.923 raeburn 2205: my ($udom,$check) = @_;
1.912 raeburn 2206: my (%ruleshash,@ruleorder);
2207: if ($udom ne '') {
2208: my $homeserver=&domain($udom,'primary');
2209: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2210: my $response;
2211: if ($check eq 'id') {
2212: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2213: $homeserver);
1.943 raeburn 2214: } elsif ($check eq 'email') {
2215: $response=&reply('instemailrules:'.&escape($udom),
2216: $homeserver);
1.923 raeburn 2217: } else {
2218: $response=&reply('instuserrules:'.&escape($udom),
2219: $homeserver);
2220: }
1.912 raeburn 2221: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2222: ($response ne 'unknown_cmd') &&
1.912 raeburn 2223: ($response ne 'no_such_host')) {
2224: my ($hashitems,$orderitems) = split(/:/,$response);
2225: my @pairs=split(/\&/,$hashitems);
2226: foreach my $item (@pairs) {
2227: my ($key,$value)=split(/=/,$item,2);
2228: $key = &unescape($key);
2229: next if ($key =~ /^error: 2 /);
2230: $ruleshash{$key}=&thaw_unescape($value);
2231: }
2232: my @esc_order = split(/\&/,$orderitems);
2233: foreach my $item (@esc_order) {
2234: push(@ruleorder,&unescape($item));
2235: }
2236: }
2237: }
2238: }
2239: return (\%ruleshash,\@ruleorder);
2240: }
2241:
1.976 raeburn 2242: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2243:
2244: sub get_domain_defaults {
1.1240 raeburn 2245: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2246: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2247: my $cachetime = 60*60*24;
1.1240 raeburn 2248: unless ($ignore_cache) {
2249: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2250: if (defined($cached)) {
2251: if (ref($result) eq 'HASH') {
2252: return %{$result};
2253: }
1.943 raeburn 2254: }
2255: }
2256: my %domdefaults;
2257: my %domconfig =
1.989 raeburn 2258: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2259: 'requestcourses','inststatus',
1.1183 raeburn 2260: 'coursedefaults','usersessions',
1.1258 raeburn 2261: 'requestauthor','selfenrollment',
1.1320 raeburn 2262: 'coursecategories','ssl','autoenroll',
1.1332 raeburn 2263: 'trust','helpsettings'],$domain);
1.1305 raeburn 2264: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2265: if (ref($domconfig{'defaults'}) eq 'HASH') {
2266: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2267: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2268: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2269: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2270: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2271: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2272: } else {
2273: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2274: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2275: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2276: }
1.976 raeburn 2277: if (ref($domconfig{'quotas'}) eq 'HASH') {
2278: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2279: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2280: } else {
2281: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2282: }
1.1177 raeburn 2283: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2284: foreach my $item (@usertools) {
2285: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2286: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2287: }
2288: }
1.1229 raeburn 2289: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2290: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2291: }
1.976 raeburn 2292: }
1.985 raeburn 2293: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2294: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2295: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2296: }
2297: }
1.1183 raeburn 2298: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2299: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2300: }
1.989 raeburn 2301: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2302: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2303: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2304: }
2305: }
1.1047 raeburn 2306: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2307: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2308: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2309: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2310: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2311: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2312: }
1.1254 raeburn 2313: foreach my $type (@coursetypes) {
2314: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2315: unless ($type eq 'community') {
2316: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2317: }
2318: }
2319: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2320: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2321: }
1.1277 raeburn 2322: if ($domdefaults{'postsubmit'} eq 'on') {
2323: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2324: $domdefaults{$type.'postsubtimeout'} =
2325: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2326: }
2327: }
1.1230 raeburn 2328: }
1.1286 raeburn 2329: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2330: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2331: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2332: if (@clonecodes) {
2333: $domdefaults{'canclone'} = join('+',@clonecodes);
2334: }
2335: }
2336: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2337: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2338: }
1.1047 raeburn 2339: }
1.1073 raeburn 2340: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2341: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2342: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2343: }
2344: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2345: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2346: }
1.1279 raeburn 2347: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2348: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2349: }
1.1073 raeburn 2350: }
1.1254 raeburn 2351: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2352: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2353: my @settings = ('types','registered','enroll_dates','access_dates','section',
2354: 'approval','limit');
2355: foreach my $type (@coursetypes) {
2356: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2357: my @mgrdc = ();
2358: foreach my $item (@settings) {
2359: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2360: push(@mgrdc,$item);
2361: }
2362: }
2363: if (@mgrdc) {
2364: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2365: }
2366: }
2367: }
2368: }
2369: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2370: foreach my $type (@coursetypes) {
2371: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2372: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2373: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2374: }
2375: }
2376: }
2377: }
2378: }
1.1258 raeburn 2379: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2380: $domdefaults{'catauth'} = 'std';
2381: $domdefaults{'catunauth'} = 'std';
2382: if ($domconfig{'coursecategories'}{'auth'}) {
2383: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2384: }
2385: if ($domconfig{'coursecategories'}{'unauth'}) {
2386: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2387: }
2388: }
1.1315 raeburn 2389: if (ref($domconfig{'ssl'}) eq 'HASH') {
2390: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2391: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2392: }
2393: if (ref($domconfig{'ssl'}{'connect'}) eq 'HASH') {
2394: $domdefaults{'connect'} = $domconfig{'ssl'}{'connect'};
2395: }
2396: }
1.1320 raeburn 2397: if (ref($domconfig{'trust'}) eq 'HASH') {
2398: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2399: foreach my $prefix (@prefixes) {
2400: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2401: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2402: }
2403: }
2404: }
1.1314 raeburn 2405: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2406: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2407: }
1.1332 raeburn 2408: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2409: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2410: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2411: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2412: }
2413: }
1.1219 raeburn 2414: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2415: return %domdefaults;
2416: }
2417:
1.1311 raeburn 2418: sub course_portal_url {
2419: my ($cnum,$cdom) = @_;
2420: my $chome = &homeserver($cnum,$cdom);
2421: my $hostname = &hostname($chome);
2422: my $protocol = $protocol{$chome};
2423: $protocol = 'http' if ($protocol ne 'https');
2424: my %domdefaults = &get_domain_defaults($cdom);
2425: my $firsturl;
2426: if ($domdefaults{'portal_def'}) {
2427: $firsturl = $domdefaults{'portal_def'};
2428: } else {
2429: $firsturl = $protocol.'://'.$hostname;
2430: }
2431: return $firsturl;
2432: }
2433:
1.344 www 2434: # --------------------------------------------------- Assign a key to a student
2435:
2436: sub assign_access_key {
1.364 www 2437: #
2438: # a valid key looks like uname:udom#comments
2439: # comments are being appended
2440: #
1.498 www 2441: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2442: $kdom=
1.620 albertel 2443: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2444: $knum=
1.620 albertel 2445: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2446: $cdom=
1.620 albertel 2447: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2448: $cnum=
1.620 albertel 2449: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2450: $udom=$env{'user.name'} unless (defined($udom));
2451: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2452: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2453: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2454: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2455: # assigned to this person
2456: # - this should not happen,
1.345 www 2457: # unless something went wrong
2458: # the first time around
2459: # ready to assign
1.364 www 2460: $logentry=$1.'; '.$logentry;
1.496 www 2461: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2462: $kdom,$knum) eq 'ok') {
1.345 www 2463: # key now belongs to user
1.346 www 2464: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2465: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2466: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2467: return 'ok';
2468: } else {
2469: return
2470: 'error: Count not permanently assign key, will need to be re-entered later.';
2471: }
2472: } else {
2473: return 'error: Could not assign key, try again later.';
2474: }
1.364 www 2475: } elsif (!$existing{$ckey}) {
1.345 www 2476: # the key does not exist
2477: return 'error: The key does not exist';
2478: } else {
2479: # the key is somebody else's
2480: return 'error: The key is already in use';
2481: }
1.344 www 2482: }
2483:
1.364 www 2484: # ------------------------------------------ put an additional comment on a key
2485:
2486: sub comment_access_key {
2487: #
2488: # a valid key looks like uname:udom#comments
2489: # comments are being appended
2490: #
2491: my ($ckey,$cdom,$cnum,$logentry)=@_;
2492: $cdom=
1.620 albertel 2493: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2494: $cnum=
1.620 albertel 2495: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2496: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2497: if ($existing{$ckey}) {
2498: $existing{$ckey}.='; '.$logentry;
2499: # ready to assign
1.367 www 2500: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2501: $cdom,$cnum) eq 'ok') {
2502: return 'ok';
2503: } else {
2504: return 'error: Count not store comment.';
2505: }
2506: } else {
2507: # the key does not exist
2508: return 'error: The key does not exist';
2509: }
2510: }
2511:
1.344 www 2512: # ------------------------------------------------------ Generate a set of keys
2513:
2514: sub generate_access_keys {
1.364 www 2515: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2516: $cdom=
1.620 albertel 2517: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2518: $cnum=
1.620 albertel 2519: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2520: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2521: unless (($cdom) && ($cnum)) { return 0; }
2522: if ($number>10000) { return 0; }
2523: sleep(2); # make sure don't get same seed twice
2524: srand(time()^($$+($$<<15))); # from "Programming Perl"
2525: my $total=0;
2526: for (my $i=1;$i<=$number;$i++) {
2527: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2528: sprintf("%lx",int(100000*rand)).'-'.
2529: sprintf("%lx",int(100000*rand));
2530: $newkey=~s/1/g/g; # folks mix up 1 and l
2531: $newkey=~s/0/h/g; # and also 0 and O
2532: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2533: if ($existing{$newkey}) {
2534: $i--;
2535: } else {
1.364 www 2536: if (&put('accesskeys',
2537: { $newkey => '# generated '.localtime().
1.620 albertel 2538: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2539: '; '.$logentry },
2540: $cdom,$cnum) eq 'ok') {
1.344 www 2541: $total++;
2542: }
2543: }
2544: }
1.620 albertel 2545: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2546: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2547: return $total;
2548: }
2549:
2550: # ------------------------------------------------------- Validate an accesskey
2551:
2552: sub validate_access_key {
2553: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2554: $cdom=
1.620 albertel 2555: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2556: $cnum=
1.620 albertel 2557: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2558: $udom=$env{'user.domain'} unless (defined($udom));
2559: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2560: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2561: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2562: }
2563:
2564: # ------------------------------------- Find the section of student in a course
1.652 albertel 2565: sub devalidate_getsection_cache {
2566: my ($udom,$unam,$courseid)=@_;
2567: my $hashid="$udom:$unam:$courseid";
2568: &devalidate_cache_new('getsection',$hashid);
2569: }
1.298 matthew 2570:
1.815 albertel 2571: sub courseid_to_courseurl {
2572: my ($courseid) = @_;
2573: #already url style courseid
2574: return $courseid if ($courseid =~ m{^/});
2575:
2576: if (exists($env{'course.'.$courseid.'.num'})) {
2577: my $cnum = $env{'course.'.$courseid.'.num'};
2578: my $cdom = $env{'course.'.$courseid.'.domain'};
2579: return "/$cdom/$cnum";
2580: }
2581:
2582: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2583: if (exists($courseinfo{'num'})) {
2584: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2585: }
2586:
2587: return undef;
2588: }
2589:
1.298 matthew 2590: sub getsection {
2591: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2592: my $cachetime=1800;
1.551 albertel 2593:
2594: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2595: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2596: if (defined($cached)) { return $result; }
2597:
1.298 matthew 2598: my %Pending;
2599: my %Expired;
2600: #
2601: # Each role can either have not started yet (pending), be active,
2602: # or have expired.
2603: #
2604: # If there is an active role, we are done.
2605: #
2606: # If there is more than one role which has not started yet,
2607: # choose the one which will start sooner
2608: # If there is one role which has not started yet, return it.
2609: #
2610: # If there is more than one expired role, choose the one which ended last.
2611: # If there is a role which has expired, return it.
2612: #
1.815 albertel 2613: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2614: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2615: foreach my $key (keys(%roleshash)) {
1.479 albertel 2616: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2617: my $section=$1;
2618: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2619: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2620: my $now=time;
1.548 albertel 2621: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2622: $Expired{$end}=$section;
2623: next;
2624: }
1.548 albertel 2625: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2626: $Pending{$start}=$section;
2627: next;
2628: }
1.599 albertel 2629: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2630: }
2631: #
2632: # Presumedly there will be few matching roles from the above
2633: # loop and the sorting time will be negligible.
2634: if (scalar(keys(%Pending))) {
2635: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2636: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2637: }
2638: if (scalar(keys(%Expired))) {
2639: my @sorted = sort {$a <=> $b} keys(%Expired);
2640: my $time = pop(@sorted);
1.599 albertel 2641: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2642: }
1.599 albertel 2643: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2644: }
1.70 www 2645:
1.599 albertel 2646: sub save_cache {
2647: &purge_remembered();
1.722 albertel 2648: #&Apache::loncommon::validate_page();
1.620 albertel 2649: undef(%env);
1.780 albertel 2650: undef($env_loaded);
1.599 albertel 2651: }
1.452 albertel 2652:
1.599 albertel 2653: my $to_remember=-1;
2654: my %remembered;
2655: my %accessed;
2656: my $kicks=0;
2657: my $hits=0;
1.849 albertel 2658: sub make_key {
2659: my ($name,$id) = @_;
1.872 albertel 2660: if (length($id) > 65
2661: && length(&escape($id)) > 200) {
2662: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2663: }
1.849 albertel 2664: return &escape($name.':'.$id);
2665: }
2666:
1.599 albertel 2667: sub devalidate_cache_new {
2668: my ($name,$id,$debug) = @_;
2669: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 2670: my $remembered_id=$name.':'.$id;
1.849 albertel 2671: $id=&make_key($name,$id);
1.599 albertel 2672: $memcache->delete($id);
1.1319 damieng 2673: delete($remembered{$remembered_id});
2674: delete($accessed{$remembered_id});
1.599 albertel 2675: }
2676:
2677: sub is_cached_new {
2678: my ($name,$id,$debug) = @_;
1.1319 damieng 2679: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
2680: if (exists($remembered{$remembered_id})) {
2681: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2682: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2683: $hits++;
1.1319 damieng 2684: return ($remembered{$remembered_id},1);
1.599 albertel 2685: }
1.1319 damieng 2686: $id=&make_key($name,$id);
1.599 albertel 2687: my $value = $memcache->get($id);
2688: if (!(defined($value))) {
2689: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2690: return (undef,undef);
1.416 albertel 2691: }
1.599 albertel 2692: if ($value eq '__undef__') {
2693: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2694: $value=undef;
2695: }
1.1319 damieng 2696: &make_room($remembered_id,$value,$debug);
1.599 albertel 2697: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2698: return ($value,1);
2699: }
2700:
2701: sub do_cache_new {
2702: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 2703: my $remembered_id=$name.':'.$id;
1.849 albertel 2704: $id=&make_key($name,$id);
1.599 albertel 2705: my $setvalue=$value;
2706: if (!defined($setvalue)) {
2707: $setvalue='__undef__';
2708: }
1.623 albertel 2709: if (!defined($time) ) {
2710: $time=600;
2711: }
1.599 albertel 2712: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2713: my $result = $memcache->set($id,$setvalue,$time);
2714: if (! $result) {
1.872 albertel 2715: &logthis("caching of id -> $id failed");
1.910 albertel 2716: $memcache->disconnect_all();
1.872 albertel 2717: }
1.600 albertel 2718: # need to make a copy of $value
1.1319 damieng 2719: &make_room($remembered_id,$value,$debug);
1.599 albertel 2720: return $value;
2721: }
2722:
2723: sub make_room {
1.1319 damieng 2724: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2725:
1.1319 damieng 2726: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2727: : $value;
1.599 albertel 2728: if ($to_remember<0) { return; }
1.1319 damieng 2729: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2730: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2731: my $to_kick;
2732: my $max_time=0;
2733: foreach my $other (keys(%accessed)) {
2734: if (&tv_interval($accessed{$other}) > $max_time) {
2735: $to_kick=$other;
2736: $max_time=&tv_interval($accessed{$other});
2737: }
2738: }
2739: delete($remembered{$to_kick});
2740: delete($accessed{$to_kick});
2741: $kicks++;
2742: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2743: return;
2744: }
2745:
1.599 albertel 2746: sub purge_remembered {
1.604 albertel 2747: #&logthis("Tossing ".scalar(keys(%remembered)));
2748: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2749: undef(%remembered);
2750: undef(%accessed);
1.428 albertel 2751: }
1.70 www 2752: # ------------------------------------- Read an entry from a user's environment
2753:
2754: sub userenvironment {
2755: my ($udom,$unam,@what)=@_;
1.976 raeburn 2756: my $items;
2757: foreach my $item (@what) {
2758: $items.=&escape($item).'&';
2759: }
2760: $items=~s/\&$//;
1.70 www 2761: my %returnhash=();
1.1009 raeburn 2762: my $uhome = &homeserver($unam,$udom);
2763: unless ($uhome eq 'no_host') {
2764: my @answer=split(/\&/,
2765: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2766: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2767: return %returnhash;
2768: }
1.1009 raeburn 2769: my $i;
2770: for ($i=0;$i<=$#what;$i++) {
2771: $returnhash{$what[$i]}=&unescape($answer[$i]);
2772: }
1.70 www 2773: }
2774: return %returnhash;
1.1 albertel 2775: }
2776:
1.617 albertel 2777: # ---------------------------------------------------------- Get a studentphoto
2778: sub studentphoto {
2779: my ($udom,$unam,$ext) = @_;
2780: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2781: if (defined($env{'request.course.id'})) {
1.708 raeburn 2782: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2783: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2784: return(&retrievestudentphoto($udom,$unam,$ext));
2785: } else {
2786: my ($result,$perm_reqd)=
1.707 albertel 2787: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2788: if ($result eq 'ok') {
2789: if (!($perm_reqd eq 'yes')) {
2790: return(&retrievestudentphoto($udom,$unam,$ext));
2791: }
2792: }
2793: }
2794: }
2795: } else {
2796: my ($result,$perm_reqd) =
1.707 albertel 2797: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2798: if ($result eq 'ok') {
2799: if (!($perm_reqd eq 'yes')) {
2800: return(&retrievestudentphoto($udom,$unam,$ext));
2801: }
2802: }
2803: }
2804: return '/adm/lonKaputt/lonlogo_broken.gif';
2805: }
2806:
2807: sub retrievestudentphoto {
2808: my ($udom,$unam,$ext,$type) = @_;
2809: my $home=&Apache::lonnet::homeserver($unam,$udom);
2810: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2811: if ($ret eq 'ok') {
2812: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2813: if ($type eq 'thumbnail') {
2814: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2815: }
2816: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2817: return $tokenurl;
2818: } else {
2819: if ($type eq 'thumbnail') {
2820: return '/adm/lonKaputt/genericstudent_tn.gif';
2821: } else {
2822: return '/adm/lonKaputt/lonlogo_broken.gif';
2823: }
1.617 albertel 2824: }
2825: }
2826:
1.263 www 2827: # -------------------------------------------------------------------- New chat
2828:
2829: sub chatsend {
1.724 raeburn 2830: my ($newentry,$anon,$group)=@_;
1.620 albertel 2831: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2832: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2833: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2834: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2835: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2836: &escape($newentry)).':'.$group,$chome);
1.292 www 2837: }
2838:
2839: # ------------------------------------------ Find current version of a resource
2840:
2841: sub getversion {
2842: my $fname=&clutter(shift);
1.1189 raeburn 2843: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2844: return ¤tversion(&filelocation('',$fname));
2845: }
2846:
2847: sub currentversion {
2848: my $fname=shift;
2849: my $author=$fname;
2850: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2851: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2852: my $home=&homeserver($uname,$udom);
1.292 www 2853: if ($home eq 'no_host') {
2854: return -1;
2855: }
1.1112 www 2856: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2857: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2858: return -1;
2859: }
1.1112 www 2860: return $answer;
1.263 www 2861: }
2862:
1.1111 www 2863: #
2864: # Return special version number of resource if set by override, empty otherwise
2865: #
2866: sub usedversion {
2867: my $fname=shift;
2868: unless ($fname) { $fname=$env{'request.uri'}; }
2869: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2870: if ($urlversion) { return $urlversion; }
2871: return '';
2872: }
2873:
1.1 albertel 2874: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2875:
1.1 albertel 2876: sub subscribe {
2877: my $fname=shift;
1.761 raeburn 2878: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2879: $fname=~s/[\n\r]//g;
1.1 albertel 2880: my $author=$fname;
2881: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2882: my ($udom,$uname)=split(/\//,$author);
2883: my $home=homeserver($uname,$udom);
1.335 albertel 2884: if ($home eq 'no_host') {
2885: return 'not_found';
1.1 albertel 2886: }
2887: my $answer=reply("sub:$fname",$home);
1.64 www 2888: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2889: $answer.=' by '.$home;
2890: }
1.1 albertel 2891: return $answer;
2892: }
2893:
1.8 www 2894: # -------------------------------------------------------------- Replicate file
2895:
2896: sub repcopy {
2897: my $filename=shift;
1.23 www 2898: $filename=~s/\/+/\//g;
1.1142 raeburn 2899: my $londocroot = $perlvar{'lonDocRoot'};
2900: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2901: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2902: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2903: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2904: return &repcopy_userfile($filename);
2905: }
1.532 albertel 2906: $filename=~s/[\n\r]//g;
1.8 www 2907: my $transname="$filename.in.transfer";
1.828 www 2908: # FIXME: this should flock
1.607 raeburn 2909: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2910: my $remoteurl=subscribe($filename);
1.64 www 2911: if ($remoteurl =~ /^con_lost by/) {
2912: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2913: return 'unavailable';
1.8 www 2914: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2915: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2916: return 'not_found';
1.64 www 2917: } elsif ($remoteurl =~ /^rejected by/) {
2918: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2919: return 'forbidden';
1.20 www 2920: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2921: return 'ok';
1.8 www 2922: } else {
1.290 www 2923: my $author=$filename;
2924: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2925: my ($udom,$uname)=split(/\//,$author);
2926: my $home=homeserver($uname,$udom);
2927: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2928: my @parts=split(/\//,$filename);
2929: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2930: if ($path ne "$londocroot/res") {
1.8 www 2931: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2932: return 'bad_request';
1.8 www 2933: }
2934: my $count;
2935: for ($count=5;$count<$#parts;$count++) {
2936: $path.="/$parts[$count]";
2937: if ((-e $path)!=1) {
2938: mkdir($path,0777);
2939: }
2940: }
2941: my $ua=new LWP::UserAgent;
2942: my $request=new HTTP::Request('GET',"$remoteurl");
2943: my $response=$ua->request($request,$transname);
2944: if ($response->is_error()) {
2945: unlink($transname);
2946: my $message=$response->status_line;
1.672 albertel 2947: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2948: ." LWP get: $message: $filename</font>");
1.607 raeburn 2949: return 'unavailable';
1.8 www 2950: } else {
1.16 www 2951: if ($remoteurl!~/\.meta$/) {
2952: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2953: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2954: if ($mresponse->is_error()) {
2955: unlink($filename.'.meta');
2956: &logthis(
1.672 albertel 2957: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2958: }
2959: }
1.8 www 2960: rename($transname,$filename);
1.607 raeburn 2961: return 'ok';
1.8 www 2962: }
1.290 www 2963: }
1.8 www 2964: }
1.330 www 2965: }
2966:
2967: # ------------------------------------------------ Get server side include body
2968: sub ssi_body {
1.381 albertel 2969: my ($filelink,%form)=@_;
1.606 matthew 2970: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2971: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2972: }
1.953 www 2973: my $output='';
2974: my $response;
1.980 raeburn 2975: if ($filelink=~/^https?\:/) {
1.954 raeburn 2976: ($output,$response)=&externalssi($filelink);
1.953 www 2977: } else {
1.1004 droeschl 2978: $filelink .= $filelink=~/\?/ ? '&' : '?';
2979: $filelink .= 'inhibitmenu=yes';
1.953 www 2980: ($output,$response)=&ssi($filelink,%form);
2981: }
1.778 albertel 2982: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2983: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2984: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2985: if (wantarray) {
2986: return ($output, $response);
2987: } else {
2988: return $output;
2989: }
1.8 www 2990: }
2991:
1.15 www 2992: # --------------------------------------------------------- Server Side Include
2993:
1.782 albertel 2994: sub absolute_url {
2995: my ($host_name) = @_;
2996: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2997: if ($host_name eq '') {
2998: $host_name = $ENV{'SERVER_NAME'};
2999: }
3000: return $protocol.$host_name;
3001: }
3002:
1.942 foxr 3003: #
3004: # Server side include.
3005: # Parameters:
3006: # fn Possibly encrypted resource name/id.
3007: # form Hash that describes how the rendering should be done
3008: # and other things.
1.944 foxr 3009: # Returns:
1.950 raeburn 3010: # Scalar context: The content of the response.
3011: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3012: #
1.15 www 3013: sub ssi {
3014:
1.944 foxr 3015: my ($fn,%form)=@_;
1.15 www 3016: my $ua=new LWP::UserAgent;
1.23 www 3017: my $request;
1.711 albertel 3018:
3019: $form{'no_update_last_known'}=1;
1.895 albertel 3020: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3021: if (%form) {
1.782 albertel 3022: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 3023: $request->content(join('&',map {
3024: my $name = escape($_);
3025: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3026: ? join("&$name=", map {escape($_) } @{$form{$_}})
3027: : &escape($form{$_}) );
3028: } keys(%form)));
1.23 www 3029: } else {
1.782 albertel 3030: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3031: }
3032:
1.15 www 3033: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 3034: my $response= $ua->request($request);
1.1182 foxr 3035: my $content = $response->content;
3036:
3037:
1.944 foxr 3038: if (wantarray) {
1.1173 foxr 3039: return ($content, $response);
1.944 foxr 3040: } else {
1.1173 foxr 3041: return $content;
1.942 foxr 3042: }
1.324 www 3043: }
3044:
3045: sub externalssi {
3046: my ($url)=@_;
3047: my $ua=new LWP::UserAgent;
3048: my $request=new HTTP::Request('GET',$url);
3049: my $response=$ua->request($request);
1.954 raeburn 3050: if (wantarray) {
3051: return ($response->content, $response);
3052: } else {
3053: return $response->content;
3054: }
1.15 www 3055: }
1.254 www 3056:
1.492 albertel 3057: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3058:
3059: sub allowuploaded {
3060: my ($srcurl,$url)=@_;
3061: $url=&clutter(&declutter($url));
3062: my $dir=$url;
3063: $dir=~s/\/[^\/]+$//;
3064: my %httpref=();
3065: my $httpurl=&hreflocation('',$url);
3066: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3067: &Apache::lonnet::appenv(\%httpref);
1.254 www 3068: }
1.477 raeburn 3069:
1.1193 raeburn 3070: #
3071: # Determine if the current user should be able to edit a particular resource,
3072: # when viewing in course context.
3073: # (a) When viewing resource used to determine if "Edit" item is included in
3074: # Functions.
3075: # (b) When displaying folder contents in course editor, used to determine if
3076: # "Edit" link will be displayed alongside resource.
3077: #
1.1196 raeburn 3078: # input: six args -- filename (decluttered), course number, course domain,
3079: # url, symb (if registered) and group (if this is a group
3080: # item -- e.g., bulletin board, group page etc.).
3081: # output: array of five scalars --
1.1193 raeburn 3082: # $cfile -- url for file editing if editable on current server
3083: # $home -- homeserver of resource (i.e., for author if published,
3084: # or course if uploaded.).
3085: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3086: # $forceedit -- 1 if icon/link should be to go to edit mode
3087: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3088: #
3089:
3090: sub can_edit_resource {
1.1194 raeburn 3091: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3092: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3093: #
3094: # For aboutme pages user can only edit his/her own.
3095: #
1.1199 raeburn 3096: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3097: my ($sdom,$sname) = ($1,$2);
3098: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3099: $home = $env{'user.home'};
3100: $cfile = $resurl;
3101: if ($env{'form.forceedit'}) {
3102: $forceview = 1;
3103: } else {
3104: $forceedit = 1;
3105: }
3106: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3107: } else {
3108: return;
3109: }
3110: }
3111:
3112: if ($env{'request.course.id'}) {
3113: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3114: if ($group ne '') {
3115: # if this is a group homepage or group bulletin board, check group privs
3116: my $allowed = 0;
1.1197 raeburn 3117: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3118: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3119: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3120: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3121: $allowed = 1;
3122: }
1.1197 raeburn 3123: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3124: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3125: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3126: $allowed = 1;
3127: }
3128: }
3129: if ($allowed) {
3130: $home=&homeserver($cnum,$cdom);
3131: if ($env{'form.forceedit'}) {
3132: $forceview = 1;
3133: } else {
3134: $forceedit = 1;
3135: }
3136: $cfile = $resurl;
3137: } else {
3138: return;
3139: }
3140: } else {
1.1208 raeburn 3141: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3142: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3143: return;
3144: }
3145: } elsif (!$crsedit) {
1.1194 raeburn 3146: #
3147: # No edit allowed where CC has switched to student role.
3148: #
3149: return;
3150: }
3151: }
3152: }
3153:
1.1193 raeburn 3154: if ($file ne '') {
3155: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3156: if (&is_course_upload($file,$cnum,$cdom)) {
3157: $uploaded = 1;
3158: $incourse = 1;
1.1193 raeburn 3159: if ($file =~/\.(htm|html|css|js|txt)$/) {
3160: $cfile = &hreflocation('',$file);
1.1201 raeburn 3161: if ($env{'form.forceedit'}) {
3162: $forceview = 1;
3163: } else {
3164: $forceedit = 1;
3165: }
1.1194 raeburn 3166: }
3167: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3168: $incourse = 1;
3169: if ($env{'form.forceedit'}) {
3170: $forceview = 1;
3171: } else {
3172: $forceedit = 1;
3173: }
3174: $cfile = $resurl;
3175: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3176: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3177: $incourse = 1;
3178: if ($env{'form.forceedit'}) {
3179: $forceview = 1;
3180: } else {
3181: $forceedit = 1;
3182: }
3183: $cfile = $resurl;
1.1199 raeburn 3184: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3185: $incourse = 1;
3186: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3187: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3188: $incourse = 1;
1.1199 raeburn 3189: if ($env{'form.forceedit'}) {
3190: $forceview = 1;
3191: } else {
3192: $forceedit = 1;
3193: }
3194: $cfile = $resurl;
1.1298 raeburn 3195: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
3196: $incourse = 1;
3197: if ($env{'form.forceedit'}) {
3198: $forceview = 1;
3199: } else {
3200: $forceedit = 1;
3201: }
3202: $cfile = $resurl;
1.1208 raeburn 3203: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3204: $incourse = 1;
3205: if ($env{'form.forceedit'}) {
3206: $forceview = 1;
3207: } else {
3208: $forceedit = 1;
3209: }
3210: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3211: }
3212: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3213: my $template = '/res/lib/templates/simpleproblem.problem';
3214: if (&is_on_map($template)) {
3215: $incourse = 1;
3216: $forceview = 1;
3217: $cfile = $template;
1.1193 raeburn 3218: }
1.1199 raeburn 3219: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3220: $incourse = 1;
3221: if ($env{'form.forceedit'}) {
3222: $forceview = 1;
3223: } else {
3224: $forceedit = 1;
3225: }
3226: $cfile = $resurl;
1.1298 raeburn 3227: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3228: $incourse = 1;
3229: if ($env{'form.forceedit'}) {
3230: $forceview = 1;
3231: } else {
3232: $forceedit = 1;
3233: }
3234: $cfile = $resurl;
1.1199 raeburn 3235: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3236: $incourse = 1;
3237: $forceview = 1;
3238: if ($symb) {
3239: my ($map,$id,$res)=&decode_symb($symb);
3240: $env{'request.symb'} = $symb;
3241: $cfile = &clutter($res);
3242: } else {
3243: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3244: my $escfile = &unescape($cfile);
3245: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
3246: $cfile = '/adm/wrapper'.$escfile;
3247: } else {
3248: $escfile =~ s{^http://}{};
3249: $cfile = &escape("/adm/wrapper/ext/$escfile");
3250: }
1.1199 raeburn 3251: }
1.1234 raeburn 3252: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3253: if ($env{'form.forceedit'}) {
3254: $forceview = 1;
3255: } else {
3256: $forceedit = 1;
3257: }
3258: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3259: }
3260: }
1.1194 raeburn 3261: if ($uploaded || $incourse) {
3262: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3263: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3264: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3265: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3266: # Check that the user has permission to edit this resource
3267: my $setpriv = 1;
3268: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3269: if (defined($cfudom)) {
3270: $home=&homeserver($cfuname,$cfudom);
3271: $cfile=$file;
3272: }
3273: }
1.1194 raeburn 3274: if (($cfile ne '') && (!$incourse || $uploaded) &&
3275: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3276: my @ids=¤t_machine_ids();
3277: unless (grep(/^\Q$home\E$/,@ids)) {
3278: $switchserver=1;
3279: }
3280: }
3281: }
1.1194 raeburn 3282: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3283: }
3284:
3285: sub is_course_upload {
3286: my ($file,$cnum,$cdom) = @_;
3287: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3288: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3289: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3290: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3291: return 1;
3292: }
3293: return;
3294: }
3295:
1.1194 raeburn 3296: sub in_course {
1.1195 raeburn 3297: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3298: if ($hideprivileged) {
3299: my $skipuser;
1.1219 raeburn 3300: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3301: my @possdoms = ($cdom);
3302: if ($coursehash{'checkforpriv'}) {
3303: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3304: }
3305: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3306: $skipuser = 1;
3307: if ($coursehash{'nothideprivileged'}) {
3308: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3309: my $user;
3310: if ($item =~ /:/) {
3311: $user = $item;
3312: } else {
3313: $user = join(':',split(/[\@]/,$item));
3314: }
3315: if ($user eq $uname.':'.$udom) {
3316: undef($skipuser);
3317: last;
3318: }
3319: }
3320: }
3321: if ($skipuser) {
3322: return 0;
3323: }
3324: }
3325: }
1.1194 raeburn 3326: $type ||= 'any';
3327: if (!defined($cdom) || !defined($cnum)) {
3328: my $cid = $env{'request.course.id'};
3329: $cdom = $env{'course.'.$cid.'.domain'};
3330: $cnum = $env{'course.'.$cid.'.num'};
3331: }
3332: my $typesref;
1.1195 raeburn 3333: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3334: $typesref = ['active','previous','future'];
3335: } elsif ($type eq 'previous' || $type eq 'future') {
3336: $typesref = [$type];
3337: }
3338: my %roles = &get_my_roles($uname,$udom,'userroles',
3339: $typesref,undef,[$cdom]);
3340: my ($tmp) = keys(%roles);
3341: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3342: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3343: if (@course_roles > 0) {
3344: return 1;
3345: }
3346: return 0;
3347: }
3348:
1.478 albertel 3349: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3350: # input: action, courseID, current domain, intended
1.637 raeburn 3351: # path to file, source of file, instruction to parse file for objects,
3352: # ref to hash for embedded objects,
3353: # ref to hash for codebase of java objects.
1.1095 raeburn 3354: # reference to scalar to accommodate mime type determined
3355: # from File::MMagic if $parser = parse.
1.637 raeburn 3356: #
1.485 raeburn 3357: # output: url to file (if action was uploaddoc),
3358: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3359: #
1.478 albertel 3360: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3361: # course.
1.477 raeburn 3362: #
1.478 albertel 3363: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3364: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3365: # course's home server.
1.477 raeburn 3366: #
1.478 albertel 3367: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3368: # be copied from $source (current location) to
3369: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3370: # and will then be copied to
3371: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3372: # course's home server.
1.485 raeburn 3373: #
1.481 raeburn 3374: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3375: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3376: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3377: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3378: # in course's home server.
1.637 raeburn 3379: #
1.477 raeburn 3380:
3381: sub process_coursefile {
1.1095 raeburn 3382: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3383: $mimetype)=@_;
1.477 raeburn 3384: my $fetchresult;
1.638 albertel 3385: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3386: if ($action eq 'propagate') {
1.638 albertel 3387: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3388: $home);
1.481 raeburn 3389: } else {
1.477 raeburn 3390: my $fpath = '';
3391: my $fname = $file;
1.478 albertel 3392: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3393: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3394: my $filepath = &build_filepath($fpath);
1.481 raeburn 3395: if ($action eq 'copy') {
3396: if ($source eq '') {
3397: $fetchresult = 'no source file';
3398: return $fetchresult;
3399: } else {
3400: my $destination = $filepath.'/'.$fname;
3401: rename($source,$destination);
3402: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3403: $home);
1.481 raeburn 3404: }
3405: } elsif ($action eq 'uploaddoc') {
3406: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3407: print $fh $env{'form.'.$source};
1.481 raeburn 3408: close($fh);
1.637 raeburn 3409: if ($parser eq 'parse') {
1.1024 raeburn 3410: my $mm = new File::MMagic;
1.1095 raeburn 3411: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3412: if ($type eq 'text/html') {
1.1024 raeburn 3413: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3414: unless ($parse_result eq 'ok') {
3415: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3416: }
1.637 raeburn 3417: }
1.1095 raeburn 3418: if (ref($mimetype)) {
3419: $$mimetype = $type;
3420: }
1.637 raeburn 3421: }
1.477 raeburn 3422: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3423: $home);
1.481 raeburn 3424: if ($fetchresult eq 'ok') {
3425: return '/uploaded/'.$fpath.'/'.$fname;
3426: } else {
3427: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3428: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3429: return '/adm/notfound.html';
3430: }
1.477 raeburn 3431: }
3432: }
1.485 raeburn 3433: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3434: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3435: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3436: }
3437: return $fetchresult;
3438: }
3439:
1.637 raeburn 3440: sub build_filepath {
3441: my ($fpath) = @_;
3442: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3443: unless ($fpath eq '') {
3444: my @parts=split('/',$fpath);
3445: foreach my $part (@parts) {
3446: $filepath.= '/'.$part;
3447: if ((-e $filepath)!=1) {
3448: mkdir($filepath,0777);
3449: }
3450: }
3451: }
3452: return $filepath;
3453: }
3454:
3455: sub store_edited_file {
1.638 albertel 3456: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3457: my $file = $primary_url;
3458: $file =~ s#^/uploaded/$docudom/$docuname/##;
3459: my $fpath = '';
3460: my $fname = $file;
3461: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3462: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3463: my $filepath = &build_filepath($fpath);
3464: open(my $fh,'>'.$filepath.'/'.$fname);
3465: print $fh $content;
3466: close($fh);
1.638 albertel 3467: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3468: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3469: $home);
1.637 raeburn 3470: if ($$fetchresult eq 'ok') {
3471: return '/uploaded/'.$fpath.'/'.$fname;
3472: } else {
1.638 albertel 3473: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3474: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3475: return '/adm/notfound.html';
3476: }
3477: }
3478:
1.531 albertel 3479: sub clean_filename {
1.831 albertel 3480: my ($fname,$args)=@_;
1.315 www 3481: # Replace Windows backslashes by forward slashes
1.257 www 3482: $fname=~s/\\/\//g;
1.831 albertel 3483: if (!$args->{'keep_path'}) {
3484: # Get rid of everything but the actual filename
3485: $fname=~s/^.*\/([^\/]+)$/$1/;
3486: }
1.315 www 3487: # Replace spaces by underscores
3488: $fname=~s/\s+/\_/g;
3489: # Replace all other weird characters by nothing
1.831 albertel 3490: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3491: # Replace all .\d. sequences with _\d. so they no longer look like version
3492: # numbers
3493: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3494: return $fname;
3495: }
1.1051 raeburn 3496: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3497: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3498: # image with the same aspect ratio as the original, but with dimensions which do
3499: # not exceed $resizewidth and $resizeheight.
3500:
1.984 neumanie 3501: sub resizeImage {
1.1051 raeburn 3502: my ($img_path,$resizewidth,$resizeheight) = @_;
3503: my $ima = Image::Magick->new;
3504: my $resized;
3505: if (-e $img_path) {
3506: $ima->Read($img_path);
3507: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3508: my $width = $ima->Get('width');
3509: my $height = $ima->Get('height');
3510: if ($width > $resizewidth) {
3511: my $factor = $width/$resizewidth;
3512: my $newheight = $height/$factor;
3513: $ima->Scale(width=>$resizewidth,height=>$newheight);
3514: $resized = 1;
3515: }
3516: }
3517: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3518: my $width = $ima->Get('width');
3519: my $height = $ima->Get('height');
3520: if ($height > $resizeheight) {
3521: my $factor = $height/$resizeheight;
3522: my $newwidth = $width/$factor;
3523: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3524: $resized = 1;
3525: }
3526: }
3527: if ($resized) {
3528: $ima->Write($img_path);
3529: }
3530: }
3531: return;
1.977 amueller 3532: }
3533:
1.608 albertel 3534: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3535: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3536: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3537: # $context - possible values: coursedoc, existingfile, overwrite,
3538: # canceloverwrite, or ''.
3539: # if 'coursedoc': upload to the current course
3540: # if 'existingfile': write file to tmp/overwrites directory
3541: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3542: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3543: # $subdir - directory in userfile to store the file into
1.858 raeburn 3544: # $parser - instruction to parse file for objects ($parser = parse)
3545: # $allfiles - reference to hash for embedded objects
3546: # $codebase - reference to hash for codebase of java objects
3547: # $desuname - username for permanent storage of uploaded file
3548: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3549: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3550: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3551: # $resizewidth - width (pixels) to which to resize uploaded image
3552: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3553: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3554: # from File::MMagic.
1.858 raeburn 3555: #
1.686 albertel 3556: # output: url of file in userspace, or error: <message>
3557: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3558:
1.531 albertel 3559: sub userfileupload {
1.1090 raeburn 3560: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3561: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3562: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3563: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3564: $fname=&clean_filename($fname);
1.1090 raeburn 3565: # See if there is anything left
1.257 www 3566: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3567: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3568: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3569: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3570: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3571: my $now = time;
1.1090 raeburn 3572: my $filepath;
1.1095 raeburn 3573: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3574: $filepath = 'tmp/helprequests/'.$now;
3575: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3576: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3577: '_'.$env{'user.domain'}.'/pending';
3578: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3579: my ($docuname,$docudom);
3580: if ($destudom) {
3581: $docudom = $destudom;
3582: } else {
3583: $docudom = $env{'user.domain'};
3584: }
3585: if ($destuname) {
3586: $docuname = $destuname;
3587: } else {
3588: $docuname = $env{'user.name'};
3589: }
3590: if (exists($env{'form.group'})) {
3591: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3592: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3593: }
3594: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3595: if ($context eq 'canceloverwrite') {
3596: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3597: if (-e $tempfile) {
3598: my @info = stat($tempfile);
3599: if ($info[9] eq $env{'form.timestamp'}) {
3600: unlink($tempfile);
3601: }
3602: }
3603: return;
1.523 raeburn 3604: }
3605: }
1.1090 raeburn 3606: # Create the directory if not present
1.741 raeburn 3607: my @parts=split(/\//,$filepath);
3608: my $fullpath = $perlvar{'lonDaemons'};
3609: for (my $i=0;$i<@parts;$i++) {
3610: $fullpath .= '/'.$parts[$i];
3611: if ((-e $fullpath)!=1) {
3612: mkdir($fullpath,0777);
3613: }
3614: }
3615: open(my $fh,'>'.$fullpath.'/'.$fname);
3616: print $fh $env{'form.'.$formname};
3617: close($fh);
1.1090 raeburn 3618: if ($context eq 'existingfile') {
3619: my @info = stat($fullpath.'/'.$fname);
3620: return ($fullpath.'/'.$fname,$info[9]);
3621: } else {
3622: return $fullpath.'/'.$fname;
3623: }
1.523 raeburn 3624: }
1.995 raeburn 3625: if ($subdir eq 'scantron') {
3626: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3627: } else {
1.995 raeburn 3628: $fname="$subdir/$fname";
3629: }
1.1090 raeburn 3630: if ($context eq 'coursedoc') {
1.638 albertel 3631: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3632: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3633: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3634: return &finishuserfileupload($docuname,$docudom,
3635: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3636: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3637: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3638: } else {
1.1218 raeburn 3639: if ($env{'form.folder'}) {
3640: $fname=$env{'form.folder'}.'/'.$fname;
3641: }
1.638 albertel 3642: return &process_coursefile('uploaddoc',$docuname,$docudom,
3643: $fname,$formname,$parser,
1.1095 raeburn 3644: $allfiles,$codebase,$mimetype);
1.481 raeburn 3645: }
1.719 banghart 3646: } elsif (defined($destuname)) {
3647: my $docuname=$destuname;
3648: my $docudom=$destudom;
1.860 raeburn 3649: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3650: $parser,$allfiles,$codebase,
1.1051 raeburn 3651: $thumbwidth,$thumbheight,
1.1095 raeburn 3652: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3653: } else {
1.638 albertel 3654: my $docuname=$env{'user.name'};
3655: my $docudom=$env{'user.domain'};
1.1220 raeburn 3656: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3657: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3658: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3659: }
1.860 raeburn 3660: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3661: $parser,$allfiles,$codebase,
1.1051 raeburn 3662: $thumbwidth,$thumbheight,
1.1095 raeburn 3663: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3664: }
1.271 www 3665: }
3666:
3667: sub finishuserfileupload {
1.860 raeburn 3668: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3669: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3670: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3671: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3672:
1.860 raeburn 3673: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3674: $file=$fname;
3675: if ($fname=~m|/|) {
3676: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3677: $path.=$fnamepath.'/';
3678: }
1.259 www 3679: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3680: my $count;
3681: for ($count=4;$count<=$#parts;$count++) {
3682: $filepath.="/$parts[$count]";
3683: if ((-e $filepath)!=1) {
3684: mkdir($filepath,0777);
3685: }
3686: }
1.984 neumanie 3687:
1.258 www 3688: # Save the file
3689: {
1.701 albertel 3690: if (!open(FH,'>'.$filepath.'/'.$file)) {
3691: &logthis('Failed to create '.$filepath.'/'.$file);
3692: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3693: return '/adm/notfound.html';
3694: }
1.1090 raeburn 3695: if ($context eq 'overwrite') {
1.1117 foxr 3696: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3697: my $target = $filepath.'/'.$file;
3698: if (-e $source) {
3699: my @info = stat($source);
3700: if ($info[9] eq $env{'form.timestamp'}) {
3701: unless (&File::Copy::move($source,$target)) {
3702: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3703: return "Moving from $source failed";
3704: }
3705: } else {
3706: return "Temporary file: $source had unexpected date/time for last modification";
3707: }
3708: } else {
3709: return "Temporary file: $source missing";
3710: }
3711: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3712: &logthis('Failed to write to '.$filepath.'/'.$file);
3713: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3714: return '/adm/notfound.html';
3715: }
1.570 albertel 3716: close(FH);
1.1051 raeburn 3717: if ($resizewidth && $resizeheight) {
3718: my $mm = new File::MMagic;
3719: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3720: if ($mime_type =~ m{^image/}) {
3721: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3722: }
1.977 amueller 3723: }
1.258 www 3724: }
1.1152 raeburn 3725: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3726: if (ref($mimetype)) {
3727: if ($$mimetype eq '') {
3728: my $mm = new File::MMagic;
3729: my $type = $mm->checktype_filename($filepath.'/'.$file);
3730: $$mimetype = $type;
3731: }
3732: }
3733: }
1.637 raeburn 3734: if ($parser eq 'parse') {
1.1152 raeburn 3735: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3736: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3737: $allfiles,$codebase);
3738: unless ($parse_result eq 'ok') {
3739: &logthis('Failed to parse '.$filepath.$file.
3740: ' for embedded media: '.$parse_result);
3741: }
1.637 raeburn 3742: }
3743: }
1.860 raeburn 3744: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3745: my $input = $filepath.'/'.$file;
3746: my $output = $filepath.'/'.'tn-'.$file;
3747: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3748: system("convert -sample $thumbsize $input $output");
3749: if (-e $filepath.'/'.'tn-'.$file) {
3750: $fetchthumb = 1;
3751: }
3752: }
1.858 raeburn 3753:
1.259 www 3754: # Notify homeserver to grep it
3755: #
1.984 neumanie 3756: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3757: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3758: if ($fetchresult eq 'ok') {
1.860 raeburn 3759: if ($fetchthumb) {
3760: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3761: if ($thumbresult ne 'ok') {
3762: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3763: $docuhome.': '.$thumbresult);
3764: }
3765: }
1.259 www 3766: #
1.258 www 3767: # Return the URL to it
1.494 albertel 3768: return '/uploaded/'.$path.$file;
1.263 www 3769: } else {
1.494 albertel 3770: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3771: ': '.$fetchresult);
1.263 www 3772: return '/adm/notfound.html';
1.858 raeburn 3773: }
1.493 albertel 3774: }
3775:
1.637 raeburn 3776: sub extract_embedded_items {
1.961 raeburn 3777: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3778: my @state = ();
1.1164 raeburn 3779: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3780: my %javafiles = (
3781: codebase => '',
3782: code => '',
3783: archive => ''
3784: );
3785: my %mediafiles = (
3786: src => '',
3787: movie => '',
3788: );
1.648 raeburn 3789: my $p;
3790: if ($content) {
3791: $p = HTML::LCParser->new($content);
3792: } else {
1.961 raeburn 3793: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3794: }
1.641 albertel 3795: while (my $t=$p->get_token()) {
1.640 albertel 3796: if ($t->[0] eq 'S') {
3797: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3798: push(@state, $tagname);
1.648 raeburn 3799: if (lc($tagname) eq 'allow') {
3800: &add_filetype($allfiles,$attr->{'src'},'src');
3801: }
1.640 albertel 3802: if (lc($tagname) eq 'img') {
3803: &add_filetype($allfiles,$attr->{'src'},'src');
3804: }
1.886 albertel 3805: if (lc($tagname) eq 'a') {
1.1222 raeburn 3806: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3807: &add_filetype($allfiles,$attr->{'href'},'href');
3808: }
1.886 albertel 3809: }
1.645 raeburn 3810: if (lc($tagname) eq 'script') {
1.1164 raeburn 3811: my $src;
1.645 raeburn 3812: if ($attr->{'archive'} =~ /\.jar$/i) {
3813: &add_filetype($allfiles,$attr->{'archive'},'archive');
3814: } else {
1.1164 raeburn 3815: if ($attr->{'src'} ne '') {
3816: $src = $attr->{'src'};
3817: &add_filetype($allfiles,$src,'src');
3818: }
3819: }
3820: my $text = $p->get_trimmed_text();
3821: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3822: my @swfargs = split(/,/,$1);
3823: foreach my $item (@swfargs) {
3824: $item =~ s/["']//g;
3825: $item =~ s/^\s+//;
3826: $item =~ s/\s+$//;
3827: }
3828: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3829: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3830: push(@{$related{$swfargs[0]}},$swfargs[2]);
3831: } else {
3832: $related{$swfargs[0]} = [$swfargs[2]];
3833: }
3834: }
1.645 raeburn 3835: }
3836: }
3837: if (lc($tagname) eq 'link') {
3838: if (lc($attr->{'rel'}) eq 'stylesheet') {
3839: &add_filetype($allfiles,$attr->{'href'},'href');
3840: }
3841: }
1.640 albertel 3842: if (lc($tagname) eq 'object' ||
3843: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3844: foreach my $item (keys(%javafiles)) {
3845: $javafiles{$item} = '';
3846: }
1.1164 raeburn 3847: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3848: $lastids{lc($tagname)} = $attr->{'id'};
3849: }
1.640 albertel 3850: }
3851: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3852: my $name = lc($attr->{'name'});
3853: foreach my $item (keys(%javafiles)) {
3854: if ($name eq $item) {
3855: $javafiles{$item} = $attr->{'value'};
3856: last;
3857: }
3858: }
1.1164 raeburn 3859: my $pathfrom;
1.640 albertel 3860: foreach my $item (keys(%mediafiles)) {
3861: if ($name eq $item) {
1.1164 raeburn 3862: $pathfrom = $attr->{'value'};
3863: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3864: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3865: last;
3866: }
3867: }
1.1164 raeburn 3868: if ($name eq 'flashvars') {
3869: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3870: }
3871: if ($pathfrom ne '') {
3872: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3873: $pathfrom);
3874: }
1.640 albertel 3875: }
3876: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3877: foreach my $item (keys(%javafiles)) {
3878: if ($attr->{$item}) {
3879: $javafiles{$item} = $attr->{$item};
3880: last;
3881: }
3882: }
3883: foreach my $item (keys(%mediafiles)) {
3884: if ($attr->{$item}) {
3885: &add_filetype($allfiles,$attr->{$item},$item);
3886: last;
3887: }
3888: }
1.1164 raeburn 3889: if (lc($tagname) eq 'embed') {
3890: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3891: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3892: $attr->{'src'});
3893: }
3894: }
1.640 albertel 3895: }
1.1243 raeburn 3896: if (lc($tagname) eq 'iframe') {
3897: my $src = $attr->{'src'} ;
3898: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3899: &add_filetype($allfiles,$src,'src');
3900: } elsif ($src =~ m{^/}) {
3901: if ($env{'request.course.id'}) {
3902: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3903: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3904: my $url = &hreflocation('',$fullpath);
3905: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3906: my $relpath = $1;
3907: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3908: &add_filetype($allfiles,$1,'src');
3909: }
3910: }
3911: }
3912: }
3913: }
1.1164 raeburn 3914: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3915: pop(@state);
1.1164 raeburn 3916: }
1.640 albertel 3917: } elsif ($t->[0] eq 'E') {
3918: my ($tagname) = ($t->[1]);
3919: if ($javafiles{'codebase'} ne '') {
3920: $javafiles{'codebase'} .= '/';
3921: }
3922: if (lc($tagname) eq 'applet' ||
3923: lc($tagname) eq 'object' ||
3924: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3925: ) {
3926: foreach my $item (keys(%javafiles)) {
3927: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3928: my $file=$javafiles{'codebase'}.$javafiles{$item};
3929: &add_filetype($allfiles,$file,$item);
3930: }
3931: }
3932: }
3933: pop @state;
3934: }
3935: }
1.1164 raeburn 3936: foreach my $id (sort(keys(%flashvars))) {
3937: if ($shockwave{$id} ne '') {
3938: my @pairs = split(/\&/,$flashvars{$id});
3939: foreach my $pair (@pairs) {
3940: my ($key,$value) = split(/\=/,$pair);
3941: if ($key eq 'thumb') {
3942: &add_filetype($allfiles,$value,$key);
3943: } elsif ($key eq 'content') {
3944: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3945: my ($ext) = ($value =~ /\.([^.]+)$/);
3946: if ($ext ne '') {
3947: &add_filetype($allfiles,$path.$value,$ext);
3948: }
3949: }
3950: }
3951: }
3952: }
1.637 raeburn 3953: return 'ok';
3954: }
3955:
1.639 albertel 3956: sub add_filetype {
3957: my ($allfiles,$file,$type)=@_;
3958: if (exists($allfiles->{$file})) {
3959: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3960: push(@{$allfiles->{$file}}, &escape($type));
3961: }
3962: } else {
3963: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3964: }
3965: }
3966:
1.1164 raeburn 3967: sub embedded_dependency {
3968: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3969: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3970: if (($identifier ne '') &&
3971: (ref($related->{$identifier}) eq 'ARRAY') &&
3972: ($pathfrom ne '')) {
3973: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3974: foreach my $dep (@{$related->{$identifier}}) {
3975: &add_filetype($allfiles,$path.$dep,'object');
3976: }
3977: }
3978: }
3979: return;
3980: }
3981:
1.493 albertel 3982: sub removeuploadedurl {
1.984 neumanie 3983: my ($url)=@_;
3984: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3985: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3986: }
3987:
3988: sub removeuserfile {
3989: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3990: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3991: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3992: if ($result eq 'ok') {
1.798 raeburn 3993: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3994: my $metafile = $fname.'.meta';
3995: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3996: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3997: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3998: my $sqlresult =
1.823 albertel 3999: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4000: 'portfolio_metadata',$group,
4001: 'delete');
1.798 raeburn 4002: }
4003: }
4004: return $result;
1.257 www 4005: }
1.15 www 4006:
1.530 albertel 4007: sub mkdiruserfile {
4008: my ($docuname,$docudom,$dir)=@_;
4009: my $home=&homeserver($docuname,$docudom);
4010: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4011: }
4012:
1.531 albertel 4013: sub renameuserfile {
4014: my ($docuname,$docudom,$old,$new)=@_;
4015: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4016: my $result = &reply("renameuserfile:$docudom:$docuname:".
4017: &escape("$old").':'.&escape("$new"),$home);
4018: if ($result eq 'ok') {
4019: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4020: my $oldmeta = $old.'.meta';
4021: my $newmeta = $new.'.meta';
4022: my $metaresult =
4023: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4024: my $url = "/uploaded/$docudom/$docuname/$old";
4025: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4026: my $sqlresult =
1.823 albertel 4027: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4028: 'portfolio_metadata',$group,
4029: 'delete');
1.798 raeburn 4030: }
4031: }
4032: return $result;
1.531 albertel 4033: }
4034:
1.14 www 4035: # ------------------------------------------------------------------------- Log
4036:
4037: sub log {
4038: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4039: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4040: }
4041:
4042: # ------------------------------------------------------------------ Course Log
1.352 www 4043: #
4044: # This routine flushes several buffers of non-mission-critical nature
4045: #
1.157 www 4046:
4047: sub flushcourselogs {
1.352 www 4048: &logthis('Flushing log buffers');
4049: #
4050: # course logs
4051: # This is a log of all transactions in a course, which can be used
4052: # for data mining purposes
4053: #
4054: # It also collects the courseid database, which lists last transaction
4055: # times and course titles for all courseids
4056: #
4057: my %courseidbuffer=();
1.921 raeburn 4058: foreach my $crsid (keys(%courselogs)) {
1.352 www 4059: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4060: &escape($courselogs{$crsid}),
4061: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4062: delete $courselogs{$crsid};
4063: } else {
4064: &logthis('Failed to flush log buffer for '.$crsid);
4065: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4066: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4067: " exceeded maximum size, deleting.</font>");
4068: delete $courselogs{$crsid};
4069: }
1.352 www 4070: }
1.920 raeburn 4071: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4072: 'description' => $coursedescrbuf{$crsid},
4073: 'inst_code' => $courseinstcodebuf{$crsid},
4074: 'type' => $coursetypebuf{$crsid},
4075: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4076: };
1.191 harris41 4077: }
1.352 www 4078: #
4079: # Write course id database (reverse lookup) to homeserver of courses
4080: # Is used in pickcourse
4081: #
1.840 albertel 4082: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4083: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4084: $courseidbuffer{$crs_home},
4085: $crs_home,'timeonly');
1.352 www 4086: }
4087: #
4088: # File accesses
4089: # Writes to the dynamic metadata of resources to get hit counts, etc.
4090: #
1.449 matthew 4091: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4092: if ($entry =~ /___count$/) {
4093: my ($dom,$name);
1.807 albertel 4094: ($dom,$name,undef)=
1.811 albertel 4095: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4096: if (! defined($dom) || $dom eq '' ||
4097: ! defined($name) || $name eq '') {
1.620 albertel 4098: my $cid = $env{'request.course.id'};
4099: $dom = $env{'request.'.$cid.'.domain'};
4100: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4101: }
1.450 matthew 4102: my $value = $accesshash{$entry};
4103: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4104: my %temphash=($url => $value);
1.449 matthew 4105: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4106: if ($result eq 'ok') {
4107: delete $accesshash{$entry};
4108: }
4109: } else {
1.811 albertel 4110: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4111: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4112: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4113: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4114: delete $accesshash{$entry};
4115: }
1.185 www 4116: }
1.191 harris41 4117: }
1.352 www 4118: #
4119: # Roles
4120: # Reverse lookup of user roles for course faculty/staff and co-authorship
4121: #
1.800 albertel 4122: foreach my $entry (keys(%userrolehash)) {
1.351 www 4123: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4124: split(/\:/,$entry);
4125: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4126: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4127: $rudom,$runame) eq 'ok') {
4128: delete $userrolehash{$entry};
4129: }
4130: }
1.662 raeburn 4131: #
1.1334 raeburn 4132: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4133: #
4134: my %domrolebuffer = ();
1.1000 raeburn 4135: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4136: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4137: if ($domrolebuffer{$rudom}) {
4138: $domrolebuffer{$rudom}.='&'.&escape($entry).
4139: '='.&escape($domainrolehash{$entry});
4140: } else {
4141: $domrolebuffer{$rudom}.=&escape($entry).
4142: '='.&escape($domainrolehash{$entry});
4143: }
4144: delete $domainrolehash{$entry};
4145: }
4146: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 4147: my %servers;
4148: if (defined(&domain($dom,'primary'))) {
4149: my $primary=&domain($dom,'primary');
4150: my $hostname=&hostname($primary);
4151: $servers{$primary} = $hostname;
4152: } else {
4153: %servers = &get_servers($dom,'library');
4154: }
1.841 albertel 4155: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 4156: if (&reply('domroleput:'.$dom.':'.
4157: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4158: last;
4159: } else {
1.841 albertel 4160: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4161: }
1.662 raeburn 4162: }
4163: }
1.186 www 4164: $dumpcount++;
1.157 www 4165: }
4166:
4167: sub courselog {
4168: my $what=shift;
1.158 www 4169: $what=time.':'.$what;
1.620 albertel 4170: unless ($env{'request.course.id'}) { return ''; }
4171: $coursedombuf{$env{'request.course.id'}}=
4172: $env{'course.'.$env{'request.course.id'}.'.domain'};
4173: $coursenumbuf{$env{'request.course.id'}}=
4174: $env{'course.'.$env{'request.course.id'}.'.num'};
4175: $coursehombuf{$env{'request.course.id'}}=
4176: $env{'course.'.$env{'request.course.id'}.'.home'};
4177: $coursedescrbuf{$env{'request.course.id'}}=
4178: $env{'course.'.$env{'request.course.id'}.'.description'};
4179: $courseinstcodebuf{$env{'request.course.id'}}=
4180: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4181: $courseownerbuf{$env{'request.course.id'}}=
4182: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4183: $coursetypebuf{$env{'request.course.id'}}=
4184: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4185: if (defined $courselogs{$env{'request.course.id'}}) {
4186: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4187: } else {
1.620 albertel 4188: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4189: }
1.620 albertel 4190: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4191: &flushcourselogs();
4192: }
1.158 www 4193: }
4194:
4195: sub courseacclog {
4196: my $fnsymb=shift;
1.620 albertel 4197: unless ($env{'request.course.id'}) { return ''; }
4198: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4199: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4200: $what.=':POST';
1.583 matthew 4201: # FIXME: Probably ought to escape things....
1.800 albertel 4202: foreach my $key (keys(%env)) {
4203: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4204: my $formitem = $1;
4205: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4206: $what.=':'.$formitem.'='.$env{$key};
4207: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4208: $what.=':'.$formitem.'='.$env{$key};
4209: }
1.158 www 4210: }
1.191 harris41 4211: }
1.583 matthew 4212: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4213: # FIXME: We should not be depending on a form parameter that someone
4214: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4215: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4216: $what.= ':POST';
4217: # FIXME: Probably ought to escape things....
4218: foreach my $element ('courseexp','crsfulltext','crsrelated',
4219: 'crsdiscuss') {
1.620 albertel 4220: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4221: }
4222: }
1.158 www 4223: }
4224: &courselog($what);
1.149 www 4225: }
4226:
1.185 www 4227: sub countacc {
4228: my $url=&declutter(shift);
1.458 matthew 4229: return if (! defined($url) || $url eq '');
1.620 albertel 4230: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4231: #
4232: # Mark that this url was used in this course
4233: #
1.620 albertel 4234: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4235: #
4236: # Increase the access count for this resource in this child process
4237: #
1.281 www 4238: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4239: $accesshash{$key}++;
1.185 www 4240: }
1.349 www 4241:
1.361 www 4242: sub linklog {
4243: my ($from,$to)=@_;
4244: $from=&declutter($from);
4245: $to=&declutter($to);
4246: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4247: $accesshash{$to.'___'.$from.'___goto'}=1;
4248: }
1.1160 www 4249:
4250: sub statslog {
4251: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4252: if ($users<2) { return; }
4253: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4254: 'course' => $env{'request.course.id'},
4255: 'sections' => '"all"',
4256: 'num_students' => $users,
4257: 'part' => $part,
4258: 'symb' => $symb,
4259: 'mean_tries' => $av_attempts,
4260: 'deg_of_diff' => $degdiff});
4261: foreach my $key (keys(%dynstore)) {
4262: $accesshash{$key}=$dynstore{$key};
4263: }
4264: }
1.361 www 4265:
1.349 www 4266: sub userrolelog {
4267: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4268: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4269: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4270: $userrolehash
4271: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4272: =$tend.':'.$tstart;
1.662 raeburn 4273: }
1.1169 droeschl 4274: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4275: $userrolehash
4276: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4277: =$tend.':'.$tstart;
4278: }
1.1334 raeburn 4279: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4280: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4281: $domainrolehash
4282: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4283: = $tend.':'.$tstart;
4284: }
1.351 www 4285: }
4286:
1.957 raeburn 4287: sub courserolelog {
4288: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 4289: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4290: my $cdom = $1;
4291: my $cnum = $2;
4292: my $sec = $3;
4293: my $namespace = 'rolelog';
4294: my %storehash = (
4295: role => $trole,
4296: start => $tstart,
4297: end => $tend,
4298: selfenroll => $selfenroll,
4299: context => $context,
4300: );
4301: if ($trole eq 'gr') {
4302: $namespace = 'groupslog';
4303: $storehash{'group'} = $sec;
4304: } else {
4305: $storehash{'section'} = $sec;
4306: }
1.1188 raeburn 4307: &write_log('course',$namespace,\%storehash,$delflag,$username,
4308: $domain,$cnum,$cdom);
1.1184 raeburn 4309: if (($trole ne 'st') || ($sec ne '')) {
4310: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4311: }
4312: }
4313: return;
4314: }
4315:
1.1184 raeburn 4316: sub domainrolelog {
4317: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4318: if ($area =~ m{^/($match_domain)/$}) {
4319: my $cdom = $1;
4320: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4321: my $namespace = 'rolelog';
4322: my %storehash = (
4323: role => $trole,
4324: start => $tstart,
4325: end => $tend,
4326: context => $context,
4327: );
1.1188 raeburn 4328: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4329: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4330: }
4331: return;
4332:
4333: }
4334:
4335: sub coauthorrolelog {
4336: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4337: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4338: my $audom = $1;
4339: my $auname = $2;
4340: my $namespace = 'rolelog';
4341: my %storehash = (
4342: role => $trole,
4343: start => $tstart,
4344: end => $tend,
4345: context => $context,
4346: );
1.1188 raeburn 4347: &write_log('author',$namespace,\%storehash,$delflag,$username,
4348: $domain,$auname,$audom);
1.1184 raeburn 4349: }
4350: return;
4351: }
4352:
1.351 www 4353: sub get_course_adv_roles {
1.948 raeburn 4354: my ($cid,$codes) = @_;
1.620 albertel 4355: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4356: my %coursehash=&coursedescription($cid);
1.988 raeburn 4357: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4358: my %nothide=();
1.800 albertel 4359: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4360: if ($user !~ /:/) {
4361: $nothide{join(':',split(/[\@]/,$user))}=1;
4362: } else {
4363: $nothide{$user}=1;
4364: }
1.470 www 4365: }
1.1219 raeburn 4366: my @possdoms = ($coursehash{'domain'});
4367: if ($coursehash{'checkforpriv'}) {
4368: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4369: }
1.351 www 4370: my %returnhash=();
4371: my %dumphash=
4372: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4373: my $now=time;
1.997 raeburn 4374: my %privileged;
1.1000 raeburn 4375: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4376: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4377: if (($tstart) && ($tstart<0)) { next; }
4378: if (($tend) && ($tend<$now)) { next; }
4379: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4380: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4381: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4382: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4383: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4384: if ($role eq 'cr') { next; }
1.948 raeburn 4385: if ($codes) {
4386: if ($section) { $role .= ':'.$section; }
4387: if ($returnhash{$role}) {
4388: $returnhash{$role}.=','.$username.':'.$domain;
4389: } else {
4390: $returnhash{$role}=$username.':'.$domain;
4391: }
1.351 www 4392: } else {
1.988 raeburn 4393: my $key=&plaintext($role,$crstype);
1.973 bisitz 4394: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4395: if ($returnhash{$key}) {
4396: $returnhash{$key}.=','.$username.':'.$domain;
4397: } else {
4398: $returnhash{$key}=$username.':'.$domain;
4399: }
1.351 www 4400: }
1.948 raeburn 4401: }
1.400 www 4402: return %returnhash;
4403: }
4404:
4405: sub get_my_roles {
1.937 raeburn 4406: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4407: unless (defined($uname)) { $uname=$env{'user.name'}; }
4408: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4409: my (%dumphash,%nothide);
1.1086 raeburn 4410: if ($context eq 'userroles') {
1.1166 raeburn 4411: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4412: } else {
1.1219 raeburn 4413: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4414: if ($hidepriv) {
4415: my %coursehash=&coursedescription($udom.'_'.$uname);
4416: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4417: if ($user !~ /:/) {
4418: $nothide{join(':',split(/[\@]/,$user))} = 1;
4419: } else {
4420: $nothide{$user} = 1;
4421: }
4422: }
4423: }
1.858 raeburn 4424: }
1.400 www 4425: my %returnhash=();
4426: my $now=time;
1.999 raeburn 4427: my %privileged;
1.800 albertel 4428: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4429: my ($role,$tend,$tstart);
4430: if ($context eq 'userroles') {
1.1149 raeburn 4431: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4432: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4433: } else {
4434: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4435: }
1.400 www 4436: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4437: my $status = 'active';
1.939 raeburn 4438: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4439: $status = 'previous';
4440: }
4441: if (($tstart) && ($now<$tstart)) {
4442: $status = 'future';
4443: }
4444: if (ref($types) eq 'ARRAY') {
4445: if (!grep(/^\Q$status\E$/,@{$types})) {
4446: next;
4447: }
4448: } else {
4449: if ($status ne 'active') {
4450: next;
4451: }
4452: }
1.867 raeburn 4453: my ($rolecode,$username,$domain,$section,$area);
4454: if ($context eq 'userroles') {
1.1186 raeburn 4455: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4456: (undef,$domain,$username,$section) = split(/\//,$area);
4457: } else {
4458: ($role,$username,$domain,$section) = split(/\:/,$entry);
4459: }
1.832 raeburn 4460: if (ref($roledoms) eq 'ARRAY') {
4461: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4462: next;
4463: }
4464: }
4465: if (ref($roles) eq 'ARRAY') {
4466: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4467: if ($role =~ /^cr\//) {
4468: if (!grep(/^cr$/,@{$roles})) {
4469: next;
4470: }
1.1104 raeburn 4471: } elsif ($role =~ /^gr\//) {
4472: if (!grep(/^gr$/,@{$roles})) {
4473: next;
4474: }
1.922 raeburn 4475: } else {
4476: next;
4477: }
1.832 raeburn 4478: }
1.867 raeburn 4479: }
1.937 raeburn 4480: if ($hidepriv) {
1.1219 raeburn 4481: my @privroles = ('dc','su');
1.999 raeburn 4482: if ($context eq 'userroles') {
1.1219 raeburn 4483: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4484: } else {
1.1219 raeburn 4485: my $possdoms = [$domain];
4486: if (ref($roledoms) eq 'ARRAY') {
4487: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4488: }
1.1219 raeburn 4489: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4490: if (!$nothide{$username.':'.$domain}) {
4491: next;
4492: }
4493: }
1.937 raeburn 4494: }
4495: }
1.933 raeburn 4496: if ($withsec) {
4497: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4498: $tstart.':'.$tend;
4499: } else {
4500: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4501: }
1.832 raeburn 4502: }
1.373 www 4503: return %returnhash;
1.399 www 4504: }
4505:
1.1333 raeburn 4506: sub get_all_adhocroles {
4507: my ($dom) = @_;
4508: my @roles_by_num = ();
4509: my %domdefaults = &get_domain_defaults($dom);
4510: my (%description,%access_in_dom,%access_info);
4511: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4512: my $count = 0;
4513: my %domcurrent = %{$domdefaults{'adhocroles'}};
4514: my %ordered;
4515: foreach my $role (sort(keys(%domcurrent))) {
4516: my ($order,$desc,$access_in_dom);
4517: if (ref($domcurrent{$role}) eq 'HASH') {
4518: $order = $domcurrent{$role}{'order'};
4519: $desc = $domcurrent{$role}{'desc'};
4520: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4521: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4522: }
4523: if ($order eq '') {
4524: $order = $count;
4525: }
4526: $ordered{$order} = $role;
4527: if ($desc ne '') {
4528: $description{$role} = $desc;
4529: } else {
4530: $description{$role}= $role;
4531: }
4532: $count++;
4533: }
4534: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4535: push(@roles_by_num,$ordered{$item});
4536: }
4537: }
4538: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4539: }
4540:
1.1332 raeburn 4541: sub get_my_adhocroles {
1.1333 raeburn 4542: my ($cid,$checkreg) = @_;
4543: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4544: if ($env{'request.course.id'} eq $cid) {
4545: $cdom = $env{'course.'.$cid.'.domain'};
4546: $cnum = $env{'course.'.$cid.'.num'};
4547: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4548: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4549: $cdom = $1;
4550: $cnum = $2;
4551: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4552: $cdom,$cnum);
4553: }
4554: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4555: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4556: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4557: if ($rosterhash{$user} ne '') {
4558: my $type = (split(/:/,$rosterhash{$user}))[5];
4559: return ([],{}) if ($type eq 'auto');
4560: }
4561: }
4562: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 4563: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 4564: my $then=$env{'user.login.time'};
4565: my $update=$env{'user.update.time'};
1.1335 raeburn 4566: if (!$update) {
4567: $update = $then;
4568: }
4569: my @liveroles;
1.1334 raeburn 4570: foreach my $role ('dh','da') {
4571: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 4572: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 4573: my $limit = $update;
4574: if ($env{'request.role'} eq "$role./$cdom/") {
4575: $limit = $then;
4576: }
1.1335 raeburn 4577: my $activerole = 1;
4578: if ($tstart && $tstart>$limit) { $activerole = 0; }
4579: if ($tend && $tend <$limit) { $activerole = 0; }
4580: if ($activerole) {
4581: push(@liveroles,$role);
4582: }
1.1334 raeburn 4583: }
1.1332 raeburn 4584: }
1.1335 raeburn 4585: if (@liveroles) {
1.1332 raeburn 4586: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 4587: my ($accessref,$accessinfo,%access_in_dom);
4588: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
4589: if (ref($roles_by_num) eq 'ARRAY') {
4590: if (@{$roles_by_num}) {
1.1332 raeburn 4591: my %settings;
4592: if ($env{'request.course.id'} eq $cid) {
4593: foreach my $envkey (keys(%env)) {
4594: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
4595: $settings{$1} = $env{$envkey};
4596: }
4597: }
4598: } else {
4599: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
4600: }
4601: my %setincrs;
4602: if ($settings{'internal.adhocaccess'}) {
4603: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
4604: }
4605: my @statuses;
4606: if ($env{'environment.inststatus'}) {
4607: @statuses = split(/,/,$env{'environment.inststatus'});
4608: }
4609: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 4610: if (ref($accessref) eq 'HASH') {
4611: %access_in_dom = %{$accessref};
4612: }
4613: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 4614: my ($curraccess,@okstatus,@personnel);
4615: if ($setincrs{$role}) {
4616: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
4617: if ($curraccess eq 'status') {
4618: @okstatus = split(/\&/,$rest);
4619: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4620: @personnel = split(/\&/,$rest);
4621: }
4622: } else {
4623: $curraccess = $access_in_dom{$role};
1.1333 raeburn 4624: if (ref($accessinfo) eq 'HASH') {
4625: if ($curraccess eq 'status') {
4626: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4627: @okstatus = @{$accessinfo->{$role}};
4628: }
4629: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4630: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4631: @personnel = @{$accessinfo->{$role}};
4632: }
1.1332 raeburn 4633: }
4634: }
4635: }
4636: if ($curraccess eq 'none') {
4637: next;
4638: } elsif ($curraccess eq 'all') {
4639: push(@possroles,$role);
1.1336 raeburn 4640: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 4641: if (grep(/^dh$/,@liveroles)) {
4642: push(@possroles,$role);
4643: } else {
4644: next;
4645: }
1.1336 raeburn 4646: } elsif ($curraccess eq 'da') {
1.1335 raeburn 4647: if (grep(/^da$/,@liveroles)) {
4648: push(@possroles,$role);
4649: } else {
4650: next;
4651: }
1.1332 raeburn 4652: } elsif ($curraccess eq 'status') {
4653: if (@okstatus) {
4654: if (!@statuses) {
4655: if (grep(/^default$/,@okstatus)) {
4656: push(@possroles,$role);
4657: }
4658: } else {
4659: foreach my $status (@okstatus) {
4660: if (grep(/^\Q$status\E$/,@statuses)) {
4661: push(@possroles,$role);
4662: last;
4663: }
4664: }
4665: }
4666: }
4667: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4668: if (grep(/^\Q$user\E$/,@personnel)) {
4669: if ($curraccess eq 'exc') {
4670: push(@possroles,$role);
4671: }
4672: } elsif ($curraccess eq 'inc') {
4673: push(@possroles,$role);
4674: }
4675: }
4676: }
4677: }
4678: }
4679: }
4680: }
4681: }
4682: }
1.1333 raeburn 4683: unless (ref($description) eq 'HASH') {
4684: if (ref($roles_by_num) eq 'ARRAY') {
4685: my %desc;
4686: map { $desc{$_} = $_; } (@{$roles_by_num});
4687: $description = \%desc;
4688: } else {
4689: $description = {};
4690: }
4691: }
4692: return (\@possroles,$description);
1.1332 raeburn 4693: }
4694:
1.399 www 4695: # ----------------------------------------------------- Frontpage Announcements
4696: #
4697: #
4698:
4699: sub postannounce {
4700: my ($server,$text)=@_;
1.844 albertel 4701: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4702: unless ($text=~/\w/) { $text=''; }
4703: return &reply('setannounce:'.&escape($text),$server);
4704: }
4705:
4706: sub getannounce {
1.448 albertel 4707:
4708: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4709: my $announcement='';
1.800 albertel 4710: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4711: close($fh);
1.399 www 4712: if ($announcement=~/\w/) {
4713: return
4714: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4715: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4716: } else {
4717: return '';
4718: }
4719: } else {
4720: return '';
4721: }
1.351 www 4722: }
1.353 www 4723:
4724: # ---------------------------------------------------------- Course ID routines
4725: # Deal with domain's nohist_courseid.db files
4726: #
4727:
4728: sub courseidput {
1.921 raeburn 4729: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4730: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4731: my $outcome;
4732: if ($caller eq 'timeonly') {
4733: my $cids = '';
4734: foreach my $item (keys(%$storehash)) {
4735: $cids.=&escape($item).'&';
4736: }
4737: $cids=~s/\&$//;
4738: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4739: $coursehome);
4740: } else {
4741: my $items = '';
4742: foreach my $item (keys(%$storehash)) {
4743: $items.= &escape($item).'='.
4744: &freeze_escape($$storehash{$item}).'&';
4745: }
4746: $items=~s/\&$//;
4747: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4748: $coursehome);
1.918 raeburn 4749: }
4750: if ($outcome eq 'unknown_cmd') {
4751: my $what;
4752: foreach my $cid (keys(%$storehash)) {
4753: $what .= &escape($cid).'=';
1.921 raeburn 4754: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4755: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4756: }
4757: $what =~ s/\:$/&/;
4758: }
4759: $what =~ s/\&$//;
4760: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4761: } else {
4762: return $outcome;
4763: }
1.353 www 4764: }
4765:
4766: sub courseiddump {
1.921 raeburn 4767: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4768: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4769: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4770: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 4771: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4772: my $as_hash = 1;
4773: my %returnhash;
4774: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4775: my %libserv = &all_library();
4776: foreach my $tryserver (keys(%libserv)) {
4777: if ( ( $hostidflag == 1
4778: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4779: || (!defined($hostidflag)) ) {
4780:
1.918 raeburn 4781: if (($domfilter eq '') ||
4782: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4783: my $rep;
4784: if (grep { $_ eq $tryserver } current_machine_ids()) {
4785: $rep = LONCAPA::Lond::dump_course_id_handler(
4786: join(":", (&host_domain($tryserver), $sincefilter,
4787: &escape($descfilter), &escape($instcodefilter),
4788: &escape($ownerfilter), &escape($coursefilter),
4789: &escape($typefilter), &escape($regexp_ok),
4790: $as_hash, &escape($selfenrollonly),
4791: &escape($catfilter), $showhidden, $caller,
4792: &escape($cloner), &escape($cc_clone), $cloneonly,
4793: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 4794: &escape($creationcontext),$domcloner,$hasuniquecode,
4795: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 4796: } else {
4797: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4798: $sincefilter.':'.&escape($descfilter).':'.
4799: &escape($instcodefilter).':'.&escape($ownerfilter).
4800: ':'.&escape($coursefilter).':'.&escape($typefilter).
4801: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4802: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4803: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4804: &escape($cc_clone).':'.$cloneonly.':'.
4805: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 4806: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4807: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 4808: }
4809:
1.918 raeburn 4810: my @pairs=split(/\&/,$rep);
4811: foreach my $item (@pairs) {
4812: my ($key,$value)=split(/\=/,$item,2);
4813: $key = &unescape($key);
4814: next if ($key =~ /^error: 2 /);
4815: my $result = &thaw_unescape($value);
4816: if (ref($result) eq 'HASH') {
4817: $returnhash{$key}=$result;
4818: } else {
1.921 raeburn 4819: my @responses = split(/:/,$value);
4820: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4821: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4822: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4823: }
1.1008 raeburn 4824: }
1.353 www 4825: }
4826: }
4827: }
4828: }
4829: return %returnhash;
4830: }
4831:
1.1055 raeburn 4832: sub courselastaccess {
4833: my ($cdom,$cnum,$hostidref) = @_;
4834: my %returnhash;
4835: if ($cdom && $cnum) {
4836: my $chome = &homeserver($cnum,$cdom);
4837: if ($chome ne 'no_host') {
4838: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4839: &extract_lastaccess(\%returnhash,$rep);
4840: }
4841: } else {
4842: if (!$cdom) { $cdom=''; }
4843: my %libserv = &all_library();
4844: foreach my $tryserver (keys(%libserv)) {
4845: if (ref($hostidref) eq 'ARRAY') {
4846: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4847: }
4848: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4849: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4850: &extract_lastaccess(\%returnhash,$rep);
4851: }
4852: }
4853: }
4854: return %returnhash;
4855: }
4856:
4857: sub extract_lastaccess {
4858: my ($returnhash,$rep) = @_;
4859: if (ref($returnhash) eq 'HASH') {
4860: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4861: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4862: $rep eq '') {
4863: my @pairs=split(/\&/,$rep);
4864: foreach my $item (@pairs) {
4865: my ($key,$value)=split(/\=/,$item,2);
4866: $key = &unescape($key);
4867: next if ($key =~ /^error: 2 /);
4868: $returnhash->{$key} = &thaw_unescape($value);
4869: }
4870: }
4871: }
4872: return;
4873: }
4874:
1.658 raeburn 4875: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4876:
4877: sub dcmailput {
1.685 raeburn 4878: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4879: my $status = &Apache::lonnet::critical(
1.740 www 4880: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4881: &escape($message),$server);
1.662 raeburn 4882: return $status;
4883: }
4884:
1.658 raeburn 4885: sub dcmaildump {
4886: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4887: my %returnhash=();
1.846 albertel 4888:
4889: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4890: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4891: &escape($enddate).':';
4892: my @esc_senders=map { &escape($_)} @$senders;
4893: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4894: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4895: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4896: if (($key) && ($value)) {
4897: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4898: }
4899: }
4900: }
4901: return %returnhash;
4902: }
1.662 raeburn 4903: # ---------------------------------------------------------- Domain roles
4904:
4905: sub get_domain_roles {
4906: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4907: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4908: $startdate = '.';
4909: }
1.1018 raeburn 4910: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4911: $enddate = '.';
4912: }
1.922 raeburn 4913: my $rolelist;
4914: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4915: $rolelist = join('&',@{$roles});
1.922 raeburn 4916: }
1.662 raeburn 4917: my %personnel = ();
1.841 albertel 4918:
4919: my %servers = &get_servers($dom,'library');
4920: foreach my $tryserver (keys(%servers)) {
4921: %{$personnel{$tryserver}}=();
4922: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4923: &escape($startdate).':'.
4924: &escape($enddate).':'.
4925: &escape($rolelist), $tryserver))) {
4926: my ($key,$value) = split(/\=/,$line,2);
4927: if (($key) && ($value)) {
4928: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4929: }
4930: }
1.662 raeburn 4931: }
4932: return %personnel;
4933: }
1.658 raeburn 4934:
1.1332 raeburn 4935: sub get_active_domroles {
4936: my ($dom,$roles) = @_;
4937: return () unless (ref($roles) eq 'ARRAY');
4938: my $now = time;
4939: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
4940: my %domroles;
4941: foreach my $server (keys(%dompersonnel)) {
4942: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
4943: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
4944: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
4945: }
4946: }
4947: return %domroles;
4948: }
4949:
1.1057 www 4950: # ----------------------------------------------------------- Interval timing
1.149 www 4951:
1.1153 www 4952: {
4953: # Caches needed for speedup of navmaps
4954: # We don't want to cache this for very long at all (5 seconds at most)
4955: #
4956: # The user for whom we cache
4957: my $cachedkey='';
4958: # The cached times for this user
4959: my %cachedtimes=();
4960: # When this was last done
1.1282 raeburn 4961: my $cachedtime='';
1.1153 www 4962:
4963: sub load_all_first_access {
1.1308 raeburn 4964: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 4965: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 4966: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
4967: (!$ignorecache)) {
1.1154 raeburn 4968: return;
4969: }
4970: $cachedtime=time;
4971: $cachedkey=$uname.':'.$udom;
4972: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4973: }
4974:
1.504 albertel 4975: sub get_first_access {
1.1308 raeburn 4976: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 4977: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4978: if ($argsymb) { $symb=$argsymb; }
4979: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4980: if ($argmap) { $map = $argmap; }
1.926 albertel 4981: if ($type eq 'course') {
4982: $res='course';
4983: } elsif ($type eq 'map') {
1.588 albertel 4984: $res=&symbread($map);
4985: } else {
4986: $res=$symb;
4987: }
1.1308 raeburn 4988: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 4989: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4990: }
4991:
4992: sub set_first_access {
1.1162 raeburn 4993: my ($type,$interval)=@_;
1.790 albertel 4994: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4995: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4996: if ($type eq 'course') {
4997: $res='course';
4998: } elsif ($type eq 'map') {
1.588 albertel 4999: $res=&symbread($map);
5000: } else {
5001: $res=$symb;
5002: }
1.1153 www 5003: $cachedkey='';
1.1162 raeburn 5004: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 5005: if (!$firstaccess) {
1.1162 raeburn 5006: my $start = time;
5007: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5008: $udom,$uname);
5009: if ($putres eq 'ok') {
5010: &put('timerinterval',{"$courseid\0$res"=>$interval},
5011: $udom,$uname);
5012: &appenv(
5013: {
5014: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5015: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5016: }
5017: );
5018: }
5019: return $putres;
1.505 albertel 5020: }
5021: return 'already_set';
1.504 albertel 5022: }
1.1153 www 5023: }
1.1282 raeburn 5024:
1.110 www 5025: # --------------------------------------------- Set Expire Date for Spreadsheet
5026:
5027: sub expirespread {
5028: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5029: my $cid=$env{'request.course.id'};
1.110 www 5030: if ($cid) {
5031: my $now=time;
5032: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5033: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5034: $env{'course.'.$cid.'.num'}.
1.110 www 5035: ':nohist_expirationdates:'.
5036: &escape($key).'='.$now,
1.620 albertel 5037: $env{'course.'.$cid.'.home'})
1.110 www 5038: }
5039: return 'ok';
1.14 www 5040: }
5041:
1.109 www 5042: # ----------------------------------------------------- Devalidate Spreadsheets
5043:
5044: sub devalidate {
1.325 www 5045: my ($symb,$uname,$udom)=@_;
1.620 albertel 5046: my $cid=$env{'request.course.id'};
1.109 www 5047: if ($cid) {
1.391 matthew 5048: # delete the stored spreadsheets for
5049: # - the student level sheet of this user in course's homespace
5050: # - the assessment level sheet for this resource
5051: # for this user in user's homespace
1.553 albertel 5052: # - current conditional state info
1.325 www 5053: my $key=$uname.':'.$udom.':';
1.109 www 5054: my $status=
1.299 matthew 5055: &del('nohist_calculatedsheets',
1.391 matthew 5056: [$key.'studentcalc:'],
1.620 albertel 5057: $env{'course.'.$cid.'.domain'},
5058: $env{'course.'.$cid.'.num'})
1.133 albertel 5059: .' '.
5060: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5061: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5062: unless ($status eq 'ok ok') {
5063: &logthis('Could not devalidate spreadsheet '.
1.325 www 5064: $uname.' at '.$udom.' for '.
1.109 www 5065: $symb.': '.$status);
1.133 albertel 5066: }
1.553 albertel 5067: &delenv('user.state.'.$cid);
1.109 www 5068: }
5069: }
5070:
1.265 albertel 5071: sub get_scalar {
5072: my ($string,$end) = @_;
5073: my $value;
5074: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5075: $value = $1;
5076: } elsif ($$string =~ s/^([^&]*?)&//) {
5077: $value = $1;
5078: }
5079: return &unescape($value);
5080: }
5081:
5082: sub array2str {
5083: my (@array) = @_;
5084: my $result=&arrayref2str(\@array);
5085: $result=~s/^__ARRAY_REF__//;
5086: $result=~s/__END_ARRAY_REF__$//;
5087: return $result;
5088: }
5089:
1.204 albertel 5090: sub arrayref2str {
5091: my ($arrayref) = @_;
1.265 albertel 5092: my $result='__ARRAY_REF__';
1.204 albertel 5093: foreach my $elem (@$arrayref) {
1.265 albertel 5094: if(ref($elem) eq 'ARRAY') {
5095: $result.=&arrayref2str($elem).'&';
5096: } elsif(ref($elem) eq 'HASH') {
5097: $result.=&hashref2str($elem).'&';
5098: } elsif(ref($elem)) {
5099: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5100: } else {
5101: $result.=&escape($elem).'&';
5102: }
5103: }
5104: $result=~s/\&$//;
1.265 albertel 5105: $result .= '__END_ARRAY_REF__';
1.204 albertel 5106: return $result;
5107: }
5108:
1.168 albertel 5109: sub hash2str {
1.204 albertel 5110: my (%hash) = @_;
5111: my $result=&hashref2str(\%hash);
1.265 albertel 5112: $result=~s/^__HASH_REF__//;
5113: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5114: return $result;
5115: }
5116:
5117: sub hashref2str {
5118: my ($hashref)=@_;
1.265 albertel 5119: my $result='__HASH_REF__';
1.800 albertel 5120: foreach my $key (sort(keys(%$hashref))) {
5121: if (ref($key) eq 'ARRAY') {
5122: $result.=&arrayref2str($key).'=';
5123: } elsif (ref($key) eq 'HASH') {
5124: $result.=&hashref2str($key).'=';
5125: } elsif (ref($key)) {
1.265 albertel 5126: $result.='=';
1.800 albertel 5127: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5128: } else {
1.1132 raeburn 5129: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5130: }
5131:
1.800 albertel 5132: if(ref($hashref->{$key}) eq 'ARRAY') {
5133: $result.=&arrayref2str($hashref->{$key}).'&';
5134: } elsif(ref($hashref->{$key}) eq 'HASH') {
5135: $result.=&hashref2str($hashref->{$key}).'&';
5136: } elsif(ref($hashref->{$key})) {
1.265 albertel 5137: $result.='&';
1.800 albertel 5138: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5139: } else {
1.800 albertel 5140: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5141: }
5142: }
1.168 albertel 5143: $result=~s/\&$//;
1.265 albertel 5144: $result .= '__END_HASH_REF__';
1.168 albertel 5145: return $result;
5146: }
5147:
5148: sub str2hash {
1.265 albertel 5149: my ($string)=@_;
5150: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5151: return %$hash;
5152: }
5153:
5154: sub str2hashref {
1.168 albertel 5155: my ($string) = @_;
1.265 albertel 5156:
5157: my %hash;
5158:
5159: if($string !~ /^__HASH_REF__/) {
5160: if (! ($string eq '' || !defined($string))) {
5161: $hash{'error'}='Not hash reference';
5162: }
5163: return (\%hash, $string);
5164: }
5165:
5166: $string =~ s/^__HASH_REF__//;
5167:
5168: while($string !~ /^__END_HASH_REF__/) {
5169: #key
5170: my $key='';
5171: if($string =~ /^__HASH_REF__/) {
5172: ($key, $string)=&str2hashref($string);
5173: if(defined($key->{'error'})) {
5174: $hash{'error'}='Bad data';
5175: return (\%hash, $string);
5176: }
5177: } elsif($string =~ /^__ARRAY_REF__/) {
5178: ($key, $string)=&str2arrayref($string);
5179: if($key->[0] eq 'Array reference error') {
5180: $hash{'error'}='Bad data';
5181: return (\%hash, $string);
5182: }
5183: } else {
5184: $string =~ s/^(.*?)=//;
1.267 albertel 5185: $key=&unescape($1);
1.265 albertel 5186: }
5187: $string =~ s/^=//;
5188:
5189: #value
5190: my $value='';
5191: if($string =~ /^__HASH_REF__/) {
5192: ($value, $string)=&str2hashref($string);
5193: if(defined($value->{'error'})) {
5194: $hash{'error'}='Bad data';
5195: return (\%hash, $string);
5196: }
5197: } elsif($string =~ /^__ARRAY_REF__/) {
5198: ($value, $string)=&str2arrayref($string);
5199: if($value->[0] eq 'Array reference error') {
5200: $hash{'error'}='Bad data';
5201: return (\%hash, $string);
5202: }
5203: } else {
5204: $value=&get_scalar(\$string,'__END_HASH_REF__');
5205: }
5206: $string =~ s/^&//;
5207:
5208: $hash{$key}=$value;
1.204 albertel 5209: }
1.265 albertel 5210:
5211: $string =~ s/^__END_HASH_REF__//;
5212:
5213: return (\%hash, $string);
1.204 albertel 5214: }
5215:
5216: sub str2array {
1.265 albertel 5217: my ($string)=@_;
5218: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5219: return @$array;
5220: }
5221:
5222: sub str2arrayref {
1.204 albertel 5223: my ($string) = @_;
1.265 albertel 5224: my @array;
5225:
5226: if($string !~ /^__ARRAY_REF__/) {
5227: if (! ($string eq '' || !defined($string))) {
5228: $array[0]='Array reference error';
5229: }
5230: return (\@array, $string);
5231: }
5232:
5233: $string =~ s/^__ARRAY_REF__//;
5234:
5235: while($string !~ /^__END_ARRAY_REF__/) {
5236: my $value='';
5237: if($string =~ /^__HASH_REF__/) {
5238: ($value, $string)=&str2hashref($string);
5239: if(defined($value->{'error'})) {
5240: $array[0] ='Array reference error';
5241: return (\@array, $string);
5242: }
5243: } elsif($string =~ /^__ARRAY_REF__/) {
5244: ($value, $string)=&str2arrayref($string);
5245: if($value->[0] eq 'Array reference error') {
5246: $array[0] ='Array reference error';
5247: return (\@array, $string);
5248: }
5249: } else {
5250: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5251: }
5252: $string =~ s/^&//;
5253:
5254: push(@array, $value);
1.191 harris41 5255: }
1.265 albertel 5256:
5257: $string =~ s/^__END_ARRAY_REF__//;
5258:
5259: return (\@array, $string);
1.168 albertel 5260: }
5261:
1.167 albertel 5262: # -------------------------------------------------------------------Temp Store
5263:
1.168 albertel 5264: sub tmpreset {
5265: my ($symb,$namespace,$domain,$stuname) = @_;
5266: if (!$symb) {
5267: $symb=&symbread();
1.620 albertel 5268: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5269: }
5270: $symb=escape($symb);
5271:
1.620 albertel 5272: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5273: $namespace=~s/\//\_/g;
5274: $namespace=~s/\W//g;
5275:
1.620 albertel 5276: if (!$domain) { $domain=$env{'user.domain'}; }
5277: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5278: if ($domain eq 'public' && $stuname eq 'public') {
5279: $stuname=$ENV{'REMOTE_ADDR'};
5280: }
1.1117 foxr 5281: my $path=LONCAPA::tempdir();
1.168 albertel 5282: my %hash;
5283: if (tie(%hash,'GDBM_File',
5284: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5285: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5286: foreach my $key (keys(%hash)) {
1.180 albertel 5287: if ($key=~ /:$symb/) {
1.168 albertel 5288: delete($hash{$key});
5289: }
5290: }
5291: }
5292: }
5293:
1.167 albertel 5294: sub tmpstore {
1.168 albertel 5295: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5296:
5297: if (!$symb) {
5298: $symb=&symbread();
1.620 albertel 5299: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5300: }
5301: $symb=escape($symb);
5302:
5303: if (!$namespace) {
5304: # I don't think we would ever want to store this for a course.
5305: # it seems this will only be used if we don't have a course.
1.620 albertel 5306: #$namespace=$env{'request.course.id'};
1.168 albertel 5307: #if (!$namespace) {
1.620 albertel 5308: $namespace=$env{'request.state'};
1.168 albertel 5309: #}
5310: }
5311: $namespace=~s/\//\_/g;
5312: $namespace=~s/\W//g;
1.620 albertel 5313: if (!$domain) { $domain=$env{'user.domain'}; }
5314: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5315: if ($domain eq 'public' && $stuname eq 'public') {
5316: $stuname=$ENV{'REMOTE_ADDR'};
5317: }
1.168 albertel 5318: my $now=time;
5319: my %hash;
1.1117 foxr 5320: my $path=LONCAPA::tempdir();
1.168 albertel 5321: if (tie(%hash,'GDBM_File',
5322: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5323: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5324: $hash{"version:$symb"}++;
5325: my $version=$hash{"version:$symb"};
5326: my $allkeys='';
5327: foreach my $key (keys(%$storehash)) {
5328: $allkeys.=$key.':';
1.591 albertel 5329: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5330: }
5331: $hash{"$version:$symb:timestamp"}=$now;
5332: $allkeys.='timestamp';
5333: $hash{"$version:keys:$symb"}=$allkeys;
5334: if (untie(%hash)) {
5335: return 'ok';
5336: } else {
5337: return "error:$!";
5338: }
5339: } else {
5340: return "error:$!";
5341: }
5342: }
1.167 albertel 5343:
1.168 albertel 5344: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5345:
1.168 albertel 5346: sub tmprestore {
5347: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5348:
1.168 albertel 5349: if (!$symb) {
5350: $symb=&symbread();
1.620 albertel 5351: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5352: }
5353: $symb=escape($symb);
5354:
1.620 albertel 5355: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5356:
1.620 albertel 5357: if (!$domain) { $domain=$env{'user.domain'}; }
5358: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5359: if ($domain eq 'public' && $stuname eq 'public') {
5360: $stuname=$ENV{'REMOTE_ADDR'};
5361: }
1.168 albertel 5362: my %returnhash;
5363: $namespace=~s/\//\_/g;
5364: $namespace=~s/\W//g;
5365: my %hash;
1.1117 foxr 5366: my $path=LONCAPA::tempdir();
1.168 albertel 5367: if (tie(%hash,'GDBM_File',
5368: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5369: &GDBM_READER(),0640)) {
1.168 albertel 5370: my $version=$hash{"version:$symb"};
5371: $returnhash{'version'}=$version;
5372: my $scope;
5373: for ($scope=1;$scope<=$version;$scope++) {
5374: my $vkeys=$hash{"$scope:keys:$symb"};
5375: my @keys=split(/:/,$vkeys);
5376: my $key;
5377: $returnhash{"$scope:keys"}=$vkeys;
5378: foreach $key (@keys) {
1.591 albertel 5379: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5380: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5381: }
5382: }
1.168 albertel 5383: if (!(untie(%hash))) {
5384: return "error:$!";
5385: }
5386: } else {
5387: return "error:$!";
5388: }
5389: return %returnhash;
1.167 albertel 5390: }
5391:
1.9 www 5392: # ----------------------------------------------------------------------- Store
5393:
5394: sub store {
1.1269 raeburn 5395: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5396: my $home='';
5397:
1.168 albertel 5398: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5399:
1.213 www 5400: $symb=&symbclean($symb);
1.122 albertel 5401: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5402:
1.620 albertel 5403: if (!$domain) { $domain=$env{'user.domain'}; }
5404: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5405:
5406: &devalidate($symb,$stuname,$domain);
1.109 www 5407:
5408: $symb=escape($symb);
1.187 www 5409: if (!$namespace) {
1.620 albertel 5410: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5411: return '';
5412: }
5413: }
1.620 albertel 5414: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5415:
5416: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5417: $$storehash{'host'}=$perlvar{'lonHostID'};
5418:
1.12 www 5419: my $namevalue='';
1.800 albertel 5420: foreach my $key (keys(%$storehash)) {
5421: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5422: }
1.12 www 5423: $namevalue=~s/\&$//;
1.187 www 5424: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 5425: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5426: }
5427:
1.47 www 5428: # -------------------------------------------------------------- Critical Store
5429:
5430: sub cstore {
1.1269 raeburn 5431: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5432: my $home='';
5433:
1.168 albertel 5434: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5435:
1.213 www 5436: $symb=&symbclean($symb);
1.122 albertel 5437: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5438:
1.620 albertel 5439: if (!$domain) { $domain=$env{'user.domain'}; }
5440: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5441:
5442: &devalidate($symb,$stuname,$domain);
1.109 www 5443:
5444: $symb=escape($symb);
1.187 www 5445: if (!$namespace) {
1.620 albertel 5446: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5447: return '';
5448: }
5449: }
1.620 albertel 5450: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5451:
5452: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5453: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5454:
1.47 www 5455: my $namevalue='';
1.800 albertel 5456: foreach my $key (keys(%$storehash)) {
5457: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5458: }
1.47 www 5459: $namevalue=~s/\&$//;
1.187 www 5460: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5461: return critical
1.1269 raeburn 5462: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5463: }
5464:
1.9 www 5465: # --------------------------------------------------------------------- Restore
5466:
5467: sub restore {
1.124 www 5468: my ($symb,$namespace,$domain,$stuname) = @_;
5469: my $home='';
5470:
1.168 albertel 5471: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5472:
1.122 albertel 5473: if (!$symb) {
1.1224 raeburn 5474: return if ($namespace eq 'courserequests');
5475: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5476: } else {
1.1224 raeburn 5477: unless ($namespace eq 'courserequests') {
5478: $symb=&escape(&symbclean($symb));
5479: }
1.122 albertel 5480: }
1.188 www 5481: if (!$namespace) {
1.620 albertel 5482: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5483: return '';
5484: }
5485: }
1.620 albertel 5486: if (!$domain) { $domain=$env{'user.domain'}; }
5487: if (!$stuname) { $stuname=$env{'user.name'}; }
5488: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5489: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5490:
1.12 www 5491: my %returnhash=();
1.800 albertel 5492: foreach my $line (split(/\&/,$answer)) {
5493: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5494: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5495: }
1.75 www 5496: my $version;
5497: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5498: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5499: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5500: }
1.75 www 5501: }
1.13 www 5502: return %returnhash;
1.34 www 5503: }
5504:
5505: # ---------------------------------------------------------- Course Description
1.1118 foxr 5506: #
5507: #
1.34 www 5508:
5509: sub coursedescription {
1.731 albertel 5510: my ($courseid,$args)=@_;
1.34 www 5511: $courseid=~s/^\///;
1.49 www 5512: $courseid=~s/\_/\//g;
1.34 www 5513: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5514: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5515: my $normalid=$cdomain.'_'.$cnum;
5516: # need to always cache even if we get errors otherwise we keep
5517: # trying and trying and trying to get the course description.
5518: my %envhash=();
5519: my %returnhash=();
1.731 albertel 5520:
5521: my $expiretime=600;
5522: if ($env{'request.course.id'} eq $normalid) {
5523: $expiretime=120;
5524: }
5525:
5526: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5527: if (!$args->{'freshen_cache'}
5528: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5529: foreach my $key (keys(%env)) {
5530: next if ($key !~ /^\Q$prefix\E(.*)/);
5531: my ($setting) = $1;
5532: $returnhash{$setting} = $env{$key};
5533: }
5534: return %returnhash;
5535: }
5536:
1.1118 foxr 5537: # get the data again
5538:
1.731 albertel 5539: if (!$args->{'one_time'}) {
5540: $envhash{'course.'.$normalid.'.last_cache'}=time;
5541: }
1.811 albertel 5542:
1.34 www 5543: if ($chome ne 'no_host') {
1.302 albertel 5544: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5545: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5546: my $username = $env{'user.name'}; # Defult username
5547: if(defined $args->{'user'}) {
5548: $username = $args->{'user'};
5549: }
1.129 albertel 5550: $returnhash{'home'}= $chome;
5551: $returnhash{'domain'} = $cdomain;
5552: $returnhash{'num'} = $cnum;
1.741 raeburn 5553: if (!defined($returnhash{'type'})) {
5554: $returnhash{'type'} = 'Course';
5555: }
1.130 albertel 5556: while (my ($name,$value) = each %returnhash) {
1.53 www 5557: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5558: }
1.270 www 5559: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5560: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5561: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5562: $envhash{'course.'.$normalid.'.home'}=$chome;
5563: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5564: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5565: }
5566: }
1.731 albertel 5567: if (!$args->{'one_time'}) {
1.949 raeburn 5568: &appenv(\%envhash);
1.731 albertel 5569: }
1.302 albertel 5570: return %returnhash;
1.461 www 5571: }
5572:
1.1080 raeburn 5573: sub update_released_required {
5574: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5575: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5576: $cid = $env{'request.course.id'};
5577: $cdom = $env{'course.'.$cid.'.domain'};
5578: $cnum = $env{'course.'.$cid.'.num'};
5579: $chome = $env{'course.'.$cid.'.home'};
5580: }
5581: if ($needsrelease) {
5582: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5583: my $needsupdate;
5584: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5585: $needsupdate = 1;
5586: } else {
5587: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5588: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5589: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5590: $needsupdate = 1;
5591: }
5592: }
5593: if ($needsupdate) {
5594: my %needshash = (
5595: 'internal.releaserequired' => $needsrelease,
5596: );
5597: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5598: if ($putresult eq 'ok') {
5599: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5600: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5601: if (ref($crsinfo{$cid}) eq 'HASH') {
5602: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5603: &courseidput($cdom,\%crsinfo,$chome,'notime');
5604: }
5605: }
5606: }
5607: }
5608: return;
5609: }
5610:
1.461 www 5611: # -------------------------------------------------See if a user is privileged
5612:
5613: sub privileged {
1.1219 raeburn 5614: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5615: my $now = time;
1.1219 raeburn 5616: my $roles;
5617: if (ref($possroles) eq 'ARRAY') {
5618: $roles = $possroles;
5619: } else {
5620: $roles = ['dc','su'];
5621: }
5622: if (ref($possdomains) eq 'ARRAY') {
5623: my %privileged = &privileged_by_domain($possdomains,$roles);
5624: foreach my $dom (@{$possdomains}) {
5625: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5626: (ref($privileged{$dom}) eq 'HASH')) {
5627: foreach my $role (@{$roles}) {
5628: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5629: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5630: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5631: return 1 unless (($end && $end < $now) ||
5632: ($start && $start > $now));
5633: }
5634: }
5635: }
5636: }
5637: }
5638: } else {
5639: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5640: my $now = time;
1.1170 droeschl 5641:
1.1275 musolffc 5642: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5643: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5644: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5645: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5646: or ($tstart && $tstart > $now);
1.1170 droeschl 5647: }
1.1219 raeburn 5648: }
5649: }
5650: return 0;
5651: }
1.1170 droeschl 5652:
1.1219 raeburn 5653: sub privileged_by_domain {
5654: my ($domains,$roles) = @_;
5655: my %privileged = ();
5656: my $cachetime = 60*60*24;
5657: my $now = time;
5658: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5659: return %privileged;
5660: }
5661: foreach my $dom (@{$domains}) {
5662: next if (ref($privileged{$dom}) eq 'HASH');
5663: my $needroles;
5664: foreach my $role (@{$roles}) {
5665: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5666: if (defined($cached)) {
5667: if (ref($result) eq 'HASH') {
5668: $privileged{$dom}{$role} = $result;
5669: }
5670: } else {
5671: $needroles = 1;
5672: }
5673: }
5674: if ($needroles) {
5675: my %dompersonnel = &get_domain_roles($dom,$roles);
5676: $privileged{$dom} = {};
5677: foreach my $server (keys(%dompersonnel)) {
5678: if (ref($dompersonnel{$server}) eq 'HASH') {
5679: foreach my $item (keys(%{$dompersonnel{$server}})) {
5680: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5681: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5682: next if ($end && $end < $now);
5683: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5684: $dompersonnel{$server}{$item};
5685: }
5686: }
5687: }
5688: if (ref($privileged{$dom}) eq 'HASH') {
5689: foreach my $role (@{$roles}) {
5690: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5691: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5692: } else {
5693: my %hash = ();
5694: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5695: }
5696: }
5697: }
5698: }
5699: }
5700: return %privileged;
1.9 www 5701: }
1.1 albertel 5702:
1.103 harris41 5703: # -------------------------------------------------------- Get user privileges
1.11 www 5704:
5705: sub rolesinit {
1.1169 droeschl 5706: my ($domain, $username) = @_;
5707: my %userroles = ('user.login.time' => time);
5708: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5709:
5710: # firstaccess and timerinterval are related to timed maps/resources.
5711: # also, blocking can be triggered by an activating timer
5712: # it's saved in the user's %env.
5713: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5714: my %timerinterval = &dump('timerinterval', $domain, $username);
5715: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5716: %timerintchk, %timerintenv);
5717:
1.1162 raeburn 5718: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5719: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5720: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5721: }
1.1169 droeschl 5722:
1.1162 raeburn 5723: foreach my $key (keys(%timerinterval)) {
5724: my ($cid,$rest) = split(/\0/,$key);
5725: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5726: }
1.1169 droeschl 5727:
1.11 www 5728: my %allroles=();
1.1162 raeburn 5729: my %allgroups=();
1.11 www 5730:
1.1274 raeburn 5731: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5732: my $role = $rolesdump{$area};
5733: $area =~ s/\_\w\w$//;
5734:
5735: my ($trole, $tend, $tstart, $group_privs);
5736:
5737: if ($role =~ /^cr/) {
5738: # Custom role, defined by a user
5739: # e.g., user.role.cr/msu/smith/mynewrole
5740: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5741: $trole = $1;
5742: ($tend, $tstart) = split('_', $2);
5743: } else {
5744: $trole = $role;
5745: }
5746: } elsif ($role =~ m|^gr/|) {
5747: # Role of member in a group, defined within a course/community
5748: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5749: ($trole, $tend, $tstart) = split(/_/, $role);
5750: next if $tstart eq '-1';
5751: ($trole, $group_privs) = split(/\//, $trole);
5752: $group_privs = &unescape($group_privs);
5753: } else {
5754: # Just a normal role, defined in roles.tab
5755: ($trole, $tend, $tstart) = split(/_/,$role);
5756: }
5757:
5758: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5759: $username);
5760: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5761:
5762: # role expired or not available yet?
5763: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5764: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5765:
5766: next if $area eq '' or $trole eq '';
5767:
5768: my $spec = "$trole.$area";
5769: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5770:
5771: if ($trole =~ /^cr\//) {
5772: # Custom role, defined by a user
5773: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5774: } elsif ($trole eq 'gr') {
5775: # Role of a member in a group, defined within a course/community
5776: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5777: next;
5778: } else {
5779: # Normal role, defined in roles.tab
5780: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5781: }
5782:
5783: my $cid = $tdomain.'_'.$trest;
5784: unless ($firstaccchk{$cid}) {
5785: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5786: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5787: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5788: $coursetimerstarts{$cid}{$item};
5789: }
5790: }
5791: $firstaccchk{$cid} = 1;
5792: }
5793: unless ($timerintchk{$cid}) {
5794: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5795: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5796: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5797: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5798: }
1.12 www 5799: }
1.1169 droeschl 5800: $timerintchk{$cid} = 1;
1.191 harris41 5801: }
1.11 www 5802: }
1.1169 droeschl 5803:
5804: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5805: \%allroles, \%allgroups);
5806: $env{'user.adv'} = $userroles{'user.adv'};
5807:
1.1162 raeburn 5808: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5809: }
5810:
1.567 raeburn 5811: sub set_arearole {
1.1215 raeburn 5812: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5813: unless ($nolog) {
1.567 raeburn 5814: # log the associated role with the area
1.1215 raeburn 5815: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5816: }
1.743 albertel 5817: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5818: }
5819:
5820: sub custom_roleprivs {
5821: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5822: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5823: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5824: if (&hostname($homsvr) ne '') {
1.567 raeburn 5825: my ($rdummy,$roledef)=
5826: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5827: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5828: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5829: if (defined($syspriv)) {
1.1043 raeburn 5830: if ($trest =~ /^$match_community$/) {
5831: $syspriv =~ s/bre\&S//;
5832: }
1.567 raeburn 5833: $$allroles{'cm./'}.=':'.$syspriv;
5834: $$allroles{$spec.'./'}.=':'.$syspriv;
5835: }
5836: if ($tdomain ne '') {
5837: if (defined($dompriv)) {
5838: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5839: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5840: }
5841: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 5842: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
5843: my $rolename = $1;
5844: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
5845: }
1.567 raeburn 5846: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5847: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5848: }
5849: }
5850: }
5851: }
5852: }
5853:
1.1332 raeburn 5854: sub course_adhocrole_privs {
5855: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
5856: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
5857: if ($overrides{"internal.adhocpriv.$rolename"}) {
5858: my (%currprivs,%storeprivs);
5859: foreach my $item (split(/:/,$coursepriv)) {
5860: my ($priv,$restrict) = split(/\&/,$item);
5861: $currprivs{$priv} = $restrict;
5862: }
5863: my (%possadd,%possremove,%full);
5864: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
5865: my ($priv,$restrict)=split(/\&/,$item);
5866: $full{$priv} = $restrict;
5867: }
5868: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
5869: next if ($item eq '');
5870: my ($rule,$rest) = split(/=/,$item);
5871: next unless (($rule eq 'off') || ($rule eq 'on'));
5872: foreach my $priv (split(/:/,$rest)) {
5873: if ($priv ne '') {
5874: if ($rule eq 'off') {
5875: $possremove{$priv} = 1;
5876: } else {
5877: $possadd{$priv} = 1;
5878: }
5879: }
5880: }
5881: }
5882: foreach my $priv (sort(keys(%full))) {
5883: if (exists($currprivs{$priv})) {
5884: unless (exists($possremove{$priv})) {
5885: $storeprivs{$priv} = $currprivs{$priv};
5886: }
5887: } elsif (exists($possadd{$priv})) {
5888: $storeprivs{$priv} = $full{$priv};
5889: }
5890: }
5891: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
5892: }
5893: return $coursepriv;
5894: }
5895:
1.678 raeburn 5896: sub group_roleprivs {
5897: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5898: my $access = 1;
5899: my $now = time;
5900: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5901: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5902: if ($access) {
1.811 albertel 5903: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5904: $$allgroups{$course}{$group} .=':'.$group_privs;
5905: }
5906: }
1.567 raeburn 5907:
5908: sub standard_roleprivs {
5909: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5910: if (defined($pr{$trole.':s'})) {
5911: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5912: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5913: }
5914: if ($tdomain ne '') {
5915: if (defined($pr{$trole.':d'})) {
5916: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5917: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5918: }
5919: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5920: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5921: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5922: }
5923: }
5924: }
5925:
5926: sub set_userprivs {
1.1064 raeburn 5927: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5928: my $author=0;
5929: my $adv=0;
1.678 raeburn 5930: my %grouproles = ();
5931: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5932: my @groupkeys;
1.1000 raeburn 5933: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5934: push(@groupkeys,$role);
5935: }
5936: if (ref($groups_roles) eq 'HASH') {
5937: foreach my $key (keys(%{$groups_roles})) {
5938: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5939: push(@groupkeys,$key);
5940: }
5941: }
5942: }
5943: if (@groupkeys > 0) {
5944: foreach my $role (@groupkeys) {
5945: my ($trole,$area,$sec,$extendedarea);
5946: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5947: $trole = $1;
5948: $area = $2;
5949: $sec = $3;
5950: $extendedarea = $area.$sec;
5951: if (exists($$allgroups{$area})) {
5952: foreach my $group (keys(%{$$allgroups{$area}})) {
5953: my $spec = $trole.'.'.$extendedarea;
5954: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5955: $$allgroups{$area}{$group};
1.1064 raeburn 5956: }
1.678 raeburn 5957: }
5958: }
5959: }
5960: }
5961: }
1.800 albertel 5962: foreach my $group (keys(%grouproles)) {
5963: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5964: }
1.800 albertel 5965: foreach my $role (keys(%{$allroles})) {
5966: my %thesepriv;
1.941 raeburn 5967: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5968: foreach my $item (split(/:/,$$allroles{$role})) {
5969: if ($item ne '') {
5970: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5971: if ($restrictions eq '') {
5972: $thesepriv{$privilege}='F';
5973: } elsif ($thesepriv{$privilege} ne 'F') {
5974: $thesepriv{$privilege}.=$restrictions;
5975: }
5976: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5977: }
5978: }
5979: my $thesestr='';
1.1104 raeburn 5980: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5981: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5982: }
5983: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5984: }
5985: return ($author,$adv);
5986: }
5987:
1.994 raeburn 5988: sub role_status {
1.1104 raeburn 5989: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5990: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5991: my ($one,$two) = split(m{\./},$rolekey,2);
5992: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5993: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5994: $$where = '/'.$two;
1.994 raeburn 5995: $$trolecode=$$role.'.'.$$where;
5996: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5997: $$tstatus='is';
1.1104 raeburn 5998: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5999: $$tstatus='future';
1.1034 raeburn 6000: if ($$tstart<$now) {
6001: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6002: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6003: my (%allroles,%allgroups,$group_privs,
6004: %groups_roles,@rolecodes);
1.1002 raeburn 6005: my %userroles = (
6006: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6007: );
1.1064 raeburn 6008: @rolecodes = ('cm');
1.1002 raeburn 6009: my $spec=$$role.'.'.$$where;
6010: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6011: if ($$role =~ /^cr\//) {
6012: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6013: push(@rolecodes,'cr');
1.1002 raeburn 6014: } elsif ($$role eq 'gr') {
1.1064 raeburn 6015: push(@rolecodes,$$role);
1.1002 raeburn 6016: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6017: $env{'user.name'});
1.1064 raeburn 6018: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6019: (undef,my $group_privs) = split(/\//,$trole);
6020: $group_privs = &unescape($group_privs);
6021: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6022: 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 6023: &get_groups_roles($tdomain,$trest,
6024: \%course_roles,\@rolecodes,
6025: \%groups_roles);
1.1002 raeburn 6026: } else {
1.1064 raeburn 6027: push(@rolecodes,$$role);
1.1002 raeburn 6028: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6029: }
1.1064 raeburn 6030: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
6031: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 6032: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
6033: }
6034: }
1.1034 raeburn 6035: $$tstatus = 'is';
1.1002 raeburn 6036: }
1.994 raeburn 6037: }
6038: if ($$tend) {
1.1104 raeburn 6039: if ($$tend<$update) {
1.994 raeburn 6040: $$tstatus='expired';
6041: } elsif ($$tend<$now) {
6042: $$tstatus='will_not';
6043: }
6044: }
6045: }
6046: }
6047: }
6048:
1.1104 raeburn 6049: sub get_groups_roles {
6050: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6051: return unless((ref($cdom_courseroles) eq 'HASH') &&
6052: (ref($rolecodes) eq 'ARRAY') &&
6053: (ref($groups_roles) eq 'HASH'));
6054: if (keys(%{$cdom_courseroles}) > 0) {
6055: my ($cnum) = ($rest =~ /^($match_courseid)/);
6056: if ($cdom ne '' && $cnum ne '') {
6057: foreach my $key (keys(%{$cdom_courseroles})) {
6058: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6059: my $crsrole = $1;
6060: my $crssec = $2;
6061: if ($crsrole =~ /^cr/) {
6062: unless (grep(/^cr$/,@{$rolecodes})) {
6063: push(@{$rolecodes},'cr');
6064: }
6065: } else {
6066: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6067: push(@{$rolecodes},$crsrole);
6068: }
6069: }
6070: my $rolekey = "$crsrole./$cdom/$cnum";
6071: if ($crssec ne '') {
6072: $rolekey .= "/$crssec";
6073: }
6074: $rolekey .= './';
6075: $groups_roles->{$rolekey} = $rolecodes;
6076: }
6077: }
6078: }
6079: }
6080: return;
6081: }
6082:
6083: sub delete_env_groupprivs {
6084: my ($where,$courseroles,$possroles) = @_;
6085: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6086: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6087: unless (ref($courseroles->{$udom}) eq 'HASH') {
6088: %{$courseroles->{$udom}} =
6089: &get_my_roles('','','userroles',['active'],
6090: $possroles,[$udom],1);
6091: }
6092: if (ref($courseroles->{$udom}) eq 'HASH') {
6093: foreach my $item (keys(%{$courseroles->{$udom}})) {
6094: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6095: my $area = '/'.$cdom.'/'.$cnum;
6096: my $privkey = "user.priv.$crsrole.$area";
6097: if ($crssec ne '') {
6098: $privkey .= '/'.$crssec;
6099: }
6100: $privkey .= ".$area/$group";
6101: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6102: }
6103: }
6104: return;
6105: }
6106:
1.994 raeburn 6107: sub check_adhoc_privs {
1.1329 raeburn 6108: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6109: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 6110: if ($sec) {
6111: $cckey .= '/'.$sec;
6112: }
1.1185 raeburn 6113: my $setprivs;
1.994 raeburn 6114: if ($env{$cckey}) {
6115: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6116: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6117: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 6118: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6119: $setprivs = 1;
1.994 raeburn 6120: }
6121: } else {
1.1330 raeburn 6122: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6123: $setprivs = 1;
1.994 raeburn 6124: }
1.1185 raeburn 6125: return $setprivs;
1.994 raeburn 6126: }
6127:
6128: sub set_adhoc_privileges {
1.1326 raeburn 6129: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 6130: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6131: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 6132: if ($sec ne '') {
6133: $area .= '/'.$sec;
6134: }
1.994 raeburn 6135: my $spec = $role.'.'.$area;
6136: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 6137: $env{'user.name'},1);
1.1326 raeburn 6138: my %rolehash = ();
1.1332 raeburn 6139: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6140: my $rolename = $1;
1.1326 raeburn 6141: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 6142: my %domdef = &get_domain_defaults($dcdom);
6143: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6144: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6145: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6146: }
6147: }
1.1326 raeburn 6148: } else {
6149: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6150: }
6151: my ($author,$adv)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6152: &appenv(\%userroles,[$role,'cm']);
6153: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 6154: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6155: &appenv( {'request.role' => $spec,
6156: 'request.role.domain' => $dcdom,
1.1332 raeburn 6157: 'request.course.sec' => $sec,
1.1088 raeburn 6158: }
6159: );
6160: my $tadv=0;
6161: if (&allowed('adv') eq 'F') { $tadv=1; }
6162: &appenv({'request.role.adv' => $tadv});
6163: }
1.994 raeburn 6164: }
6165:
1.12 www 6166: # --------------------------------------------------------------- get interface
6167:
6168: sub get {
1.131 albertel 6169: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6170: my $items='';
1.800 albertel 6171: foreach my $item (@$storearr) {
6172: $items.=&escape($item).'&';
1.191 harris41 6173: }
1.12 www 6174: $items=~s/\&$//;
1.620 albertel 6175: if (!$udomain) { $udomain=$env{'user.domain'}; }
6176: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6177: my $uhome=&homeserver($uname,$udomain);
6178:
1.133 albertel 6179: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6180: my @pairs=split(/\&/,$rep);
1.273 albertel 6181: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6182: return @pairs;
6183: }
1.15 www 6184: my %returnhash=();
1.42 www 6185: my $i=0;
1.800 albertel 6186: foreach my $item (@$storearr) {
6187: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6188: $i++;
1.191 harris41 6189: }
1.15 www 6190: return %returnhash;
1.27 www 6191: }
6192:
6193: # --------------------------------------------------------------- del interface
6194:
6195: sub del {
1.133 albertel 6196: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6197: my $items='';
1.800 albertel 6198: foreach my $item (@$storearr) {
6199: $items.=&escape($item).'&';
1.191 harris41 6200: }
1.984 neumanie 6201:
1.27 www 6202: $items=~s/\&$//;
1.620 albertel 6203: if (!$udomain) { $udomain=$env{'user.domain'}; }
6204: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6205: my $uhome=&homeserver($uname,$udomain);
6206: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6207: }
6208:
6209: # -------------------------------------------------------------- dump interface
6210:
1.1180 droeschl 6211: sub unserialize {
6212: my ($rep, $escapedkeys) = @_;
6213:
6214: return {} if $rep =~ /^error/;
6215:
6216: my %returnhash=();
1.1252 raeburn 6217: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 6218: my ($key, $value) = split(/=/, $item, 2);
6219: $key = unescape($key) unless $escapedkeys;
6220: next if $key =~ /^error: 2 /;
1.1252 raeburn 6221: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 6222: }
6223: #return %returnhash;
6224: return \%returnhash;
6225: }
6226:
6227: # see Lond::dump_with_regexp
6228: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6229: sub dump {
1.1180 droeschl 6230: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6231: if (!$udomain) { $udomain=$env{'user.domain'}; }
6232: if (!$uname) { $uname=$env{'user.name'}; }
6233: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6234:
1.1266 raeburn 6235: if ($regexp) {
6236: $regexp=&escape($regexp);
6237: } else {
6238: $regexp='.';
6239: }
1.1180 droeschl 6240: if (grep { $_ eq $uhome } current_machine_ids()) {
6241: # user is hosted on this machine
1.1266 raeburn 6242: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 6243: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 6244: return %{unserialize($reply, $escapedkeys)};
6245: }
1.1166 raeburn 6246: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6247: my @pairs=split(/\&/,$rep);
6248: my %returnhash=();
1.1098 foxr 6249: if (!($rep =~ /^error/ )) {
6250: foreach my $item (@pairs) {
6251: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 6252: $key = unescape($key) unless $escapedkeys;
6253: #$key = &unescape($key);
1.1098 foxr 6254: next if ($key =~ /^error: 2 /);
6255: $returnhash{$key}=&thaw_unescape($value);
6256: }
1.755 albertel 6257: }
6258: return %returnhash;
1.407 www 6259: }
6260:
1.1098 foxr 6261:
1.717 albertel 6262: # --------------------------------------------------------- dumpstore interface
6263:
6264: sub dumpstore {
6265: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 6266: # same as dump but keys must be escaped. They may contain colon separated
6267: # lists of values that may themself contain colons (e.g. symbs).
6268: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6269: }
6270:
1.407 www 6271: # -------------------------------------------------------------- keys interface
6272:
6273: sub getkeys {
6274: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6275: if (!$udomain) { $udomain=$env{'user.domain'}; }
6276: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6277: my $uhome=&homeserver($uname,$udomain);
6278: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6279: my @keyarray=();
1.800 albertel 6280: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6281: next if ($key =~ /^error: 2 /);
1.800 albertel 6282: push(@keyarray,&unescape($key));
1.407 www 6283: }
6284: return @keyarray;
1.318 matthew 6285: }
6286:
1.319 matthew 6287: # --------------------------------------------------------------- currentdump
6288: sub currentdump {
1.328 matthew 6289: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6290: $courseid = $env{'request.course.id'} if (! defined($courseid));
6291: $sdom = $env{'user.domain'} if (! defined($sdom));
6292: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6293: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 6294: my $rep;
6295:
6296: if (grep { $_ eq $uhome } current_machine_ids()) {
6297: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6298: $courseid)));
6299: } else {
6300: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6301: }
6302:
1.318 matthew 6303: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6304: #
1.318 matthew 6305: my %returnhash=();
1.319 matthew 6306: #
6307: if ($rep eq "unknown_cmd") {
6308: # an old lond will not know currentdump
6309: # Do a dump and make it look like a currentdump
1.822 albertel 6310: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6311: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6312: my %hash = @tmp;
6313: @tmp=();
1.424 matthew 6314: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6315: } else {
6316: my @pairs=split(/\&/,$rep);
1.800 albertel 6317: foreach my $pair (@pairs) {
6318: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6319: my ($symb,$param) = split(/:/,$key);
6320: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6321: &thaw_unescape($value);
1.319 matthew 6322: }
1.191 harris41 6323: }
1.12 www 6324: return %returnhash;
1.424 matthew 6325: }
6326:
6327: sub convert_dump_to_currentdump{
6328: my %hash = %{shift()};
6329: my %returnhash;
6330: # Code ripped from lond, essentially. The only difference
6331: # here is the unescaping done by lonnet::dump(). Conceivably
6332: # we might run in to problems with parameter names =~ /^v\./
6333: while (my ($key,$value) = each(%hash)) {
6334: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6335: $symb = &unescape($symb);
6336: $param = &unescape($param);
1.424 matthew 6337: next if ($v eq 'version' || $symb eq 'keys');
6338: next if (exists($returnhash{$symb}) &&
6339: exists($returnhash{$symb}->{$param}) &&
6340: $returnhash{$symb}->{'v.'.$param} > $v);
6341: $returnhash{$symb}->{$param}=$value;
6342: $returnhash{$symb}->{'v.'.$param}=$v;
6343: }
6344: #
6345: # Remove all of the keys in the hashes which keep track of
6346: # the version of the parameter.
6347: while (my ($symb,$param_hash) = each(%returnhash)) {
6348: # use a foreach because we are going to delete from the hash.
6349: foreach my $key (keys(%$param_hash)) {
6350: delete($param_hash->{$key}) if ($key =~ /^v\./);
6351: }
6352: }
6353: return \%returnhash;
1.12 www 6354: }
6355:
1.627 albertel 6356: # ------------------------------------------------------ critical inc interface
6357:
6358: sub cinc {
6359: return &inc(@_,'critical');
6360: }
6361:
1.449 matthew 6362: # --------------------------------------------------------------- inc interface
6363:
6364: sub inc {
1.627 albertel 6365: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6366: if (!$udomain) { $udomain=$env{'user.domain'}; }
6367: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6368: my $uhome=&homeserver($uname,$udomain);
6369: my $items='';
6370: if (! ref($store)) {
6371: # got a single value, so use that instead
6372: $items = &escape($store).'=&';
6373: } elsif (ref($store) eq 'SCALAR') {
6374: $items = &escape($$store).'=&';
6375: } elsif (ref($store) eq 'ARRAY') {
6376: $items = join('=&',map {&escape($_);} @{$store});
6377: } elsif (ref($store) eq 'HASH') {
6378: while (my($key,$value) = each(%{$store})) {
6379: $items.= &escape($key).'='.&escape($value).'&';
6380: }
6381: }
6382: $items=~s/\&$//;
1.627 albertel 6383: if ($critical) {
6384: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6385: } else {
6386: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6387: }
1.449 matthew 6388: }
6389:
1.12 www 6390: # --------------------------------------------------------------- put interface
6391:
6392: sub put {
1.134 albertel 6393: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6394: if (!$udomain) { $udomain=$env{'user.domain'}; }
6395: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6396: my $uhome=&homeserver($uname,$udomain);
1.12 www 6397: my $items='';
1.800 albertel 6398: foreach my $item (keys(%$storehash)) {
6399: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6400: }
1.12 www 6401: $items=~s/\&$//;
1.134 albertel 6402: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6403: }
6404:
1.631 albertel 6405: # ------------------------------------------------------------ newput interface
6406:
6407: sub newput {
6408: my ($namespace,$storehash,$udomain,$uname)=@_;
6409: if (!$udomain) { $udomain=$env{'user.domain'}; }
6410: if (!$uname) { $uname=$env{'user.name'}; }
6411: my $uhome=&homeserver($uname,$udomain);
6412: my $items='';
6413: foreach my $key (keys(%$storehash)) {
6414: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6415: }
6416: $items=~s/\&$//;
6417: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6418: }
6419:
6420: # --------------------------------------------------------- putstore interface
6421:
1.524 raeburn 6422: sub putstore {
1.1269 raeburn 6423: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6424: if (!$udomain) { $udomain=$env{'user.domain'}; }
6425: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6426: my $uhome=&homeserver($uname,$udomain);
6427: my $items='';
1.715 albertel 6428: foreach my $key (keys(%$storehash)) {
6429: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6430: }
1.715 albertel 6431: $items=~s/\&$//;
1.716 albertel 6432: my $esc_symb=&escape($symb);
6433: my $esc_v=&escape($version);
1.715 albertel 6434: my $reply =
1.716 albertel 6435: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6436: $uhome);
1.1269 raeburn 6437: if (($tolog) && ($reply eq 'ok')) {
6438: my $namevalue='';
6439: foreach my $key (keys(%{$storehash})) {
6440: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6441: }
6442: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6443: '&host='.&escape($perlvar{'lonHostID'}).
6444: '&version='.$esc_v.
6445: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6446: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6447: }
1.715 albertel 6448: if ($reply eq 'unknown_cmd') {
1.716 albertel 6449: # gfall back to way things use to be done
1.715 albertel 6450: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6451: $uname);
1.524 raeburn 6452: }
1.715 albertel 6453: return $reply;
6454: }
6455:
6456: sub old_putstore {
1.716 albertel 6457: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6458: if (!$udomain) { $udomain=$env{'user.domain'}; }
6459: if (!$uname) { $uname=$env{'user.name'}; }
6460: my $uhome=&homeserver($uname,$udomain);
6461: my %newstorehash;
1.800 albertel 6462: foreach my $item (keys(%$storehash)) {
6463: my $key = $version.':'.&escape($symb).':'.$item;
6464: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6465: }
6466: my $items='';
6467: my %allitems = ();
1.800 albertel 6468: foreach my $item (keys(%newstorehash)) {
6469: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6470: my $key = $1.':keys:'.$2;
6471: $allitems{$key} .= $3.':';
6472: }
1.800 albertel 6473: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6474: }
1.800 albertel 6475: foreach my $item (keys(%allitems)) {
6476: $allitems{$item} =~ s/\:$//;
6477: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6478: }
6479: $items=~s/\&$//;
6480: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6481: }
6482:
1.47 www 6483: # ------------------------------------------------------ critical put interface
6484:
6485: sub cput {
1.134 albertel 6486: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6487: if (!$udomain) { $udomain=$env{'user.domain'}; }
6488: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6489: my $uhome=&homeserver($uname,$udomain);
1.47 www 6490: my $items='';
1.800 albertel 6491: foreach my $item (keys(%$storehash)) {
6492: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6493: }
1.47 www 6494: $items=~s/\&$//;
1.134 albertel 6495: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6496: }
6497:
6498: # -------------------------------------------------------------- eget interface
6499:
6500: sub eget {
1.133 albertel 6501: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6502: my $items='';
1.800 albertel 6503: foreach my $item (@$storearr) {
6504: $items.=&escape($item).'&';
1.191 harris41 6505: }
1.12 www 6506: $items=~s/\&$//;
1.620 albertel 6507: if (!$udomain) { $udomain=$env{'user.domain'}; }
6508: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6509: my $uhome=&homeserver($uname,$udomain);
6510: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6511: my @pairs=split(/\&/,$rep);
6512: my %returnhash=();
1.42 www 6513: my $i=0;
1.800 albertel 6514: foreach my $item (@$storearr) {
6515: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6516: $i++;
1.191 harris41 6517: }
1.12 www 6518: return %returnhash;
6519: }
6520:
1.667 albertel 6521: # ------------------------------------------------------------ tmpput interface
6522: sub tmpput {
1.802 raeburn 6523: my ($storehash,$server,$context)=@_;
1.667 albertel 6524: my $items='';
1.800 albertel 6525: foreach my $item (keys(%$storehash)) {
6526: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6527: }
6528: $items=~s/\&$//;
1.802 raeburn 6529: if (defined($context)) {
6530: $items .= ':'.&escape($context);
6531: }
1.667 albertel 6532: return &reply("tmpput:$items",$server);
6533: }
6534:
6535: # ------------------------------------------------------------ tmpget interface
6536: sub tmpget {
1.688 albertel 6537: my ($token,$server)=@_;
6538: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6539: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6540: my %returnhash;
1.1328 raeburn 6541: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6542: return %returnhash;
6543: }
1.667 albertel 6544: foreach my $item (split(/\&/,$rep)) {
6545: my ($key,$value)=split(/=/,$item);
6546: $returnhash{&unescape($key)}=&thaw_unescape($value);
6547: }
6548: return %returnhash;
6549: }
6550:
1.1113 raeburn 6551: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6552: sub tmpdel {
6553: my ($token,$server)=@_;
6554: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6555: return &reply("tmpdel:$token",$server);
6556: }
6557:
1.1198 raeburn 6558: # ------------------------------------------------------------ get_timebased_id
6559:
6560: sub get_timebased_id {
6561: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6562: $maxtries) = @_;
6563: my ($newid,$error,$dellock);
6564: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6565: return ('','ok','invalid call to get suffix');
6566: }
6567:
6568: # set defaults for any optional args for which values were not supplied
6569: if ($who eq '') {
6570: $who = $env{'user.name'}.':'.$env{'user.domain'};
6571: }
6572: if (!$locktries) {
6573: $locktries = 3;
6574: }
6575: if (!$maxtries) {
6576: $maxtries = 10;
6577: }
6578:
6579: if (($cdom eq '') || ($cnum eq '')) {
6580: if ($env{'request.course.id'}) {
6581: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6582: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6583: }
6584: if (($cdom eq '') || ($cnum eq '')) {
6585: return ('','ok','call to get suffix not in course context');
6586: }
6587: }
6588:
6589: # construct locking item
6590: my $lockhash = {
6591: $prefix."\0".'locked_'.$keyid => $who,
6592: };
6593: my $tries = 0;
6594:
6595: # attempt to get lock on nohist_$namespace file
6596: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6597: while (($gotlock ne 'ok') && $tries <$locktries) {
6598: $tries ++;
6599: sleep 1;
6600: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6601: }
6602:
6603: # attempt to get unique identifier, based on current timestamp
6604: if ($gotlock eq 'ok') {
6605: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6606: my $id = time;
6607: $newid = $id;
1.1268 raeburn 6608: if ($idtype eq 'addcode') {
6609: $newid .= &sixnum_code();
6610: }
1.1198 raeburn 6611: my $idtries = 0;
6612: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6613: if ($idtype eq 'concat') {
6614: $newid = $id.$idtries;
1.1268 raeburn 6615: } elsif ($idtype eq 'addcode') {
6616: $newid = $newid.&sixnum_code();
1.1198 raeburn 6617: } else {
6618: $newid ++;
6619: }
6620: $idtries ++;
6621: }
6622: if (!exists($inuse{$prefix."\0".$newid})) {
6623: my %new_item = (
6624: $prefix."\0".$newid => $who,
6625: );
6626: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6627: $cdom,$cnum);
6628: if ($putresult ne 'ok') {
6629: undef($newid);
6630: $error = 'error saving new item: '.$putresult;
6631: }
6632: } else {
1.1268 raeburn 6633: undef($newid);
1.1198 raeburn 6634: $error = ('error: no unique suffix available for the new item ');
6635: }
6636: # remove lock
6637: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6638: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6639: } else {
6640: $error = "error: could not obtain lockfile\n";
6641: $dellock = 'ok';
1.1276 raeburn 6642: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6643: $dellock = 'nolock';
6644: }
1.1198 raeburn 6645: }
6646: return ($newid,$dellock,$error);
6647: }
6648:
1.1268 raeburn 6649: sub sixnum_code {
6650: my $code;
6651: for (0..6) {
6652: $code .= int( rand(9) );
6653: }
6654: return $code;
6655: }
6656:
1.765 albertel 6657: # -------------------------------------------------- portfolio access checking
6658:
6659: sub portfolio_access {
1.1270 raeburn 6660: my ($requrl,$clientip) = @_;
1.765 albertel 6661: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6662: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6663: if ($result) {
6664: my %setters;
6665: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6666: my ($startblock,$endblock) =
6667: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6668: if ($startblock && $endblock) {
6669: return 'B';
6670: }
6671: } else {
6672: my ($startblock,$endblock) =
6673: &Apache::loncommon::blockcheck(\%setters,'port');
6674: if ($startblock && $endblock) {
6675: return 'B';
6676: }
6677: }
6678: }
1.765 albertel 6679: if ($result eq 'ok') {
1.766 albertel 6680: return 'F';
1.765 albertel 6681: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6682: return 'A';
1.765 albertel 6683: }
1.766 albertel 6684: return '';
1.765 albertel 6685: }
6686:
6687: sub get_portfolio_access {
1.1270 raeburn 6688: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6689:
6690: if (!ref($access_hash)) {
6691: my $current_perms = &get_portfile_permissions($udom,$unum);
6692: my %access_controls = &get_access_controls($current_perms,$group,
6693: $file_name);
6694: $access_hash = $access_controls{$file_name};
6695: }
6696:
1.1270 raeburn 6697: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6698: my $now = time;
6699: if (ref($access_hash) eq 'HASH') {
6700: foreach my $key (keys(%{$access_hash})) {
6701: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6702: if ($start > $now) {
6703: next;
6704: }
6705: if ($end && $end<$now) {
6706: next;
6707: }
6708: if ($scope eq 'public') {
6709: $public = $key;
6710: last;
6711: } elsif ($scope eq 'guest') {
6712: $guest = $key;
6713: } elsif ($scope eq 'domains') {
6714: push(@domains,$key);
6715: } elsif ($scope eq 'users') {
6716: push(@users,$key);
6717: } elsif ($scope eq 'course') {
6718: push(@courses,$key);
6719: } elsif ($scope eq 'group') {
6720: push(@groups,$key);
1.1270 raeburn 6721: } elsif ($scope eq 'ip') {
6722: push(@ips,$key);
1.765 albertel 6723: }
6724: }
6725: if ($public) {
6726: return 'ok';
1.1270 raeburn 6727: } elsif (@ips > 0) {
6728: my $allowed;
6729: foreach my $ipkey (@ips) {
6730: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6731: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6732: $allowed = 1;
6733: last;
6734: }
6735: }
6736: }
6737: if ($allowed) {
6738: return 'ok';
6739: }
1.765 albertel 6740: }
6741: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6742: if ($guest) {
6743: return $guest;
6744: }
6745: } else {
6746: if (@domains > 0) {
6747: foreach my $domkey (@domains) {
6748: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6749: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6750: return 'ok';
6751: }
6752: }
6753: }
6754: }
6755: if (@users > 0) {
6756: foreach my $userkey (@users) {
1.865 raeburn 6757: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6758: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6759: if (ref($item) eq 'HASH') {
6760: if (($item->{'uname'} eq $env{'user.name'}) &&
6761: ($item->{'udom'} eq $env{'user.domain'})) {
6762: return 'ok';
6763: }
6764: }
6765: }
6766: }
1.765 albertel 6767: }
6768: }
6769: my %roleshash;
6770: my @courses_and_groups = @courses;
6771: push(@courses_and_groups,@groups);
6772: if (@courses_and_groups > 0) {
6773: my (%allgroups,%allroles);
6774: my ($start,$end,$role,$sec,$group);
6775: foreach my $envkey (%env) {
1.1060 raeburn 6776: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6777: my $cid = $2.'_'.$3;
6778: if ($1 eq 'gr') {
6779: $group = $4;
6780: $allgroups{$cid}{$group} = $env{$envkey};
6781: } else {
6782: if ($4 eq '') {
6783: $sec = 'none';
6784: } else {
6785: $sec = $4;
6786: }
6787: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6788: }
1.811 albertel 6789: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6790: my $cid = $2.'_'.$3;
6791: if ($4 eq '') {
6792: $sec = 'none';
6793: } else {
6794: $sec = $4;
6795: }
6796: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6797: }
6798: }
6799: if (keys(%allroles) == 0) {
6800: return;
6801: }
6802: foreach my $key (@courses_and_groups) {
6803: my %content = %{$$access_hash{$key}};
6804: my $cnum = $content{'number'};
6805: my $cdom = $content{'domain'};
6806: my $cid = $cdom.'_'.$cnum;
6807: if (!exists($allroles{$cid})) {
6808: next;
6809: }
6810: foreach my $role_id (keys(%{$content{'roles'}})) {
6811: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6812: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6813: my @status = @{$content{'roles'}{$role_id}{'access'}};
6814: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6815: foreach my $role (keys(%{$allroles{$cid}})) {
6816: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6817: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6818: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6819: if (grep/^all$/,@sections) {
6820: return 'ok';
6821: } else {
6822: if (grep/^$sec$/,@sections) {
6823: return 'ok';
6824: }
6825: }
6826: }
6827: }
6828: if (keys(%{$allgroups{$cid}}) == 0) {
6829: if (grep/^none$/,@groups) {
6830: return 'ok';
6831: }
6832: } else {
6833: if (grep/^all$/,@groups) {
6834: return 'ok';
6835: }
6836: foreach my $group (keys(%{$allgroups{$cid}})) {
6837: if (grep/^$group$/,@groups) {
6838: return 'ok';
6839: }
6840: }
6841: }
6842: }
6843: }
6844: }
6845: }
6846: }
6847: if ($guest) {
6848: return $guest;
6849: }
6850: }
6851: }
6852: return;
6853: }
6854:
6855: sub course_group_datechecker {
6856: my ($dates,$now,$status) = @_;
6857: my ($start,$end) = split(/\./,$dates);
6858: if (!$start && !$end) {
6859: return 'ok';
6860: }
6861: if (grep/^active$/,@{$status}) {
6862: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6863: return 'ok';
6864: }
6865: }
6866: if (grep/^previous$/,@{$status}) {
6867: if ($end > $now ) {
6868: return 'ok';
6869: }
6870: }
6871: if (grep/^future$/,@{$status}) {
6872: if ($start > $now) {
6873: return 'ok';
6874: }
6875: }
6876: return;
6877: }
6878:
6879: sub parse_portfolio_url {
6880: my ($url) = @_;
6881:
6882: my ($type,$udom,$unum,$group,$file_name);
6883:
1.823 albertel 6884: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6885: $type = 1;
6886: $udom = $1;
6887: $unum = $2;
6888: $file_name = $3;
1.823 albertel 6889: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6890: $type = 2;
6891: $udom = $1;
6892: $unum = $2;
6893: $group = $3;
6894: $file_name = $3.'/'.$4;
6895: }
6896: if (wantarray) {
6897: return ($type,$udom,$unum,$file_name,$group);
6898: }
6899: return $type;
6900: }
6901:
6902: sub is_portfolio_url {
6903: my ($url) = @_;
6904: return scalar(&parse_portfolio_url($url));
6905: }
6906:
1.798 raeburn 6907: sub is_portfolio_file {
6908: my ($file) = @_;
1.820 raeburn 6909: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6910: return 1;
6911: }
6912: return;
6913: }
6914:
1.976 raeburn 6915: sub usertools_access {
1.1084 raeburn 6916: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6917: my ($access,%tools);
6918: if ($context eq '') {
6919: $context = 'tools';
6920: }
6921: if ($context eq 'requestcourses') {
6922: %tools = (
6923: official => 1,
6924: unofficial => 1,
1.1006 raeburn 6925: community => 1,
1.1246 raeburn 6926: textbook => 1,
1.1305 raeburn 6927: placement => 1,
1.985 raeburn 6928: );
1.1183 raeburn 6929: } elsif ($context eq 'requestauthor') {
6930: %tools = (
6931: requestauthor => 1,
6932: );
1.985 raeburn 6933: } else {
6934: %tools = (
6935: aboutme => 1,
6936: blog => 1,
1.1177 raeburn 6937: webdav => 1,
1.985 raeburn 6938: portfolio => 1,
6939: );
6940: }
1.976 raeburn 6941: return if (!defined($tools{$tool}));
6942:
1.1242 raeburn 6943: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6944: $udom = $env{'user.domain'};
6945: $uname = $env{'user.name'};
6946: }
6947:
1.978 raeburn 6948: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6949: if ($action ne 'reload') {
1.985 raeburn 6950: if ($context eq 'requestcourses') {
6951: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6952: } elsif ($context eq 'requestauthor') {
6953: return $env{'environment.canrequest.author'};
1.985 raeburn 6954: } else {
6955: return $env{'environment.availabletools.'.$tool};
6956: }
6957: }
1.976 raeburn 6958: }
6959:
1.1183 raeburn 6960: my ($toolstatus,$inststatus,$envkey);
6961: if ($context eq 'requestauthor') {
6962: $envkey = $context;
6963: } else {
6964: $envkey = $context.'.'.$tool;
6965: }
1.976 raeburn 6966:
1.985 raeburn 6967: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6968: ($action ne 'reload')) {
1.1183 raeburn 6969: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6970: $inststatus = $env{'environment.inststatus'};
6971: } else {
1.1084 raeburn 6972: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6973: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6974: $inststatus = $userenvref->{'inststatus'};
6975: } else {
1.1183 raeburn 6976: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6977: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6978: $inststatus = $userenv{'inststatus'};
6979: }
1.976 raeburn 6980: }
6981:
6982: if ($toolstatus ne '') {
6983: if ($toolstatus) {
6984: $access = 1;
6985: } else {
6986: $access = 0;
6987: }
6988: return $access;
6989: }
6990:
1.1084 raeburn 6991: my ($is_adv,%domdef);
6992: if (ref($is_advref) eq 'HASH') {
6993: $is_adv = $is_advref->{'is_adv'};
6994: } else {
6995: $is_adv = &is_advanced_user($udom,$uname);
6996: }
6997: if (ref($domdefref) eq 'HASH') {
6998: %domdef = %{$domdefref};
6999: } else {
7000: %domdef = &get_domain_defaults($udom);
7001: }
1.976 raeburn 7002: if (ref($domdef{$tool}) eq 'HASH') {
7003: if ($is_adv) {
7004: if ($domdef{$tool}{'_LC_adv'} ne '') {
7005: if ($domdef{$tool}{'_LC_adv'}) {
7006: $access = 1;
7007: } else {
7008: $access = 0;
7009: }
7010: return $access;
7011: }
7012: }
7013: if ($inststatus ne '') {
7014: my ($hasaccess,$hasnoaccess);
7015: foreach my $affiliation (split(/:/,$inststatus)) {
7016: if ($domdef{$tool}{$affiliation} ne '') {
7017: if ($domdef{$tool}{$affiliation}) {
7018: $hasaccess = 1;
7019: } else {
7020: $hasnoaccess = 1;
7021: }
7022: }
7023: }
7024: if ($hasaccess || $hasnoaccess) {
7025: if ($hasaccess) {
7026: $access = 1;
7027: } elsif ($hasnoaccess) {
7028: $access = 0;
7029: }
7030: return $access;
7031: }
7032: } else {
7033: if ($domdef{$tool}{'default'} ne '') {
7034: if ($domdef{$tool}{'default'}) {
7035: $access = 1;
7036: } elsif ($domdef{$tool}{'default'} == 0) {
7037: $access = 0;
7038: }
7039: return $access;
7040: }
7041: }
7042: } else {
1.1177 raeburn 7043: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7044: $access = 1;
7045: } else {
7046: $access = 0;
7047: }
1.976 raeburn 7048: return $access;
7049: }
7050: }
7051:
1.1050 raeburn 7052: sub is_course_owner {
7053: my ($cdom,$cnum,$udom,$uname) = @_;
7054: if (($udom eq '') || ($uname eq '')) {
7055: $udom = $env{'user.domain'};
7056: $uname = $env{'user.name'};
7057: }
7058: unless (($udom eq '') || ($uname eq '')) {
7059: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7060: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7061: return 1;
7062: } else {
7063: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7064: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7065: return 1;
7066: }
7067: }
7068: }
7069: }
7070: return;
7071: }
7072:
1.976 raeburn 7073: sub is_advanced_user {
7074: my ($udom,$uname) = @_;
1.1085 raeburn 7075: if ($udom ne '' && $uname ne '') {
7076: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7077: if (wantarray) {
7078: return ($env{'user.adv'},$env{'user.author'});
7079: } else {
7080: return $env{'user.adv'};
7081: }
1.1085 raeburn 7082: }
7083: }
1.976 raeburn 7084: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7085: my %allroles;
1.1128 raeburn 7086: my ($is_adv,$is_author);
1.976 raeburn 7087: foreach my $role (keys(%roleshash)) {
7088: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7089: my $area = '/'.$tdomain.'/'.$trest;
7090: if ($sec ne '') {
7091: $area .= '/'.$sec;
7092: }
7093: if (($area ne '') && ($trole ne '')) {
7094: my $spec=$trole.'.'.$area;
7095: if ($trole =~ /^cr\//) {
7096: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7097: } elsif ($trole ne 'gr') {
7098: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7099: }
1.1128 raeburn 7100: if ($trole eq 'au') {
7101: $is_author = 1;
7102: }
1.976 raeburn 7103: }
7104: }
7105: foreach my $role (keys(%allroles)) {
7106: last if ($is_adv);
7107: foreach my $item (split(/:/,$allroles{$role})) {
7108: if ($item ne '') {
7109: my ($privilege,$restrictions)=split(/&/,$item);
7110: if ($privilege eq 'adv') {
7111: $is_adv = 1;
7112: last;
7113: }
7114: }
7115: }
7116: }
1.1128 raeburn 7117: if (wantarray) {
7118: return ($is_adv,$is_author);
7119: }
1.976 raeburn 7120: return $is_adv;
7121: }
1.798 raeburn 7122:
1.1035 raeburn 7123: sub check_can_request {
1.1036 raeburn 7124: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7125: my $canreq = 0;
7126: my ($types,$typename) = &Apache::loncommon::course_types();
7127: my @options = ('approval','validate','autolimit');
7128: my $optregex = join('|',@options);
7129: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7130: foreach my $type (@{$types}) {
7131: if (&usertools_access($env{'user.name'},
7132: $env{'user.domain'},
7133: $type,undef,'requestcourses')) {
7134: $canreq ++;
1.1036 raeburn 7135: if (ref($request_domains) eq 'HASH') {
7136: push(@{$request_domains->{$type}},$env{'user.domain'});
7137: }
1.1035 raeburn 7138: if ($dom eq $env{'user.domain'}) {
7139: $can_request->{$type} = 1;
7140: }
7141: }
7142: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7143: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7144: if (@curr > 0) {
1.1036 raeburn 7145: foreach my $item (@curr) {
7146: if (ref($request_domains) eq 'HASH') {
7147: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7148: if ($otherdom ne '') {
7149: if (ref($request_domains->{$type}) eq 'ARRAY') {
7150: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7151: push(@{$request_domains->{$type}},$otherdom);
7152: }
7153: } else {
7154: push(@{$request_domains->{$type}},$otherdom);
7155: }
7156: }
7157: }
7158: }
7159: unless($dom eq $env{'user.domain'}) {
7160: $canreq ++;
1.1035 raeburn 7161: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7162: $can_request->{$type} = 1;
7163: }
7164: }
7165: }
7166: }
7167: }
7168: }
7169: return $canreq;
7170: }
7171:
1.341 www 7172: # ---------------------------------------------- Custom access rule evaluation
7173:
7174: sub customaccess {
7175: my ($priv,$uri)=@_;
1.807 albertel 7176: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7177: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7178: $udom = &LONCAPA::clean_domain($udom);
7179: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7180: my $access=0;
1.800 albertel 7181: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7182: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7183: if ($type eq 'user') {
7184: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7185: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7186: if ($tdom) {
7187: if ($tdom ne $env{'user.domain'}) { next; }
7188: }
1.896 albertel 7189: if ($tuname) {
7190: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7191: }
7192: $access=($effect eq 'allow');
7193: last;
7194: }
7195: } else {
7196: if ($role) {
7197: if ($role ne $urole) { next; }
7198: }
7199: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7200: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7201: if ($tdom) {
7202: if ($tdom ne $udom) { next; }
7203: }
7204: if ($tcrs) {
7205: if ($tcrs ne $ucrs) { next; }
7206: }
7207: if ($tsec) {
7208: if ($tsec ne $usec) { next; }
7209: }
7210: $access=($effect eq 'allow');
7211: last;
7212: }
7213: if ($realm eq '' && $role eq '') {
7214: $access=($effect eq 'allow');
7215: }
1.402 bowersj2 7216: }
1.341 www 7217: }
7218: return $access;
7219: }
7220:
1.103 harris41 7221: # ------------------------------------------------- Check for a user privilege
1.12 www 7222:
7223: sub allowed {
1.1281 raeburn 7224: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7225: my $ver_orguri=$uri;
1.439 www 7226: $uri=&deversion($uri);
1.152 www 7227: my $orguri=$uri;
1.52 www 7228: $uri=&declutter($uri);
1.809 raeburn 7229:
1.810 raeburn 7230: if ($priv eq 'evb') {
7231: # Evade communication block restrictions for specified role in a course
7232: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7233: return $1;
7234: } else {
7235: return;
7236: }
7237: }
7238:
1.620 albertel 7239: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7240: # Free bre access to adm and meta resources
1.775 albertel 7241: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 7242: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7243: && ($priv eq 'bre')) {
1.14 www 7244: return 'F';
1.159 www 7245: }
7246:
1.545 banghart 7247: # Free bre access to user's own portfolio contents
1.714 raeburn 7248: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7249: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7250: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7251: my %setters;
7252: my ($startblock,$endblock) =
7253: &Apache::loncommon::blockcheck(\%setters,'port');
7254: if ($startblock && $endblock) {
7255: return 'B';
7256: } else {
7257: return 'F';
7258: }
1.545 banghart 7259: }
7260:
1.762 raeburn 7261: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7262: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7263: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7264: if (exists($env{'request.course.id'})) {
7265: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7266: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7267: if (($domain eq $cdom) && ($name eq $cnum)) {
7268: my $courseprivid=$env{'request.course.id'};
7269: $courseprivid=~s/\_/\//;
7270: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7271: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7272: return $1;
1.762 raeburn 7273: } else {
7274: if ($env{'request.course.sec'}) {
7275: $courseprivid.='/'.$env{'request.course.sec'};
7276: }
7277: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7278: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7279: return $2;
7280: }
1.714 raeburn 7281: }
7282: }
7283: }
7284: }
7285:
1.159 www 7286: # Free bre to public access
7287:
7288: if ($priv eq 'bre') {
1.238 www 7289: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7290: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7291: return 'F';
7292: }
1.238 www 7293: if ($copyright eq 'priv') {
7294: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7295: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7296: return '';
7297: }
7298: }
7299: if ($copyright eq 'domain') {
7300: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7301: unless (($env{'user.domain'} eq $1) ||
7302: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7303: return '';
7304: }
1.262 matthew 7305: }
1.620 albertel 7306: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7307: # Library role, so allow browsing of resources in this domain.
7308: return 'F';
1.238 www 7309: }
1.341 www 7310: if ($copyright eq 'custom') {
7311: unless (&customaccess($priv,$uri)) { return ''; }
7312: }
1.14 www 7313: }
1.264 matthew 7314: # Domain coordinator is trying to create a course
1.620 albertel 7315: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7316: # uri is the requested domain in this case.
7317: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7318: # a role of dc for the domain in question.
1.620 albertel 7319: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7320: }
1.29 www 7321:
1.52 www 7322: my $thisallowed='';
7323: my $statecond=0;
7324: my $courseprivid='';
7325:
1.1039 raeburn 7326: my $ownaccess;
1.1043 raeburn 7327: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7328: if (($priv eq 'bro') && ($env{'user.author'})) {
7329: if ($uri eq '') {
7330: $ownaccess = 1;
7331: } else {
7332: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7333: my $udom = $env{'user.domain'};
7334: my $uname = $env{'user.name'};
7335: if ($uri =~ m{^\Q$udom\E/?$}) {
7336: $ownaccess = 1;
1.1040 raeburn 7337: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7338: unless ($uri =~ m{\.\./}) {
7339: $ownaccess = 1;
7340: }
7341: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7342: my $now = time;
7343: if ($uri =~ m{^([^/]+)/?$}) {
7344: my $adom = $1;
7345: foreach my $key (keys(%env)) {
1.1042 raeburn 7346: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7347: my ($start,$end) = split('.',$env{$key});
7348: if (($now >= $start) && (!$end || $end < $now)) {
7349: $ownaccess = 1;
7350: last;
7351: }
7352: }
7353: }
7354: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7355: my $adom = $1;
7356: my $aname = $2;
1.1042 raeburn 7357: foreach my $role ('ca','aa') {
7358: if ($env{"user.role.$role./$adom/$aname"}) {
7359: my ($start,$end) =
7360: split('.',$env{"user.role.$role./$adom/$aname"});
7361: if (($now >= $start) && (!$end || $end < $now)) {
7362: $ownaccess = 1;
7363: last;
7364: }
1.1039 raeburn 7365: }
7366: }
7367: }
7368: }
7369: }
7370: }
7371: }
7372:
1.52 www 7373: # Course
7374:
1.620 albertel 7375: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7376: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7377: $thisallowed.=$1;
7378: }
1.52 www 7379: }
1.29 www 7380:
1.52 www 7381: # Domain
7382:
1.620 albertel 7383: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7384: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7385: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7386: $thisallowed.=$1;
7387: }
1.12 www 7388: }
1.52 www 7389:
1.1141 raeburn 7390: # User who is not author or co-author might still be able to edit
7391: # resource of an author in the domain (e.g., if Domain Coordinator).
7392: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7393: (&allowed('mdc',$env{'request.course.id'}))) {
7394: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7395: $thisallowed.=$1;
7396: }
7397: }
7398:
1.52 www 7399: # Course: uri itself is a course
1.66 www 7400: my $courseuri=$uri;
7401: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7402: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7403:
1.620 albertel 7404: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7405: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7406: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7407: $thisallowed.=$1;
7408: }
1.12 www 7409: }
1.29 www 7410:
1.665 albertel 7411: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7412: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7413: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7414: $thisallowed='';
1.671 raeburn 7415: my ($match)=&is_on_map($uri);
7416: if ($match) {
7417: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7418: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 7419: my $value = $1;
7420: if ($noblockcheck) {
7421: $thisallowed.=$value;
1.1162 raeburn 7422: } else {
1.1281 raeburn 7423: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7424: if (@blockers > 0) {
7425: $thisallowed = 'B';
7426: } else {
7427: $thisallowed.=$value;
7428: }
1.1162 raeburn 7429: }
1.671 raeburn 7430: }
7431: } else {
1.705 albertel 7432: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7433: if ($refuri) {
7434: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7435: $thisallowed='F';
1.671 raeburn 7436: } else {
7437: $refuri=&declutter($refuri);
7438: my ($match) = &is_on_map($refuri);
7439: if ($match) {
1.1281 raeburn 7440: if ($noblockcheck) {
7441: $thisallowed='F';
1.1162 raeburn 7442: } else {
1.1281 raeburn 7443: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7444: if (@blockers > 0) {
7445: $thisallowed = 'B';
7446: } else {
7447: $thisallowed='F';
7448: }
1.1162 raeburn 7449: }
1.671 raeburn 7450: }
1.669 raeburn 7451: }
1.671 raeburn 7452: }
7453: }
1.314 www 7454: }
1.492 albertel 7455:
1.766 albertel 7456: if ($priv eq 'bre'
7457: && $thisallowed ne 'F'
7458: && $thisallowed ne '2'
7459: && &is_portfolio_url($uri)) {
1.1270 raeburn 7460: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7461: }
1.1250 raeburn 7462:
1.52 www 7463: # Full access at system, domain or course-wide level? Exit.
1.29 www 7464: if ($thisallowed=~/F/) {
7465: return 'F';
7466: }
7467:
1.52 www 7468: # If this is generating or modifying users, exit with special codes
1.29 www 7469:
1.643 www 7470: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7471: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7472: my ($audom,$auname)=split('/',$uri);
1.643 www 7473: # no author name given, so this just checks on the general right to make a co-author in this domain
7474: unless ($auname) { return $thisallowed; }
7475: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7476: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7477: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7478: ($audom ne $env{'request.role.domain'}))) { return ''; }
7479: }
1.52 www 7480: return $thisallowed;
7481: }
7482: #
1.103 harris41 7483: # Gathered so far: system, domain and course wide privileges
1.52 www 7484: #
7485: # Course: See if uri or referer is an individual resource that is part of
7486: # the course
7487:
1.620 albertel 7488: if ($env{'request.course.id'}) {
1.232 www 7489:
1.620 albertel 7490: $courseprivid=$env{'request.course.id'};
7491: if ($env{'request.course.sec'}) {
7492: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7493: }
7494: $courseprivid=~s/\_/\//;
7495: my $checkreferer=1;
1.232 www 7496: my ($match,$cond)=&is_on_map($uri);
7497: if ($match) {
7498: $statecond=$cond;
1.620 albertel 7499: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7500: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7501: my $value = $1;
7502: if ($priv eq 'bre') {
1.1281 raeburn 7503: if ($noblockcheck) {
7504: $thisallowed.=$value;
1.1162 raeburn 7505: } else {
1.1281 raeburn 7506: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7507: if (@blockers > 0) {
7508: $thisallowed = 'B';
7509: } else {
7510: $thisallowed.=$value;
7511: }
1.1162 raeburn 7512: }
7513: } else {
7514: $thisallowed.=$value;
7515: }
1.52 www 7516: $checkreferer=0;
7517: }
1.29 www 7518: }
1.83 www 7519:
1.148 www 7520: if ($checkreferer) {
1.620 albertel 7521: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7522: unless ($refuri) {
1.800 albertel 7523: foreach my $key (keys(%env)) {
7524: if ($key=~/^httpref\..*\*/) {
7525: my $pattern=$key;
1.156 www 7526: $pattern=~s/^httpref\.\/res\///;
1.148 www 7527: $pattern=~s/\*/\[\^\/\]\+/g;
7528: $pattern=~s/\//\\\//g;
1.152 www 7529: if ($orguri=~/$pattern/) {
1.800 albertel 7530: $refuri=$env{$key};
1.148 www 7531: }
7532: }
1.191 harris41 7533: }
1.148 www 7534: }
1.232 www 7535:
1.148 www 7536: if ($refuri) {
1.152 www 7537: $refuri=&declutter($refuri);
1.232 www 7538: my ($match,$cond)=&is_on_map($refuri);
7539: if ($match) {
7540: my $refstatecond=$cond;
1.620 albertel 7541: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7542: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7543: my $value = $1;
7544: if ($priv eq 'bre') {
1.1281 raeburn 7545: if ($noblockcheck) {
7546: $thisallowed.=$value;
1.1162 raeburn 7547: } else {
1.1281 raeburn 7548: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7549: if (@blockers > 0) {
7550: $thisallowed = 'B';
7551: } else {
7552: $thisallowed.=$value;
7553: }
1.1162 raeburn 7554: }
7555: } else {
7556: $thisallowed.=$value;
7557: }
1.53 www 7558: $uri=$refuri;
7559: $statecond=$refstatecond;
1.52 www 7560: }
7561: }
1.148 www 7562: }
1.29 www 7563: }
1.52 www 7564: }
1.29 www 7565:
1.52 www 7566: #
1.103 harris41 7567: # Gathered now: all privileges that could apply, and condition number
1.52 www 7568: #
7569: #
7570: # Full or no access?
7571: #
1.29 www 7572:
1.52 www 7573: if ($thisallowed=~/F/) {
7574: return 'F';
7575: }
1.29 www 7576:
1.52 www 7577: unless ($thisallowed) {
7578: return '';
7579: }
1.29 www 7580:
1.52 www 7581: # Restrictions exist, deal with them
7582: #
7583: # C:according to course preferences
7584: # R:according to resource settings
7585: # L:unless locked
7586: # X:according to user session state
7587: #
7588:
7589: # Possibly locked functionality, check all courses
1.54 www 7590: # Locks might take effect only after 10 minutes cache expiration for other
7591: # courses, and 2 minutes for current course
1.52 www 7592:
7593: my $envkey;
7594: if ($thisallowed=~/L/) {
1.1000 raeburn 7595: foreach $envkey (keys(%env)) {
1.54 www 7596: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7597: my $courseid=$2;
7598: my $roleid=$1.'.'.$2;
1.92 www 7599: $courseid=~s/^\///;
1.54 www 7600: my $expiretime=600;
1.620 albertel 7601: if ($env{'request.role'} eq $roleid) {
1.54 www 7602: $expiretime=120;
7603: }
7604: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7605: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7606: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7607: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7608: }
1.620 albertel 7609: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7610: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7611: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7612: &log($env{'user.domain'},$env{'user.name'},
7613: $env{'user.home'},
1.57 www 7614: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7615: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7616: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7617: return '';
7618: }
7619: }
1.620 albertel 7620: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7621: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7622: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7623: &log($env{'user.domain'},$env{'user.name'},
7624: $env{'user.home'},
1.57 www 7625: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7626: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7627: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7628: return '';
7629: }
7630: }
7631: }
1.29 www 7632: }
1.52 www 7633: }
7634:
7635: #
7636: # Rest of the restrictions depend on selected course
7637: #
7638:
1.620 albertel 7639: unless ($env{'request.course.id'}) {
1.766 albertel 7640: if ($thisallowed eq 'A') {
7641: return 'A';
1.814 raeburn 7642: } elsif ($thisallowed eq 'B') {
7643: return 'B';
1.766 albertel 7644: } else {
7645: return '1';
7646: }
1.52 www 7647: }
1.29 www 7648:
1.52 www 7649: #
7650: # Now user is definitely in a course
7651: #
1.53 www 7652:
7653:
7654: # Course preferences
7655:
7656: if ($thisallowed=~/C/) {
1.620 albertel 7657: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7658: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7659: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7660: =~/\Q$rolecode\E/) {
1.1304 raeburn 7661: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7662: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7663: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7664: $env{'request.course.id'});
7665: }
1.237 www 7666: return '';
7667: }
7668:
1.620 albertel 7669: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7670: =~/\Q$unamedom\E/) {
1.1304 raeburn 7671: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7672: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7673: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7674: $env{'request.course.id'});
7675: }
1.54 www 7676: return '';
7677: }
1.53 www 7678: }
7679:
7680: # Resource preferences
7681:
7682: if ($thisallowed=~/R/) {
1.620 albertel 7683: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7684: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7685: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7686: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7687: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7688: }
7689: return '';
1.54 www 7690: }
1.53 www 7691: }
1.30 www 7692:
1.246 www 7693: # Restricted by state or randomout?
1.30 www 7694:
1.52 www 7695: if ($thisallowed=~/X/) {
1.620 albertel 7696: if ($env{'acc.randomout'}) {
1.579 albertel 7697: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7698: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7699: return '';
7700: }
1.247 www 7701: }
7702: if (&condval($statecond)) {
1.52 www 7703: return '2';
7704: } else {
7705: return '';
7706: }
7707: }
1.30 www 7708:
1.766 albertel 7709: if ($thisallowed eq 'A') {
7710: return 'A';
1.814 raeburn 7711: } elsif ($thisallowed eq 'B') {
7712: return 'B';
1.766 albertel 7713: }
1.52 www 7714: return 'F';
1.232 www 7715: }
1.1162 raeburn 7716:
1.1192 raeburn 7717: # ------------------------------------------- Check construction space access
7718:
7719: sub constructaccess {
7720: my ($url,$setpriv)=@_;
7721:
7722: # We do not allow editing of previous versions of files
7723: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7724:
7725: # Get username and domain from URL
7726: my ($ownername,$ownerdomain,$ownerhome);
7727:
7728: ($ownerdomain,$ownername) =
1.1325 raeburn 7729: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 7730:
7731: # The URL does not really point to any authorspace, forget it
7732: unless (($ownername) && ($ownerdomain)) { return ''; }
7733:
7734: # Now we need to see if the user has access to the authorspace of
7735: # $ownername at $ownerdomain
7736:
7737: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7738: # Real author for this?
7739: $ownerhome = $env{'user.home'};
7740: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7741: return ($ownername,$ownerdomain,$ownerhome);
7742: }
7743: } else {
7744: # Co-author for this?
7745: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7746: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7747: $ownerhome = &homeserver($ownername,$ownerdomain);
7748: return ($ownername,$ownerdomain,$ownerhome);
7749: }
1.1312 raeburn 7750: if ($env{'request.course.id'}) {
7751: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
7752: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
7753: if (&allowed('mdc',$env{'request.course.id'})) {
7754: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
7755: return ($ownername,$ownerdomain,$ownerhome);
7756: }
7757: }
7758: }
1.1192 raeburn 7759: }
7760:
7761: # We don't have any access right now. If we are not possibly going to do anything about this,
7762: # we might as well leave
7763: unless ($setpriv) { return ''; }
7764:
7765: # Backdoor access?
7766: my $allowed=&allowed('eco',$ownerdomain);
7767: # Nope
7768: unless ($allowed) { return ''; }
7769: # Looks like we may have access, but could be locked by the owner of the construction space
7770: if ($allowed eq 'U') {
7771: my %blocked=&get('environment',['domcoord.author'],
7772: $ownerdomain,$ownername);
7773: # Is blocked by owner
7774: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7775: }
7776: if (($allowed eq 'F') || ($allowed eq 'U')) {
7777: # Grant temporary access
7778: my $then=$env{'user.login.time'};
1.1209 raeburn 7779: my $update=$env{'user.update.time'};
1.1192 raeburn 7780: if (!$update) { $update = $then; }
7781: my $refresh=$env{'user.refresh.time'};
7782: if (!$refresh) { $refresh = $update; }
7783: my $now = time;
7784: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7785: $now,'ca','constructaccess');
7786: $ownerhome = &homeserver($ownername,$ownerdomain);
7787: return($ownername,$ownerdomain,$ownerhome);
7788: }
7789: # No business here
7790: return '';
7791: }
7792:
1.1282 raeburn 7793: # ----------------------------------------------------------- Content Blocking
7794:
7795: {
7796: # Caches for faster Course Contents display where content blocking
7797: # is in operation (i.e., interval param set) for timed quiz.
7798: #
7799: # User for whom data are being temporarily cached.
7800: my $cacheduser='';
7801: # Cached blockers for this user (a hash of blocking items).
7802: my %cachedblockers=();
7803: # When the data were last cached.
7804: my $cachedlast='';
7805:
7806: sub load_all_blockers {
7807: my ($uname,$udom,$blocks)=@_;
7808: if (($uname ne '') && ($udom ne '')) {
7809: if (($cacheduser eq $uname.':'.$udom) &&
7810: (abs($cachedlast-time)<5)) {
7811: return;
7812: }
7813: }
7814: $cachedlast=time;
7815: $cacheduser=$uname.':'.$udom;
7816: %cachedblockers = &get_commblock_resources($blocks);
7817: }
7818:
1.1162 raeburn 7819: sub get_comm_blocks {
7820: my ($cdom,$cnum) = @_;
7821: if ($cdom eq '' || $cnum eq '') {
7822: return unless ($env{'request.course.id'});
7823: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7824: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7825: }
7826: my %commblocks;
7827: my $hashid=$cdom.'_'.$cnum;
7828: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7829: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7830: %commblocks = %{$blocksref};
7831: } else {
7832: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7833: my $cachetime = 600;
7834: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7835: }
7836: return %commblocks;
7837: }
7838:
1.1282 raeburn 7839: sub get_commblock_resources {
7840: my ($blocks) = @_;
7841: my %blockers = ();
7842: return %blockers unless ($env{'request.course.id'});
7843: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7844: my %commblocks;
7845: if (ref($blocks) eq 'HASH') {
7846: %commblocks = %{$blocks};
7847: } else {
7848: %commblocks = &get_comm_blocks();
7849: }
1.1282 raeburn 7850: return %blockers unless (keys(%commblocks) > 0);
7851: my $navmap = Apache::lonnavmaps::navmap->new();
7852: return %blockers unless (ref($navmap));
1.1162 raeburn 7853: my $now = time;
7854: foreach my $block (keys(%commblocks)) {
7855: if ($block =~ /^(\d+)____(\d+)$/) {
7856: my ($start,$end) = ($1,$2);
7857: if ($start <= $now && $end >= $now) {
7858: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7859: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7860: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 7861: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7862: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7863: }
7864: }
7865: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 7866: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7867: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7868: }
7869: }
7870: }
7871: }
7872: }
7873: } elsif ($block =~ /^firstaccess____(.+)$/) {
7874: my $item = $1;
1.1163 raeburn 7875: my @to_test;
1.1162 raeburn 7876: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7877: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 7878: my @interval;
7879: my $type = 'map';
7880: if ($item eq 'course') {
7881: $type = 'course';
7882: @interval=&EXT("resource.0.interval");
7883: } else {
7884: if ($item =~ /___\d+___/) {
7885: $type = 'resource';
7886: @interval=&EXT("resource.0.interval",$item);
7887: if (ref($navmap)) {
7888: my $res = $navmap->getBySymb($item);
7889: push(@to_test,$res);
7890: }
1.1162 raeburn 7891: } else {
1.1282 raeburn 7892: my $mapsymb = &symbread($item,1);
7893: if ($mapsymb) {
7894: if (ref($navmap)) {
7895: my $mapres = $navmap->getBySymb($mapsymb);
7896: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7897: foreach my $res (@to_test) {
7898: my $symb = $res->symb();
7899: next if ($symb eq $mapsymb);
7900: if ($symb ne '') {
7901: @interval=&EXT("resource.0.interval",$symb);
7902: if ($interval[1] eq 'map') {
7903: last;
1.1162 raeburn 7904: }
7905: }
7906: }
7907: }
7908: }
7909: }
1.1282 raeburn 7910: }
1.1310 raeburn 7911: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 7912: my $timelimit = $1;
1.1282 raeburn 7913: my $first_access;
7914: if ($type eq 'resource') {
7915: $first_access=&get_first_access($interval[1],$item);
7916: } elsif ($type eq 'map') {
7917: $first_access=&get_first_access($interval[1],undef,$item);
7918: } else {
7919: $first_access=&get_first_access($interval[1]);
7920: }
7921: if ($first_access) {
1.1292 raeburn 7922: my $timesup = $first_access+$timelimit;
1.1282 raeburn 7923: if ($timesup > $now) {
7924: my $activeblock;
7925: foreach my $res (@to_test) {
1.1283 raeburn 7926: if ($res->answerable()) {
1.1282 raeburn 7927: $activeblock = 1;
7928: last;
7929: }
7930: }
7931: if ($activeblock) {
7932: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7933: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7934: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7935: }
7936: }
7937: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7938: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7939: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7940: }
1.1162 raeburn 7941: }
7942: }
7943: }
7944: }
7945: }
7946: }
7947: }
7948: }
7949: }
1.1282 raeburn 7950: return %blockers;
1.1162 raeburn 7951: }
7952:
1.1282 raeburn 7953: sub has_comm_blocking {
7954: my ($priv,$symb,$uri,$blocks) = @_;
7955: my @blockers;
7956: return unless ($env{'request.course.id'});
7957: return unless ($priv eq 'bre');
7958: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7959: return if ($env{'request.state'} eq 'construct');
7960: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7961: return unless (keys(%cachedblockers) > 0);
7962: my (%possibles,@symbs);
7963: if (!$symb) {
7964: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7965: }
1.1282 raeburn 7966: if ($symb) {
7967: @symbs = ($symb);
7968: } elsif (keys(%possibles)) {
7969: @symbs = keys(%possibles);
7970: }
7971: my $noblock;
7972: foreach my $symb (@symbs) {
7973: last if ($noblock);
7974: my ($map,$resid,$resurl)=&decode_symb($symb);
7975: foreach my $block (keys(%cachedblockers)) {
7976: if ($block =~ /^firstaccess____(.+)$/) {
7977: my $item = $1;
7978: if (($item eq $map) || ($item eq $symb)) {
7979: $noblock = 1;
7980: last;
7981: }
7982: }
7983: if (ref($cachedblockers{$block}) eq 'HASH') {
7984: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7985: if ($cachedblockers{$block}{'resources'}{$symb}) {
7986: unless (grep(/^\Q$block\E$/,@blockers)) {
7987: push(@blockers,$block);
7988: }
7989: }
7990: }
1.1162 raeburn 7991: }
1.1282 raeburn 7992: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7993: if ($cachedblockers{$block}{'maps'}{$map}) {
7994: unless (grep(/^\Q$block\E$/,@blockers)) {
7995: push(@blockers,$block);
7996: }
7997: }
1.1162 raeburn 7998: }
7999: }
8000: }
1.1282 raeburn 8001: return if ($noblock);
8002: return @blockers;
8003: }
1.1162 raeburn 8004: }
8005:
1.1282 raeburn 8006: # -------------------------------- Deversion and split uri into path an filename
8007:
1.1133 foxr 8008: #
1.1282 raeburn 8009: # Removes the version from a URI and
1.1133 foxr 8010: # splits it in to its filename and path to the filename.
8011: # Seems like File::Basename could have done this more clearly.
8012: # Parameters:
8013: # $uri - input URI
8014: # Returns:
8015: # Two element list consisting of
8016: # $pathname - the URI up to and excluding the trailing /
8017: # $filename - The part of the URI following the last /
8018: # NOTE:
8019: # Another realization of this is simply:
8020: # use File::Basename;
8021: # ...
8022: # $uri = shift;
8023: # $filename = basename($uri);
8024: # $path = dirname($uri);
8025: # return ($filename, $path);
8026: #
8027: # The implementation below is probably faster however.
8028: #
1.710 albertel 8029: sub split_uri_for_cond {
8030: my $uri=&deversion(&declutter(shift));
8031: my @uriparts=split(/\//,$uri);
8032: my $filename=pop(@uriparts);
8033: my $pathname=join('/',@uriparts);
8034: return ($pathname,$filename);
8035: }
1.232 www 8036: # --------------------------------------------------- Is a resource on the map?
8037:
8038: sub is_on_map {
1.710 albertel 8039: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8040: #Trying to find the conditional for the file
1.620 albertel 8041: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8042: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8043: if ($match) {
1.289 bowersj2 8044: return (1,$1);
8045: } else {
1.434 www 8046: return (0,0);
1.289 bowersj2 8047: }
1.12 www 8048: }
8049:
1.427 www 8050: # --------------------------------------------------------- Get symb from alias
8051:
8052: sub get_symb_from_alias {
8053: my $symb=shift;
8054: my ($map,$resid,$url)=&decode_symb($symb);
8055: # Already is a symb
8056: if ($url) { return $symb; }
8057: # Must be an alias
8058: my $aliassymb='';
8059: my %bighash;
1.620 albertel 8060: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8061: &GDBM_READER(),0640)) {
8062: my $rid=$bighash{'mapalias_'.$symb};
8063: if ($rid) {
8064: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8065: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8066: $resid,$bighash{'src_'.$rid});
1.427 www 8067: }
8068: untie %bighash;
8069: }
8070: return $aliassymb;
8071: }
8072:
1.12 www 8073: # ----------------------------------------------------------------- Define Role
8074:
8075: sub definerole {
8076: if (allowed('mcr','/')) {
1.1326 raeburn 8077: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8078: foreach my $role (split(':',$sysrole)) {
8079: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8080: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8081: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8082: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8083: return "refused:s:$crole&$cqual";
8084: }
8085: }
1.191 harris41 8086: }
1.800 albertel 8087: foreach my $role (split(':',$domrole)) {
8088: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8089: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8090: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8091: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8092: return "refused:d:$crole&$cqual";
8093: }
8094: }
1.191 harris41 8095: }
1.800 albertel 8096: foreach my $role (split(':',$courole)) {
8097: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8098: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8099: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8100: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8101: return "refused:c:$crole&$cqual";
8102: }
8103: }
1.191 harris41 8104: }
1.1326 raeburn 8105: my $uhome;
8106: if (($uname ne '') && ($udom ne '')) {
8107: $uhome = &homeserver($uname,$udom);
8108: return $uhome if ($uhome eq 'no_host');
8109: } else {
8110: $uname = $env{'user.name'};
8111: $udom = $env{'user.domain'};
8112: $uhome = $env{'user.home'};
8113: }
1.620 albertel 8114: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 8115: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8116: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 8117: return reply($command,$uhome);
1.12 www 8118: } else {
8119: return 'refused';
8120: }
1.105 harris41 8121: }
8122:
8123: # ---------------- Make a metadata query against the network of library servers
8124:
8125: sub metadata_query {
1.1237 raeburn 8126: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8127: my %rhash;
1.845 albertel 8128: my %libserv = &all_library();
1.244 matthew 8129: my @server_list = (defined($server_array) ? @$server_array
8130: : keys(%libserv) );
8131: for my $server (@server_list) {
1.1237 raeburn 8132: my $domains = '';
8133: if (ref($domains_hash) eq 'HASH') {
8134: $domains = $domains_hash->{$server};
8135: }
1.118 harris41 8136: unless ($custom or $customshow) {
1.1237 raeburn 8137: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8138: $rhash{$server}=$reply;
8139: }
8140: else {
8141: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 8142: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8143: $server);
8144: $rhash{$server}=$reply;
8145: }
1.112 harris41 8146: }
1.118 harris41 8147: return \%rhash;
1.240 www 8148: }
8149:
8150: # ----------------------------------------- Send log queries and wait for reply
8151:
8152: sub log_query {
8153: my ($uname,$udom,$query,%filters)=@_;
8154: my $uhome=&homeserver($uname,$udom);
8155: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8156: my $uhost=&hostname($uhome);
1.800 albertel 8157: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8158: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8159: $uhome);
1.479 albertel 8160: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8161: return get_query_reply($queryid);
8162: }
8163:
1.818 raeburn 8164: # -------------------------- Update MySQL table for portfolio file
8165:
8166: sub update_portfolio_table {
1.821 raeburn 8167: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8168: if ($group ne '') {
8169: $file_name =~s /^\Q$group\E//;
8170: }
1.818 raeburn 8171: my $homeserver = &homeserver($uname,$udom);
8172: my $queryid=
1.821 raeburn 8173: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8174: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8175: my $reply = &get_query_reply($queryid);
8176: return $reply;
8177: }
8178:
1.899 raeburn 8179: # -------------------------- Update MySQL allusers table
8180:
8181: sub update_allusers_table {
8182: my ($uname,$udom,$names) = @_;
8183: my $homeserver = &homeserver($uname,$udom);
8184: my $queryid=
8185: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8186: 'lastname='.&escape($names->{'lastname'}).'%%'.
8187: 'firstname='.&escape($names->{'firstname'}).'%%'.
8188: 'middlename='.&escape($names->{'middlename'}).'%%'.
8189: 'generation='.&escape($names->{'generation'}).'%%'.
8190: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8191: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8192: return;
1.899 raeburn 8193: }
8194:
1.508 raeburn 8195: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8196:
8197: sub fetch_enrollment_query {
1.511 raeburn 8198: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 8199: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8200: my $maxtries = 1;
1.508 raeburn 8201: if ($context eq 'automated') {
8202: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 8203: $sleep = 2;
8204: $loopmax = 100;
1.547 raeburn 8205: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8206: } else {
8207: $homeserver = &homeserver($cnum,$dom);
8208: }
1.838 albertel 8209: my $host=&hostname($homeserver);
1.506 raeburn 8210: my $cmd = '';
1.1000 raeburn 8211: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8212: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8213: }
8214: $cmd =~ s/%%$//;
8215: $cmd = &escape($cmd);
8216: my $query = 'fetchenrollment';
1.620 albertel 8217: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8218: unless ($queryid=~/^\Q$host\E\_/) {
8219: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8220: return 'error: '.$queryid;
8221: }
1.1317 raeburn 8222: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8223: my $tries = 1;
8224: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 8225: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8226: $tries ++;
8227: }
1.526 raeburn 8228: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8229: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8230: } else {
1.901 albertel 8231: my @responses = split(/:/,$reply);
1.1322 raeburn 8232: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8233: foreach my $line (@responses) {
8234: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8235: $$replyref{$key} = $value;
8236: }
8237: } else {
1.1117 foxr 8238: my $pathname = LONCAPA::tempdir();
1.800 albertel 8239: foreach my $line (@responses) {
8240: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8241: $$replyref{$key} = $value;
8242: if ($value > 0) {
1.800 albertel 8243: foreach my $item (@{$$affiliatesref{$key}}) {
8244: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8245: my $destname = $pathname.'/'.$filename;
8246: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8247: if ($xml_classlist =~ /^error/) {
8248: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8249: } else {
1.506 raeburn 8250: if ( open(FILE,">$destname") ) {
8251: print FILE &unescape($xml_classlist);
8252: close(FILE);
1.526 raeburn 8253: } else {
8254: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8255: }
8256: }
8257: }
8258: }
8259: }
8260: }
8261: return 'ok';
8262: }
8263: return 'error';
8264: }
8265:
1.242 www 8266: sub get_query_reply {
1.1317 raeburn 8267: my ($queryid,$sleep,$loopmax) = @_;;
8268: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8269: $sleep = 0.2;
8270: }
8271: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8272: $loopmax = 100;
8273: }
1.1117 foxr 8274: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8275: my $reply='';
1.1317 raeburn 8276: for (1..$loopmax) {
8277: sleep($sleep);
1.240 www 8278: if (-e $replyfile.'.end') {
1.448 albertel 8279: if (open(my $fh,$replyfile)) {
1.904 albertel 8280: $reply = join('',<$fh>);
8281: close($fh);
1.240 www 8282: } else { return 'error: reply_file_error'; }
1.242 www 8283: return &unescape($reply);
8284: }
1.240 www 8285: }
1.242 www 8286: return 'timeout:'.$queryid;
1.240 www 8287: }
8288:
8289: sub courselog_query {
1.241 www 8290: #
8291: # possible filters:
8292: # url: url or symb
8293: # username
8294: # domain
8295: # action: view, submit, grade
8296: # start: timestamp
8297: # end: timestamp
8298: #
1.240 www 8299: my (%filters)=@_;
1.620 albertel 8300: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8301: if ($filters{'url'}) {
8302: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8303: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8304: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8305: }
1.620 albertel 8306: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8307: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8308: return &log_query($cname,$cdom,'courselog',%filters);
8309: }
8310:
8311: sub userlog_query {
1.858 raeburn 8312: #
8313: # possible filters:
8314: # action: log check role
8315: # start: timestamp
8316: # end: timestamp
8317: #
1.240 www 8318: my ($uname,$udom,%filters)=@_;
8319: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8320: }
8321:
1.506 raeburn 8322: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8323:
8324: sub auto_run {
1.508 raeburn 8325: my ($cnum,$cdom) = @_;
1.876 raeburn 8326: my $response = 0;
8327: my $settings;
8328: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8329: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8330: $settings = $domconfig{'autoenroll'};
8331: if ($settings->{'run'} eq '1') {
8332: $response = 1;
8333: }
8334: } else {
1.934 raeburn 8335: my $homeserver;
8336: if (&is_course($cdom,$cnum)) {
8337: $homeserver = &homeserver($cnum,$cdom);
8338: } else {
8339: $homeserver = &domain($cdom,'primary');
8340: }
8341: if ($homeserver ne 'no_host') {
8342: $response = &reply('autorun:'.$cdom,$homeserver);
8343: }
1.876 raeburn 8344: }
1.506 raeburn 8345: return $response;
8346: }
1.776 albertel 8347:
1.506 raeburn 8348: sub auto_get_sections {
1.508 raeburn 8349: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8350: my $homeserver;
8351: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8352: $homeserver = &homeserver($cnum,$cdom);
8353: }
8354: if (!defined($homeserver)) {
8355: if ($cdom =~ /^$match_domain$/) {
8356: $homeserver = &domain($cdom,'primary');
8357: }
8358: }
8359: my @secs;
8360: if (defined($homeserver)) {
8361: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8362: unless ($response eq 'refused') {
8363: @secs = split(/:/,$response);
8364: }
1.506 raeburn 8365: }
8366: return @secs;
8367: }
1.776 albertel 8368:
1.506 raeburn 8369: sub auto_new_course {
1.1099 raeburn 8370: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8371: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8372: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8373: return $response;
8374: }
1.776 albertel 8375:
1.506 raeburn 8376: sub auto_validate_courseID {
1.508 raeburn 8377: my ($cnum,$cdom,$inst_course_id) = @_;
8378: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8379: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8380: return $response;
8381: }
1.776 albertel 8382:
1.1007 raeburn 8383: sub auto_validate_instcode {
1.1020 raeburn 8384: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8385: my ($homeserver,$response);
8386: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8387: $homeserver = &homeserver($cnum,$cdom);
8388: }
8389: if (!defined($homeserver)) {
8390: if ($cdom =~ /^$match_domain$/) {
8391: $homeserver = &domain($cdom,'primary');
8392: }
8393: }
1.1065 raeburn 8394: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8395: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 8396: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8397: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8398: }
8399:
1.506 raeburn 8400: sub auto_create_password {
1.873 raeburn 8401: my ($cnum,$cdom,$authparam,$udom) = @_;
8402: my ($homeserver,$response);
1.506 raeburn 8403: my $create_passwd = 0;
8404: my $authchk = '';
1.873 raeburn 8405: if ($udom =~ /^$match_domain$/) {
8406: $homeserver = &domain($udom,'primary');
8407: }
8408: if ($homeserver eq '') {
8409: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8410: $homeserver = &homeserver($cnum,$cdom);
8411: }
8412: }
8413: if ($homeserver eq '') {
8414: $authchk = 'nodomain';
1.506 raeburn 8415: } else {
1.873 raeburn 8416: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8417: if ($response eq 'refused') {
8418: $authchk = 'refused';
8419: } else {
1.901 albertel 8420: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8421: }
1.506 raeburn 8422: }
8423: return ($authparam,$create_passwd,$authchk);
8424: }
8425:
1.706 raeburn 8426: sub auto_photo_permission {
8427: my ($cnum,$cdom,$students) = @_;
8428: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8429: my ($outcome,$perm_reqd,$conditions) =
8430: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8431: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8432: return (undef,undef);
8433: }
1.706 raeburn 8434: return ($outcome,$perm_reqd,$conditions);
8435: }
8436:
8437: sub auto_checkphotos {
8438: my ($uname,$udom,$pid) = @_;
8439: my $homeserver = &homeserver($uname,$udom);
8440: my ($result,$resulttype);
8441: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8442: &escape($uname).':'.&escape($pid),
8443: $homeserver));
1.709 albertel 8444: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8445: return (undef,undef);
8446: }
1.706 raeburn 8447: if ($outcome) {
8448: ($result,$resulttype) = split(/:/,$outcome);
8449: }
8450: return ($result,$resulttype);
8451: }
8452:
8453: sub auto_photochoice {
8454: my ($cnum,$cdom) = @_;
8455: my $homeserver = &homeserver($cnum,$cdom);
8456: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8457: &escape($cdom),
8458: $homeserver)));
1.709 albertel 8459: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8460: return (undef,undef);
8461: }
1.706 raeburn 8462: return ($update,$comment);
8463: }
8464:
8465: sub auto_photoupdate {
8466: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8467: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8468: my $host=&hostname($homeserver);
1.706 raeburn 8469: my $cmd = '';
8470: my $maxtries = 1;
1.800 albertel 8471: foreach my $affiliate (keys(%{$affiliatesref})) {
8472: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8473: }
8474: $cmd =~ s/%%$//;
8475: $cmd = &escape($cmd);
8476: my $query = 'institutionalphotos';
8477: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8478: unless ($queryid=~/^\Q$host\E\_/) {
8479: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8480: return 'error: '.$queryid;
8481: }
8482: my $reply = &get_query_reply($queryid);
8483: my $tries = 1;
8484: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8485: $reply = &get_query_reply($queryid);
8486: $tries ++;
8487: }
8488: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8489: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8490: } else {
8491: my @responses = split(/:/,$reply);
8492: my $outcome = shift(@responses);
8493: foreach my $item (@responses) {
8494: my ($key,$value) = split(/=/,$item);
8495: $$photo{$key} = $value;
8496: }
8497: return $outcome;
8498: }
8499: return 'error';
8500: }
8501:
1.521 raeburn 8502: sub auto_instcode_format {
1.793 albertel 8503: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8504: $cat_order) = @_;
1.521 raeburn 8505: my $courses = '';
1.772 raeburn 8506: my @homeservers;
1.521 raeburn 8507: if ($caller eq 'global') {
1.841 albertel 8508: my %servers = &get_servers($codedom,'library');
8509: foreach my $tryserver (keys(%servers)) {
8510: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8511: push(@homeservers,$tryserver);
8512: }
1.584 raeburn 8513: }
1.1022 raeburn 8514: } elsif ($caller eq 'requests') {
8515: if ($codedom =~ /^$match_domain$/) {
8516: my $chome = &domain($codedom,'primary');
8517: unless ($chome eq 'no_host') {
8518: push(@homeservers,$chome);
8519: }
8520: }
1.521 raeburn 8521: } else {
1.772 raeburn 8522: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8523: }
1.793 albertel 8524: foreach my $code (keys(%{$instcodes})) {
8525: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8526: }
8527: chop($courses);
1.772 raeburn 8528: my $ok_response = 0;
8529: my $response;
8530: while (@homeservers > 0 && $ok_response == 0) {
8531: my $server = shift(@homeservers);
8532: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8533: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8534: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8535: split(/:/,$response);
1.772 raeburn 8536: %{$codes} = (%{$codes},&str2hash($codes_str));
8537: push(@{$codetitles},&str2array($codetitles_str));
8538: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8539: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8540: $ok_response = 1;
8541: }
8542: }
8543: if ($ok_response) {
1.521 raeburn 8544: return 'ok';
1.772 raeburn 8545: } else {
8546: return $response;
1.521 raeburn 8547: }
8548: }
8549:
1.792 raeburn 8550: sub auto_instcode_defaults {
8551: my ($domain,$returnhash,$code_order) = @_;
8552: my @homeservers;
1.841 albertel 8553:
8554: my %servers = &get_servers($domain,'library');
8555: foreach my $tryserver (keys(%servers)) {
8556: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8557: push(@homeservers,$tryserver);
8558: }
1.792 raeburn 8559: }
1.841 albertel 8560:
1.792 raeburn 8561: my $response;
1.841 albertel 8562: foreach my $server (@homeservers) {
1.792 raeburn 8563: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8564: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8565:
8566: foreach my $pair (split(/\&/,$response)) {
8567: my ($name,$value)=split(/\=/,$pair);
8568: if ($name eq 'code_order') {
8569: @{$code_order} = split(/\&/,&unescape($value));
8570: } else {
8571: $returnhash->{&unescape($name)}=&unescape($value);
8572: }
8573: }
8574: return 'ok';
1.792 raeburn 8575: }
1.841 albertel 8576:
8577: return $response;
1.1003 raeburn 8578: }
8579:
8580: sub auto_possible_instcodes {
1.1007 raeburn 8581: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8582: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8583: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8584: return;
8585: }
1.1003 raeburn 8586: my (@homeservers,$uhome);
8587: if (defined(&domain($domain,'primary'))) {
8588: $uhome=&domain($domain,'primary');
8589: push(@homeservers,&domain($domain,'primary'));
8590: } else {
8591: my %servers = &get_servers($domain,'library');
8592: foreach my $tryserver (keys(%servers)) {
8593: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8594: push(@homeservers,$tryserver);
8595: }
8596: }
8597: }
8598: my $response;
8599: foreach my $server (@homeservers) {
8600: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8601: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8602: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8603: split(':',$response);
8604: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8605: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8606: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8607: my ($name,$value)=split('=',$item);
8608: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8609: }
8610: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8611: my ($name,$value)=split('=',$item);
8612: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8613: }
8614: return 'ok';
8615: }
8616: return $response;
8617: }
1.792 raeburn 8618:
1.1010 raeburn 8619: sub auto_courserequest_checks {
8620: my ($dom) = @_;
1.1020 raeburn 8621: my ($homeserver,%validations);
8622: if ($dom =~ /^$match_domain$/) {
8623: $homeserver = &domain($dom,'primary');
8624: }
8625: unless ($homeserver eq 'no_host') {
8626: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8627: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8628: my @items = split(/&/,$response);
8629: foreach my $item (@items) {
8630: my ($key,$value) = split('=',$item);
8631: $validations{&unescape($key)} = &thaw_unescape($value);
8632: }
8633: }
8634: }
1.1010 raeburn 8635: return %validations;
8636: }
8637:
1.1020 raeburn 8638: sub auto_courserequest_validation {
1.1255 raeburn 8639: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8640: my ($homeserver,$response);
8641: if ($dom =~ /^$match_domain$/) {
8642: $homeserver = &domain($dom,'primary');
8643: }
1.1255 raeburn 8644: unless ($homeserver eq 'no_host') {
8645: my $customdata;
8646: if (ref($custominfo) eq 'HASH') {
8647: $customdata = &freeze_escape($custominfo);
8648: }
1.1020 raeburn 8649: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8650: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8651: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8652: $customdata,$homeserver));
1.1020 raeburn 8653: }
8654: return $response;
8655: }
8656:
1.777 albertel 8657: sub auto_validate_class_sec {
1.918 raeburn 8658: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8659: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8660: my $ownerlist;
8661: if (ref($owners) eq 'ARRAY') {
8662: $ownerlist = join(',',@{$owners});
8663: } else {
8664: $ownerlist = $owners;
8665: }
1.773 raeburn 8666: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8667: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8668: return $response;
8669: }
8670:
1.1248 raeburn 8671: sub auto_crsreq_update {
8672: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8673: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8674: my ($homeserver,%crsreqresponse);
8675: if ($cdom =~ /^$match_domain$/) {
8676: $homeserver = &domain($cdom,'primary');
8677: }
8678: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8679: my $info;
8680: if (ref($inbound) eq 'HASH') {
8681: $info = &freeze_escape($inbound);
8682: }
8683: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8684: ':'.&escape($action).':'.&escape($ownername).':'.
8685: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8686: &escape($title).':'.&escape($code).':'.
8687: &escape($accessstart).':'.&escape($accessend).':'.$info,
8688: $homeserver);
1.1248 raeburn 8689: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8690: my @items = split(/&/,$response);
8691: foreach my $item (@items) {
8692: my ($key,$value) = split('=',$item);
8693: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8694: }
8695: }
8696: }
8697: return \%crsreqresponse;
8698: }
8699:
1.1305 raeburn 8700: sub auto_export_grades {
1.1309 raeburn 8701: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8702: my ($homeserver,%exportresponse);
8703: if ($cdom =~ /^$match_domain$/) {
8704: $homeserver = &domain($cdom,'primary');
8705: }
8706: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8707: my $info;
8708: if (ref($inforef) eq 'HASH') {
8709: $info = &freeze_escape($inforef);
8710: }
8711: if (ref($gradesref) eq 'HASH') {
8712: my $grades = &freeze_escape($gradesref);
8713: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8714: $info.':'.$grades,$homeserver);
8715: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8716: my @items = split(/&/,$response);
8717: foreach my $item (@items) {
8718: my ($key,$value) = split('=',$item);
8719: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8720: }
8721: }
8722: }
8723: }
8724: return \%exportresponse;
1.1305 raeburn 8725: }
8726:
1.1287 raeburn 8727: sub check_instcode_cloning {
8728: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8729: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8730: return;
8731: }
8732: my $canclone;
8733: if (@{$code_order} > 0) {
8734: my $instcoderegexp ='^';
8735: my @clonecodes = split(/\&/,$cloner);
8736: foreach my $item (@{$code_order}) {
8737: if (grep(/^\Q$item\E=/,@clonecodes)) {
8738: foreach my $pair (@clonecodes) {
8739: my ($key,$val) = split(/\=/,$pair,2);
8740: $val = &unescape($val);
8741: if ($key eq $item) {
8742: $instcoderegexp .= '('.$val.')';
8743: last;
8744: }
8745: }
8746: } else {
8747: $instcoderegexp .= $codedefaults->{$item};
8748: }
8749: }
8750: $instcoderegexp .= '$';
8751: my (@from,@to);
8752: eval {
8753: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8754: (@to) = ($clonetocode =~ /$instcoderegexp/);
8755: };
8756: if ((@from > 0) && (@to > 0)) {
8757: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8758: if (!@diffs) {
8759: $canclone = 1;
8760: }
8761: }
8762: }
8763: return $canclone;
8764: }
8765:
8766: sub default_instcode_cloning {
8767: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8768: my (%codedefaults,@code_order,$canclone);
8769: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8770: %codedefaults = %{$codedefaultsref};
8771: @code_order = @{$codeorderref};
8772: } elsif ($clonedom) {
8773: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8774: }
8775: if (($domdefclone) && (@code_order)) {
8776: my @clonecodes = split(/\+/,$domdefclone);
8777: my $instcoderegexp ='^';
8778: foreach my $item (@code_order) {
8779: if (grep(/^\Q$item\E$/,@clonecodes)) {
8780: $instcoderegexp .= '('.$codedefaults{$item}.')';
8781: } else {
8782: $instcoderegexp .= $codedefaults{$item};
8783: }
8784: }
8785: $instcoderegexp .= '$';
8786: my (@from,@to);
8787: eval {
8788: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8789: (@to) = ($clonetocode =~ /$instcoderegexp/);
8790: };
8791: if ((@from > 0) && (@to > 0)) {
8792: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8793: if (!@diffs) {
8794: $canclone = 1;
8795: }
8796: }
8797: }
8798: return $canclone;
8799: }
8800:
1.679 raeburn 8801: # ------------------------------------------------------- Course Group routines
8802:
8803: sub get_coursegroups {
1.809 raeburn 8804: my ($cdom,$cnum,$group,$namespace) = @_;
8805: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8806: }
8807:
1.679 raeburn 8808: sub modify_coursegroup {
8809: my ($cdom,$cnum,$groupsettings) = @_;
8810: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8811: }
8812:
1.809 raeburn 8813: sub toggle_coursegroup_status {
8814: my ($cdom,$cnum,$group,$action) = @_;
8815: my ($from_namespace,$to_namespace);
8816: if ($action eq 'delete') {
8817: $from_namespace = 'coursegroups';
8818: $to_namespace = 'deleted_groups';
8819: } else {
8820: $from_namespace = 'deleted_groups';
8821: $to_namespace = 'coursegroups';
8822: }
8823: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8824: if (my $tmp = &error(%curr_group)) {
8825: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8826: return ('read error',$tmp);
8827: } else {
8828: my %savedsettings = %curr_group;
1.809 raeburn 8829: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8830: my $deloutcome;
8831: if ($result eq 'ok') {
1.809 raeburn 8832: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8833: } else {
8834: return ('write error',$result);
8835: }
8836: if ($deloutcome eq 'ok') {
8837: return 'ok';
8838: } else {
8839: return ('delete error',$deloutcome);
8840: }
8841: }
8842: }
8843:
1.679 raeburn 8844: sub modify_group_roles {
1.957 raeburn 8845: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8846: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8847: my $role = 'gr/'.&escape($userprivs);
8848: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8849: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8850: if ($result eq 'ok') {
8851: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8852: }
1.679 raeburn 8853: return $result;
8854: }
8855:
8856: sub modify_coursegroup_membership {
8857: my ($cdom,$cnum,$membership) = @_;
8858: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8859: return $result;
8860: }
8861:
1.682 raeburn 8862: sub get_active_groups {
8863: my ($udom,$uname,$cdom,$cnum) = @_;
8864: my $now = time;
8865: my %groups = ();
8866: foreach my $key (keys(%env)) {
1.811 albertel 8867: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8868: my ($start,$end) = split(/\./,$env{$key});
8869: if (($end!=0) && ($end<$now)) { next; }
8870: if (($start!=0) && ($start>$now)) { next; }
8871: if ($1 eq $cdom && $2 eq $cnum) {
8872: $groups{$3} = $env{$key} ;
8873: }
8874: }
8875: }
8876: return %groups;
8877: }
8878:
1.683 raeburn 8879: sub get_group_membership {
8880: my ($cdom,$cnum,$group) = @_;
8881: return(&dump('groupmembership',$cdom,$cnum,$group));
8882: }
8883:
8884: sub get_users_groups {
8885: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8886: my @usersgroups;
1.683 raeburn 8887: my $cachetime=1800;
8888:
8889: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8890: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8891: if (defined($cached)) {
1.734 albertel 8892: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8893: } else {
8894: $grouplist = '';
1.816 raeburn 8895: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8896: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8897: my $access_end = $env{'course.'.$courseid.
8898: '.default_enrollment_end_date'};
8899: my $now = time;
8900: foreach my $key (keys(%roleshash)) {
8901: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8902: my $group = $1;
8903: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8904: my $start = $2;
8905: my $end = $1;
8906: if ($start == -1) { next; } # deleted from group
8907: if (($start!=0) && ($start>$now)) { next; }
8908: if (($end!=0) && ($end<$now)) {
8909: if ($access_end && $access_end < $now) {
8910: if ($access_end - $end < 86400) {
8911: push(@usersgroups,$group);
1.733 raeburn 8912: }
8913: }
1.817 raeburn 8914: next;
1.733 raeburn 8915: }
1.817 raeburn 8916: push(@usersgroups,$group);
1.683 raeburn 8917: }
8918: }
8919: }
1.817 raeburn 8920: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8921: $grouplist = join(':',@usersgroups);
8922: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8923: }
1.733 raeburn 8924: return @usersgroups;
1.683 raeburn 8925: }
8926:
8927: sub devalidate_getgroups_cache {
8928: my ($udom,$uname,$cdom,$cnum)=@_;
8929: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8930:
1.683 raeburn 8931: my $hashid="$udom:$uname:$courseid";
8932: &devalidate_cache_new('getgroups',$hashid);
8933: }
8934:
1.12 www 8935: # ------------------------------------------------------------------ Plain Text
8936:
8937: sub plaintext {
1.988 raeburn 8938: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8939: if ($short =~ m{^cr/}) {
1.758 albertel 8940: return (split('/',$short))[-1];
8941: }
1.742 raeburn 8942: if (!defined($cid)) {
8943: $cid = $env{'request.course.id'};
8944: }
8945: my %rolenames = (
1.1008 raeburn 8946: Course => 'std',
8947: Community => 'alt1',
1.1305 raeburn 8948: Placement => 'std',
1.742 raeburn 8949: );
1.1037 raeburn 8950: if ($cid ne '') {
8951: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8952: unless ($forcedefault) {
8953: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8954: &Apache::lonlocal::mt_escape(\$roletext);
8955: return &Apache::lonlocal::mt($roletext);
8956: }
8957: }
8958: }
8959: if ((defined($type)) && (defined($rolenames{$type})) &&
8960: (defined($rolenames{$type})) &&
8961: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8962: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8963: } elsif ($cid ne '') {
8964: my $crstype = $env{'course.'.$cid.'.type'};
8965: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8966: (defined($prp{$short}{$rolenames{$crstype}}))) {
8967: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8968: }
1.742 raeburn 8969: }
1.1037 raeburn 8970: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8971: }
8972:
8973: # ----------------------------------------------------------------- Assign Role
8974:
8975: sub assignrole {
1.957 raeburn 8976: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8977: $context)=@_;
1.21 www 8978: my $mrole;
8979: if ($role =~ /^cr\//) {
1.393 www 8980: my $cwosec=$url;
1.811 albertel 8981: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8982: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8983: my $refused = 1;
8984: if ($context eq 'requestcourses') {
8985: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8986: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8987: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8988: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8989: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8990: if ($crsenv{'internal.courseowner'} eq
8991: $env{'user.name'}.':'.$env{'user.domain'}) {
8992: $refused = '';
8993: }
8994: }
8995: }
8996: }
8997: }
8998: if ($refused) {
8999: &logthis('Refused custom assignrole: '.
9000: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9001: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9002: return 'refused';
9003: }
1.104 www 9004: }
1.21 www 9005: $mrole='cr';
1.678 raeburn 9006: } elsif ($role =~ /^gr\//) {
9007: my $cwogrp=$url;
1.811 albertel 9008: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9009: unless (&allowed('mdg',$cwogrp)) {
9010: &logthis('Refused group assignrole: '.
9011: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9012: $env{'user.name'}.' at '.$env{'user.domain'});
9013: return 'refused';
9014: }
9015: $mrole='gr';
1.21 www 9016: } else {
1.82 www 9017: my $cwosec=$url;
1.811 albertel 9018: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9019: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9020: my $refused;
9021: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9022: if (!(&allowed('c'.$role,$url))) {
9023: $refused = 1;
9024: }
9025: } else {
9026: $refused = 1;
9027: }
1.947 raeburn 9028: if ($refused) {
1.1045 raeburn 9029: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9030: if (!$selfenroll && $context eq 'course') {
9031: my %crsenv;
9032: if ($role eq 'cc' || $role eq 'co') {
9033: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9034: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9035: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9036: if ($crsenv{'internal.courseowner'} eq
9037: $env{'user.name'}.':'.$env{'user.domain'}) {
9038: $refused = '';
9039: }
9040: }
9041: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9042: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9043: if ($crsenv{'internal.courseowner'} eq
9044: $env{'user.name'}.':'.$env{'user.domain'}) {
9045: $refused = '';
9046: }
9047: }
9048: }
9049: }
9050: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9051: $refused = '';
1.1017 raeburn 9052: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9053: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9054: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9055: my $wrongcc;
9056: if ($cnum =~ /^$match_community$/) {
9057: $wrongcc = 1 if ($role eq 'cc');
9058: } else {
9059: $wrongcc = 1 if ($role eq 'co');
9060: }
9061: unless ($wrongcc) {
9062: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9063: if ($crsenv{'internal.courseowner'} eq
9064: $env{'user.name'}.':'.$env{'user.domain'}) {
9065: $refused = '';
9066: }
1.1017 raeburn 9067: }
9068: }
1.1183 raeburn 9069: } elsif ($context eq 'requestauthor') {
9070: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9071: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9072: if ($env{'environment.requestauthor'} eq 'automatic') {
9073: $refused = '';
9074: } else {
9075: my %domdefaults = &get_domain_defaults($udom);
9076: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9077: my $checkbystatus;
9078: if ($env{'user.adv'}) {
9079: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9080: if ($disposition eq 'automatic') {
9081: $refused = '';
9082: } elsif ($disposition eq '') {
9083: $checkbystatus = 1;
9084: }
9085: } else {
9086: $checkbystatus = 1;
9087: }
9088: if ($checkbystatus) {
9089: if ($env{'environment.inststatus'}) {
9090: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9091: foreach my $type (@inststatuses) {
9092: if (($type ne '') &&
9093: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9094: $refused = '';
9095: }
9096: }
9097: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9098: $refused = '';
9099: }
9100: }
9101: }
9102: }
9103: }
1.1017 raeburn 9104: }
9105: if ($refused) {
1.947 raeburn 9106: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9107: ' '.$role.' '.$end.' '.$start.' by '.
9108: $env{'user.name'}.' at '.$env{'user.domain'});
9109: return 'refused';
9110: }
1.932 raeburn 9111: }
1.1131 raeburn 9112: } elsif ($role eq 'au') {
9113: if ($url ne '/'.$udom.'/') {
9114: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9115: ' to assign author role for '.$uname.':'.$udom.
9116: ' in domain: '.$url.' refused (wrong domain).');
9117: return 'refused';
9118: }
1.104 www 9119: }
1.21 www 9120: $mrole=$role;
9121: }
1.620 albertel 9122: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9123: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9124: if ($end) { $command.='_'.$end; }
1.21 www 9125: if ($start) {
9126: if ($end) {
1.81 www 9127: $command.='_'.$start;
1.21 www 9128: } else {
1.81 www 9129: $command.='_0_'.$start;
1.21 www 9130: }
9131: }
1.739 raeburn 9132: my $origstart = $start;
9133: my $origend = $end;
1.957 raeburn 9134: my $delflag;
1.357 www 9135: # actually delete
9136: if ($deleteflag) {
1.373 www 9137: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9138: # modify command to delete the role
1.620 albertel 9139: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9140: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9141: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9142: # set start and finish to negative values for userrolelog
9143: $start=-1;
9144: $end=-1;
1.957 raeburn 9145: $delflag = 1;
1.357 www 9146: }
9147: }
9148: # send command
1.349 www 9149: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9150: # log new user role if status is ok
1.349 www 9151: if ($answer eq 'ok') {
1.663 raeburn 9152: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 9153: if (($role eq 'cc') || ($role eq 'in') ||
9154: ($role eq 'ep') || ($role eq 'ad') ||
9155: ($role eq 'ta') || ($role eq 'st') ||
9156: ($role=~/^cr/) || ($role eq 'gr') ||
9157: ($role eq 'co')) {
1.1200 raeburn 9158: # for course roles, perform group memberships changes triggered by role change.
9159: unless ($role =~ /^gr/) {
9160: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9161: $origstart,$selfenroll,$context);
9162: }
1.1184 raeburn 9163: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9164: $selfenroll,$context);
9165: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 9166: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9167: ($role eq 'da')) {
1.1184 raeburn 9168: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9169: $context);
9170: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9171: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9172: $context);
9173: }
1.1053 raeburn 9174: if ($role eq 'cc') {
9175: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9176: }
1.349 www 9177: }
9178: return $answer;
1.169 harris41 9179: }
9180:
1.1053 raeburn 9181: sub autoupdate_coowners {
9182: my ($url,$end,$start,$uname,$udom) = @_;
9183: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9184: if (($cdom ne '') && ($cnum ne '')) {
9185: my $now = time;
9186: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9187: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9188: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9189: my $instcode = $coursehash{'internal.coursecode'};
9190: if ($instcode ne '') {
1.1056 raeburn 9191: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9192: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9193: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9194: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9195: if ($result eq 'valid') {
9196: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9197: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9198: push(@newcoowners,$coowner);
9199: }
9200: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9201: push(@newcoowners,$uname.':'.$udom);
9202: }
9203: @newcoowners = sort(@newcoowners);
9204: } else {
9205: push(@newcoowners,$uname.':'.$udom);
9206: }
9207: } else {
9208: if ($coursehash{'internal.co-owners'}) {
9209: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9210: unless ($coowner eq $uname.':'.$udom) {
9211: push(@newcoowners,$coowner);
9212: }
9213: }
9214: unless (@newcoowners > 0) {
9215: $delcoowners = 1;
9216: $coowners = '';
9217: }
9218: }
9219: }
9220: if (@newcoowners || $delcoowners) {
9221: &store_coowners($cdom,$cnum,$coursehash{'home'},
9222: $delcoowners,@newcoowners);
9223: }
9224: }
9225: }
9226: }
9227: }
9228: }
9229: }
9230:
9231: sub store_coowners {
9232: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9233: my $cid = $cdom.'_'.$cnum;
9234: my ($coowners,$delresult,$putresult);
9235: if (@newcoowners) {
9236: $coowners = join(',',@newcoowners);
9237: my %coownershash = (
9238: 'internal.co-owners' => $coowners,
9239: );
9240: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9241: if ($putresult eq 'ok') {
9242: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9243: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9244: }
9245: }
9246: }
9247: if ($delcoowners) {
9248: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9249: if ($delresult eq 'ok') {
9250: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9251: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9252: }
9253: }
9254: }
9255: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9256: my %crsinfo =
9257: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9258: if (ref($crsinfo{$cid}) eq 'HASH') {
9259: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9260: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9261: }
9262: }
9263: }
9264:
1.169 harris41 9265: # -------------------------------------------------- Modify user authentication
1.197 www 9266: # Overrides without validation
9267:
1.169 harris41 9268: sub modifyuserauth {
9269: my ($udom,$uname,$umode,$upass)=@_;
9270: my $uhome=&homeserver($uname,$udom);
1.197 www 9271: unless (&allowed('mau',$udom)) { return 'refused'; }
9272: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9273: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9274: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9275: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9276: &escape($upass),$uhome);
1.620 albertel 9277: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9278: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9279: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9280: &log($udom,,$uname,$uhome,
1.620 albertel 9281: 'Authentication changed by '.$env{'user.domain'}.', '.
9282: $env{'user.name'}.', '.$umode.
1.197 www 9283: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9284: unless ($reply eq 'ok') {
1.197 www 9285: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9286: return 'error: '.$reply;
9287: }
1.170 harris41 9288: return 'ok';
1.80 www 9289: }
9290:
1.81 www 9291: # --------------------------------------------------------------- Modify a user
1.80 www 9292:
1.81 www 9293: sub modifyuser {
1.206 matthew 9294: my ($udom, $uname, $uid,
9295: $umode, $upass, $first,
9296: $middle, $last, $gene,
1.1058 raeburn 9297: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9298: $udom= &LONCAPA::clean_domain($udom);
9299: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9300: my $showcandelete = 'none';
9301: if (ref($candelete) eq 'ARRAY') {
9302: if (@{$candelete} > 0) {
9303: $showcandelete = join(', ',@{$candelete});
9304: }
9305: }
1.81 www 9306: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9307: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9308: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9309: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9310: ' desiredhome not specified').
1.620 albertel 9311: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9312: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9313: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9314: my $newuser;
9315: if ($uhome eq 'no_host') {
9316: $newuser = 1;
9317: }
1.80 www 9318: # ----------------------------------------------------------------- Create User
1.406 albertel 9319: if (($uhome eq 'no_host') &&
9320: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9321: my $unhome='';
1.844 albertel 9322: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9323: $unhome = $desiredhome;
1.620 albertel 9324: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9325: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9326: } else { # load balancing routine for determining $unhome
1.81 www 9327: my $loadm=10000000;
1.841 albertel 9328: my %servers = &get_servers($udom,'library');
9329: foreach my $tryserver (keys(%servers)) {
9330: my $answer=reply('load',$tryserver);
9331: if (($answer=~/\d+/) && ($answer<$loadm)) {
9332: $loadm=$answer;
9333: $unhome=$tryserver;
9334: }
1.80 www 9335: }
9336: }
9337: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9338: return 'error: unable to find a home server for '.$uname.
9339: ' in domain '.$udom;
1.80 www 9340: }
9341: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9342: &escape($upass),$unhome);
9343: unless ($reply eq 'ok') {
9344: return 'error: '.$reply;
9345: }
1.230 stredwic 9346: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9347: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9348: return 'error: unable verify users home machine.';
1.80 www 9349: }
1.209 matthew 9350: } # End of creation of new user
1.80 www 9351: # ---------------------------------------------------------------------- Add ID
9352: if ($uid) {
9353: $uid=~tr/A-Z/a-z/;
9354: my %uidhash=&idrget($udom,$uname);
1.196 www 9355: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9356: && (!$forceid)) {
1.80 www 9357: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9358: return 'error: user id "'.$uid.'" does not match '.
9359: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9360: }
9361: } else {
1.1300 raeburn 9362: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 9363: }
9364: }
9365: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9366: my @tmp=&get('environment',
1.899 raeburn 9367: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9368: 'permanentemail','inststatus'],
1.134 albertel 9369: $udom,$uname);
1.1075 raeburn 9370: my (%names,%oldnames);
1.313 matthew 9371: if ($tmp[0] =~ m/^error:.*/) {
9372: %names=();
9373: } else {
9374: %names = @tmp;
1.1075 raeburn 9375: %oldnames = %names;
1.313 matthew 9376: }
1.388 www 9377: #
1.1058 raeburn 9378: # If name, email and/or uid are blank (e.g., because an uploaded file
9379: # of users did not contain them), do not overwrite existing values
9380: # unless field is in $candelete array ref.
9381: #
9382:
9383: my @fields = ('firstname','middlename','lastname','generation',
9384: 'permanentemail','id');
9385: my %newvalues;
9386: if (ref($candelete) eq 'ARRAY') {
9387: foreach my $field (@fields) {
9388: if (grep(/^\Q$field\E$/,@{$candelete})) {
9389: if ($field eq 'firstname') {
9390: $names{$field} = $first;
9391: } elsif ($field eq 'middlename') {
9392: $names{$field} = $middle;
9393: } elsif ($field eq 'lastname') {
9394: $names{$field} = $last;
9395: } elsif ($field eq 'generation') {
9396: $names{$field} = $gene;
9397: } elsif ($field eq 'permanentemail') {
9398: $names{$field} = $email;
9399: } elsif ($field eq 'id') {
9400: $names{$field} = $uid;
9401: }
9402: }
9403: }
9404: }
1.388 www 9405: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9406: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9407: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9408: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9409: if ($email) {
9410: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9411: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9412: }
1.899 raeburn 9413: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9414: if (defined($inststatus)) {
9415: $names{'inststatus'} = '';
9416: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9417: if (ref($usertypes) eq 'HASH') {
9418: my @okstatuses;
9419: foreach my $item (split(/:/,$inststatus)) {
9420: if (defined($usertypes->{$item})) {
9421: push(@okstatuses,$item);
9422: }
9423: }
9424: if (@okstatuses) {
9425: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9426: }
9427: }
9428: }
1.1075 raeburn 9429: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9430: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9431: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9432: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9433: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9434: } else {
9435: $logmsg .= ' during self creation';
9436: }
1.1075 raeburn 9437: my $changed;
9438: if ($newuser) {
9439: $changed = 1;
9440: } else {
9441: foreach my $field (@fields) {
9442: if ($names{$field} ne $oldnames{$field}) {
9443: $changed = 1;
9444: last;
9445: }
9446: }
9447: }
9448: unless ($changed) {
9449: $logmsg = 'No changes in user information needed for: '.$logmsg;
9450: &logthis($logmsg);
9451: return 'ok';
9452: }
9453: my $reply = &put('environment', \%names, $udom,$uname);
9454: if ($reply ne 'ok') {
9455: return 'error: '.$reply;
9456: }
1.1087 raeburn 9457: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9458: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9459: }
1.1075 raeburn 9460: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9461: &devalidate_cache_new('namescache',$uname.':'.$udom);
9462: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9463: &logthis($logmsg);
1.134 albertel 9464: return 'ok';
1.80 www 9465: }
9466:
1.81 www 9467: # -------------------------------------------------------------- Modify student
1.80 www 9468:
1.81 www 9469: sub modifystudent {
9470: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9471: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 9472: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9473: if (!$cid) {
1.620 albertel 9474: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9475: return 'not_in_class';
9476: }
1.80 www 9477: }
9478: # --------------------------------------------------------------- Make the user
1.81 www 9479: my $reply=&modifyuser
1.209 matthew 9480: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9481: $desiredhome,$email,$inststatus);
1.80 www 9482: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9483: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 9484: # student's environment
1.297 matthew 9485: $uid = undef if (!$forceid);
1.455 albertel 9486: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 9487: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 9488: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9489: return $reply;
9490: }
9491:
9492: sub modify_student_enrollment {
1.1216 raeburn 9493: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 9494: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9495: my ($cdom,$cnum,$chome);
9496: if (!$cid) {
1.620 albertel 9497: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9498: return 'not_in_class';
9499: }
1.620 albertel 9500: $cdom=$env{'course.'.$cid.'.domain'};
9501: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9502: } else {
9503: ($cdom,$cnum)=split(/_/,$cid);
9504: }
1.620 albertel 9505: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9506: if (!$chome) {
1.457 raeburn 9507: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9508: }
1.455 albertel 9509: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9510: # Make sure the user exists
1.81 www 9511: my $uhome=&homeserver($uname,$udom);
9512: if (($uhome eq '') || ($uhome eq 'no_host')) {
9513: return 'error: no such user';
9514: }
1.297 matthew 9515: # Get student data if we were not given enough information
9516: if (!defined($first) || $first eq '' ||
9517: !defined($last) || $last eq '' ||
9518: !defined($uid) || $uid eq '' ||
9519: !defined($middle) || $middle eq '' ||
9520: !defined($gene) || $gene eq '') {
1.294 matthew 9521: # They did not supply us with enough data to enroll the student, so
9522: # we need to pick up more information.
1.297 matthew 9523: my %tmp = &get('environment',
1.294 matthew 9524: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9525: ,$udom,$uname);
9526:
1.800 albertel 9527: #foreach my $key (keys(%tmp)) {
9528: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9529: #}
1.294 matthew 9530: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9531: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9532: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9533: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9534: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9535: }
1.556 albertel 9536: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9537: my $user = "$uname:$udom";
9538: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9539: my $reply=cput('classlist',
1.1148 raeburn 9540: {$user =>
1.1314 raeburn 9541: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9542: $cdom,$cnum);
1.1148 raeburn 9543: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9544: &devalidate_getsection_cache($udom,$uname,$cid);
9545: } else {
1.81 www 9546: return 'error: '.$reply;
9547: }
1.297 matthew 9548: # Add student role to user
1.83 www 9549: my $uurl='/'.$cid;
1.81 www 9550: $uurl=~s/\_/\//g;
9551: if ($usec) {
9552: $uurl.='/'.$usec;
9553: }
1.1148 raeburn 9554: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9555: $selfenroll,$context);
9556: if ($result ne 'ok') {
9557: if ($old_entry{$user} ne '') {
9558: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9559: } else {
9560: $reply = &del('classlist',[$user],$cdom,$cnum);
9561: }
9562: }
9563: return $result;
1.21 www 9564: }
9565:
1.556 albertel 9566: sub format_name {
9567: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9568: my $name;
9569: if ($first ne 'lastname') {
9570: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9571: } else {
9572: if ($lastname=~/\S/) {
9573: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9574: $name=~s/\s+,/,/;
9575: } else {
9576: $name.= $firstname.' '.$middlename.' '.$generation;
9577: }
9578: }
9579: $name=~s/^\s+//;
9580: $name=~s/\s+$//;
9581: $name=~s/\s+/ /g;
9582: return $name;
9583: }
9584:
1.84 www 9585: # ------------------------------------------------- Write to course preferences
9586:
9587: sub writecoursepref {
9588: my ($courseid,%prefs)=@_;
9589: $courseid=~s/^\///;
9590: $courseid=~s/\_/\//g;
9591: my ($cdomain,$cnum)=split(/\//,$courseid);
9592: my $chome=homeserver($cnum,$cdomain);
9593: if (($chome eq '') || ($chome eq 'no_host')) {
9594: return 'error: no such course';
9595: }
9596: my $cstring='';
1.800 albertel 9597: foreach my $pref (keys(%prefs)) {
9598: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9599: }
1.84 www 9600: $cstring=~s/\&$//;
9601: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9602: }
9603:
9604: # ---------------------------------------------------------- Make/modify course
9605:
9606: sub createcourse {
1.741 raeburn 9607: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9608: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9609: $url=&declutter($url);
9610: my $cid='';
1.1028 raeburn 9611: if ($context eq 'requestcourses') {
9612: my $can_create = 0;
9613: my ($ownername,$ownerdom) = split(':',$course_owner);
9614: if ($udom eq $ownerdom) {
9615: if (&usertools_access($ownername,$ownerdom,$category,undef,
9616: $context)) {
9617: $can_create = 1;
9618: }
9619: } else {
9620: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9621: $category);
9622: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9623: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9624: if (@curr > 0) {
9625: my @options = qw(approval validate autolimit);
9626: my $optregex = join('|',@options);
9627: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9628: $can_create = 1;
9629: }
9630: }
9631: }
9632: }
9633: if ($can_create) {
9634: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9635: unless (&allowed('ccc',$udom)) {
9636: return 'refused';
9637: }
1.1017 raeburn 9638: }
9639: } else {
9640: return 'refused';
9641: }
1.1028 raeburn 9642: } elsif (!&allowed('ccc',$udom)) {
9643: return 'refused';
1.84 www 9644: }
1.1011 raeburn 9645: # --------------------------------------------------------------- Get Unique ID
9646: my $uname;
9647: if ($cnum =~ /^$match_courseid$/) {
9648: my $chome=&homeserver($cnum,$udom,'true');
9649: if (($chome eq '') || ($chome eq 'no_host')) {
9650: $uname = $cnum;
9651: } else {
1.1038 raeburn 9652: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9653: }
9654: } else {
1.1038 raeburn 9655: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9656: }
9657: return $uname if ($uname =~ /^error/);
9658: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9659: if (!defined($course_server)) {
9660: if (defined(&domain($udom,'primary'))) {
9661: $course_server = &domain($udom,'primary');
9662: } else {
9663: $course_server = $env{'user.home'};
9664: }
9665: }
9666: my %host_servers =
9667: &Apache::lonnet::get_servers($udom,'library');
9668: unless ($host_servers{$course_server}) {
9669: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9670: }
1.84 www 9671: # ------------------------------------------------------------- Make the course
9672: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9673: $course_server);
1.84 www 9674: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9675: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9676: if (($uhome eq '') || ($uhome eq 'no_host')) {
9677: return 'error: no such course';
9678: }
1.271 www 9679: # ----------------------------------------------------------------- Course made
1.516 raeburn 9680: # log existence
1.1029 raeburn 9681: my $now = time;
1.918 raeburn 9682: my $newcourse = {
9683: $udom.'_'.$uname => {
1.921 raeburn 9684: description => $description,
9685: inst_code => $inst_code,
9686: owner => $course_owner,
9687: type => $crstype,
1.1029 raeburn 9688: creator => $env{'user.name'}.':'.
9689: $env{'user.domain'},
9690: created => $now,
9691: context => $context,
1.918 raeburn 9692: },
9693: };
1.921 raeburn 9694: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9695: # set toplevel url
1.271 www 9696: my $topurl=$url;
9697: unless ($nonstandard) {
9698: # ------------------------------------------ For standard courses, make top url
9699: my $mapurl=&clutter($url);
1.278 www 9700: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9701: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9702: <map>
9703: <resource id="1" type="start"></resource>
9704: <resource id="2" src="$mapurl"></resource>
9705: <resource id="3" type="finish"></resource>
9706: <link index="1" from="1" to="2"></link>
9707: <link index="2" from="2" to="3"></link>
9708: </map>
9709: ENDINITMAP
9710: $topurl=&declutter(
1.638 albertel 9711: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9712: );
9713: }
9714: # ----------------------------------------------------------- Write preferences
1.84 www 9715: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9716: ('description' => $description,
9717: 'url' => $topurl,
9718: 'internal.creator' => $env{'user.name'}.':'.
9719: $env{'user.domain'},
9720: 'internal.created' => $now,
9721: 'internal.creationcontext' => $context)
9722: );
1.84 www 9723: return '/'.$udom.'/'.$uname;
9724: }
9725:
1.1011 raeburn 9726: # ------------------------------------------------------------------- Create ID
9727: sub generate_coursenum {
1.1038 raeburn 9728: my ($udom,$crstype) = @_;
1.1011 raeburn 9729: my $domdesc = &domain($udom);
9730: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9731: my $first;
9732: if ($crstype eq 'Community') {
9733: $first = '0';
9734: } else {
9735: $first = int(1+rand(9));
9736: }
9737: my $uname=$first.
1.1011 raeburn 9738: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9739: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9740: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9741: # ----------------------------------------------- Make sure that does not exist
9742: my $uhome=&homeserver($uname,$udom,'true');
9743: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9744: if ($crstype eq 'Community') {
9745: $first = '0';
9746: } else {
9747: $first = int(1+rand(9));
9748: }
9749: $uname=$first.
1.1011 raeburn 9750: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9751: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9752: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9753: $uhome=&homeserver($uname,$udom,'true');
9754: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9755: return 'error: unable to generate unique course-ID';
9756: }
9757: }
9758: return $uname;
9759: }
9760:
1.813 albertel 9761: sub is_course {
1.1167 droeschl 9762: my ($cdom, $cnum) = scalar(@_) == 1 ?
9763: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9764:
9765: return unless $cdom and $cnum;
9766:
9767: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9768: '.');
9769:
1.1219 raeburn 9770: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9771: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9772: }
9773:
1.1015 raeburn 9774: sub store_userdata {
9775: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9776: my $result;
1.1016 raeburn 9777: if ($datakey ne '') {
1.1013 raeburn 9778: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9779: if ($udom eq '' || $uname eq '') {
9780: $udom = $env{'user.domain'};
9781: $uname = $env{'user.name'};
9782: }
9783: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9784: if (($uhome eq '') || ($uhome eq 'no_host')) {
9785: $result = 'error: no_host';
9786: } else {
9787: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9788: $storehash->{'host'} = $perlvar{'lonHostID'};
9789:
9790: my $namevalue='';
9791: foreach my $key (keys(%{$storehash})) {
9792: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9793: }
9794: $namevalue=~s/\&$//;
1.1224 raeburn 9795: unless ($namespace eq 'courserequests') {
9796: $datakey = &escape($datakey);
9797: }
1.1105 raeburn 9798: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9799: $namevalue,$uhome);
1.1013 raeburn 9800: }
9801: } else {
9802: $result = 'error: data to store was not a hash reference';
9803: }
9804: } else {
9805: $result= 'error: invalid requestkey';
9806: }
9807: return $result;
9808: }
9809:
1.21 www 9810: # ---------------------------------------------------------- Assign Custom Role
9811:
9812: sub assigncustomrole {
1.957 raeburn 9813: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9814: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9815: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9816: }
9817:
9818: # ----------------------------------------------------------------- Revoke Role
9819:
9820: sub revokerole {
1.957 raeburn 9821: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9822: my $now=time;
1.965 raeburn 9823: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9824: }
9825:
9826: # ---------------------------------------------------------- Revoke Custom Role
9827:
9828: sub revokecustomrole {
1.957 raeburn 9829: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9830: my $now=time;
1.357 www 9831: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9832: $deleteflag,$selfenroll,$context);
1.17 www 9833: }
9834:
1.533 banghart 9835: # ------------------------------------------------------------ Disk usage
1.535 albertel 9836: sub diskusage {
1.955 raeburn 9837: my ($udom,$uname,$directorypath,$getpropath)=@_;
9838: $directorypath =~ s/\/$//;
9839: my $listing=&reply('du2:'.&escape($directorypath).':'
9840: .&escape($getpropath).':'.&escape($uname).':'
9841: .&escape($udom),homeserver($uname,$udom));
9842: if ($listing eq 'unknown_cmd') {
9843: if ($getpropath) {
9844: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9845: }
9846: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9847: }
1.514 albertel 9848: return $listing;
1.512 banghart 9849: }
9850:
1.566 banghart 9851: sub is_locked {
1.1096 raeburn 9852: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9853: my @check;
9854: my $is_locked;
1.1093 raeburn 9855: push (@check,$file_name);
1.613 albertel 9856: my %locked = &get('file_permissions',\@check,
1.620 albertel 9857: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9858: my ($tmp)=keys(%locked);
9859: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9860:
1.566 banghart 9861: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9862: $is_locked = 'false';
9863: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9864: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9865: $is_locked = 'true';
1.1096 raeburn 9866: if (ref($which) eq 'ARRAY') {
9867: push(@{$which},$entry);
9868: } else {
9869: last;
9870: }
1.745 raeburn 9871: }
9872: }
1.566 banghart 9873: } else {
9874: $is_locked = 'false';
9875: }
1.1093 raeburn 9876: return $is_locked;
1.566 banghart 9877: }
9878:
1.759 albertel 9879: sub declutter_portfile {
9880: my ($file) = @_;
1.833 albertel 9881: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9882: return $file;
9883: }
9884:
1.559 banghart 9885: # ------------------------------------------------------------- Mark as Read Only
9886:
9887: sub mark_as_readonly {
9888: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9889: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9890: my ($tmp)=keys(%current_permissions);
9891: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9892: foreach my $file (@{$files}) {
1.759 albertel 9893: $file = &declutter_portfile($file);
1.561 banghart 9894: push(@{$current_permissions{$file}},$what);
1.559 banghart 9895: }
1.613 albertel 9896: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9897: return;
9898: }
9899:
1.572 banghart 9900: # ------------------------------------------------------------Save Selected Files
9901:
9902: sub save_selected_files {
9903: my ($user, $path, @files) = @_;
9904: my $filename = $user."savedfiles";
1.573 banghart 9905: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9906: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9907: foreach my $file (@files) {
1.620 albertel 9908: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9909: }
9910: foreach my $file (@other_files) {
1.574 banghart 9911: print (OUT $file."\n");
1.572 banghart 9912: }
1.574 banghart 9913: close (OUT);
1.572 banghart 9914: return 'ok';
9915: }
9916:
1.574 banghart 9917: sub clear_selected_files {
9918: my ($user) = @_;
9919: my $filename = $user."savedfiles";
1.1117 foxr 9920: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9921: print (OUT undef);
9922: close (OUT);
9923: return ("ok");
9924: }
9925:
1.572 banghart 9926: sub files_in_path {
9927: my ($user, $path) = @_;
9928: my $filename = $user."savedfiles";
9929: my %return_files;
1.1117 foxr 9930: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9931: while (my $line_in = <IN>) {
1.574 banghart 9932: chomp ($line_in);
9933: my @paths_and_file = split (m!/!, $line_in);
9934: my $file_part = pop (@paths_and_file);
9935: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9936: $path_part.='/';
9937: my $path_and_file = $path_part.$file_part;
9938: if ($path_part eq $path) {
9939: $return_files{$file_part}= 'selected';
9940: }
9941: }
1.574 banghart 9942: close (IN);
9943: return (\%return_files);
1.572 banghart 9944: }
9945:
9946: # called in portfolio select mode, to show files selected NOT in current directory
9947: sub files_not_in_path {
9948: my ($user, $path) = @_;
9949: my $filename = $user."savedfiles";
9950: my @return_files;
9951: my $path_part;
1.1117 foxr 9952: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9953: while (my $line = <IN>) {
1.572 banghart 9954: #ok, I know it's clunky, but I want it to work
1.800 albertel 9955: my @paths_and_file = split(m|/|, $line);
9956: my $file_part = pop(@paths_and_file);
9957: chomp($file_part);
9958: my $path_part = join('/', @paths_and_file);
1.572 banghart 9959: $path_part .= '/';
9960: my $path_and_file = $path_part.$file_part;
9961: if ($path_part ne $path) {
1.800 albertel 9962: push(@return_files, ($path_and_file));
1.572 banghart 9963: }
9964: }
1.800 albertel 9965: close(OUT);
1.574 banghart 9966: return (@return_files);
1.572 banghart 9967: }
9968:
1.1273 raeburn 9969: #------------------------------Submitted/Handedback Portfolio Files Versioning
9970:
9971: sub portfiles_versioning {
9972: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9973: my $portfolio_root = '/userfiles/portfolio';
9974: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9975: foreach my $file (@{$portfiles}) {
9976: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9977: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9978: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9979: my $getpropath = 1;
9980: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9981: $stu_name,$getpropath);
9982: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9983: my $new_answer =
9984: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9985: if ($new_answer ne 'problem getting file') {
9986: push(@{$versioned_portfiles}, $directory.$new_answer);
9987: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9988: [$symb,$env{'request.course.id'},'graded']);
9989: }
9990: }
9991: }
9992:
9993: sub get_next_version {
9994: my ($answer_name, $answer_ext, $dir_list) = @_;
9995: my $version;
9996: if (ref($dir_list) eq 'ARRAY') {
9997: foreach my $row (@{$dir_list}) {
9998: my ($file) = split(/\&/,$row,2);
9999: my ($file_name,$file_version,$file_ext) =
10000: &file_name_version_ext($file);
10001: if (($file_name eq $answer_name) &&
10002: ($file_ext eq $answer_ext)) {
10003: # gets here if filename and extension match,
10004: # regardless of version
10005: if ($file_version ne '') {
10006: # a versioned file is found so save it for later
10007: if ($file_version > $version) {
10008: $version = $file_version;
10009: }
10010: }
10011: }
10012: }
10013: }
10014: $version ++;
10015: return($version);
10016: }
10017:
10018: sub version_selected_portfile {
10019: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10020: my ($answer_name,$answer_ver,$answer_ext) =
10021: &file_name_version_ext($file_name);
10022: my $new_answer;
10023: $env{'form.copy'} =
10024: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10025: if($env{'form.copy'} eq '-1') {
10026: $new_answer = 'problem getting file';
10027: } else {
10028: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10029: my $copy_result =
10030: &finishuserfileupload($stu_name,$domain,'copy',
10031: '/portfolio'.$directory.$new_answer);
10032: }
10033: undef($env{'form.copy'});
10034: return ($new_answer);
10035: }
10036:
10037: sub file_name_version_ext {
10038: my ($file)=@_;
10039: my @file_parts = split(/\./, $file);
10040: my ($name,$version,$ext);
10041: if (@file_parts > 1) {
10042: $ext=pop(@file_parts);
10043: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10044: $version=pop(@file_parts);
10045: }
10046: $name=join('.',@file_parts);
10047: } else {
10048: $name=join('.',@file_parts);
10049: }
10050: return($name,$version,$ext);
10051: }
10052:
1.745 raeburn 10053: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10054:
1.745 raeburn 10055: sub get_portfile_permissions {
10056: my ($domain,$user) = @_;
1.613 albertel 10057: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10058: my ($tmp)=keys(%current_permissions);
10059: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10060: return \%current_permissions;
10061: }
10062:
10063: #---------------------------------------------Get portfolio file access controls
10064:
1.749 raeburn 10065: sub get_access_controls {
1.745 raeburn 10066: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10067: my %access;
10068: my $real_file = $file;
10069: $file =~ s/\.meta$//;
1.745 raeburn 10070: if (defined($file)) {
1.749 raeburn 10071: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10072: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10073: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10074: }
10075: }
1.745 raeburn 10076: } else {
1.749 raeburn 10077: foreach my $key (keys(%{$current_permissions})) {
10078: if ($key =~ /\0accesscontrol$/) {
10079: if (defined($group)) {
10080: if ($key !~ m-^\Q$group\E/-) {
10081: next;
10082: }
10083: }
10084: my ($fullpath) = split(/\0/,$key);
10085: if (ref($$current_permissions{$key}) eq 'HASH') {
10086: foreach my $control (keys(%{$$current_permissions{$key}})) {
10087: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10088: }
10089: }
10090: }
10091: }
10092: }
10093: return %access;
10094: }
10095:
10096: sub modify_access_controls {
10097: my ($file_name,$changes,$domain,$user)=@_;
10098: my ($outcome,$deloutcome);
10099: my %store_permissions;
10100: my %new_values;
10101: my %new_control;
10102: my %translation;
10103: my @deletions = ();
10104: my $now = time;
10105: if (exists($$changes{'activate'})) {
10106: if (ref($$changes{'activate'}) eq 'HASH') {
10107: my @newitems = sort(keys(%{$$changes{'activate'}}));
10108: my $numnew = scalar(@newitems);
10109: for (my $i=0; $i<$numnew; $i++) {
10110: my $newkey = $newitems[$i];
10111: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10112: if ($newkey =~ /^\d+:/) {
10113: $newkey =~ s/^(\d+)/$newid/;
10114: $translation{$1} = $newid;
10115: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10116: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10117: $translation{$1} = $newid;
10118: }
1.749 raeburn 10119: $new_values{$file_name."\0".$newkey} =
10120: $$changes{'activate'}{$newitems[$i]};
10121: $new_control{$newkey} = $now;
10122: }
10123: }
10124: }
10125: my %todelete;
10126: my %changed_items;
10127: foreach my $action ('delete','update') {
10128: if (exists($$changes{$action})) {
10129: if (ref($$changes{$action}) eq 'HASH') {
10130: foreach my $key (keys(%{$$changes{$action}})) {
10131: my ($itemnum) = ($key =~ /^([^:]+):/);
10132: if ($action eq 'delete') {
10133: $todelete{$itemnum} = 1;
10134: } else {
10135: $changed_items{$itemnum} = $key;
10136: }
10137: }
1.745 raeburn 10138: }
10139: }
1.749 raeburn 10140: }
10141: # get lock on access controls for file.
10142: my $lockhash = {
10143: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10144: ':'.$env{'user.domain'},
10145: };
10146: my $tries = 0;
10147: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10148:
1.1288 damieng 10149: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10150: $tries ++;
1.1289 damieng 10151: sleep(0.1);
1.749 raeburn 10152: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10153: }
10154: if ($gotlock eq 'ok') {
10155: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10156: my ($tmp)=keys(%curr_permissions);
10157: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10158: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10159: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10160: if (ref($curr_controls) eq 'HASH') {
10161: foreach my $control_item (keys(%{$curr_controls})) {
10162: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10163: if (defined($todelete{$itemnum})) {
10164: push(@deletions,$file_name."\0".$control_item);
10165: } else {
10166: if (defined($changed_items{$itemnum})) {
10167: $new_control{$changed_items{$itemnum}} = $now;
10168: push(@deletions,$file_name."\0".$control_item);
10169: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10170: } else {
10171: $new_control{$control_item} = $$curr_controls{$control_item};
10172: }
10173: }
1.745 raeburn 10174: }
10175: }
10176: }
1.970 raeburn 10177: my ($group);
10178: if (&is_course($domain,$user)) {
10179: ($group,my $file) = split(/\//,$file_name,2);
10180: }
1.749 raeburn 10181: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10182: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10183: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10184: # remove lock
10185: my @del_lock = ($file_name."\0".'locked_access_records');
10186: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10187: my $sqlresult =
1.970 raeburn 10188: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10189: $group);
1.749 raeburn 10190: } else {
10191: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10192: }
1.749 raeburn 10193: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10194: }
10195:
1.827 raeburn 10196: sub make_public_indefinitely {
1.1271 raeburn 10197: my (@requrl) = @_;
10198: return &automated_portfile_access('public',\@requrl);
10199: }
10200:
10201: sub automated_portfile_access {
10202: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 10203: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10204: return 'invalid';
10205: }
1.1271 raeburn 10206: my %urls;
10207: if (ref($addsref) eq 'ARRAY') {
10208: foreach my $requrl (@{$addsref}) {
10209: if (&is_portfolio_url($requrl)) {
10210: unless (exists($urls{$requrl})) {
10211: $urls{$requrl} = 'add';
10212: }
10213: }
10214: }
10215: }
10216: if (ref($delsref) eq 'ARRAY') {
10217: foreach my $requrl (@{$delsref}) {
10218: if (&is_portfolio_url($requrl)) {
10219: unless (exists($urls{$requrl})) {
10220: $urls{$requrl} = 'delete';
10221: }
10222: }
10223: }
10224: }
10225: unless (keys(%urls)) {
10226: return 'invalid';
10227: }
10228: my $ip;
10229: if ($accesstype eq 'ip') {
10230: if (ref($info) eq 'HASH') {
10231: if ($info->{'ip'} ne '') {
10232: $ip = $info->{'ip'};
10233: }
10234: }
10235: if ($ip eq '') {
10236: return 'invalid';
10237: }
10238: }
10239: my $errors;
1.827 raeburn 10240: my $now = time;
1.1271 raeburn 10241: my %current_perms;
10242: foreach my $requrl (sort(keys(%urls))) {
10243: my $action;
10244: if ($urls{$requrl} eq 'add') {
10245: $action = 'activate';
10246: } else {
10247: $action = 'none';
10248: }
10249: my $aclnum = 0;
1.827 raeburn 10250: my (undef,$udom,$unum,$file_name,$group) =
10251: &parse_portfolio_url($requrl);
1.1271 raeburn 10252: unless (exists($current_perms{$unum.':'.$udom})) {
10253: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10254: }
10255: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 10256: $group,$file_name);
10257: foreach my $key (keys(%{$access_controls{$file_name}})) {
10258: my ($num,$scope,$end,$start) =
10259: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 10260: if ($scope eq $accesstype) {
10261: if (($start <= $now) && ($end == 0)) {
10262: if ($accesstype eq 'ip') {
10263: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10264: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10265: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10266: if ($urls{$requrl} eq 'add') {
10267: $action = 'none';
10268: last;
10269: } else {
10270: $action = 'delete';
10271: $aclnum = $num;
10272: last;
10273: }
10274: }
10275: }
10276: }
10277: } elsif ($accesstype eq 'public') {
10278: if ($urls{$requrl} eq 'add') {
10279: $action = 'none';
10280: last;
10281: } else {
10282: $action = 'delete';
10283: $aclnum = $num;
10284: last;
10285: }
10286: }
10287: } elsif ($accesstype eq 'public') {
1.827 raeburn 10288: $action = 'update';
10289: $aclnum = $num;
1.1271 raeburn 10290: last;
1.827 raeburn 10291: }
10292: }
10293: }
10294: if ($action eq 'none') {
1.1271 raeburn 10295: next;
1.827 raeburn 10296: } else {
10297: my %changes;
10298: my $newend = 0;
10299: my $newstart = $now;
1.1271 raeburn 10300: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 10301: $changes{$action}{$newkey} = {
1.1271 raeburn 10302: type => $accesstype,
1.827 raeburn 10303: time => {
10304: start => $newstart,
10305: end => $newend,
10306: },
10307: };
1.1271 raeburn 10308: if ($accesstype eq 'ip') {
10309: $changes{$action}{$newkey}{'ip'} = [$ip];
10310: }
1.827 raeburn 10311: my ($outcome,$deloutcome,$new_values,$translation) =
10312: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 10313: unless ($outcome eq 'ok') {
10314: $errors .= $outcome.' ';
10315: }
1.827 raeburn 10316: }
1.1271 raeburn 10317: }
10318: if ($errors) {
10319: $errors =~ s/\s$//;
10320: return $errors;
1.827 raeburn 10321: } else {
1.1271 raeburn 10322: return 'ok';
1.827 raeburn 10323: }
10324: }
10325:
1.745 raeburn 10326: #------------------------------------------------------Get Marked as Read Only
10327:
10328: sub get_marked_as_readonly {
10329: my ($domain,$user,$what,$group) = @_;
10330: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10331: my @readonly_files;
1.629 banghart 10332: my $cmp1=$what;
10333: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10334: while (my ($file_name,$value) = each(%{$current_permissions})) {
10335: if (defined($group)) {
10336: if ($file_name !~ m-^\Q$group\E/-) {
10337: next;
10338: }
10339: }
1.561 banghart 10340: if (ref($value) eq "ARRAY"){
10341: foreach my $stored_what (@{$value}) {
1.629 banghart 10342: my $cmp2=$stored_what;
1.759 albertel 10343: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10344: $cmp2=join('',@{$stored_what});
1.745 raeburn 10345: }
1.629 banghart 10346: if ($cmp1 eq $cmp2) {
1.561 banghart 10347: push(@readonly_files, $file_name);
1.745 raeburn 10348: last;
1.563 banghart 10349: } elsif (!defined($what)) {
10350: push(@readonly_files, $file_name);
1.745 raeburn 10351: last;
1.561 banghart 10352: }
10353: }
1.745 raeburn 10354: }
1.561 banghart 10355: }
10356: return @readonly_files;
10357: }
1.577 banghart 10358: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10359:
1.577 banghart 10360: sub get_marked_as_readonly_hash {
1.745 raeburn 10361: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10362: my %readonly_files;
1.745 raeburn 10363: while (my ($file_name,$value) = each(%{$current_permissions})) {
10364: if (defined($group)) {
10365: if ($file_name !~ m-^\Q$group\E/-) {
10366: next;
10367: }
10368: }
1.577 banghart 10369: if (ref($value) eq "ARRAY"){
10370: foreach my $stored_what (@{$value}) {
1.745 raeburn 10371: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10372: foreach my $lock_descriptor(@{$stored_what}) {
10373: if ($lock_descriptor eq 'graded') {
10374: $readonly_files{$file_name} = 'graded';
10375: } elsif ($lock_descriptor eq 'handback') {
10376: $readonly_files{$file_name} = 'handback';
10377: } else {
10378: if (!exists($readonly_files{$file_name})) {
10379: $readonly_files{$file_name} = 'locked';
10380: }
10381: }
1.745 raeburn 10382: }
1.750 banghart 10383: }
1.577 banghart 10384: }
10385: }
10386: }
10387: return %readonly_files;
10388: }
1.559 banghart 10389: # ------------------------------------------------------------ Unmark as Read Only
10390:
10391: sub unmark_as_readonly {
1.629 banghart 10392: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10393: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10394: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10395: $file_name = &declutter_portfile($file_name);
1.634 albertel 10396: my $symb_crs = $what;
10397: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10398: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10399: my ($tmp)=keys(%current_permissions);
10400: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10401: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10402: foreach my $file (@readonly_files) {
1.759 albertel 10403: my $clean_file = &declutter_portfile($file);
10404: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10405: my $current_locks = $current_permissions{$file};
1.563 banghart 10406: my @new_locks;
10407: my @del_keys;
10408: if (ref($current_locks) eq "ARRAY"){
10409: foreach my $locker (@{$current_locks}) {
1.632 albertel 10410: my $compare=$locker;
1.749 raeburn 10411: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10412: $compare=join('',@{$locker});
1.746 raeburn 10413: if ($compare ne $symb_crs) {
10414: push(@new_locks, $locker);
10415: }
1.563 banghart 10416: }
10417: }
1.650 albertel 10418: if (scalar(@new_locks) > 0) {
1.563 banghart 10419: $current_permissions{$file} = \@new_locks;
10420: } else {
10421: push(@del_keys, $file);
1.613 albertel 10422: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10423: delete($current_permissions{$file});
1.563 banghart 10424: }
10425: }
1.561 banghart 10426: }
1.613 albertel 10427: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10428: return;
10429: }
1.512 banghart 10430:
1.17 www 10431: # ------------------------------------------------------------ Directory lister
10432:
10433: sub dirlist {
1.955 raeburn 10434: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10435: $uri=~s/^\///;
10436: $uri=~s/\/$//;
1.253 stredwic 10437: my ($udom, $uname);
1.955 raeburn 10438: if ($getuserdir) {
1.253 stredwic 10439: $udom = $userdomain;
10440: $uname = $username;
1.955 raeburn 10441: } else {
10442: (undef,$udom,$uname)=split(/\//,$uri);
10443: if(defined($userdomain)) {
10444: $udom = $userdomain;
10445: }
10446: if(defined($username)) {
10447: $uname = $username;
10448: }
1.253 stredwic 10449: }
1.955 raeburn 10450: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10451:
1.955 raeburn 10452: $dirRoot = $perlvar{'lonDocRoot'};
10453: if (defined($getpropath)) {
10454: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10455: $dirRoot =~ s/\/$//;
1.955 raeburn 10456: } elsif (defined($getuserdir)) {
10457: my $subdir=$uname.'__';
10458: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10459: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10460: ."/$udom/$subdir/$uname";
10461: } elsif (defined($alternateRoot)) {
10462: $dirRoot = $alternateRoot;
1.751 banghart 10463: }
1.253 stredwic 10464:
10465: if($udom) {
10466: if($uname) {
1.1135 raeburn 10467: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10468: if ($uhome eq 'no_host') {
10469: return ([],'no_host');
10470: }
1.955 raeburn 10471: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10472: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10473: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10474: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10475: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10476: } else {
10477: @listing_results = map { &unescape($_); } split(/:/,$listing);
10478: }
1.605 matthew 10479: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10480: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10481: @listing_results = split(/:/,$listing);
10482: } else {
10483: @listing_results = map { &unescape($_); } split(/:/,$listing);
10484: }
1.1135 raeburn 10485: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10486: ($listing eq 'rejected') || ($listing eq 'refused') ||
10487: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10488: return ([],$listing);
10489: } else {
10490: return (\@listing_results);
1.1135 raeburn 10491: }
1.955 raeburn 10492: } elsif(!$alternateRoot) {
1.1136 raeburn 10493: my (%allusers,%listerror);
1.841 albertel 10494: my %servers = &get_servers($udom,'library');
1.955 raeburn 10495: foreach my $tryserver (keys(%servers)) {
10496: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10497: &escape($udom),$tryserver);
10498: if ($listing eq 'unknown_cmd') {
10499: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10500: $udom, $tryserver);
10501: } else {
10502: @listing_results = map { &unescape($_); } split(/:/,$listing);
10503: }
1.841 albertel 10504: if ($listing eq 'unknown_cmd') {
10505: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10506: $udom, $tryserver);
10507: @listing_results = split(/:/,$listing);
10508: } else {
10509: @listing_results =
10510: map { &unescape($_); } split(/:/,$listing);
10511: }
1.1136 raeburn 10512: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10513: ($listing eq 'rejected') || ($listing eq 'refused') ||
10514: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10515: $listerror{$tryserver} = $listing;
10516: } else {
1.841 albertel 10517: foreach my $line (@listing_results) {
10518: my ($entry) = split(/&/,$line,2);
10519: $allusers{$entry} = 1;
10520: }
10521: }
1.253 stredwic 10522: }
1.1136 raeburn 10523: my @alluserslist=();
1.800 albertel 10524: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10525: push(@alluserslist,$user.'&user');
1.253 stredwic 10526: }
1.1318 droeschl 10527:
10528: if (!%listerror) {
10529: # no errors
10530: return (\@alluserslist);
10531: } elsif (scalar(keys(%servers)) == 1) {
10532: # one library server, one error
10533: my ($key) = keys(%listerror);
10534: return (\@alluserslist, $listerror{$key});
10535: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10536: # con_lost indicates that we might miss data from at least one
10537: # library server
10538: return (\@alluserslist, 'con_lost');
10539: } else {
10540: # multiple library servers and no con_lost -> data should be
10541: # complete.
10542: return (\@alluserslist);
10543: }
10544:
1.253 stredwic 10545: } else {
1.1136 raeburn 10546: return ([],'missing username');
1.253 stredwic 10547: }
1.955 raeburn 10548: } elsif(!defined($getpropath)) {
1.1136 raeburn 10549: my $path = $perlvar{'lonDocRoot'}.'/res/';
10550: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10551: return (\@all_domains);
1.955 raeburn 10552: } else {
1.1136 raeburn 10553: return ([],'missing domain');
1.275 stredwic 10554: }
10555: }
10556:
10557: # --------------------------------------------- GetFileTimestamp
10558: # This function utilizes dirlist and returns the date stamp for
10559: # when it was last modified. It will also return an error of -1
10560: # if an error occurs
10561:
10562: sub GetFileTimestamp {
1.955 raeburn 10563: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10564: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10565: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10566: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10567: undef,$getuserdir);
10568: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10569: return -1;
10570: }
10571: if (ref($fileref) eq 'ARRAY') {
10572: my @stats = split('&',$fileref->[0]);
1.375 matthew 10573: # @stats contains first the filename, then the stat output
10574: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10575: } else {
10576: return -1;
1.253 stredwic 10577: }
1.26 www 10578: }
10579:
1.712 albertel 10580: sub stat_file {
10581: my ($uri) = @_;
1.787 albertel 10582: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10583:
1.955 raeburn 10584: my ($udom,$uname,$file);
1.712 albertel 10585: if ($uri =~ m-^/(uploaded|editupload)/-) {
10586: ($udom,$uname,$file) =
1.811 albertel 10587: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10588: $file = 'userfiles/'.$file;
10589: }
10590: if ($uri =~ m-^/res/-) {
10591: ($udom,$uname) =
1.807 albertel 10592: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10593: $file = $uri;
10594: }
10595:
10596: if (!$udom || !$uname || !$file) {
10597: # unable to handle the uri
10598: return ();
10599: }
1.956 raeburn 10600: my $getpropath;
10601: if ($file =~ /^userfiles\//) {
10602: $getpropath = 1;
10603: }
1.1136 raeburn 10604: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10605: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10606: return ();
10607: } else {
10608: if (ref($listref) eq 'ARRAY') {
10609: my @stats = split('&',$listref->[0]);
10610: shift(@stats); #filename is first
10611: return @stats;
10612: }
1.712 albertel 10613: }
10614: return ();
10615: }
10616:
1.1313 raeburn 10617: # --------------------------------------------------------- recursedirs
10618: # Recursive function to traverse either a specific user's Authoring Space
10619: # or corresponding Published Resource Space, and populate the hash ref:
10620: # $dirhashref with URLs of all directories, and if $filehashref hash
10621: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10622: # or .rights files in resource space, and .meta, .save, .log, and .bak
10623: # files in Authoring Space.
10624: #
10625: # Inputs:
10626: #
10627: # $is_home - true if current server is home server for user's space
10628: # $context - either: priv, or res respectively for Authoring or Resource Space.
10629: # $docroot - Document root (i.e., /home/httpd/html
10630: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10631: # $relpath - Current path (relative to top level).
10632: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10633: # $filehashref - reference to hash to populate with URLs of files (Optional)
10634: #
10635: # Returns: nothing
10636: #
10637: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10638: #
10639: # Currently used by interface/londocs.pm to create linked select boxes for
10640: # directory and filename to import a Course "Author" resource into a course, and
10641: # also to create linked select boxes for Authoring Space and Directory to choose
10642: # save location for creation of a new "standard" problem from the Course Editor.
10643: #
10644:
10645: sub recursedirs {
10646: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10647: return unless (ref($dirhashref) eq 'HASH');
10648: my $currpath = $docroot.$toppath;
10649: if ($relpath) {
10650: $currpath .= "/$relpath";
10651: }
10652: my $savefile;
10653: if (ref($filehashref)) {
10654: $savefile = 1;
10655: }
10656: if ($is_home) {
10657: if (opendir(my $dirh,$currpath)) {
10658: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10659: next if ($item eq '');
10660: if (-d "$currpath/$item") {
10661: my $newpath;
10662: if ($relpath) {
10663: $newpath = "$relpath/$item";
10664: } else {
10665: $newpath = $item;
10666: }
10667: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10668: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10669: } elsif ($savefile) {
10670: if ($context eq 'priv') {
10671: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10672: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10673: }
10674: } else {
10675: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10676: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10677: }
10678: }
10679: }
10680: }
10681: closedir($dirh);
10682: }
10683: } else {
10684: my ($dirlistref,$listerror) =
10685: &dirlist($toppath.$relpath);
10686: my @dir_lines;
10687: my $dirptr=16384;
10688: if (ref($dirlistref) eq 'ARRAY') {
10689: foreach my $dir_line (sort
10690: {
10691: my ($afile)=split('&',$a,2);
10692: my ($bfile)=split('&',$b,2);
10693: return (lc($afile) cmp lc($bfile));
10694: } (@{$dirlistref})) {
10695: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10696: split(/\&/,$dir_line,16);
10697: $item =~ s/\s+$//;
10698: next if (($item =~ /^\.\.?$/) || ($obs));
10699: if ($dirptr&$testdir) {
10700: my $newpath;
10701: if ($relpath) {
10702: $newpath = "$relpath/$item";
10703: } else {
10704: $relpath = '/';
10705: $newpath = $item;
10706: }
10707: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10708: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10709: } elsif ($savefile) {
10710: if ($context eq 'priv') {
10711: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10712: $filehashref->{$relpath}{$item} = 1;
10713: }
10714: } else {
10715: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10716: $filehashref->{$relpath}{$item} = 1;
10717: }
10718: }
10719: }
10720: }
10721: }
10722: }
10723: return;
10724: }
10725:
1.26 www 10726: # -------------------------------------------------------- Value of a Condition
10727:
1.713 albertel 10728: # gets the value of a specific preevaluated condition
10729: # stored in the string $env{user.state.<cid>}
10730: # or looks up a condition reference in the bighash and if if hasn't
10731: # already been evaluated recurses into docondval to get the value of
10732: # the condition, then memoizing it to
10733: # $env{user.state.<cid>.<condition>}
1.40 www 10734: sub directcondval {
10735: my $number=shift;
1.620 albertel 10736: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10737: &Apache::lonuserstate::evalstate();
10738: }
1.713 albertel 10739: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10740: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10741: } elsif ($number =~ /^_/) {
10742: my $sub_condition;
10743: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10744: &GDBM_READER(),0640)) {
10745: $sub_condition=$bighash{'conditions'.$number};
10746: untie(%bighash);
10747: }
10748: my $value = &docondval($sub_condition);
1.949 raeburn 10749: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10750: return $value;
10751: }
1.620 albertel 10752: if ($env{'user.state.'.$env{'request.course.id'}}) {
10753: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10754: } else {
10755: return 2;
10756: }
10757: }
10758:
1.713 albertel 10759: # get the collection of conditions for this resource
1.26 www 10760: sub condval {
10761: my $condidx=shift;
1.54 www 10762: my $allpathcond='';
1.713 albertel 10763: foreach my $cond (split(/\|/,$condidx)) {
10764: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10765: $allpathcond.=
10766: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10767: }
1.191 harris41 10768: }
1.54 www 10769: $allpathcond=~s/\|$//;
1.713 albertel 10770: return &docondval($allpathcond);
10771: }
10772:
10773: #evaluates an expression of conditions
10774: sub docondval {
10775: my ($allpathcond) = @_;
10776: my $result=0;
10777: if ($env{'request.course.id'}
10778: && defined($allpathcond)) {
10779: my $operand='|';
10780: my @stack;
10781: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10782: if ($chunk eq '(') {
10783: push @stack,($operand,$result);
10784: } elsif ($chunk eq ')') {
10785: my $before=pop @stack;
10786: if (pop @stack eq '&') {
10787: $result=$result>$before?$before:$result;
10788: } else {
10789: $result=$result>$before?$result:$before;
10790: }
10791: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10792: $operand=$chunk;
10793: } else {
10794: my $new=directcondval($chunk);
10795: if ($operand eq '&') {
10796: $result=$result>$new?$new:$result;
10797: } else {
10798: $result=$result>$new?$result:$new;
10799: }
10800: }
10801: }
1.26 www 10802: }
10803: return $result;
1.421 albertel 10804: }
10805:
10806: # ---------------------------------------------------- Devalidate courseresdata
10807:
10808: sub devalidatecourseresdata {
10809: my ($coursenum,$coursedomain)=@_;
10810: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10811: &devalidate_cache_new('courseres',$hashid);
1.28 www 10812: }
10813:
1.763 www 10814:
1.200 www 10815: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10816: #
10817: # Parameters:
10818: # $coursenum - Number of the course.
10819: # $coursedomain - Domain at which the course was created.
10820: # Returns:
10821: # A hash of the course parameters along (I think) with timestamps
10822: # and version info.
1.877 foxr 10823:
1.624 albertel 10824: sub get_courseresdata {
10825: my ($coursenum,$coursedomain)=@_;
1.200 www 10826: my $coursehom=&homeserver($coursenum,$coursedomain);
10827: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10828: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10829: my %dumpreply;
1.417 albertel 10830: unless (defined($cached)) {
1.624 albertel 10831: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10832: $result=\%dumpreply;
1.251 albertel 10833: my ($tmp) = keys(%dumpreply);
10834: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10835: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10836: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10837: return $tmp;
1.416 albertel 10838: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10839: $result=undef;
1.599 albertel 10840: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10841: }
10842: }
1.624 albertel 10843: return $result;
10844: }
10845:
1.633 albertel 10846: sub devalidateuserresdata {
10847: my ($uname,$udom)=@_;
10848: my $hashid="$udom:$uname";
10849: &devalidate_cache_new('userres',$hashid);
10850: }
10851:
1.624 albertel 10852: sub get_userresdata {
10853: my ($uname,$udom)=@_;
10854: #most student don\'t have any data set, check if there is some data
10855: if (&EXT_cache_status($udom,$uname)) { return undef; }
10856:
10857: my $hashid="$udom:$uname";
10858: my ($result,$cached)=&is_cached_new('userres',$hashid);
10859: if (!defined($cached)) {
10860: my %resourcedata=&dump('resourcedata',$udom,$uname);
10861: $result=\%resourcedata;
10862: &do_cache_new('userres',$hashid,$result,600);
10863: }
10864: my ($tmp)=keys(%$result);
10865: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10866: return $result;
10867: }
10868: #error 2 occurs when the .db doesn't exist
10869: if ($tmp!~/error: 2 /) {
1.1294 raeburn 10870: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10871: &logthis("<font color=\"blue\">WARNING:".
10872: " Trying to get resource data for ".
10873: $uname." at ".$udom.": ".
10874: $tmp."</font>");
10875: }
1.624 albertel 10876: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10877: #&EXT_cache_set($udom,$uname);
10878: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10879: undef($tmp); # not really an error so don't send it back
1.624 albertel 10880: }
10881: return $tmp;
10882: }
1.879 foxr 10883: #----------------------------------------------- resdata - return resource data
10884: # Purpose:
10885: # Return resource data for either users or for a course.
10886: # Parameters:
10887: # $name - Course/user name.
10888: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 10889: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 10890: # $mapp - decluttered URL of enclosing map
10891: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
10892: # $recurseup - Ref to array of map URLs, starting with map containing
10893: # $mapp up through hierarchy of nested maps to top level map.
10894: # $courseid - CourseID (first part of param identifier).
10895: # $modifier - Middle part of param identifier.
10896: # $what - Last part of param identifier.
1.879 foxr 10897: # @which - Array of names of resources desired.
10898: # Returns:
10899: # The value of the first reasource in @which that is found in the
10900: # resource hash.
10901: # Exceptional Conditions:
10902: # If the $type passed in is not valid (not the string 'course' or
10903: # 'user', an undefined reference is returned.
10904: # If none of the resources are found, an undef is returned
1.624 albertel 10905: sub resdata {
1.1301 raeburn 10906: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
10907: $modifier,$what,@which)=@_;
1.624 albertel 10908: my $result;
10909: if ($type eq 'course') {
10910: $result=&get_courseresdata($name,$domain);
10911: } elsif ($type eq 'user') {
10912: $result=&get_userresdata($name,$domain);
10913: }
10914: if (!ref($result)) { return $result; }
1.251 albertel 10915: foreach my $item (@which) {
1.1301 raeburn 10916: if ($item->[1] eq 'course') {
10917: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
10918: unless ($$recursed) {
1.1302 raeburn 10919: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 10920: $$recursed = 1;
10921: }
10922: foreach my $item (@${recurseup}) {
10923: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
10924: last if (defined($result->{$norecursechk}));
10925: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
10926: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
10927: }
10928: }
10929: }
10930: if (defined($result->{$item->[0]})) {
1.927 albertel 10931: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10932: }
1.250 albertel 10933: }
1.291 albertel 10934: return undef;
1.200 www 10935: }
10936:
1.1298 raeburn 10937: sub get_domain_ltitools {
10938: my ($cdom) = @_;
10939: my %ltitools;
10940: my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10941: if (defined($cached)) {
10942: if (ref($result) eq 'HASH') {
10943: %ltitools = %{$result};
10944: }
10945: } else {
10946: my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10947: if (ref($domconfig{'ltitools'}) eq 'HASH') {
10948: %ltitools = %{$domconfig{'ltitools'}};
10949: }
10950: my $cachetime = 24*60*60;
10951: &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10952: }
10953: return %ltitools;
10954: }
10955:
1.1236 raeburn 10956: sub get_numsuppfiles {
10957: my ($cnum,$cdom,$ignorecache)=@_;
10958: my $hashid=$cnum.':'.$cdom;
10959: my ($suppcount,$cached);
10960: unless ($ignorecache) {
10961: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10962: }
10963: unless (defined($cached)) {
10964: my $chome=&homeserver($cnum,$cdom);
10965: unless ($chome eq 'no_host') {
10966: ($suppcount,my $errors) = (0,0);
10967: my $suppmap = 'supplemental.sequence';
10968: ($suppcount,$errors) =
10969: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10970: }
10971: &do_cache_new('suppcount',$hashid,$suppcount,600);
10972: }
10973: return $suppcount;
10974: }
10975:
1.379 matthew 10976: #
10977: # EXT resource caching routines
10978: #
10979:
1.1302 raeburn 10980: {
10981: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
10982: #
10983: # The course for which we cache
10984: my $cachedmapkey='';
10985: # The cached recursive maps for this course
10986: my %cachedmaps=();
10987: # When this was last done
10988: my $cachedmaptime='';
10989:
1.379 matthew 10990: sub clear_EXT_cache_status {
1.383 albertel 10991: &delenv('cache.EXT.');
1.379 matthew 10992: }
10993:
10994: sub EXT_cache_status {
10995: my ($target_domain,$target_user) = @_;
1.383 albertel 10996: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10997: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10998: # We know already the user has no data
10999: return 1;
11000: } else {
11001: return 0;
11002: }
11003: }
11004:
11005: sub EXT_cache_set {
11006: my ($target_domain,$target_user) = @_;
1.383 albertel 11007: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11008: #&appenv({$cachename => time});
1.379 matthew 11009: }
11010:
1.28 www 11011: # --------------------------------------------------------- Value of a Variable
1.58 www 11012: sub EXT {
1.715 albertel 11013:
1.1228 raeburn 11014: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11015: unless ($varname) { return ''; }
1.218 albertel 11016: #get real user name/domain, courseid and symb
11017: my $courseid;
1.359 albertel 11018: my $publicuser;
1.427 www 11019: if ($symbparm) {
11020: $symbparm=&get_symb_from_alias($symbparm);
11021: }
1.218 albertel 11022: if (!($uname && $udom)) {
1.790 albertel 11023: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11024: if (!$symbparm) { $symbparm=$cursymb; }
11025: } else {
1.620 albertel 11026: $courseid=$env{'request.course.id'};
1.218 albertel 11027: }
1.48 www 11028: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11029: my $rest;
1.320 albertel 11030: if (defined($therest[0])) {
1.48 www 11031: $rest=join('.',@therest);
11032: } else {
11033: $rest='';
11034: }
1.320 albertel 11035:
1.57 www 11036: my $qualifierrest=$qualifier;
11037: if ($rest) { $qualifierrest.='.'.$rest; }
11038: my $spacequalifierrest=$space;
11039: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11040: if ($realm eq 'user') {
1.48 www 11041: # --------------------------------------------------------------- user.resource
11042: if ($space eq 'resource') {
1.651 albertel 11043: if ( (defined($Apache::lonhomework::parsing_a_problem)
11044: || defined($Apache::lonhomework::parsing_a_task))
11045: &&
1.744 albertel 11046: ($symbparm eq &symbread()) ) {
11047: # if we are in the middle of processing the resource the
11048: # get the value we are planning on committing
11049: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11050: return $Apache::lonhomework::results{$qualifierrest};
11051: } else {
11052: return $Apache::lonhomework::history{$qualifierrest};
11053: }
1.335 albertel 11054: } else {
1.359 albertel 11055: my %restored;
1.620 albertel 11056: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11057: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11058: } else {
11059: %restored=&restore($symbparm,$courseid,$udom,$uname);
11060: }
1.335 albertel 11061: return $restored{$qualifierrest};
11062: }
1.48 www 11063: # ----------------------------------------------------------------- user.access
11064: } elsif ($space eq 'access') {
1.218 albertel 11065: # FIXME - not supporting calls for a specific user
1.48 www 11066: return &allowed($qualifier,$rest);
11067: # ------------------------------------------ user.preferences, user.environment
11068: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11069: if (($uname eq $env{'user.name'}) &&
11070: ($udom eq $env{'user.domain'})) {
11071: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11072: } else {
1.359 albertel 11073: my %returnhash;
11074: if (!$publicuser) {
11075: %returnhash=&userenvironment($udom,$uname,
11076: $qualifierrest);
11077: }
1.218 albertel 11078: return $returnhash{$qualifierrest};
11079: }
1.48 www 11080: # ----------------------------------------------------------------- user.course
11081: } elsif ($space eq 'course') {
1.218 albertel 11082: # FIXME - not supporting calls for a specific user
1.620 albertel 11083: return $env{join('.',('request.course',$qualifier))};
1.48 www 11084: # ------------------------------------------------------------------- user.role
11085: } elsif ($space eq 'role') {
1.218 albertel 11086: # FIXME - not supporting calls for a specific user
1.620 albertel 11087: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11088: if ($qualifier eq 'value') {
11089: return $role;
11090: } elsif ($qualifier eq 'extent') {
11091: return $where;
11092: }
11093: # ----------------------------------------------------------------- user.domain
11094: } elsif ($space eq 'domain') {
1.218 albertel 11095: return $udom;
1.48 www 11096: # ------------------------------------------------------------------- user.name
11097: } elsif ($space eq 'name') {
1.218 albertel 11098: return $uname;
1.48 www 11099: # ---------------------------------------------------- Any other user namespace
1.29 www 11100: } else {
1.359 albertel 11101: my %reply;
11102: if (!$publicuser) {
11103: %reply=&get($space,[$qualifierrest],$udom,$uname);
11104: }
11105: return $reply{$qualifierrest};
1.48 www 11106: }
1.236 www 11107: } elsif ($realm eq 'query') {
11108: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11109: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11110: [$spacequalifierrest]);
1.620 albertel 11111: return $env{'form.'.$spacequalifierrest};
1.236 www 11112: } elsif ($realm eq 'request') {
1.48 www 11113: # ------------------------------------------------------------- request.browser
11114: if ($space eq 'browser') {
1.1145 bisitz 11115: return $env{'browser.'.$qualifier};
1.57 www 11116: # ------------------------------------------------------------ request.filename
11117: } else {
1.620 albertel 11118: return $env{'request.'.$spacequalifierrest};
1.29 www 11119: }
1.28 www 11120: } elsif ($realm eq 'course') {
1.48 www 11121: # ---------------------------------------------------------- course.description
1.620 albertel 11122: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11123: } elsif ($realm eq 'resource') {
1.165 www 11124:
1.620 albertel 11125: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11126: if (!$symbparm) { $symbparm=&symbread(); }
11127: }
1.693 albertel 11128:
1.1232 raeburn 11129: if ($qualifier eq '') {
11130: if ($space eq 'title') {
11131: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11132: return &gettitle($symbparm);
11133: }
1.693 albertel 11134:
1.1232 raeburn 11135: if ($space eq 'map') {
11136: my ($map) = &decode_symb($symbparm);
11137: return &symbread($map);
11138: }
11139: if ($space eq 'maptitle') {
11140: my ($map) = &decode_symb($symbparm);
11141: return &gettitle($map);
11142: }
11143: if ($space eq 'filename') {
11144: if ($symbparm) {
11145: return &clutter((&decode_symb($symbparm))[2]);
11146: }
11147: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11148: }
1.1232 raeburn 11149:
1.1233 raeburn 11150: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11151: if ($space eq 'visibleparts') {
11152: my $navmap = Apache::lonnavmaps::navmap->new();
11153: my $item;
11154: if (ref($navmap)) {
11155: my $res = $navmap->getBySymb($symbparm);
11156: my $parts = $res->parts();
11157: if (ref($parts) eq 'ARRAY') {
11158: $item = join(',',@{$parts});
11159: }
11160: undef($navmap);
1.1232 raeburn 11161: }
1.1233 raeburn 11162: return $item;
1.1232 raeburn 11163: }
11164: }
11165: }
1.693 albertel 11166:
1.1301 raeburn 11167: my ($section, $group, @groups, @recurseup, $recursed);
11168: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 11169: if (($courseid eq '') && ($cid)) {
11170: $courseid = $cid;
11171: }
11172: if (($symbparm && $courseid) &&
11173: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11174:
1.218 albertel 11175: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11176:
1.60 www 11177: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11178: my $symbp=$symbparm;
1.1301 raeburn 11179: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11180: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 11181: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 11182: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 11183: if (($env{'user.name'} eq $uname) &&
11184: ($env{'user.domain'} eq $udom)) {
11185: $section=$env{'request.course.sec'};
1.733 raeburn 11186: @groups = split(/:/,$env{'request.course.groups'});
11187: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11188: } else {
1.539 albertel 11189: if (! defined($usection)) {
1.551 albertel 11190: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11191: } else {
11192: $section = $usection;
11193: }
1.733 raeburn 11194: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11195: }
11196:
11197: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11198: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 11199: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 11200: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11201:
1.593 albertel 11202: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11203: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 11204: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 11205: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11206:
1.60 www 11207: # ----------------------------------------------------------- first, check user
1.624 albertel 11208:
1.1301 raeburn 11209: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11210: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 11211: ([$courselevelr,'resource'],
11212: [$courselevelm,'map' ],
1.1301 raeburn 11213: [$courseleveli,'map' ],
1.927 albertel 11214: [$courselevel, 'course' ]));
1.931 albertel 11215: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11216:
1.594 albertel 11217: # ------------------------------------------------ second, check some of course
1.684 raeburn 11218: my $coursereply;
1.691 raeburn 11219: if (@groups > 0) {
11220: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 11221: $recurseparm,$mapparm,$spacequalifierrest,
11222: $mapp,\$recursed,\@recurseup);
11223: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11224: }
1.96 www 11225:
1.684 raeburn 11226: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11227: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 11228: 'course',$mapp,\$recursed,\@recurseup,
11229: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 11230: ([$seclevelr, 'resource'],
11231: [$seclevelm, 'map' ],
1.1301 raeburn 11232: [$secleveli, 'map' ],
1.927 albertel 11233: [$seclevel, 'course' ],
11234: [$courselevelr,'resource']));
11235: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11236:
1.60 www 11237: # ------------------------------------------------------ third, check map parms
1.218 albertel 11238: my %parmhash=();
11239: my $thisparm='';
11240: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11241: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11242: &GDBM_READER(),0640)) {
1.218 albertel 11243: $thisparm=$parmhash{$symbparm};
11244: untie(%parmhash);
11245: }
1.927 albertel 11246: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11247: }
1.594 albertel 11248: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 11249:
11250: my $what = $spacequalifierrest;
11251: $what=~s/\./\_/;
1.282 albertel 11252: my $filename;
11253: if (!$symbparm) { $symbparm=&symbread(); }
11254: if ($symbparm) {
1.409 www 11255: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11256: } else {
1.620 albertel 11257: $filename=$env{'request.filename'};
1.282 albertel 11258: }
1.1301 raeburn 11259: my $metadata=&metadata($filename,$what);
1.927 albertel 11260: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301 raeburn 11261: $metadata=&metadata($filename,'parameter_'.$what);
1.927 albertel 11262: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11263:
1.1301 raeburn 11264: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 11265: if ($symbparm && defined($courseid) &&
1.620 albertel 11266: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11267: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11268: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 11269: 'course',$mapp,\$recursed,\@recurseup,
11270: $courseid,'.',$spacequalifierrest,
1.927 albertel 11271: ([$courselevelm,'map' ],
1.1301 raeburn 11272: [$courseleveli,'map' ],
1.927 albertel 11273: [$courselevel, 'course']));
11274: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11275: }
1.145 www 11276: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11277: unless ($space eq '0') {
1.336 albertel 11278: my @parts=split(/_/,$space);
11279: my $id=pop(@parts);
11280: my $part=join('_',@parts);
11281: if ($part eq '') { $part='0'; }
1.927 albertel 11282: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11283: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11284: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11285: }
1.395 albertel 11286: if ($recurse) { return undef; }
11287: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11288: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11289: # ---------------------------------------------------- Any other user namespace
11290: } elsif ($realm eq 'environment') {
11291: # ----------------------------------------------------------------- environment
1.620 albertel 11292: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11293: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11294: } else {
1.770 albertel 11295: if ($uname eq 'anonymous' && $udom eq '') {
11296: return '';
11297: }
1.219 albertel 11298: my %returnhash=&userenvironment($udom,$uname,
11299: $spacequalifierrest);
11300: return $returnhash{$spacequalifierrest};
11301: }
1.28 www 11302: } elsif ($realm eq 'system') {
1.48 www 11303: # ----------------------------------------------------------------- system.time
11304: if ($space eq 'time') {
11305: return time;
11306: }
1.696 albertel 11307: } elsif ($realm eq 'server') {
11308: # ----------------------------------------------------------------- system.time
11309: if ($space eq 'name') {
11310: return $ENV{'SERVER_NAME'};
11311: }
1.28 www 11312: }
1.48 www 11313: return '';
1.61 www 11314: }
11315:
1.927 albertel 11316: sub get_reply {
11317: my ($reply_value) = @_;
1.940 raeburn 11318: if (ref($reply_value) eq 'ARRAY') {
11319: if (wantarray) {
11320: return @$reply_value;
11321: }
11322: return $reply_value->[0];
11323: } else {
11324: return $reply_value;
1.927 albertel 11325: }
11326: }
11327:
1.691 raeburn 11328: sub check_group_parms {
1.1301 raeburn 11329: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11330: $recursed,$recurseupref) = @_;
11331: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11332: [$what,'course']);
11333: my $coursereply;
1.691 raeburn 11334: foreach my $group (@{$groups}) {
1.1301 raeburn 11335: my @groupitems = ();
1.691 raeburn 11336: foreach my $level (@levels) {
1.927 albertel 11337: my $item = $courseid.'.['.$group.'].'.$level->[0];
11338: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11339: }
1.1301 raeburn 11340: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11341: $env{'course.'.$courseid.'.domain'},
11342: 'course',$mapp,$recursed,$recurseupref,
11343: $courseid,'.['.$group.'].',$what,
11344: @groupitems);
11345: last if (defined($coursereply));
1.691 raeburn 11346: }
11347: return $coursereply;
11348: }
11349:
1.1301 raeburn 11350: sub get_map_hierarchy {
1.1302 raeburn 11351: my ($mapname,$courseid) = @_;
11352: my @recurseup = ();
1.1301 raeburn 11353: if ($mapname) {
1.1302 raeburn 11354: if (($cachedmapkey eq $courseid) &&
11355: (abs($cachedmaptime-time)<5)) {
11356: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11357: return @{$cachedmaps{$mapname}};
11358: }
11359: }
1.1301 raeburn 11360: my $navmap = Apache::lonnavmaps::navmap->new();
11361: if (ref($navmap)) {
11362: @recurseup = $navmap->recurseup_maps($mapname);
11363: undef($navmap);
1.1302 raeburn 11364: $cachedmaps{$mapname} = \@recurseup;
11365: $cachedmaptime=time;
11366: $cachedmapkey=$courseid;
1.1301 raeburn 11367: }
11368: }
11369: return @recurseup;
11370: }
11371:
1.1302 raeburn 11372: }
11373:
1.691 raeburn 11374: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11375: my ($courseid,@groups) = @_;
11376: @groups = sort(@groups);
1.691 raeburn 11377: return @groups;
11378: }
11379:
1.395 albertel 11380: sub packages_tab_default {
11381: my ($uri,$varname)=@_;
11382: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11383:
11384: my (@extension,@specifics,$do_default);
11385: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11386: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11387: if ($pack_type eq 'default') {
11388: $do_default=1;
11389: } elsif ($pack_type eq 'extension') {
11390: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11391: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11392: # only look at packages defaults for packages that this id is
1.738 albertel 11393: push(@specifics,[$package,$pack_type,$pack_part]);
11394: }
11395: }
11396: # first look for a package that matches the requested part id
11397: foreach my $package (@specifics) {
11398: my (undef,$pack_type,$pack_part)=@{$package};
11399: next if ($pack_part ne $part);
11400: if (defined($packagetab{"$pack_type&$name&default"})) {
11401: return $packagetab{"$pack_type&$name&default"};
11402: }
11403: }
11404: # look for any possible matching non extension_ package
11405: foreach my $package (@specifics) {
11406: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11407: if (defined($packagetab{"$pack_type&$name&default"})) {
11408: return $packagetab{"$pack_type&$name&default"};
11409: }
1.585 albertel 11410: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11411: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11412: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11413: }
11414: }
1.738 albertel 11415: # look for any posible extension_ match
11416: foreach my $package (@extension) {
11417: my ($package,$pack_type)=@{$package};
11418: if (defined($packagetab{"$pack_type&$name&default"})) {
11419: return $packagetab{"$pack_type&$name&default"};
11420: }
11421: if (defined($packagetab{$package."&$name&default"})) {
11422: return $packagetab{$package."&$name&default"};
11423: }
11424: }
11425: # look for a global default setting
11426: if ($do_default && defined($packagetab{"default&$name&default"})) {
11427: return $packagetab{"default&$name&default"};
11428: }
1.395 albertel 11429: return undef;
11430: }
11431:
1.334 albertel 11432: sub add_prefix_and_part {
11433: my ($prefix,$part)=@_;
11434: my $keyroot;
11435: if (defined($prefix) && $prefix !~ /^__/) {
11436: # prefix that has a part already
11437: $keyroot=$prefix;
11438: } elsif (defined($prefix)) {
11439: # prefix that is missing a part
11440: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11441: } else {
11442: # no prefix at all
11443: if (defined($part)) { $keyroot='_'.$part; }
11444: }
11445: return $keyroot;
11446: }
11447:
1.71 www 11448: # ---------------------------------------------------------------- Get metadata
11449:
1.599 albertel 11450: my %metaentry;
1.1070 www 11451: my %importedpartids;
1.71 www 11452: sub metadata {
1.176 www 11453: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11454: $uri=&declutter($uri);
1.288 albertel 11455: # if it is a non metadata possible uri return quickly
1.529 albertel 11456: if (($uri eq '') ||
11457: (($uri =~ m|^/*adm/|) &&
1.1298 raeburn 11458: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108 raeburn 11459: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11460: return undef;
11461: }
1.1261 raeburn 11462: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11463: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11464: return undef;
1.288 albertel 11465: }
1.73 www 11466: my $filename=$uri;
11467: $uri=~s/\.meta$//;
1.172 www 11468: #
11469: # Is the metadata already cached?
1.177 www 11470: # Look at timestamp of caching
1.172 www 11471: # Everything is cached by the main uri, libraries are never directly cached
11472: #
1.428 albertel 11473: if (!defined($liburi)) {
1.599 albertel 11474: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11475: if (defined($cached)) { return $result->{':'.$what}; }
11476: }
11477: {
1.1069 www 11478: # Imported parts would go here
1.1070 www 11479: my %importedids=();
11480: my @origfileimportpartids=();
1.1069 www 11481: my $importedparts=0;
1.172 www 11482: #
11483: # Is this a recursive call for a library?
11484: #
1.599 albertel 11485: # if (! exists($metacache{$uri})) {
11486: # $metacache{$uri}={};
11487: # }
1.924 albertel 11488: my $cachetime = 60*60;
1.171 www 11489: if ($liburi) {
11490: $liburi=&declutter($liburi);
11491: $filename=$liburi;
1.401 bowersj2 11492: } else {
1.599 albertel 11493: &devalidate_cache_new('meta',$uri);
11494: undef(%metaentry);
1.401 bowersj2 11495: }
1.140 www 11496: my %metathesekeys=();
1.73 www 11497: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11498: my $metastring;
1.1140 www 11499: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11500: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11501: $metastring =
1.929 albertel 11502: &Apache::lonnet::ssi_body($which,
1.924 albertel 11503: ('grade_target' => 'meta'));
11504: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11505: } elsif (($uri !~ m -^(editupload)/-) &&
11506: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11507: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11508: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11509: $metastring=&getfile($file);
1.489 albertel 11510: }
1.208 albertel 11511: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11512: my $token;
1.140 www 11513: undef %metathesekeys;
1.71 www 11514: while ($token=$parser->get_token) {
1.339 albertel 11515: if ($token->[0] eq 'S') {
11516: if (defined($token->[2]->{'package'})) {
1.172 www 11517: #
11518: # This is a package - get package info
11519: #
1.339 albertel 11520: my $package=$token->[2]->{'package'};
11521: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11522: if (defined($token->[2]->{'id'})) {
11523: $keyroot.='_'.$token->[2]->{'id'};
11524: }
1.599 albertel 11525: if ($metaentry{':packages'}) {
11526: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11527: } else {
1.599 albertel 11528: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11529: }
1.736 albertel 11530: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11531: my $part=$keyroot;
11532: $part=~s/^\_//;
1.736 albertel 11533: if ($pack_entry=~/^\Q$package\E\&/ ||
11534: $pack_entry=~/^\Q$package\E_0\&/) {
11535: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11536: # ignore package.tab specified default values
11537: # here &package_tab_default() will fetch those
11538: if ($subp eq 'default') { next; }
1.736 albertel 11539: my $value=$packagetab{$pack_entry};
1.432 albertel 11540: my $unikey;
11541: if ($pack =~ /_0$/) {
11542: $unikey='parameter_0_'.$name;
11543: $part=0;
11544: } else {
11545: $unikey='parameter'.$keyroot.'_'.$name;
11546: }
1.339 albertel 11547: if ($subp eq 'display') {
11548: $value.=' [Part: '.$part.']';
11549: }
1.599 albertel 11550: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11551: $metathesekeys{$unikey}=1;
1.599 albertel 11552: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11553: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11554: }
1.599 albertel 11555: if (defined($metaentry{':'.$unikey.'.default'})) {
11556: $metaentry{':'.$unikey}=
11557: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11558: }
1.339 albertel 11559: }
11560: }
11561: } else {
1.172 www 11562: #
11563: # This is not a package - some other kind of start tag
1.339 albertel 11564: #
11565: my $entry=$token->[1];
1.1068 www 11566: my $unikey='';
1.175 www 11567:
1.339 albertel 11568: if ($entry eq 'import') {
1.175 www 11569: #
11570: # Importing a library here
1.339 albertel 11571: #
1.1067 www 11572: my $location=$parser->get_text('/import');
11573: my $dir=$filename;
11574: $dir=~s|[^/]*$||;
11575: $location=&filelocation($dir,$location);
1.1069 www 11576:
1.1068 www 11577: my $importmode=$token->[2]->{'importmode'};
11578: if ($importmode eq 'problem') {
1.1069 www 11579: # Import as problem/response
1.1068 www 11580: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11581: } elsif ($importmode eq 'part') {
11582: # Import as part(s)
1.1069 www 11583: $importedparts=1;
11584: # We need to get the original file and the imported file to get the part order correct
11585: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11586: # Load and inspect original file
1.1070 www 11587: if ($#origfileimportpartids<0) {
11588: undef(%importedpartids);
11589: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11590: my $origfile=&getfile($origfilelocation);
11591: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11592: }
11593:
1.1069 www 11594: # Load and inspect imported file
11595: my $impfile=&getfile($location);
11596: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11597: if ($#impfilepartids>=0) {
11598: # This problem had parts
1.1070 www 11599: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11600: } else {
11601: # Importing by turning a single problem into a problem part
11602: # It gets the import-tags ID as part-ID
11603: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11604: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11605: }
1.1068 www 11606: } else {
11607: # Normal import
11608: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11609: if (defined($token->[2]->{'id'})) {
11610: $unikey.='_'.$token->[2]->{'id'};
11611: }
1.1067 www 11612: }
11613:
1.339 albertel 11614: if ($depthcount<20) {
1.736 albertel 11615: my $metadata =
11616: &metadata($uri,'keys', $location,$unikey,
11617: $depthcount+1);
11618: foreach my $meta (split(',',$metadata)) {
11619: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11620: $metathesekeys{$meta}=1;
1.339 albertel 11621: }
1.1068 www 11622:
11623: }
1.1067 www 11624: } else {
11625: #
11626: # Not importing, some other kind of non-package, non-library start tag
11627: #
11628: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11629: if (defined($token->[2]->{'id'})) {
11630: $unikey.='_'.$token->[2]->{'id'};
11631: }
1.339 albertel 11632: if (defined($token->[2]->{'name'})) {
11633: $unikey.='_'.$token->[2]->{'name'};
11634: }
11635: $metathesekeys{$unikey}=1;
1.736 albertel 11636: foreach my $param (@{$token->[3]}) {
11637: $metaentry{':'.$unikey.'.'.$param} =
11638: $token->[2]->{$param};
1.339 albertel 11639: }
11640: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11641: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11642: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11643: # only ws inside the tag, and not in default, so use default
11644: # as value
1.599 albertel 11645: $metaentry{':'.$unikey}=$default;
1.908 albertel 11646: } elsif ( $internaltext =~ /\S/ ) {
11647: # something interesting inside the tag
11648: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11649: } else {
1.908 albertel 11650: # no interesting values, don't set a default
1.339 albertel 11651: }
1.172 www 11652: # end of not-a-package not-a-library import
1.339 albertel 11653: }
1.172 www 11654: # end of not-a-package start tag
1.339 albertel 11655: }
1.172 www 11656: # the next is the end of "start tag"
1.339 albertel 11657: }
11658: }
1.483 albertel 11659: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11660: $extension = lc($extension);
11661: if ($extension eq 'htm') { $extension='html'; }
11662:
1.737 albertel 11663: foreach my $key (keys(%packagetab)) {
1.483 albertel 11664: #no specific packages #how's our extension
11665: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11666: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11667: \%metathesekeys);
11668: }
1.883 albertel 11669:
11670: if (!exists($metaentry{':packages'})
11671: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11672: foreach my $key (keys(%packagetab)) {
1.483 albertel 11673: #no specific packages well let's get default then
11674: if ($key!~/^default&/) { next; }
1.488 albertel 11675: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11676: \%metathesekeys);
11677: }
11678: }
1.338 www 11679: # are there custom rights to evaluate
1.599 albertel 11680: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11681:
1.338 www 11682: #
11683: # Importing a rights file here
1.339 albertel 11684: #
11685: unless ($depthcount) {
1.599 albertel 11686: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11687: my $dir=$filename;
11688: $dir=~s|[^/]*$||;
11689: $location=&filelocation($dir,$location);
1.736 albertel 11690: my $rights_metadata =
11691: &metadata($uri,'keys',$location,'_rights',
11692: $depthcount+1);
11693: foreach my $rights (split(',',$rights_metadata)) {
11694: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11695: $metathesekeys{$rights}=1;
1.339 albertel 11696: }
11697: }
11698: }
1.737 albertel 11699: # uniqifiy package listing
11700: my %seen;
11701: my @uniq_packages =
11702: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11703: $metaentry{':packages'} = join(',',@uniq_packages);
11704:
1.1070 www 11705: if ($importedparts) {
11706: # We had imported parts and need to rebuild partorder
11707: $metaentry{':partorder'}='';
11708: $metathesekeys{'partorder'}=1;
11709: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11710: if ($origfileimportpartids[$index] eq 'part') {
11711: # original part, part of the problem
11712: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11713: } else {
11714: # we have imported parts at this position
11715: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11716: }
11717: }
11718: $metaentry{':partorder'}=~s/^\,//;
11719: }
11720:
1.737 albertel 11721: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11722: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 11723: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11724: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11725: # this is the end of "was not already recently cached
1.71 www 11726: }
1.599 albertel 11727: return $metaentry{':'.$what};
1.261 albertel 11728: }
11729:
1.488 albertel 11730: sub metadata_create_package_def {
1.483 albertel 11731: my ($uri,$key,$package,$metathesekeys)=@_;
11732: my ($pack,$name,$subp)=split(/\&/,$key);
11733: if ($subp eq 'default') { next; }
11734:
1.599 albertel 11735: if (defined($metaentry{':packages'})) {
11736: $metaentry{':packages'}.=','.$package;
1.483 albertel 11737: } else {
1.599 albertel 11738: $metaentry{':packages'}=$package;
1.483 albertel 11739: }
11740: my $value=$packagetab{$key};
11741: my $unikey;
11742: $unikey='parameter_0_'.$name;
1.599 albertel 11743: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11744: $$metathesekeys{$unikey}=1;
1.599 albertel 11745: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11746: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11747: }
1.599 albertel 11748: if (defined($metaentry{':'.$unikey.'.default'})) {
11749: $metaentry{':'.$unikey}=
11750: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11751: }
11752: }
11753:
1.261 albertel 11754: sub metadata_generate_part0 {
11755: my ($metadata,$metacache,$uri) = @_;
11756: my %allnames;
1.737 albertel 11757: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11758: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11759: my $part=$$metacache{':'.$metakey.'.part'};
11760: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11761: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11762: $allnames{$name}=$part;
11763: }
11764: }
11765: }
11766: foreach my $name (keys(%allnames)) {
11767: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11768: my $key=":parameter_0_$name";
1.261 albertel 11769: $$metacache{"$key.part"}='0';
11770: $$metacache{"$key.name"}=$name;
1.428 albertel 11771: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11772: $allnames{$name}.'_'.$name.
11773: '.type'};
1.428 albertel 11774: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11775: '.display'};
1.644 www 11776: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11777: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11778: $$metacache{"$key.display"}=$olddis;
11779: }
1.71 www 11780: }
11781:
1.764 albertel 11782: # ------------------------------------------------------ Devalidate title cache
11783:
11784: sub devalidate_title_cache {
11785: my ($url)=@_;
11786: if (!$env{'request.course.id'}) { return; }
11787: my $symb=&symbread($url);
11788: if (!$symb) { return; }
11789: my $key=$env{'request.course.id'}."\0".$symb;
11790: &devalidate_cache_new('title',$key);
11791: }
11792:
1.1014 droeschl 11793: # ------------------------------------------------- Get the title of a course
11794:
11795: sub current_course_title {
11796: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11797: }
1.301 www 11798: # ------------------------------------------------- Get the title of a resource
11799:
11800: sub gettitle {
11801: my $urlsymb=shift;
11802: my $symb=&symbread($urlsymb);
1.534 albertel 11803: if ($symb) {
1.620 albertel 11804: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11805: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11806: if (defined($cached)) {
11807: return $result;
11808: }
1.534 albertel 11809: my ($map,$resid,$url)=&decode_symb($symb);
11810: my $title='';
1.907 albertel 11811: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11812: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11813: } else {
11814: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11815: &GDBM_READER(),0640)) {
11816: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11817: $title=$bighash{'title_'.$mapid.'.'.$resid};
11818: untie(%bighash);
11819: }
1.534 albertel 11820: }
11821: $title=~s/\&colon\;/\:/gs;
11822: if ($title) {
1.1159 www 11823: # Remember both $symb and $title for dynamic metadata
11824: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11825: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11826: # Cache this title and then return it
1.599 albertel 11827: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11828: }
11829: $urlsymb=$url;
11830: }
11831: my $title=&metadata($urlsymb,'title');
11832: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11833: return $title;
1.301 www 11834: }
1.613 albertel 11835:
1.614 albertel 11836: sub get_slot {
11837: my ($which,$cnum,$cdom)=@_;
11838: if (!$cnum || !$cdom) {
1.790 albertel 11839: (undef,my $courseid)=&whichuser();
1.620 albertel 11840: $cdom=$env{'course.'.$courseid.'.domain'};
11841: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11842: }
1.703 albertel 11843: my $key=join("\0",'slots',$cdom,$cnum,$which);
11844: my %slotinfo;
11845: if (exists($remembered{$key})) {
11846: $slotinfo{$which} = $remembered{$key};
11847: } else {
11848: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11849: &Apache::lonhomework::showhash(%slotinfo);
11850: my ($tmp)=keys(%slotinfo);
11851: if ($tmp=~/^error:/) { return (); }
11852: $remembered{$key} = $slotinfo{$which};
11853: }
1.616 albertel 11854: if (ref($slotinfo{$which}) eq 'HASH') {
11855: return %{$slotinfo{$which}};
11856: }
11857: return $slotinfo{$which};
1.614 albertel 11858: }
1.1150 raeburn 11859:
11860: sub get_reservable_slots {
11861: my ($cnum,$cdom,$uname,$udom) = @_;
11862: my $now = time;
11863: my $reservable_info;
11864: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11865: if (exists($remembered{$key})) {
11866: $reservable_info = $remembered{$key};
11867: } else {
11868: my %resv;
11869: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11870: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11871: $reservable_info = \%resv;
11872: $remembered{$key} = $reservable_info;
11873: }
11874: return $reservable_info;
11875: }
11876:
11877: sub get_course_slots {
11878: my ($cnum,$cdom) = @_;
11879: my $hashid=$cnum.':'.$cdom;
11880: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11881: if (defined($cached)) {
11882: if (ref($result) eq 'HASH') {
11883: return %{$result};
11884: }
11885: } else {
11886: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11887: my ($tmp) = keys(%slots);
11888: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 11889: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11890: return %slots;
11891: }
11892: }
11893: return;
11894: }
11895:
11896: sub devalidate_slots_cache {
11897: my ($cnum,$cdom)=@_;
11898: my $hashid=$cnum.':'.$cdom;
11899: &devalidate_cache_new('allslots',$hashid);
11900: }
11901:
1.1181 raeburn 11902: sub get_coursechange {
11903: my ($cdom,$cnum) = @_;
11904: if ($cdom eq '' || $cnum eq '') {
11905: return unless ($env{'request.course.id'});
11906: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11907: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11908: }
11909: my $hashid=$cdom.'_'.$cnum;
11910: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11911: if ((defined($cached)) && ($change ne '')) {
11912: return $change;
11913: } else {
11914: my %crshash;
11915: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11916: if ($crshash{'internal.contentchange'} eq '') {
11917: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11918: if ($change eq '') {
11919: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11920: $change = $crshash{'internal.created'};
11921: }
11922: } else {
11923: $change = $crshash{'internal.contentchange'};
11924: }
11925: my $cachetime = 600;
11926: &do_cache_new('crschange',$hashid,$change,$cachetime);
11927: }
11928: return $change;
11929: }
11930:
11931: sub devalidate_coursechange_cache {
11932: my ($cnum,$cdom)=@_;
11933: my $hashid=$cnum.':'.$cdom;
11934: &devalidate_cache_new('crschange',$hashid);
11935: }
11936:
1.31 www 11937: # ------------------------------------------------- Update symbolic store links
11938:
11939: sub symblist {
11940: my ($mapname,%newhash)=@_;
1.438 www 11941: $mapname=&deversion(&declutter($mapname));
1.31 www 11942: my %hash;
1.620 albertel 11943: if (($env{'request.course.fn'}) && (%newhash)) {
11944: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11945: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11946: foreach my $url (keys(%newhash)) {
1.711 albertel 11947: next if ($url eq 'last_known'
11948: && $env{'form.no_update_last_known'});
11949: $hash{declutter($url)}=&encode_symb($mapname,
11950: $newhash{$url}->[1],
11951: $newhash{$url}->[0]);
1.191 harris41 11952: }
1.31 www 11953: if (untie(%hash)) {
11954: return 'ok';
11955: }
11956: }
11957: }
11958: return 'error';
1.212 www 11959: }
11960:
11961: # --------------------------------------------------------------- Verify a symb
11962:
11963: sub symbverify {
1.1190 raeburn 11964: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11965: my $thisfn=$thisurl;
1.439 www 11966: $thisfn=&declutter($thisfn);
1.215 www 11967: # direct jump to resource in page or to a sequence - will construct own symbs
11968: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11969: # check URL part
1.409 www 11970: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11971:
1.431 www 11972: unless ($url eq $thisfn) { return 0; }
1.213 www 11973:
1.216 www 11974: $symb=&symbclean($symb);
1.510 www 11975: $thisurl=&deversion($thisurl);
1.439 www 11976: $thisfn=&deversion($thisfn);
1.213 www 11977:
11978: my %bighash;
11979: my $okay=0;
1.431 www 11980:
1.620 albertel 11981: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11982: &GDBM_READER(),0640)) {
1.1204 raeburn 11983: my $noclutter;
1.1032 raeburn 11984: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11985: $thisurl =~ s/\?.+$//;
1.1204 raeburn 11986: if ($map =~ m{^uploaded/.+\.page$}) {
11987: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11988: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11989: $noclutter = 1;
11990: }
11991: }
11992: my $ids;
11993: if ($noclutter) {
11994: $ids=$bighash{'ids_'.$thisurl};
11995: } else {
11996: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11997: }
1.1102 raeburn 11998: unless ($ids) {
11999: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12000: $ids=$bighash{$idkey};
1.216 www 12001: }
12002: if ($ids) {
12003: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 12004: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 12005: $symb =~ s/\?.+$//;
1.1202 raeburn 12006: }
1.800 albertel 12007: foreach my $id (split(/\,/,$ids)) {
12008: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12009: if (
12010: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 12011: eq $symb) {
12012: if (ref($encstate)) {
12013: $$encstate = $bighash{'encrypted_'.$id};
12014: }
1.620 albertel 12015: if (($env{'request.role.adv'}) ||
1.1101 raeburn 12016: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12017: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 12018: $okay=1;
1.1202 raeburn 12019: last;
1.582 albertel 12020: }
12021: }
1.216 www 12022: }
12023: }
1.213 www 12024: untie(%bighash);
12025: }
12026: return $okay;
1.31 www 12027: }
12028:
1.210 www 12029: # --------------------------------------------------------------- Clean-up symb
12030:
12031: sub symbclean {
12032: my $symb=shift;
1.568 albertel 12033: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12034: # remove version from map
12035: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12036:
1.210 www 12037: # remove version from URL
12038: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12039:
1.507 www 12040: # remove wrapper
12041:
1.510 www 12042: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12043: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12044: return $symb;
1.409 www 12045: }
12046:
12047: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12048:
12049: sub encode_symb {
12050: my ($map,$resid,$url)=@_;
12051: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12052: }
1.409 www 12053:
12054: sub decode_symb {
1.568 albertel 12055: my $symb=shift;
12056: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12057: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12058: return (&fixversion($map),$resid,&fixversion($url));
12059: }
12060:
12061: sub fixversion {
12062: my $fn=shift;
1.609 banghart 12063: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12064: my %bighash;
12065: my $uri=&clutter($fn);
1.620 albertel 12066: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12067: # is this cached?
1.599 albertel 12068: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12069: if (defined($cached)) { return $result; }
12070: # unfortunately not cached, or expired
1.620 albertel 12071: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12072: &GDBM_READER(),0640)) {
12073: if ($bighash{'version_'.$uri}) {
12074: my $version=$bighash{'version_'.$uri};
1.444 www 12075: unless (($version eq 'mostrecent') ||
12076: ($version==&getversion($uri))) {
1.440 www 12077: $uri=~s/\.(\w+)$/\.$version\.$1/;
12078: }
12079: }
12080: untie %bighash;
1.413 www 12081: }
1.599 albertel 12082: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12083: }
12084:
12085: sub deversion {
12086: my $url=shift;
12087: $url=~s/\.\d+\.(\w+)$/\.$1/;
12088: return $url;
1.210 www 12089: }
12090:
1.31 www 12091: # ------------------------------------------------------ Return symb list entry
12092:
12093: sub symbread {
1.1282 raeburn 12094: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 12095: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 12096: if (defined($env{$cache_str})) {
12097: if ($ignorecachednull) {
12098: return $env{$cache_str} unless ($env{$cache_str} eq '');
12099: } else {
12100: return $env{$cache_str};
12101: }
12102: }
1.242 www 12103: # no filename provided? try from environment
1.1265 raeburn 12104: unless ($thisfn) {
1.620 albertel 12105: if ($env{'request.symb'}) {
12106: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 12107: }
1.620 albertel 12108: $thisfn=$env{'request.filename'};
1.44 www 12109: }
1.569 albertel 12110: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12111: # is that filename actually a symb? Verify, clean, and return
12112: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12113: if (&symbverify($thisfn,$1)) {
1.620 albertel 12114: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12115: }
1.242 www 12116: }
1.44 www 12117: $thisfn=declutter($thisfn);
1.31 www 12118: my %hash;
1.37 www 12119: my %bighash;
12120: my $syval='';
1.620 albertel 12121: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12122: my $targetfn = $thisfn;
1.609 banghart 12123: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12124: $targetfn = 'adm/wrapper/'.$thisfn;
12125: }
1.687 albertel 12126: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12127: $targetfn=$1;
12128: }
1.620 albertel 12129: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12130: &GDBM_READER(),0640)) {
1.481 raeburn 12131: $syval=$hash{$targetfn};
1.37 www 12132: untie(%hash);
12133: }
12134: # ---------------------------------------------------------- There was an entry
12135: if ($syval) {
1.601 albertel 12136: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12137: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12138: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12139: #return $env{$cache_str}='';
1.601 albertel 12140: #}
12141: #$syval.=$1;
12142: #}
1.37 www 12143: } else {
12144: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12145: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12146: &GDBM_READER(),0640)) {
1.37 www 12147: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12148: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12149: unless ($ids) {
12150: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12151: }
12152: unless ($ids) {
12153: # alias?
12154: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12155: }
1.37 www 12156: if ($ids) {
12157: # ------------------------------------------------------------------- Has ID(s)
12158: my @possibilities=split(/\,/,$ids);
1.39 www 12159: if ($#possibilities==0) {
12160: # ----------------------------------------------- There is only one possibility
1.37 www 12161: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12162: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12163: $resid,$thisfn);
1.1282 raeburn 12164: if (ref($possibles) eq 'HASH') {
12165: $possibles->{$syval} = 1;
12166: }
12167: if ($checkforblock) {
12168: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12169: if (@blockers) {
12170: $syval = '';
12171: return;
12172: }
12173: }
12174: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12175: # ------------------------------------------ There is more than one possibility
12176: my $realpossible=0;
1.800 albertel 12177: foreach my $id (@possibilities) {
12178: my $file=$bighash{'src_'.$id};
1.1282 raeburn 12179: my $canaccess;
12180: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12181: $canaccess = 1;
12182: } else {
12183: $canaccess = &allowed('bre',$file);
12184: }
12185: if ($canaccess) {
12186: my ($mapid,$resid)=split(/\./,$id);
12187: if ($bighash{'map_type_'.$mapid} ne 'page') {
12188: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12189: $resid,$thisfn);
12190: if (ref($possibles) eq 'HASH') {
12191: $possibles->{$syval} = 1;
12192: }
12193: if ($checkforblock) {
12194: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12195: unless (@blockers > 0) {
12196: $syval = $poss_syval;
12197: $realpossible++;
12198: }
12199: } else {
12200: $syval = $poss_syval;
12201: $realpossible++;
12202: }
12203: }
1.39 www 12204: }
1.191 harris41 12205: }
1.39 www 12206: if ($realpossible!=1) { $syval=''; }
1.249 www 12207: } else {
12208: $syval='';
1.37 www 12209: }
12210: }
1.1282 raeburn 12211: untie(%bighash);
1.481 raeburn 12212: }
1.31 www 12213: }
1.62 www 12214: if ($syval) {
1.620 albertel 12215: return $env{$cache_str}=$syval;
1.62 www 12216: }
1.31 www 12217: }
1.949 raeburn 12218: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12219: return $env{$cache_str}='';
1.31 www 12220: }
12221:
12222: # ---------------------------------------------------------- Return random seed
12223:
1.32 www 12224: sub numval {
12225: my $txt=shift;
12226: $txt=~tr/A-J/0-9/;
12227: $txt=~tr/a-j/0-9/;
12228: $txt=~tr/K-T/0-9/;
12229: $txt=~tr/k-t/0-9/;
12230: $txt=~tr/U-Z/0-5/;
12231: $txt=~tr/u-z/0-5/;
12232: $txt=~s/\D//g;
1.564 albertel 12233: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12234: return int($txt);
1.368 albertel 12235: }
12236:
1.484 albertel 12237: sub numval2 {
12238: my $txt=shift;
12239: $txt=~tr/A-J/0-9/;
12240: $txt=~tr/a-j/0-9/;
12241: $txt=~tr/K-T/0-9/;
12242: $txt=~tr/k-t/0-9/;
12243: $txt=~tr/U-Z/0-5/;
12244: $txt=~tr/u-z/0-5/;
12245: $txt=~s/\D//g;
12246: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12247: my $total;
12248: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12249: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12250: return int($total);
12251: }
12252:
1.575 albertel 12253: sub numval3 {
12254: use integer;
12255: my $txt=shift;
12256: $txt=~tr/A-J/0-9/;
12257: $txt=~tr/a-j/0-9/;
12258: $txt=~tr/K-T/0-9/;
12259: $txt=~tr/k-t/0-9/;
12260: $txt=~tr/U-Z/0-5/;
12261: $txt=~tr/u-z/0-5/;
12262: $txt=~s/\D//g;
12263: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12264: my $total;
12265: foreach my $val (@txts) { $total+=$val; }
12266: if ($_64bit) { $total=(($total<<32)>>32); }
12267: return $total;
12268: }
12269:
1.675 albertel 12270: sub digest {
12271: my ($data)=@_;
12272: my $digest=&Digest::MD5::md5($data);
12273: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12274: my ($e,$f);
12275: {
12276: use integer;
12277: $e=($a+$b);
12278: $f=($c+$d);
12279: if ($_64bit) {
12280: $e=(($e<<32)>>32);
12281: $f=(($f<<32)>>32);
12282: }
12283: }
12284: if (wantarray) {
12285: return ($e,$f);
12286: } else {
12287: my $g;
12288: {
12289: use integer;
12290: $g=($e+$f);
12291: if ($_64bit) {
12292: $g=(($g<<32)>>32);
12293: }
12294: }
12295: return $g;
12296: }
12297: }
12298:
1.368 albertel 12299: sub latest_rnd_algorithm_id {
1.675 albertel 12300: return '64bit5';
1.366 albertel 12301: }
1.32 www 12302:
1.503 albertel 12303: sub get_rand_alg {
12304: my ($courseid)=@_;
1.790 albertel 12305: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12306: if ($courseid) {
1.620 albertel 12307: return $env{"course.$courseid.rndseed"};
1.503 albertel 12308: }
12309: return &latest_rnd_algorithm_id();
12310: }
12311:
1.562 albertel 12312: sub validCODE {
12313: my ($CODE)=@_;
12314: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12315: return 0;
12316: }
12317:
1.491 albertel 12318: sub getCODE {
1.620 albertel 12319: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12320: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12321: defined($Apache::lonhomework::parsing_a_task) ) &&
12322: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12323: return $Apache::lonhomework::history{'resource.CODE'};
12324: }
12325: return undef;
12326: }
1.1133 foxr 12327: #
12328: # Determines the random seed for a specific context:
12329: #
12330: # parameters:
12331: # symb - in course context the symb for the seed.
12332: # course_id - The course id of the form domain_coursenum.
12333: # domain - Domain for the user.
12334: # course - Course for the user.
12335: # cenv - environment of the course.
12336: #
12337: # NOTE:
12338: # All parameters are picked out of the environment if missing
12339: # or not defined.
12340: # If a symb cannot be determined the current time is used instead.
12341: #
12342: # For a given well defined symb, courside, domain, username,
12343: # and course environment, the seed is reproducible.
12344: #
1.31 www 12345: sub rndseed {
1.1133 foxr 12346: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12347: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12348: if (!defined($symb)) {
1.366 albertel 12349: unless ($symb=$wsymb) { return time; }
12350: }
1.1146 foxr 12351: if (!defined $courseid) {
12352: $courseid=$wcourseid;
12353: }
12354: if (!defined $domain) { $domain=$wdomain; }
12355: if (!defined $username) { $username=$wusername }
1.1133 foxr 12356:
12357: my $which;
12358: if (defined($cenv->{'rndseed'})) {
12359: $which = $cenv->{'rndseed'};
12360: } else {
12361: $which =&get_rand_alg($courseid);
12362: }
1.491 albertel 12363: if (defined(&getCODE())) {
1.1133 foxr 12364:
1.675 albertel 12365: if ($which eq '64bit5') {
12366: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12367: } elsif ($which eq '64bit4') {
1.575 albertel 12368: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12369: } else {
12370: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12371: }
1.675 albertel 12372: } elsif ($which eq '64bit5') {
12373: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12374: } elsif ($which eq '64bit4') {
12375: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12376: } elsif ($which eq '64bit3') {
12377: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12378: } elsif ($which eq '64bit2') {
12379: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12380: } elsif ($which eq '64bit') {
12381: return &rndseed_64bit($symb,$courseid,$domain,$username);
12382: }
12383: return &rndseed_32bit($symb,$courseid,$domain,$username);
12384: }
12385:
12386: sub rndseed_32bit {
12387: my ($symb,$courseid,$domain,$username)=@_;
12388: {
12389: use integer;
12390: my $symbchck=unpack("%32C*",$symb) << 27;
12391: my $symbseed=numval($symb) << 22;
12392: my $namechck=unpack("%32C*",$username) << 17;
12393: my $nameseed=numval($username) << 12;
12394: my $domainseed=unpack("%32C*",$domain) << 7;
12395: my $courseseed=unpack("%32C*",$courseid);
12396: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12397: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12398: #&logthis("rndseed :$num:$symb");
1.564 albertel 12399: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12400: return $num;
12401: }
12402: }
12403:
12404: sub rndseed_64bit {
12405: my ($symb,$courseid,$domain,$username)=@_;
12406: {
12407: use integer;
12408: my $symbchck=unpack("%32S*",$symb) << 21;
12409: my $symbseed=numval($symb) << 10;
12410: my $namechck=unpack("%32S*",$username);
12411:
12412: my $nameseed=numval($username) << 21;
12413: my $domainseed=unpack("%32S*",$domain) << 10;
12414: my $courseseed=unpack("%32S*",$courseid);
12415:
12416: my $num1=$symbchck+$symbseed+$namechck;
12417: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12418: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12419: #&logthis("rndseed :$num:$symb");
1.564 albertel 12420: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12421: return "$num1,$num2";
1.155 albertel 12422: }
1.366 albertel 12423: }
12424:
1.443 albertel 12425: sub rndseed_64bit2 {
12426: my ($symb,$courseid,$domain,$username)=@_;
12427: {
12428: use integer;
12429: # strings need to be an even # of cahracters long, it it is odd the
12430: # last characters gets thrown away
12431: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12432: my $symbseed=numval($symb) << 10;
12433: my $namechck=unpack("%32S*",$username.' ');
12434:
12435: my $nameseed=numval($username) << 21;
1.501 albertel 12436: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12437: my $courseseed=unpack("%32S*",$courseid.' ');
12438:
12439: my $num1=$symbchck+$symbseed+$namechck;
12440: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12441: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12442: #&logthis("rndseed :$num:$symb");
1.803 albertel 12443: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12444: return "$num1,$num2";
12445: }
12446: }
12447:
12448: sub rndseed_64bit3 {
12449: my ($symb,$courseid,$domain,$username)=@_;
12450: {
12451: use integer;
12452: # strings need to be an even # of cahracters long, it it is odd the
12453: # last characters gets thrown away
12454: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12455: my $symbseed=numval2($symb) << 10;
12456: my $namechck=unpack("%32S*",$username.' ');
12457:
12458: my $nameseed=numval2($username) << 21;
1.443 albertel 12459: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12460: my $courseseed=unpack("%32S*",$courseid.' ');
12461:
12462: my $num1=$symbchck+$symbseed+$namechck;
12463: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12464: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12465: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12466: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12467:
1.503 albertel 12468: return "$num1:$num2";
1.443 albertel 12469: }
12470: }
12471:
1.575 albertel 12472: sub rndseed_64bit4 {
12473: my ($symb,$courseid,$domain,$username)=@_;
12474: {
12475: use integer;
12476: # strings need to be an even # of cahracters long, it it is odd the
12477: # last characters gets thrown away
12478: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12479: my $symbseed=numval3($symb) << 10;
12480: my $namechck=unpack("%32S*",$username.' ');
12481:
12482: my $nameseed=numval3($username) << 21;
12483: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12484: my $courseseed=unpack("%32S*",$courseid.' ');
12485:
12486: my $num1=$symbchck+$symbseed+$namechck;
12487: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12488: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12489: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12490: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12491:
1.575 albertel 12492: return "$num1:$num2";
12493: }
12494: }
12495:
1.675 albertel 12496: sub rndseed_64bit5 {
12497: my ($symb,$courseid,$domain,$username)=@_;
12498: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12499: return "$num1:$num2";
12500: }
12501:
1.366 albertel 12502: sub rndseed_CODE_64bit {
12503: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12504: {
1.366 albertel 12505: use integer;
1.443 albertel 12506: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12507: my $symbseed=numval2($symb);
1.491 albertel 12508: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12509: my $CODEseed=numval(&getCODE());
1.443 albertel 12510: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12511: my $num1=$symbseed+$CODEchck;
12512: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12513: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12514: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12515: if ($_64bit) { $num1=(($num1<<32)>>32); }
12516: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12517: return "$num1:$num2";
1.366 albertel 12518: }
12519: }
12520:
1.575 albertel 12521: sub rndseed_CODE_64bit4 {
12522: my ($symb,$courseid,$domain,$username)=@_;
12523: {
12524: use integer;
12525: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12526: my $symbseed=numval3($symb);
12527: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12528: my $CODEseed=numval3(&getCODE());
12529: my $courseseed=unpack("%32S*",$courseid.' ');
12530: my $num1=$symbseed+$CODEchck;
12531: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12532: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12533: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12534: if ($_64bit) { $num1=(($num1<<32)>>32); }
12535: if ($_64bit) { $num2=(($num2<<32)>>32); }
12536: return "$num1:$num2";
12537: }
12538: }
12539:
1.675 albertel 12540: sub rndseed_CODE_64bit5 {
12541: my ($symb,$courseid,$domain,$username)=@_;
12542: my $code = &getCODE();
12543: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12544: return "$num1:$num2";
12545: }
12546:
1.366 albertel 12547: sub setup_random_from_rndseed {
12548: my ($rndseed)=@_;
1.503 albertel 12549: if ($rndseed =~/([,:])/) {
1.1262 raeburn 12550: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12551: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12552: &Math::Random::random_set_seed_from_phrase($rndseed);
12553: } else {
12554: &Math::Random::random_set_seed($num1,$num2);
12555: }
1.366 albertel 12556: } else {
12557: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12558: }
1.36 albertel 12559: }
12560:
1.474 albertel 12561: sub latest_receipt_algorithm_id {
1.835 albertel 12562: return 'receipt3';
1.474 albertel 12563: }
12564:
1.480 www 12565: sub recunique {
12566: my $fucourseid=shift;
12567: my $unique;
1.835 albertel 12568: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12569: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12570: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12571: } else {
12572: $unique=$perlvar{'lonReceipt'};
12573: }
12574: return unpack("%32C*",$unique);
12575: }
12576:
12577: sub recprefix {
12578: my $fucourseid=shift;
12579: my $prefix;
1.835 albertel 12580: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12581: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12582: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12583: } else {
12584: $prefix=$perlvar{'lonHostID'};
12585: }
12586: return unpack("%32C*",$prefix);
12587: }
12588:
1.76 www 12589: sub ireceipt {
1.474 albertel 12590: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12591:
12592: my $return =&recprefix($fucourseid).'-';
12593:
12594: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12595: $env{'request.state'} eq 'construct') {
12596: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12597: return $return;
12598: }
12599:
1.76 www 12600: my $cuname=unpack("%32C*",$funame);
12601: my $cudom=unpack("%32C*",$fudom);
12602: my $cucourseid=unpack("%32C*",$fucourseid);
12603: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12604: my $cunique=&recunique($fucourseid);
1.474 albertel 12605: my $cpart=unpack("%32S*",$part);
1.835 albertel 12606: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12607:
1.790 albertel 12608: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12609:
12610: $return.= ($cunique%$cuname+
12611: $cunique%$cudom+
12612: $cusymb%$cuname+
12613: $cusymb%$cudom+
12614: $cucourseid%$cuname+
12615: $cucourseid%$cudom+
12616: $cpart%$cuname+
12617: $cpart%$cudom);
12618: } else {
12619: $return.= ($cunique%$cuname+
12620: $cunique%$cudom+
12621: $cusymb%$cuname+
12622: $cusymb%$cudom+
12623: $cucourseid%$cuname+
12624: $cucourseid%$cudom);
12625: }
12626: return $return;
1.76 www 12627: }
12628:
12629: sub receipt {
1.474 albertel 12630: my ($part)=@_;
1.790 albertel 12631: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12632: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12633: }
1.260 ng 12634:
1.790 albertel 12635: sub whichuser {
12636: my ($passedsymb)=@_;
12637: my ($symb,$courseid,$domain,$name,$publicuser);
12638: if (defined($env{'form.grade_symb'})) {
12639: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12640: my $allowed=&allowed('vgr',$tmp_courseid);
12641: if (!$allowed &&
12642: exists($env{'request.course.sec'}) &&
12643: $env{'request.course.sec'} !~ /^\s*$/) {
12644: $allowed=&allowed('vgr',$tmp_courseid.
12645: '/'.$env{'request.course.sec'});
12646: }
12647: if ($allowed) {
12648: ($symb)=&get_env_multiple('form.grade_symb');
12649: $courseid=$tmp_courseid;
12650: ($domain)=&get_env_multiple('form.grade_domain');
12651: ($name)=&get_env_multiple('form.grade_username');
12652: return ($symb,$courseid,$domain,$name,$publicuser);
12653: }
12654: }
12655: if (!$passedsymb) {
12656: $symb=&symbread();
12657: } else {
12658: $symb=$passedsymb;
12659: }
12660: $courseid=$env{'request.course.id'};
12661: $domain=$env{'user.domain'};
12662: $name=$env{'user.name'};
12663: if ($name eq 'public' && $domain eq 'public') {
12664: if (!defined($env{'form.username'})) {
12665: $env{'form.username'}.=time.rand(10000000);
12666: }
12667: $name.=$env{'form.username'};
12668: }
12669: return ($symb,$courseid,$domain,$name,$publicuser);
12670:
12671: }
12672:
1.36 albertel 12673: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12674: # returns either the contents of the file or
12675: # -1 if the file doesn't exist
1.481 raeburn 12676: #
12677: # if the target is a file that was uploaded via DOCS,
12678: # a check will be made to see if a current copy exists on the local server,
12679: # if it does this will be served, otherwise a copy will be retrieved from
12680: # the home server for the course and stored in /home/httpd/html/userfiles on
12681: # the local server.
1.472 albertel 12682:
1.36 albertel 12683: sub getfile {
1.538 albertel 12684: my ($file) = @_;
1.609 banghart 12685: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12686: &repcopy($file);
12687: return &readfile($file);
12688: }
12689:
12690: sub repcopy_userfile {
12691: my ($file)=@_;
1.1142 raeburn 12692: my $londocroot = $perlvar{'lonDocRoot'};
12693: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12694: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12695: my ($cdom,$cnum,$filename) =
1.811 albertel 12696: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12697: my $uri="/uploaded/$cdom/$cnum/$filename";
12698: if (-e "$file") {
1.828 www 12699: # we already have a local copy, check it out
1.538 albertel 12700: my @fileinfo = stat($file);
1.828 www 12701: my $rtncode;
12702: my $info;
1.538 albertel 12703: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12704: if ($lwpresp ne 'ok') {
1.828 www 12705: # there is no such file anymore, even though we had a local copy
1.482 albertel 12706: if ($rtncode eq '404') {
1.538 albertel 12707: unlink($file);
1.482 albertel 12708: }
12709: return -1;
12710: }
12711: if ($info < $fileinfo[9]) {
1.828 www 12712: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12713: return 'ok';
1.828 www 12714: } else {
12715: # the file is outdated, get rid of it
12716: unlink($file);
1.482 albertel 12717: }
1.828 www 12718: }
12719: # one way or the other, at this point, we don't have the file
12720: # construct the correct path for the file
12721: my @parts = ($cdom,$cnum);
12722: if ($filename =~ m|^(.+)/[^/]+$|) {
12723: push @parts, split(/\//,$1);
12724: }
12725: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12726: foreach my $part (@parts) {
12727: $path .= '/'.$part;
12728: if (!-e $path) {
12729: mkdir($path,0770);
1.482 albertel 12730: }
12731: }
1.828 www 12732: # now the path exists for sure
12733: # get a user agent
12734: my $ua=new LWP::UserAgent;
12735: my $transferfile=$file.'.in.transfer';
12736: # FIXME: this should flock
12737: if (-e $transferfile) { return 'ok'; }
12738: my $request;
12739: $uri=~s/^\///;
1.980 raeburn 12740: my $homeserver = &homeserver($cnum,$cdom);
12741: my $protocol = $protocol{$homeserver};
12742: $protocol = 'http' if ($protocol ne 'https');
12743: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12744: my $response=$ua->request($request,$transferfile);
12745: # did it work?
12746: if ($response->is_error()) {
12747: unlink($transferfile);
12748: &logthis("Userfile repcopy failed for $uri");
12749: return -1;
12750: }
12751: # worked, rename the transfer file
12752: rename($transferfile,$file);
1.607 raeburn 12753: return 'ok';
1.481 raeburn 12754: }
12755:
1.517 albertel 12756: sub tokenwrapper {
12757: my $uri=shift;
1.980 raeburn 12758: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12759: $uri=~s|^/||;
1.620 albertel 12760: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12761: my $token=$1;
1.552 albertel 12762: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12763: if ($udom && $uname && $file) {
12764: $file=~s|(\?\.*)*$||;
1.949 raeburn 12765: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12766: my $homeserver = &homeserver($uname,$udom);
12767: my $protocol = $protocol{$homeserver};
12768: $protocol = 'http' if ($protocol ne 'https');
12769: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12770: (($uri=~/\?/)?'&':'?').'token='.$token.
12771: '&tokenissued='.$perlvar{'lonHostID'};
12772: } else {
12773: return '/adm/notfound.html';
12774: }
12775: }
12776:
1.828 www 12777: # call with reqtype HEAD: get last modification time
12778: # call with reqtype GET: get the file contents
12779: # Do not call this with reqtype GET for large files! It loads everything into memory
12780: #
1.481 raeburn 12781: sub getuploaded {
12782: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12783: $uri=~s/^\///;
1.980 raeburn 12784: my $homeserver = &homeserver($cnum,$cdom);
12785: my $protocol = $protocol{$homeserver};
12786: $protocol = 'http' if ($protocol ne 'https');
12787: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12788: my $ua=new LWP::UserAgent;
12789: my $request=new HTTP::Request($reqtype,$uri);
12790: my $response=$ua->request($request);
12791: $$rtncode = $response->code;
1.482 albertel 12792: if (! $response->is_success()) {
12793: return 'failed';
12794: }
12795: if ($reqtype eq 'HEAD') {
1.486 www 12796: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12797: } elsif ($reqtype eq 'GET') {
12798: $$info = $response->content;
1.472 albertel 12799: }
1.482 albertel 12800: return 'ok';
1.36 albertel 12801: }
12802:
1.481 raeburn 12803: sub readfile {
12804: my $file = shift;
12805: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12806: my $fh;
12807: open($fh,"<$file");
12808: my $a='';
1.800 albertel 12809: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12810: return $a;
12811: }
12812:
1.36 albertel 12813: sub filelocation {
1.590 banghart 12814: my ($dir,$file) = @_;
12815: my $location;
12816: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12817:
12818: if ($file =~ m-^/adm/-) {
12819: $file=~s-^/adm/wrapper/-/-;
12820: $file=~s-^/adm/coursedocs/showdoc/-/-;
12821: }
1.882 albertel 12822:
1.1139 www 12823: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12824: $location = $file;
1.609 banghart 12825: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12826: my ($udom,$uname,$filename)=
1.811 albertel 12827: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12828: my $home=&homeserver($uname,$udom);
12829: my $is_me=0;
12830: my @ids=¤t_machine_ids();
12831: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12832: if ($is_me) {
1.1117 foxr 12833: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12834: } else {
12835: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12836: $udom.'/'.$uname.'/'.$filename;
12837: }
1.882 albertel 12838: } elsif ($file =~ m-^/adm/-) {
12839: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12840: } else {
12841: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12842: $file=~s:^/(res|priv)/:/:;
12843: my $space=$1;
1.590 banghart 12844: if ( !( $file =~ m:^/:) ) {
12845: $location = $dir. '/'.$file;
12846: } else {
1.1142 raeburn 12847: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12848: }
1.59 albertel 12849: }
1.590 banghart 12850: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12851: while ($location=~m{/\.\./}) {
12852: if ($location =~ m{/[^/]+/\.\./}) {
12853: $location=~ s{/[^/]+/\.\./}{/}g;
12854: } else {
12855: $location=~ s{/\.\./}{/}g;
12856: }
12857: } #remove dir/..
1.590 banghart 12858: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12859: return $location;
1.46 www 12860: }
1.36 albertel 12861:
1.46 www 12862: sub hreflocation {
12863: my ($dir,$file)=@_;
1.980 raeburn 12864: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12865: $file=filelocation($dir,$file);
1.700 albertel 12866: } elsif ($file=~m-^/adm/-) {
12867: $file=~s-^/adm/wrapper/-/-;
12868: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12869: }
12870: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12871: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12872: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12873: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12874: {/uploaded/$1/$2/}x;
1.46 www 12875: }
1.913 albertel 12876: if ($file=~ m{^/userfiles/}) {
12877: $file =~ s{^/userfiles/}{/uploaded/};
12878: }
1.462 albertel 12879: return $file;
1.465 albertel 12880: }
12881:
1.1139 www 12882:
12883:
12884:
12885:
1.465 albertel 12886: sub current_machine_domains {
1.853 albertel 12887: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12888: }
12889:
12890: sub machine_domains {
12891: my ($hostname) = @_;
1.465 albertel 12892: my @domains;
1.838 albertel 12893: my %hostname = &all_hostnames();
1.465 albertel 12894: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12895: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12896: if ($hostname eq $name) {
1.844 albertel 12897: push(@domains,&host_domain($id));
1.465 albertel 12898: }
12899: }
12900: return @domains;
12901: }
12902:
12903: sub current_machine_ids {
1.853 albertel 12904: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12905: }
12906:
12907: sub machine_ids {
12908: my ($hostname) = @_;
12909: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12910: my @ids;
1.888 albertel 12911: my %name_to_host = &all_names();
1.889 albertel 12912: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12913: return @{ $name_to_host{$hostname} };
12914: }
12915: return;
1.31 www 12916: }
12917:
1.824 raeburn 12918: sub additional_machine_domains {
12919: my @domains;
12920: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12921: while( my $line = <$fh>) {
12922: $line =~ s/\s//g;
12923: push(@domains,$line);
12924: }
12925: return @domains;
12926: }
12927:
12928: sub default_login_domain {
12929: my $domain = $perlvar{'lonDefDomain'};
12930: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12931: foreach my $posdom (¤t_machine_domains(),
12932: &additional_machine_domains()) {
12933: if (lc($posdom) eq lc($testdomain)) {
12934: $domain=$posdom;
12935: last;
12936: }
12937: }
12938: return $domain;
12939: }
12940:
1.31 www 12941: # ------------------------------------------------------------- Declutters URLs
12942:
12943: sub declutter {
12944: my $thisfn=shift;
1.569 albertel 12945: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 12946: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12947: $thisfn=~s{^/home/httpd/html}{};
12948: }
1.31 www 12949: $thisfn=~s/^\///;
1.697 albertel 12950: $thisfn=~s|^adm/wrapper/||;
12951: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12952: $thisfn=~s/^res\///;
1.1172 bisitz 12953: $thisfn=~s/^priv\///;
1.1032 raeburn 12954: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12955: $thisfn=~s/\?.+$//;
12956: }
1.268 www 12957: return $thisfn;
12958: }
12959:
12960: # ------------------------------------------------------------- Clutter up URLs
12961:
12962: sub clutter {
12963: my $thisfn='/'.&declutter(shift);
1.887 albertel 12964: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12965: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12966: $thisfn='/res'.$thisfn;
12967: }
1.1031 raeburn 12968: if ($thisfn !~m|^/adm|) {
12969: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12970: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12971: } else {
12972: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12973: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12974: if ($embstyle eq 'ssi'
12975: || ($embstyle eq 'hdn')
12976: || ($embstyle eq 'rat')
12977: || ($embstyle eq 'prv')
12978: || ($embstyle eq 'ign')) {
12979: #do nothing with these
12980: } elsif (($embstyle eq 'img')
1.695 albertel 12981: || ($embstyle eq 'emb')
12982: || ($embstyle eq 'wrp')) {
12983: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12984: } elsif ($embstyle eq 'unk'
12985: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12986: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12987: } else {
1.718 www 12988: # &logthis("Got a blank emb style");
1.695 albertel 12989: }
1.694 albertel 12990: }
1.1298 raeburn 12991: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
12992: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 12993: }
1.31 www 12994: return $thisfn;
1.12 www 12995: }
12996:
1.787 albertel 12997: sub clutter_with_no_wrapper {
12998: my $uri = &clutter(shift);
12999: if ($uri =~ m-^/adm/-) {
13000: $uri =~ s-^/adm/wrapper/-/-;
13001: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13002: }
13003: return $uri;
13004: }
13005:
1.557 albertel 13006: sub freeze_escape {
13007: my ($value)=@_;
13008: if (ref($value)) {
13009: $value=&nfreeze($value);
13010: return '__FROZEN__'.&escape($value);
13011: }
13012: return &escape($value);
13013: }
13014:
1.11 www 13015:
1.557 albertel 13016: sub thaw_unescape {
13017: my ($value)=@_;
13018: if ($value =~ /^__FROZEN__/) {
13019: substr($value,0,10,undef);
13020: $value=&unescape($value);
13021: return &thaw($value);
13022: }
13023: return &unescape($value);
13024: }
13025:
1.436 albertel 13026: sub correct_line_ends {
13027: my ($result)=@_;
13028: $$result =~s/\r\n/\n/mg;
13029: $$result =~s/\r/\n/mg;
1.415 albertel 13030: }
1.1 albertel 13031: # ================================================================ Main Program
13032:
1.184 www 13033: sub goodbye {
1.204 albertel 13034: &logthis("Starting Shut down");
1.443 albertel 13035: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13036: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13037: #converted
1.599 albertel 13038: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13039: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13040: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13041: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13042: #1.1 only
1.870 albertel 13043: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13044: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13045: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13046: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13047: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13048: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13049: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13050: &flushcourselogs();
13051: &logthis("Shutting down");
13052: }
13053:
1.852 albertel 13054: sub get_dns {
1.1210 raeburn 13055: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13056: if (!$ignore_cache) {
13057: my ($content,$cached)=
13058: &Apache::lonnet::is_cached_new('dns',$url);
13059: if ($cached) {
1.1210 raeburn 13060: &$func($content,$hashref);
1.869 albertel 13061: return;
13062: }
13063: }
13064:
13065: my %alldns;
1.852 albertel 13066: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13067: foreach my $dns (<$config>) {
13068: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 13069: my $line = $1;
13070: my ($host,$protocol) = split(/:/,$line);
13071: if ($protocol ne 'https') {
13072: $protocol = 'http';
13073: }
13074: $alldns{$host} = $protocol;
1.869 albertel 13075: }
13076: while (%alldns) {
1.1263 raeburn 13077: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 13078: my $ua=new LWP::UserAgent;
1.1134 raeburn 13079: $ua->timeout(30);
1.979 raeburn 13080: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 13081: my $response=$ua->request($request);
1.979 raeburn 13082: delete($alldns{$dns});
1.852 albertel 13083: next if ($response->is_error());
13084: my @content = split("\n",$response->content);
1.1210 raeburn 13085: unless ($nocache) {
1.1219 raeburn 13086: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 13087: }
13088: &$func(\@content,$hashref);
1.869 albertel 13089: return;
1.852 albertel 13090: }
13091: close($config);
1.871 albertel 13092: my $which = (split('/',$url))[3];
13093: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13094: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 13095: my @content = <$config>;
1.1210 raeburn 13096: &$func(\@content,$hashref);
13097: return;
13098: }
13099:
13100: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 13101: sub parse_dns_checksums_tab {
1.1210 raeburn 13102: my ($lines,$hashref) = @_;
1.1264 raeburn 13103: my $lonhost = $perlvar{'lonHostID'};
13104: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 13105: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 13106: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13107: my $webconfdir = '/etc/httpd/conf';
13108: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13109: $webconfdir = '/etc/apache2';
13110: } elsif ($distro =~ /^sles(\d+)$/) {
13111: if ($1 >= 10) {
13112: $webconfdir = '/etc/apache2';
13113: }
13114: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13115: if ($1 >= 10.0) {
13116: $webconfdir = '/etc/apache2';
13117: }
13118: }
1.1210 raeburn 13119: my ($release,$timestamp) = split(/\-/,$loncaparev);
13120: my (%chksum,%revnum);
13121: if (ref($lines) eq 'ARRAY') {
13122: chomp(@{$lines});
1.1238 raeburn 13123: my $version = shift(@{$lines});
13124: if ($version eq $release) {
1.1210 raeburn 13125: foreach my $line (@{$lines}) {
1.1238 raeburn 13126: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 13127: if ($file =~ m{^/etc/httpd/conf}) {
13128: if ($webconfdir eq '/etc/apache2') {
13129: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13130: }
13131: }
1.1238 raeburn 13132: $chksum{$file} = $shasum;
13133: $revnum{$file} = $version;
1.1210 raeburn 13134: }
13135: if (ref($hashref) eq 'HASH') {
13136: %{$hashref} = (
13137: sums => \%chksum,
13138: versions => \%revnum,
13139: );
13140: }
13141: }
13142: }
1.869 albertel 13143: return;
1.852 albertel 13144: }
1.1210 raeburn 13145:
13146: sub fetch_dns_checksums {
1.1238 raeburn 13147: my %checksums;
13148: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 13149: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 13150: my ($release,$timestamp) = split(/\-/,$loncaparev);
13151: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 13152: \%checksums);
1.1210 raeburn 13153: return \%checksums;
13154: }
13155:
1.327 albertel 13156: # ------------------------------------------------------------ Read domain file
13157: {
1.852 albertel 13158: my $loaded;
1.846 albertel 13159: my %domain;
13160:
1.852 albertel 13161: sub parse_domain_tab {
13162: my ($lines) = @_;
13163: foreach my $line (@$lines) {
13164: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 13165:
1.846 albertel 13166: chomp($line);
1.852 albertel 13167: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 13168: my %this_domain;
13169: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13170: 'lang_def', 'city', 'longi', 'lati',
13171: 'primary') {
13172: $this_domain{$field} = shift(@elements);
13173: }
13174: $domain{$name} = \%this_domain;
1.852 albertel 13175: }
13176: }
1.864 albertel 13177:
13178: sub reset_domain_info {
13179: undef($loaded);
13180: undef(%domain);
13181: }
13182:
1.852 albertel 13183: sub load_domain_tab {
1.1293 raeburn 13184: my ($ignore_cache,$nocache) = @_;
13185: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 13186: my $fh;
13187: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
13188: my @lines = <$fh>;
13189: &parse_domain_tab(\@lines);
1.448 albertel 13190: }
1.852 albertel 13191: close($fh);
13192: $loaded = 1;
1.327 albertel 13193: }
1.846 albertel 13194:
13195: sub domain {
1.852 albertel 13196: &load_domain_tab() if (!$loaded);
13197:
1.846 albertel 13198: my ($name,$what) = @_;
13199: return if ( !exists($domain{$name}) );
13200:
13201: if (!$what) {
13202: return $domain{$name}{'description'};
13203: }
13204: return $domain{$name}{$what};
13205: }
1.974 raeburn 13206:
13207: sub domain_info {
13208: &load_domain_tab() if (!$loaded);
13209: return %domain;
13210: }
13211:
1.327 albertel 13212: }
13213:
13214:
1.1 albertel 13215: # ------------------------------------------------------------- Read hosts file
13216: {
1.838 albertel 13217: my %hostname;
1.844 albertel 13218: my %hostdom;
1.845 albertel 13219: my %libserv;
1.852 albertel 13220: my $loaded;
1.888 albertel 13221: my %name_to_host;
1.1074 raeburn 13222: my %internetdom;
1.1107 raeburn 13223: my %LC_dns_serv;
1.852 albertel 13224:
13225: sub parse_hosts_tab {
13226: my ($file) = @_;
13227: foreach my $configline (@$file) {
13228: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 13229: chomp($configline);
13230: if ($configline =~ /^\^/) {
13231: if ($configline =~ /^\^([\w.\-]+)/) {
13232: $LC_dns_serv{$1} = 1;
13233: }
13234: next;
13235: }
1.1074 raeburn 13236: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 13237: $name=~s/\s//g;
13238: if ($id && $domain && $role && $name) {
13239: $hostname{$id}=$name;
1.888 albertel 13240: push(@{$name_to_host{$name}}, $id);
1.852 albertel 13241: $hostdom{$id}=$domain;
13242: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 13243: if (defined($protocol)) {
13244: if ($protocol eq 'https') {
13245: $protocol{$id} = $protocol;
13246: } else {
13247: $protocol{$id} = 'http';
13248: }
1.968 raeburn 13249: } else {
1.969 raeburn 13250: $protocol{$id} = 'http';
1.968 raeburn 13251: }
1.1074 raeburn 13252: if (defined($intdom)) {
13253: $internetdom{$id} = $intdom;
13254: }
1.852 albertel 13255: }
13256: }
13257: }
1.864 albertel 13258:
13259: sub reset_hosts_info {
1.897 albertel 13260: &purge_remembered();
1.864 albertel 13261: &reset_domain_info();
13262: &reset_hosts_ip_info();
1.892 albertel 13263: undef(%name_to_host);
1.864 albertel 13264: undef(%hostname);
13265: undef(%hostdom);
13266: undef(%libserv);
13267: undef($loaded);
13268: }
1.1 albertel 13269:
1.852 albertel 13270: sub load_hosts_tab {
1.1293 raeburn 13271: my ($ignore_cache,$nocache) = @_;
13272: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 13273: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13274: my @config = <$config>;
13275: &parse_hosts_tab(\@config);
13276: close($config);
13277: $loaded=1;
1.1 albertel 13278: }
1.852 albertel 13279:
1.838 albertel 13280: sub hostname {
1.852 albertel 13281: &load_hosts_tab() if (!$loaded);
13282:
1.838 albertel 13283: my ($lonid) = @_;
13284: return $hostname{$lonid};
13285: }
1.845 albertel 13286:
1.838 albertel 13287: sub all_hostnames {
1.852 albertel 13288: &load_hosts_tab() if (!$loaded);
13289:
1.838 albertel 13290: return %hostname;
13291: }
1.845 albertel 13292:
1.888 albertel 13293: sub all_names {
1.1293 raeburn 13294: my ($ignore_cache,$nocache) = @_;
13295: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13296:
13297: return %name_to_host;
13298: }
13299:
1.974 raeburn 13300: sub all_host_domain {
13301: &load_hosts_tab() if (!$loaded);
13302: return %hostdom;
13303: }
13304:
1.845 albertel 13305: sub is_library {
1.852 albertel 13306: &load_hosts_tab() if (!$loaded);
13307:
1.845 albertel 13308: return exists($libserv{$_[0]});
13309: }
13310:
13311: sub all_library {
1.852 albertel 13312: &load_hosts_tab() if (!$loaded);
13313:
1.845 albertel 13314: return %libserv;
13315: }
13316:
1.1062 droeschl 13317: sub unique_library {
13318: #2x reverse removes all hostnames that appear more than once
13319: my %unique = reverse &all_library();
13320: return reverse %unique;
13321: }
13322:
1.841 albertel 13323: sub get_servers {
1.852 albertel 13324: &load_hosts_tab() if (!$loaded);
13325:
1.841 albertel 13326: my ($domain,$type) = @_;
13327: my %possible_hosts = ($type eq 'library') ? %libserv
13328: : %hostname;
13329: my %result;
1.842 albertel 13330: if (ref($domain) eq 'ARRAY') {
13331: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13332: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13333: $result{$host} = $hostname;
13334: }
13335: }
13336: } else {
13337: while ( my ($host,$hostname) = each(%possible_hosts)) {
13338: if ($hostdom{$host} eq $domain) {
13339: $result{$host} = $hostname;
13340: }
1.841 albertel 13341: }
13342: }
13343: return %result;
13344: }
1.845 albertel 13345:
1.1062 droeschl 13346: sub get_unique_servers {
13347: my %unique = reverse &get_servers(@_);
13348: return reverse %unique;
13349: }
13350:
1.844 albertel 13351: sub host_domain {
1.852 albertel 13352: &load_hosts_tab() if (!$loaded);
13353:
1.844 albertel 13354: my ($lonid) = @_;
13355: return $hostdom{$lonid};
13356: }
13357:
1.841 albertel 13358: sub all_domains {
1.852 albertel 13359: &load_hosts_tab() if (!$loaded);
13360:
1.841 albertel 13361: my %seen;
13362: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13363: return @uniq;
13364: }
1.1074 raeburn 13365:
13366: sub internet_dom {
13367: &load_hosts_tab() if (!$loaded);
13368:
13369: my ($lonid) = @_;
13370: return $internetdom{$lonid};
13371: }
1.1107 raeburn 13372:
13373: sub is_LC_dns {
13374: &load_hosts_tab() if (!$loaded);
13375:
13376: my ($hostname) = @_;
13377: return exists($LC_dns_serv{$hostname});
13378: }
13379:
1.1 albertel 13380: }
13381:
1.847 albertel 13382: {
13383: my %iphost;
1.856 albertel 13384: my %name_to_ip;
13385: my %lonid_to_ip;
1.869 albertel 13386:
1.847 albertel 13387: sub get_hosts_from_ip {
13388: my ($ip) = @_;
13389: my %iphosts = &get_iphost();
13390: if (ref($iphosts{$ip})) {
13391: return @{$iphosts{$ip}};
13392: }
13393: return;
1.839 albertel 13394: }
1.864 albertel 13395:
13396: sub reset_hosts_ip_info {
13397: undef(%iphost);
13398: undef(%name_to_ip);
13399: undef(%lonid_to_ip);
13400: }
1.856 albertel 13401:
13402: sub get_host_ip {
13403: my ($lonid) = @_;
13404: if (exists($lonid_to_ip{$lonid})) {
13405: return $lonid_to_ip{$lonid};
13406: }
13407: my $name=&hostname($lonid);
13408: my $ip = gethostbyname($name);
13409: return if (!$ip || length($ip) ne 4);
13410: $ip=inet_ntoa($ip);
13411: $name_to_ip{$name} = $ip;
13412: $lonid_to_ip{$lonid} = $ip;
13413: return $ip;
13414: }
1.847 albertel 13415:
13416: sub get_iphost {
1.1293 raeburn 13417: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13418:
1.869 albertel 13419: if (!$ignore_cache) {
13420: if (%iphost) {
13421: return %iphost;
13422: }
13423: my ($ip_info,$cached)=
13424: &Apache::lonnet::is_cached_new('iphost','iphost');
13425: if ($cached) {
13426: %iphost = %{$ip_info->[0]};
13427: %name_to_ip = %{$ip_info->[1]};
13428: %lonid_to_ip = %{$ip_info->[2]};
13429: return %iphost;
13430: }
13431: }
1.894 albertel 13432:
13433: # get yesterday's info for fallback
13434: my %old_name_to_ip;
13435: my ($ip_info,$cached)=
13436: &Apache::lonnet::is_cached_new('iphost','iphost');
13437: if ($cached) {
13438: %old_name_to_ip = %{$ip_info->[1]};
13439: }
13440:
1.1293 raeburn 13441: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13442: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13443: my $ip;
13444: if (!exists($name_to_ip{$name})) {
13445: $ip = gethostbyname($name);
13446: if (!$ip || length($ip) ne 4) {
1.894 albertel 13447: if (defined($old_name_to_ip{$name})) {
13448: $ip = $old_name_to_ip{$name};
13449: &logthis("Can't find $name defaulting to old $ip");
13450: } else {
13451: &logthis("Name $name no IP found");
13452: next;
13453: }
13454: } else {
13455: $ip=inet_ntoa($ip);
1.847 albertel 13456: }
13457: $name_to_ip{$name} = $ip;
13458: } else {
13459: $ip = $name_to_ip{$name};
1.653 albertel 13460: }
1.888 albertel 13461: foreach my $id (@{ $name_to_host{$name} }) {
13462: $lonid_to_ip{$id} = $ip;
13463: }
13464: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13465: }
1.1293 raeburn 13466: unless ($nocache) {
13467: &do_cache_new('iphost','iphost',
13468: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13469: 48*60*60);
13470: }
1.869 albertel 13471:
1.847 albertel 13472: return %iphost;
1.598 albertel 13473: }
13474:
1.992 raeburn 13475: #
13476: # Given a DNS returns the loncapa host name for that DNS
13477: #
13478: sub host_from_dns {
13479: my ($dns) = @_;
13480: my @hosts;
13481: my $ip;
13482:
1.993 raeburn 13483: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13484: $ip = $name_to_ip{$dns};
13485: }
13486: if (!$ip) {
13487: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13488: if (length($ip) == 4) {
13489: $ip = &IO::Socket::inet_ntoa($ip);
13490: }
13491: }
13492: if ($ip) {
13493: @hosts = get_hosts_from_ip($ip);
13494: return $hosts[0];
13495: }
13496: return undef;
1.986 foxr 13497: }
1.992 raeburn 13498:
1.1074 raeburn 13499: sub get_internet_names {
13500: my ($lonid) = @_;
13501: return if ($lonid eq '');
13502: my ($idnref,$cached)=
13503: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13504: if ($cached) {
13505: return $idnref;
13506: }
13507: my $ip = &get_host_ip($lonid);
13508: my @hosts = &get_hosts_from_ip($ip);
13509: my %iphost = &get_iphost();
13510: my (@idns,%seen);
13511: foreach my $id (@hosts) {
13512: my $dom = &host_domain($id);
13513: my $prim_id = &domain($dom,'primary');
13514: my $prim_ip = &get_host_ip($prim_id);
13515: next if ($seen{$prim_ip});
13516: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13517: foreach my $id (@{$iphost{$prim_ip}}) {
13518: my $intdom = &internet_dom($id);
13519: unless (grep(/^\Q$intdom\E$/,@idns)) {
13520: push(@idns,$intdom);
13521: }
13522: }
13523: }
13524: $seen{$prim_ip} = 1;
13525: }
1.1219 raeburn 13526: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13527: }
13528:
1.986 foxr 13529: }
13530:
1.1079 raeburn 13531: sub all_loncaparevs {
1.1249 raeburn 13532: 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 13533: }
13534:
1.1227 raeburn 13535: # ---------------------------------------------------------- Read loncaparev table
13536: {
13537: sub load_loncaparevs {
13538: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13539: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13540: while (my $configline=<$config>) {
13541: chomp($configline);
13542: my ($hostid,$loncaparev)=split(/:/,$configline);
13543: $loncaparevs{$hostid}=$loncaparev;
13544: }
13545: close($config);
13546: }
13547: }
13548: }
13549: }
13550:
13551: # ---------------------------------------------------------- Read serverhostID table
13552: {
13553: sub load_serverhomeIDs {
13554: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13555: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13556: while (my $configline=<$config>) {
13557: chomp($configline);
13558: my ($name,$id)=split(/:/,$configline);
13559: $serverhomeIDs{$name}=$id;
13560: }
13561: close($config);
13562: }
13563: }
13564: }
13565: }
13566:
13567:
1.862 albertel 13568: BEGIN {
13569:
13570: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13571: unless ($readit) {
13572: {
13573: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13574: %perlvar = (%perlvar,%{$configvars});
13575: }
13576:
13577:
1.1 albertel 13578: # ------------------------------------------------------ Read spare server file
13579: {
1.448 albertel 13580: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13581:
13582: while (my $configline=<$config>) {
13583: chomp($configline);
1.284 matthew 13584: if ($configline) {
1.784 albertel 13585: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13586: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13587: push(@{ $spareid{$type} }, $host);
1.1 albertel 13588: }
13589: }
1.448 albertel 13590: close($config);
1.1 albertel 13591: }
1.11 www 13592: # ------------------------------------------------------------ Read permissions
13593: {
1.448 albertel 13594: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13595:
13596: while (my $configline=<$config>) {
1.448 albertel 13597: chomp($configline);
13598: if ($configline) {
13599: my ($role,$perm)=split(/ /,$configline);
13600: if ($perm ne '') { $pr{$role}=$perm; }
13601: }
1.11 www 13602: }
1.448 albertel 13603: close($config);
1.11 www 13604: }
13605:
13606: # -------------------------------------------- Read plain texts for permissions
13607: {
1.448 albertel 13608: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13609:
13610: while (my $configline=<$config>) {
1.448 albertel 13611: chomp($configline);
13612: if ($configline) {
1.742 raeburn 13613: my ($short,@plain)=split(/:/,$configline);
13614: %{$prp{$short}} = ();
13615: if (@plain > 0) {
13616: $prp{$short}{'std'} = $plain[0];
13617: for (my $i=1; $i<@plain; $i++) {
13618: $prp{$short}{'alt'.$i} = $plain[$i];
13619: }
13620: }
1.448 albertel 13621: }
1.135 www 13622: }
1.448 albertel 13623: close($config);
1.135 www 13624: }
13625:
13626: # ---------------------------------------------------------- Read package table
13627: {
1.448 albertel 13628: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13629:
13630: while (my $configline=<$config>) {
1.483 albertel 13631: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13632: chomp($configline);
13633: my ($short,$plain)=split(/:/,$configline);
13634: my ($pack,$name)=split(/\&/,$short);
13635: if ($plain ne '') {
13636: $packagetab{$pack.'&'.$name.'&name'}=$name;
13637: $packagetab{$short}=$plain;
13638: }
1.11 www 13639: }
1.448 albertel 13640: close($config);
1.329 matthew 13641: }
13642:
1.1073 raeburn 13643: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 13644:
13645: &load_loncaparevs();
1.1073 raeburn 13646:
1.1074 raeburn 13647: # ---------------------------------------------------------- Read serverhostID table
13648:
1.1227 raeburn 13649: &load_serverhomeIDs();
13650:
13651: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13652: {
13653: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13654: if (-e $file) {
13655: my $parser = HTML::LCParser->new($file);
13656: while (my $token = $parser->get_token()) {
13657: if ($token->[0] eq 'S') {
13658: my $item = $token->[1];
13659: my $name = $token->[2]{'name'};
13660: my $value = $token->[2]{'value'};
1.1285 raeburn 13661: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 13662: my $namematch = $token->[2]{'namematch'};
13663: if ($item eq 'parameter') {
13664: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13665: my $release = $parser->get_text();
13666: $release =~ s/(^\s*|\s*$ )//gx;
13667: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13668: }
13669: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 13670: my $release = $parser->get_text();
13671: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 13672: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 13673: }
13674: }
13675: }
13676: }
1.1073 raeburn 13677: }
13678:
1.1138 raeburn 13679: # ---------------------------------------------------------- Read managers table
13680: {
13681: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13682: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13683: while (my $configline=<$config>) {
13684: chomp($configline);
13685: next if ($configline =~ /^\#/);
13686: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13687: $managerstab{$configline} = 1;
13688: }
13689: }
13690: close($config);
13691: }
13692: }
13693: }
13694:
1.329 matthew 13695: # ------------- set up temporary directory
13696: {
1.1117 foxr 13697: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13698:
1.11 www 13699: }
13700:
1.794 albertel 13701: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13702: 'compress_threshold'=> 20_000,
13703: });
1.185 www 13704:
1.281 www 13705: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13706: $dumpcount=0;
1.958 www 13707: $locknum=0;
1.22 www 13708:
1.163 harris41 13709: &logtouch();
1.672 albertel 13710: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13711: $readit=1;
1.564 albertel 13712: {
13713: use integer;
13714: my $test=(2**32)+1;
1.568 albertel 13715: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13716: &logthis(" Detected 64bit platform ($_64bit)");
13717: }
1.195 www 13718: }
1.1 albertel 13719: }
1.179 www 13720:
1.1 albertel 13721: 1;
1.191 harris41 13722: __END__
13723:
1.243 albertel 13724: =pod
13725:
1.191 harris41 13726: =head1 NAME
13727:
1.243 albertel 13728: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13729:
13730: =head1 SYNOPSIS
13731:
1.243 albertel 13732: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13733:
13734: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13735:
1.243 albertel 13736: Common parameters:
13737:
13738: =over 4
13739:
13740: =item *
13741:
13742: $uname : an internal username (if $cname expecting a course Id specifically)
13743:
13744: =item *
13745:
13746: $udom : a domain (if $cdom expecting a course's domain specifically)
13747:
13748: =item *
13749:
13750: $symb : a resource instance identifier
13751:
13752: =item *
13753:
13754: $namespace : the name of a .db file that contains the data needed or
13755: being set.
13756:
13757: =back
13758:
1.394 bowersj2 13759: =head1 OVERVIEW
1.191 harris41 13760:
1.394 bowersj2 13761: lonnet provides subroutines which interact with the
13762: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13763: about classes, users, and resources.
1.243 albertel 13764:
13765: For many of these objects you can also use this to store data about
13766: them or modify them in various ways.
1.191 harris41 13767:
1.394 bowersj2 13768: =head2 Symbs
1.191 harris41 13769:
1.394 bowersj2 13770: To identify a specific instance of a resource, LON-CAPA uses symbols
13771: or "symbs"X<symb>. These identifiers are built from the URL of the
13772: map, the resource number of the resource in the map, and the URL of
13773: the resource itself. The latter is somewhat redundant, but might help
13774: if maps change.
13775:
13776: An example is
13777:
13778: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13779:
13780: The respective map entry is
13781:
13782: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13783: title="Problem 2">
13784: </resource>
13785:
13786: Symbs are used by the random number generator, as well as to store and
13787: restore data specific to a certain instance of for example a problem.
13788:
13789: =head2 Storing And Retrieving Data
13790:
13791: X<store()>X<cstore()>X<restore()>Three of the most important functions
13792: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13793: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13794: is is the non-critical message twin of cstore. These functions are for
13795: handlers to store a perl hash to a user's permanent data space in an
13796: easy manner, and to retrieve it again on another call. It is expected
13797: that a handler would use this once at the beginning to retrieve data,
13798: and then again once at the end to send only the new data back.
13799:
13800: The data is stored in the user's data directory on the user's
13801: homeserver under the ID of the course.
13802:
13803: The hash that is returned by restore will have all of the previous
13804: value for all of the elements of the hash.
13805:
13806: Example:
13807:
13808: #creating a hash
13809: my %hash;
13810: $hash{'foo'}='bar';
13811:
13812: #storing it
13813: &Apache::lonnet::cstore(\%hash);
13814:
13815: #changing a value
13816: $hash{'foo'}='notbar';
13817:
13818: #adding a new value
13819: $hash{'bar'}='foo';
13820: &Apache::lonnet::cstore(\%hash);
13821:
13822: #retrieving the hash
13823: my %history=&Apache::lonnet::restore();
13824:
13825: #print the hash
13826: foreach my $key (sort(keys(%history))) {
13827: print("\%history{$key} = $history{$key}");
13828: }
13829:
13830: Will print out:
1.191 harris41 13831:
1.394 bowersj2 13832: %history{1:foo} = bar
13833: %history{1:keys} = foo:timestamp
13834: %history{1:timestamp} = 990455579
13835: %history{2:bar} = foo
13836: %history{2:foo} = notbar
13837: %history{2:keys} = foo:bar:timestamp
13838: %history{2:timestamp} = 990455580
13839: %history{bar} = foo
13840: %history{foo} = notbar
13841: %history{timestamp} = 990455580
13842: %history{version} = 2
13843:
13844: Note that the special hash entries C<keys>, C<version> and
13845: C<timestamp> were added to the hash. C<version> will be equal to the
13846: total number of versions of the data that have been stored. The
13847: C<timestamp> attribute will be the UNIX time the hash was
13848: stored. C<keys> is available in every historical section to list which
13849: keys were added or changed at a specific historical revision of a
13850: hash.
13851:
13852: B<Warning>: do not store the hash that restore returns directly. This
13853: will cause a mess since it will restore the historical keys as if the
13854: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13855:
1.394 bowersj2 13856: Calling convention:
1.191 harris41 13857:
1.1225 raeburn 13858: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 13859: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13860:
1.394 bowersj2 13861: For more detailed information, see lonnet specific documentation.
1.191 harris41 13862:
1.394 bowersj2 13863: =head1 RETURN MESSAGES
1.191 harris41 13864:
1.394 bowersj2 13865: =over 4
1.191 harris41 13866:
1.394 bowersj2 13867: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13868:
1.394 bowersj2 13869: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13870: when the connection is brought back up
1.191 harris41 13871:
1.394 bowersj2 13872: =item * B<con_failed>: unable to contact remote host and unable to save message
13873: for later delivery
1.191 harris41 13874:
1.967 bisitz 13875: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13876:
1.394 bowersj2 13877: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13878: that was requested
1.191 harris41 13879:
1.243 albertel 13880: =back
1.191 harris41 13881:
1.243 albertel 13882: =head1 PUBLIC SUBROUTINES
1.191 harris41 13883:
1.243 albertel 13884: =head2 Session Environment Functions
1.191 harris41 13885:
1.243 albertel 13886: =over 4
1.191 harris41 13887:
1.394 bowersj2 13888: =item *
13889: X<appenv()>
1.949 raeburn 13890: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13891: the user envirnoment file, and will be restored for each access this
1.620 albertel 13892: user makes during this session, also modifies the %env for the current
1.949 raeburn 13893: process. Optional rolesarrayref - if defined contains a reference to an array
13894: of roles which are exempt from the restriction on modifying user.role entries
13895: in the user's environment.db and in %env.
1.191 harris41 13896:
13897: =item *
1.394 bowersj2 13898: X<delenv()>
1.987 raeburn 13899: B<delenv($delthis,$regexp)>: removes all items from the session
13900: environment file that begin with $delthis. If the
13901: optional second arg - $regexp - is true, $delthis is treated as a
13902: regular expression, otherwise \Q$delthis\E is used.
13903: The values are also deleted from the current processes %env.
1.191 harris41 13904:
1.795 albertel 13905: =item * get_env_multiple($name)
13906:
13907: gets $name from the %env hash, it seemlessly handles the cases where multiple
13908: values may be defined and end up as an array ref.
13909:
13910: returns an array of values
13911:
1.243 albertel 13912: =back
13913:
13914: =head2 User Information
1.191 harris41 13915:
1.243 albertel 13916: =over 4
1.191 harris41 13917:
13918: =item *
1.394 bowersj2 13919: X<queryauthenticate()>
13920: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13921: authentication scheme
13922:
13923: =item *
1.394 bowersj2 13924: X<authenticate()>
1.1073 raeburn 13925: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13926: authenticate user from domain's lib servers (first use the current
13927: one). C<$upass> should be the users password.
1.1073 raeburn 13928: $checkdefauth is optional (value is 1 if a check should be made to
13929: authenticate user using default authentication method, and allow
13930: account creation if username does not have account in the domain).
13931: $clientcancheckhost is optional (value is 1 if checking whether the
13932: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13933:
13934: =item *
1.394 bowersj2 13935: X<homeserver()>
13936: B<homeserver($uname,$udom)>: find the server which has
13937: the user's directory and files (there must be only one), this caches
13938: the answer, and also caches if there is a borken connection.
1.191 harris41 13939:
13940: =item *
1.394 bowersj2 13941: X<idget()>
1.1300 raeburn 13942: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
13943: a list of student/employee IDs or clicker IDs
13944: (student/employee IDs are a unique resource in a domain, there must be
13945: only 1 ID per username, and only 1 username per ID in a specific domain).
13946: clickerIDs are not necessarily unique, as students might share clickers.
13947: (returns hash: id=>name,id=>name)
1.191 harris41 13948:
13949: =item *
1.394 bowersj2 13950: X<idrget()>
13951: B<idrget($udom,@unames)>: find the IDs behind a list of
13952: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13953:
13954: =item *
1.394 bowersj2 13955: X<idput()>
1.1300 raeburn 13956: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
13957: names and associated student/employee IDs or clicker IDs.
13958:
13959: =item *
13960: X<iddel()>
13961: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
13962: student/employee ID or clicker ID username look-ups from domain.
13963: The homeserver ($uhome) and namespace ($namespace) are optional.
13964: If no $uhome is provided, it will be determined usig &homeserver()
13965: for each user. If no $namespace is provided, the default is ids.
13966:
13967: =item *
13968: X<updateclickers()>
13969: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
13970: clicker ID-to-username look-ups in clickers.db on library server.
13971: Permitted actions are add or del (i.e., add or delete). The
13972: clickers.db contains clickerID as keys (escaped), and each corresponding
13973: value is an escaped comma-separated list of usernames (for whom the
13974: library server is the homeserver), who registered that particular ID.
13975: If $critical is true, the update will be sent via &critical, otherwise
13976: &reply() will be used.
1.191 harris41 13977:
13978: =item *
1.394 bowersj2 13979: X<rolesinit()>
1.1169 droeschl 13980: B<rolesinit($udom,$username)>: get user privileges.
13981: returns user role, first access and timer interval hashes
1.243 albertel 13982:
13983: =item *
1.1171 droeschl 13984: X<privileged()>
13985: B<privileged($username,$domain)>: returns a true if user has a
13986: privileged and active role (i.e. su or dc), false otherwise.
13987:
13988: =item *
1.551 albertel 13989: X<getsection()>
13990: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13991: course $cname, return section name/number or '' for "not in course"
13992: and '-1' for "no section"
13993:
13994: =item *
1.394 bowersj2 13995: X<userenvironment()>
13996: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13997: passed in @what from the requested user's environment, returns a hash
13998:
1.858 raeburn 13999: =item *
14000: X<userlog_query()>
1.859 albertel 14001: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14002: activity.log file. %filters defines filters applied when parsing the
14003: log file. These can be start or end timestamps, or the type of action
14004: - log to look for Login or Logout events, check for Checkin or
14005: Checkout, role for role selection. The response is in the form
14006: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14007: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14008:
1.243 albertel 14009: =back
14010:
14011: =head2 User Roles
14012:
14013: =over 4
14014:
14015: =item *
14016:
1.1284 raeburn 14017: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14018: returns codes for allowed actions.
14019:
14020: The first argument is required, all others are optional.
14021:
14022: $priv is the privilege being checked.
14023: $uri contains additional information about what is being checked for access (e.g.,
14024: URL, course ID etc.).
14025: $symb is the unique resource instance identifier in a course; if needed,
14026: but not provided, it will be retrieved via a call to &symbread().
14027: $role is the role for which a priv is being checked (only used if priv is evb).
14028: $clientip is the user's IP address (only used when checking for access to portfolio
14029: files).
14030: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14031: prevents recursive calls to &allowed.
14032:
1.243 albertel 14033: F: full access
14034: U,I,K: authentication modes (cxx only)
14035: '': forbidden
14036: 1: user needs to choose course
14037: 2: browse allowed
1.766 albertel 14038: A: passphrase authentication needed
1.1284 raeburn 14039: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14040:
14041: =item *
14042:
1.1192 raeburn 14043: constructaccess($url,$setpriv) : check for access to construction space URL
14044:
14045: See if the owner domain and name in the URL match those in the
14046: expected environment. If so, return three element list
14047: ($ownername,$ownerdomain,$ownerhome).
14048:
14049: Otherwise return the null string.
14050:
14051: If second argument 'setpriv' is true, it assigns the privileges,
14052: and returns the same three element list, unless the owner has
14053: blocked "ad hoc" Domain Coordinator access to the Author Space,
14054: in which case the null string is returned.
14055:
14056: =item *
14057:
1.1326 raeburn 14058: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14059: define a custom role rolename set privileges in format of lonTabs/roles.tab
14060: for system, domain, and course level. $uname and $udom are optional (current
14061: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14062:
14063: =item *
14064:
1.988 raeburn 14065: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14066: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 14067: $type is Course (default) or Community.
1.988 raeburn 14068: If $forcedefault evaluates to true, text returned will be default
14069: text for $type. Otherwise, if this is a course, the text returned
14070: will be a custom name for the role (if defined in the course's
14071: environment). If no custom name is defined the default is returned.
14072:
1.832 raeburn 14073: =item *
14074:
1.1219 raeburn 14075: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 14076: All arguments are optional. Returns a hash of a roles, either for
14077: co-author/assistant author roles for a user's Construction Space
1.906 albertel 14078: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 14079: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14080: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14081: For each key, value is set to colon-separated start and end times for
14082: the role. If no username and domain are specified, will default to
1.934 raeburn 14083: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 14084: of role statuses (active, future or previous), roles
14085: (e.g., cc,in, st etc.) and domains of the roles which can be used
14086: to restrict the list of roles reported. If no array ref is
14087: provided for types, will default to return only active roles.
1.834 albertel 14088:
1.1195 raeburn 14089: =item *
14090:
14091: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 14092: user: $uname:$udom has a role in the course: $cdom_$cnum.
14093:
14094: Additional optional arguments are: $type (if role checking is to be restricted
14095: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 14096: available roles) or future (roles available in the future), and
14097: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 14098: have active Domain Coordinator role in course's domain or in additional
14099: domains (specified in 'Domains to check for privileged users' in course
14100: environment -- set via: Course Settings -> Classlists and staff listing).
14101:
14102: =item *
14103:
14104: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14105: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14106: $possdomains and $possroles are optional array refs -- to domains to check and
14107: roles to check. If $possdomains is not specified, a dump will be done of the
14108: users' roles.db to check for a dc or su role in any domain. This can be
14109: time consuming if &privileged is called repeatedly (e.g., when displaying a
14110: classlist), so in such cases, supplying a $possdomains array is preferred, as
14111: this then allows &privileged_by_domain() to be used, which caches the identity
14112: of privileged users, eliminating the need for repeated calls to &dump().
14113:
14114: =item *
14115:
14116: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14117: where the outer hash keys are domains specified in the $possdomains array ref,
14118: next inner hash keys are privileged roles specified in the $roles array ref,
14119: and the innermost hash contains key = value pairs for username:domain = end:start
14120: for active or future "privileged" users with that role in that domain. To avoid
14121: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14122: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 14123:
1.243 albertel 14124: =back
14125:
14126: =head2 User Modification
14127:
14128: =over 4
14129:
14130: =item *
14131:
1.957 raeburn 14132: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 14133: user for the level given by URL. Optional start and end dates (leave empty
14134: string or zero for "no date")
1.191 harris41 14135:
14136: =item *
14137:
1.243 albertel 14138: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14139: change a users, password, possible return values are: ok,
14140: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14141: refused
1.191 harris41 14142:
14143: =item *
14144:
1.243 albertel 14145: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 14146:
14147: =item *
14148:
1.1058 raeburn 14149: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14150: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14151:
14152: will update user information (firstname,middlename,lastname,generation,
14153: permanentemail), and if forceid is true, student/employee ID also.
14154: A user's institutional affiliation(s) can also be updated.
14155: User information fields will not be overwritten with empty entries
14156: unless the field is included in the $candelete array reference.
14157: This array is included when a single user is modified via "Manage Users",
14158: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 14159:
14160: =item *
14161:
1.286 matthew 14162: modifystudent
14163:
1.957 raeburn 14164: modify a student's enrollment and identification information.
1.1235 raeburn 14165: The course id is resolved based on the current user's environment.
14166: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 14167: associated with a course.
14168:
1.297 matthew 14169: This call is essentially a wrapper for lonnet::modifyuser and
14170: lonnet::modify_student_enrollment
1.286 matthew 14171:
14172: Inputs:
14173:
14174: =over 4
14175:
1.957 raeburn 14176: =item B<$udom> Student's loncapa domain
1.286 matthew 14177:
1.957 raeburn 14178: =item B<$uname> Student's loncapa login name
1.286 matthew 14179:
1.964 bisitz 14180: =item B<$uid> Student/Employee ID
1.286 matthew 14181:
1.957 raeburn 14182: =item B<$umode> Student's authentication mode
1.286 matthew 14183:
1.957 raeburn 14184: =item B<$upass> Student's password
1.286 matthew 14185:
1.957 raeburn 14186: =item B<$first> Student's first name
1.286 matthew 14187:
1.957 raeburn 14188: =item B<$middle> Student's middle name
1.286 matthew 14189:
1.957 raeburn 14190: =item B<$last> Student's last name
1.286 matthew 14191:
1.957 raeburn 14192: =item B<$gene> Student's generation
1.286 matthew 14193:
1.957 raeburn 14194: =item B<$usec> Student's section in course
1.286 matthew 14195:
14196: =item B<$end> Unix time of the roles expiration
14197:
14198: =item B<$start> Unix time of the roles start date
14199:
14200: =item B<$forceid> If defined, allow $uid to be changed
14201:
14202: =item B<$desiredhome> server to use as home server for student
14203:
1.957 raeburn 14204: =item B<$email> Student's permanent e-mail address
14205:
14206: =item B<$type> Type of enrollment (auto or manual)
14207:
1.963 raeburn 14208: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14209:
14210: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 14211:
1.963 raeburn 14212: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 14213:
1.963 raeburn 14214: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 14215:
1.1216 raeburn 14216: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14217:
14218: =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 14219:
1.286 matthew 14220: =back
1.297 matthew 14221:
14222: =item *
14223:
14224: modify_student_enrollment
14225:
1.1235 raeburn 14226: Change a student's enrollment status in a class. The environment variable
1.297 matthew 14227: 'role.request.course' must be defined for this function to proceed.
14228:
14229: Inputs:
14230:
14231: =over 4
14232:
1.1235 raeburn 14233: =item $udom, student's domain
1.297 matthew 14234:
1.1235 raeburn 14235: =item $uname, student's name
1.297 matthew 14236:
1.1235 raeburn 14237: =item $uid, student's user id
1.297 matthew 14238:
1.1235 raeburn 14239: =item $first, student's first name
1.297 matthew 14240:
14241: =item $middle
14242:
14243: =item $last
14244:
14245: =item $gene
14246:
14247: =item $usec
14248:
14249: =item $end
14250:
14251: =item $start
14252:
1.957 raeburn 14253: =item $type
14254:
14255: =item $locktype
14256:
14257: =item $cid
14258:
14259: =item $selfenroll
14260:
14261: =item $context
14262:
1.1216 raeburn 14263: =item $credits, number of credits student will earn from this class
14264:
1.1314 raeburn 14265: =item $instsec, institutional course section code for student
14266:
1.297 matthew 14267: =back
14268:
1.191 harris41 14269:
14270: =item *
14271:
1.243 albertel 14272: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14273: custom role; give a custom role to a user for the level given by URL. Specify
14274: name and domain of role author, and role name
1.191 harris41 14275:
14276: =item *
14277:
1.243 albertel 14278: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 14279:
14280: =item *
14281:
1.243 albertel 14282: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14283:
14284: =back
14285:
14286: =head2 Course Infomation
14287:
14288: =over 4
1.191 harris41 14289:
14290: =item *
14291:
1.1118 foxr 14292: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 14293: specified course id, including all environment settings for the
14294: course, the description of the course will be in the hash under the
14295: key 'description'
1.191 harris41 14296:
1.1118 foxr 14297: $options is an optional parameter that if supplied is a hash reference that controls
14298: what how this function works. It has the following key/values:
14299:
14300: =over 4
14301:
14302: =item freshen_cache
14303:
14304: If defined, and the environment cache for the course is valid, it is
14305: returned in the returned hash.
14306:
14307: =item one_time
14308:
14309: If defined, the last cache time is set to _now_
14310:
14311: =item user
14312:
14313: If defined, the supplied username is used instead of the current user.
14314:
14315:
14316: =back
14317:
1.191 harris41 14318: =item *
14319:
1.624 albertel 14320: resdata($name,$domain,$type,@which) : request for current parameter
14321: setting for a specific $type, where $type is either 'course' or 'user',
14322: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 14323: answers for 10 minutes.
1.243 albertel 14324:
1.877 foxr 14325: =item *
14326:
14327: get_courseresdata($courseid, $domain) : dump the entire course resource
14328: data base, returning a hash that is keyed by the resource name and has
14329: values that are the resource value. I believe that the timestamps and
14330: versions are also returned.
14331:
1.1236 raeburn 14332: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14333: supplemental content area. This routine caches the number of files for
14334: 10 minutes.
14335:
1.243 albertel 14336: =back
14337:
14338: =head2 Course Modification
14339:
14340: =over 4
1.191 harris41 14341:
14342: =item *
14343:
1.243 albertel 14344: writecoursepref($courseid,%prefs) : write preferences (environment
14345: database) for a course
1.191 harris41 14346:
14347: =item *
14348:
1.1011 raeburn 14349: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14350:
14351: =item *
14352:
1.1038 raeburn 14353: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14354:
1.1167 droeschl 14355: =item *
14356:
14357: is_course($courseid), is_course($cdom, $cnum)
14358:
14359: Accepts either a combined $courseid (in the form of domain_courseid) or the
14360: two component version $cdom, $cnum. It checks if the specified course exists.
14361:
14362: Returns:
14363: undef if the course doesn't exist, otherwise
14364: in scalar context the combined courseid.
14365: in list context the two components of the course identifier, domain and
14366: courseid.
14367:
1.243 albertel 14368: =back
14369:
14370: =head2 Resource Subroutines
14371:
14372: =over 4
1.191 harris41 14373:
14374: =item *
14375:
1.243 albertel 14376: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14377:
14378: =item *
14379:
1.243 albertel 14380: repcopy($filename) : subscribes to the requested file, and attempts to
14381: replicate from the owning library server, Might return
1.607 raeburn 14382: 'unavailable', 'not_found', 'forbidden', 'ok', or
14383: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14384: resource. Expects the local filesystem pathname
14385: (/home/httpd/html/res/....)
14386:
14387: =back
14388:
14389: =head2 Resource Information
14390:
14391: =over 4
1.191 harris41 14392:
14393: =item *
14394:
1.1228 raeburn 14395: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14396: and returns the value of a variety of different possible values,
14397: $varname should be a request string, and the other parameters can be
14398: used to specify who and what one is asking about. Ordinarily, $cid
14399: does not need to be specified, as it is retrived from
14400: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14401: within lonuserstate::loadmap() when initializing a course, before
14402: $env{'request.course.id'} has been set, so it needs to be provided
14403: in that one case.
1.243 albertel 14404:
14405: Possible values for $varname are environment.lastname (or other item
14406: from the envirnment hash), user.name (or someother aspect about the
14407: user), resource.0.maxtries (or some other part and parameter of a
14408: resource)
1.204 albertel 14409:
14410: =item *
14411:
1.243 albertel 14412: directcondval($number) : get current value of a condition; reads from a state
14413: string
1.204 albertel 14414:
14415: =item *
14416:
1.243 albertel 14417: condval($condidx) : value of condition index based on state
1.204 albertel 14418:
14419: =item *
14420:
1.243 albertel 14421: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14422: resource's metadata, $what should be either a specific key, or either
14423: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14424: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14425:
14426: this function automatically caches all requests
1.191 harris41 14427:
14428: =item *
14429:
1.243 albertel 14430: metadata_query($query,$custom,$customshow) : make a metadata query against the
14431: network of library servers; returns file handle of where SQL and regex results
14432: will be stored for query
1.191 harris41 14433:
14434: =item *
14435:
1.1282 raeburn 14436: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14437: return symbolic list entry (all arguments optional).
14438:
14439: Args: filename is the filename (including path) for the file for which a symb
14440: is required; donotrecurse, if true will prevent calls to allowed() being made
14441: to check access status if more than one resource was found in the bighash
14442: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14443: a randompick); ignorecachednull, if true will prevent a symb of '' being
14444: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14445: cause possible symbs to be checked to determine if they are subject to content
14446: blocking, if so they will not be included as possible symbs; possibles is a
14447: ref to a hash, which, as a side effect, will be populated with all possible
14448: symbs (content blocking not tested).
14449:
1.243 albertel 14450: returns the data handle
1.191 harris41 14451:
14452: =item *
14453:
1.1190 raeburn 14454: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14455: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14456: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 14457: on failure, user must be in a course, as it assumes the existence of
14458: the course initial hash, and uses $env('request.course.id'}. The third
14459: arg is an optional reference to a scalar. If this arg is passed in the
14460: call to symbverify, it will be set to 1 if the symb has been set to be
14461: encrypted; otherwise it will be null.
1.191 harris41 14462:
14463: =item *
14464:
1.243 albertel 14465: symbclean($symb) : removes versions numbers from a symb, returns the
14466: cleaned symb
1.191 harris41 14467:
14468: =item *
14469:
1.243 albertel 14470: is_on_map($uri) : checks if the $uri is somewhere on the current
14471: course map, user must be in a course for it to work.
1.191 harris41 14472:
14473: =item *
14474:
1.243 albertel 14475: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14476:
14477: =item *
14478:
1.243 albertel 14479: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14480: a random seed, all arguments are optional, if they aren't sent it uses the
14481: environment to derive them. Note: if symb isn't sent and it can't get one
14482: from &symbread it will use the current time as its return value
1.191 harris41 14483:
14484: =item *
14485:
1.243 albertel 14486: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14487: unfakeable, receipt
1.191 harris41 14488:
14489: =item *
14490:
1.620 albertel 14491: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14492:
14493: =item *
14494:
1.243 albertel 14495: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14496:
14497: =item *
14498:
1.243 albertel 14499: 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 14500:
14501: =item *
14502:
1.243 albertel 14503: 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 14504:
14505: =item *
14506:
1.243 albertel 14507: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14508:
14509: =item *
14510:
1.243 albertel 14511: devalidate($symb) : devalidate temporary spreadsheet calculations,
14512: forcing spreadsheet to reevaluate the resource scores next time.
14513:
1.1195 raeburn 14514: =item *
14515:
1.1196 raeburn 14516: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14517: when viewing in course context.
1.1195 raeburn 14518:
1.1196 raeburn 14519: input: six args -- filename (decluttered), course number, course domain,
14520: url, symb (if registered) and group (if this is a
14521: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 14522:
1.1196 raeburn 14523: output: array of five scalars --
1.1195 raeburn 14524: $cfile -- url for file editing if editable on current server
14525: $home -- homeserver of resource (i.e., for author if published,
14526: or course if uploaded.).
14527: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 14528: $forceedit -- 1 if icon/link should be to go to edit mode
14529: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 14530:
14531: =item *
14532:
14533: is_course_upload($file,$cnum,$cdom)
14534:
14535: Used in course context to determine if current file was uploaded to
14536: the course (i.e., would be found in /userfiles/docs on the course's
14537: homeserver.
14538:
14539: input: 3 args -- filename (decluttered), course number and course domain.
14540: output: boolean -- 1 if file was uploaded.
14541:
1.243 albertel 14542: =back
14543:
14544: =head2 Storing/Retreiving Data
14545:
14546: =over 4
1.191 harris41 14547:
14548: =item *
14549:
1.1269 raeburn 14550: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14551: permanently for this url; hashref needs to be given and should be a \%hashname;
14552: the remaining args aren't required and if they aren't passed or are '' they will
14553: be derived from the env (with the exception of $laststore, which is an
14554: optional arg used when a user's submission is stored in grading).
14555: $laststore is $version=$timestamp, where $version is the most recent version
14556: number retrieved for the corresponding $symb in the $namespace db file, and
14557: $timestamp is the timestamp for that transaction (UNIX time).
14558: $laststore is currently only passed when cstore() is called by
14559: structuretags::finalize_storage().
1.191 harris41 14560:
14561: =item *
14562:
1.1269 raeburn 14563: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14564: but uses critical subroutine
1.191 harris41 14565:
14566: =item *
14567:
1.243 albertel 14568: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14569: all args are optional
1.191 harris41 14570:
14571: =item *
14572:
1.717 albertel 14573: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14574: dumps the complete (or key matching regexp) namespace into a hash
14575: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14576: normally &store()ed into
14577:
14578: $range should be either an integer '100' (give me the first 100
14579: matching records)
14580: or be two integers sperated by a - with no spaces
14581: '30-50' (give me the 30th through the 50th matching
14582: records)
14583:
14584:
14585: =item *
14586:
1.1269 raeburn 14587: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14588: replaces a &store() version of data with a replacement set of data
14589: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 14590: reference. If $tolog is true, the transaction is logged in the courselog
14591: with an action=PUTSTORE.
1.717 albertel 14592:
14593: =item *
14594:
1.243 albertel 14595: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14596: works very similar to store/cstore, but all data is stored in a
14597: temporary location and can be reset using tmpreset, $storehash should
14598: be a hash reference, returns nothing on success
1.191 harris41 14599:
14600: =item *
14601:
1.243 albertel 14602: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14603: similar to restore, but all data is stored in a temporary location and
14604: can be reset using tmpreset. Returns a hash of values on success,
14605: error string otherwise.
1.191 harris41 14606:
14607: =item *
14608:
1.243 albertel 14609: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14610: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14611:
14612: =item *
14613:
1.243 albertel 14614: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14615: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14616:
14617: =item *
14618:
1.243 albertel 14619: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14620: namesp ($udom and $uname are optional)
1.191 harris41 14621:
14622: =item *
14623:
1.702 albertel 14624: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14625: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14626: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14627:
1.702 albertel 14628: $range should be either an integer '100' (give me the first 100
14629: matching records)
14630: or be two integers sperated by a - with no spaces
14631: '30-50' (give me the 30th through the 50th matching
14632: records)
1.449 matthew 14633: =item *
14634:
14635: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14636: $store can be a scalar, an array reference, or if the amount to be
14637: incremented is > 1, a hash reference.
14638:
14639: ($udom and $uname are optional)
1.191 harris41 14640:
14641: =item *
14642:
1.243 albertel 14643: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14644: ($udom and $uname are optional)
1.191 harris41 14645:
14646: =item *
14647:
1.243 albertel 14648: cput($namespace,$storehash,$udom,$uname) : critical put
14649: ($udom and $uname are optional)
1.191 harris41 14650:
14651: =item *
14652:
1.748 albertel 14653: newput($namespace,$storehash,$udom,$uname) :
14654:
14655: Attempts to store the items in the $storehash, but only if they don't
14656: currently exist, if this succeeds you can be certain that you have
14657: successfully created a new key value pair in the $namespace db.
14658:
14659:
14660: Args:
14661: $namespace: name of database to store values to
14662: $storehash: hashref to store to the db
14663: $udom: (optional) domain of user containing the db
14664: $uname: (optional) name of user caontaining the db
14665:
14666: Returns:
14667: 'ok' -> succeeded in storing all keys of $storehash
14668: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14669: least <key> already existed in the db (other
14670: requested keys may also already exist)
1.967 bisitz 14671: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14672: 'con_lost' -> unable to contact request server
14673: 'refused' -> action was not allowed by remote machine
14674:
14675:
14676: =item *
14677:
1.243 albertel 14678: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14679: reference filled in from namesp (encrypts the return communication)
14680: ($udom and $uname are optional)
1.191 harris41 14681:
14682: =item *
14683:
1.243 albertel 14684: log($udom,$name,$home,$message) : write to permanent log for user; use
14685: critical subroutine
14686:
1.806 raeburn 14687: =item *
14688:
1.860 raeburn 14689: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14690: array reference filled in from namespace found in domain level on either
14691: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14692:
14693: =item *
14694:
1.860 raeburn 14695: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14696: domain level either on specified domain server ($uhome) or primary domain
14697: server ($udom and $uhome are optional)
1.806 raeburn 14698:
1.943 raeburn 14699: =item *
14700:
1.1240 raeburn 14701: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14702: for: authentication, language, quotas, timezone, date locale, and portal URL in
14703: the target domain.
14704:
14705: May also include additional key => value pairs for the following groups:
14706:
14707: =over
14708:
14709: =item
14710: disk quotas (MB allocated by default to portfolios and authoring spaces).
14711:
14712: =over
14713:
14714: =item defaultquota, authorquota
14715:
14716: =back
14717:
14718: =item
14719: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14720: portfolio for users).
14721:
14722: =over
14723:
14724: =item
14725: aboutme, blog, webdav, portfolio
14726:
14727: =back
14728:
14729: =item
14730: requestcourses: ability to request courses, and how requests are processed.
14731:
14732: =over
14733:
14734: =item
1.1305 raeburn 14735: official, unofficial, community, textbook, placement
1.1240 raeburn 14736:
14737: =back
14738:
14739: =item
14740: inststatus: types of institutional affiliation, and order in which they are displayed.
14741:
14742: =over
14743:
14744: =item
1.1256 raeburn 14745: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 14746:
14747: =back
14748:
14749: =item
14750: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14751: for course's uploaded content.
14752:
14753: =over
14754:
14755: =item
1.1246 raeburn 14756: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 14757: communityquota, textbookquota, placementquota
1.1240 raeburn 14758:
14759: =back
14760:
14761: =item
14762: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14763: on your servers.
14764:
14765: =over
14766:
14767: =item
14768: remotesessions, hostedsessions
14769:
14770: =back
14771:
14772: =back
14773:
14774: In cases where a domain coordinator has never used the "Set Domain Configuration"
14775: utility to create a configuration.db file on a domain's primary library server
14776: only the following domain defaults: auth_def, auth_arg_def, lang_def
14777: -- corresponding values are authentication type (internal, krb4, krb5,
14778: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14779: will be available. Values are retrieved from cache (if current), unless the
14780: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14781: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14782:
14783: Typical usage:
1.943 raeburn 14784:
1.1240 raeburn 14785: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14786:
1.243 albertel 14787: =back
14788:
14789: =head2 Network Status Functions
14790:
14791: =over 4
1.191 harris41 14792:
14793: =item *
14794:
1.1137 raeburn 14795: dirlist() : return directory list based on URI (first arg).
14796:
14797: Inputs: 1 required, 5 optional.
14798:
14799: =over
14800:
14801: =item
14802: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14803:
14804: =item
14805: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14806:
14807: =item
14808: $username - username of user/course to be listed. Extracted from $uri if absent.
14809:
14810: =item
14811: $getpropath - boolean: 1 if prepend path using &propath().
14812:
14813: =item
14814: $getuserdir - boolean: 1 if prepend path for "userfiles".
14815:
14816: =item
14817: $alternateRoot - path to prepend in place of path from $uri.
14818:
14819: =back
14820:
14821: Returns: Array of up to two items.
14822:
14823: =over
14824:
14825: a reference to an array of files/subdirectories
14826:
14827: =over
14828:
14829: Each element in the array of files/subdirectories is a & separated list of
14830: item name and the result of running stat on the item. If dirlist was requested
14831: for a file instead of a directory, the item name will be ''. For a directory
14832: listing, if the item is a metadata file, the element will end &N&M
14833: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14834: default copyright set (1).
14835:
14836: =back
14837:
14838: a scalar containing error condition (if encountered).
14839:
14840: =over
14841:
14842: =item
14843: no_host (no homeserver identified for $username:$domain).
14844:
14845: =item
14846: no_such_host (server contacted for listing not identified as valid host).
14847:
14848: =item
14849: con_lost (connection to remote server failed).
14850:
14851: =item
14852: refused (invalid $username:$domain received on lond side).
14853:
14854: =item
14855: no_such_dir (directory at specified path on lond side does not exist).
14856:
14857: =item
14858: empty (directory at specified path on lond side is empty).
14859:
14860: =over
14861:
14862: This is currently not encountered because the &ls3, &ls2,
14863: &ls (_handler) routines on the lond side do not filter out
14864: . and .. from a directory listing.
14865:
14866: =back
14867:
14868: =back
14869:
14870: =back
1.191 harris41 14871:
14872: =item *
14873:
1.243 albertel 14874: spareserver() : find server with least workload from spare.tab
14875:
1.986 foxr 14876:
14877: =item *
14878:
14879: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14880: if there is no corresponding loncapa host.
14881:
1.243 albertel 14882: =back
14883:
1.986 foxr 14884:
1.243 albertel 14885: =head2 Apache Request
14886:
14887: =over 4
1.191 harris41 14888:
14889: =item *
14890:
1.243 albertel 14891: ssi($url,%hash) : server side include, does a complete request cycle on url to
14892: localhost, posts hash
14893:
14894: =back
14895:
14896: =head2 Data to String to Data
14897:
14898: =over 4
1.191 harris41 14899:
14900: =item *
14901:
1.243 albertel 14902: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14903: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14904:
14905: =item *
14906:
1.243 albertel 14907: hashref2str($hashref) : convert a hashref into a string complete with
14908: escaping and '=' and '&' separators, supports elements that are
14909: arrayrefs and hashrefs
1.191 harris41 14910:
14911: =item *
14912:
1.243 albertel 14913: arrayref2str($arrayref) : convert an arrayref into a string complete
14914: with escaping and '&' separators, supports elements that are arrayrefs
14915: and hashrefs
1.191 harris41 14916:
14917: =item *
14918:
1.243 albertel 14919: str2hash($string) : convert string to hash using unescaping and
14920: splitting on '=' and '&', supports elements that are arrayrefs and
14921: hashrefs
1.191 harris41 14922:
14923: =item *
14924:
1.243 albertel 14925: str2array($string) : convert string to hash using unescaping and
14926: splitting on '&', supports elements that are arrayrefs and hashrefs
14927:
14928: =back
14929:
14930: =head2 Logging Routines
14931:
14932:
14933: These routines allow one to make log messages in the lonnet.log and
14934: lonnet.perm logfiles.
1.191 harris41 14935:
1.1119 foxr 14936: =over 4
14937:
1.191 harris41 14938: =item *
14939:
1.243 albertel 14940: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14941:
14942: =item *
14943:
1.243 albertel 14944: logthis() : append message to the normal lonnet.log file, it gets
14945: preiodically rolled over and deleted.
1.191 harris41 14946:
14947: =item *
14948:
1.243 albertel 14949: logperm() : append a permanent message to lonnet.perm.log, this log
14950: file never gets deleted by any automated portion of the system, only
14951: messages of critical importance should go in here.
14952:
1.1119 foxr 14953:
1.243 albertel 14954: =back
14955:
14956: =head2 General File Helper Routines
14957:
14958: =over 4
1.191 harris41 14959:
14960: =item *
14961:
1.481 raeburn 14962: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14963: (a) files in /uploaded
14964: (i) If a local copy of the file exists -
14965: compares modification date of local copy with last-modified date for
14966: definitive version stored on home server for course. If local copy is
14967: stale, requests a new version from the home server and stores it.
14968: If the original has been removed from the home server, then local copy
14969: is unlinked.
14970: (ii) If local copy does not exist -
14971: requests the file from the home server and stores it.
14972:
14973: If $caller is 'uploadrep':
14974: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14975: for request for files originally uploaded via DOCS.
14976: - returns 'ok' if fresh local copy now available, -1 otherwise.
14977:
14978: Otherwise:
14979: This indicates a call from the content generation phase of the request.
14980: - returns the entire contents of the file or -1.
14981:
14982: (b) files in /res
14983: - returns the entire contents of a file or -1;
14984: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14985:
1.712 albertel 14986:
14987: =item *
14988:
14989: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14990: reference
14991:
14992: returns either a stat() list of data about the file or an empty list
14993: if the file doesn't exist or couldn't find out about it (connection
14994: problems or user unknown)
14995:
1.191 harris41 14996: =item *
14997:
1.243 albertel 14998: filelocation($dir,$file) : returns file system location of a file
14999: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15000: directory that relative $file lookups are to looked in ($dir of /a/dir
15001: and a file of ../bob will become /a/bob)
1.191 harris41 15002:
15003: =item *
15004:
15005: hreflocation($dir,$file) : returns file system location or a URL; same as
15006: filelocation except for hrefs
15007:
15008: =item *
15009:
1.1261 raeburn 15010: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15011: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 15012:
1.243 albertel 15013: =back
15014:
1.608 albertel 15015: =head2 Usererfile file routines (/uploaded*)
15016:
15017: =over 4
15018:
15019: =item *
15020:
15021: userfileupload(): main rotine for putting a file in a user or course's
15022: filespace, arguments are,
15023:
1.620 albertel 15024: formname - required - this is the name of the element in $env where the
1.608 albertel 15025: filename, and the contents of the file to create/modifed exist
1.620 albertel 15026: the filename is in $env{'form.'.$formname.'.filename'} and the
15027: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 15028: context - if coursedoc, store the file in the course of the active role
15029: of the current user;
15030: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15031: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 15032: subdir - required - subdirectory to put the file in under ../userfiles/
15033: if undefined, it will be placed in "unknown"
15034:
15035: (This routine calls clean_filename() to remove any dangerous
15036: characters from the filename, and then calls finuserfileupload() to
15037: complete the transaction)
15038:
15039: returns either the url of the uploaded file (/uploaded/....) if successful
15040: and /adm/notfound.html if unsuccessful
15041:
15042: =item *
15043:
15044: clean_filename(): routine for cleaing a filename up for storage in
15045: userfile space, argument is:
15046:
15047: filename - proposed filename
15048:
15049: returns: the new clean filename
15050:
15051: =item *
15052:
1.1090 raeburn 15053: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 15054: userspace, probably shouldn't be called directly
15055:
15056: docuname: username or courseid of destination for the file
15057: docudom: domain of user/course of destination for the file
15058: formname: same as for userfileupload()
1.1090 raeburn 15059: fname: filename (including subdirectories) for the file
15060: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15061: allfiles: reference to hash used to store objects found by parser
15062: codebase: reference to hash used for codebases of java objects found by parser
15063: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15064: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15065: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15066: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15067: context: if 'overwrite', will move the uploaded file from its temporary location to
15068: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 15069: mimetype: reference to scalar to accommodate mime type determined
15070: from File::MMagic if $parser = parse.
1.608 albertel 15071:
15072: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 15073: and /adm/notfound.html if unsuccessful (or an error message if context
15074: was 'overwrite').
15075:
1.608 albertel 15076:
15077: =item *
15078:
15079: renameuserfile(): renames an existing userfile to a new name
15080:
15081: Args:
15082: docuname: username or courseid of destination for the file
15083: docudom: domain of user/course of destination for the file
15084: old: current file name (including any subdirs under userfiles)
15085: new: desired file name (including any subdirs under userfiles)
15086:
15087: =item *
15088:
15089: mkdiruserfile(): creates a directory is a userfiles dir
15090:
15091: Args:
15092: docuname: username or courseid of destination for the file
15093: docudom: domain of user/course of destination for the file
15094: dir: dir to create (including any subdirs under userfiles)
15095:
15096: =item *
15097:
15098: removeuserfile(): removes a file that exists in userfiles
15099:
15100: Args:
15101: docuname: username or courseid of destination for the file
15102: docudom: domain of user/course of destination for the file
15103: fname: filname to delete (including any subdirs under userfiles)
15104:
15105: =item *
15106:
15107: removeuploadedurl(): convience function for removeuserfile()
15108:
15109: Args:
15110: url: a full /uploaded/... url to delete
15111:
1.747 albertel 15112: =item *
15113:
15114: get_portfile_permissions():
15115: Args:
15116: domain: domain of user or course contain the portfolio files
15117: user: name of user or num of course contain the portfolio files
15118: Returns:
15119: hashref of a dump of the proper file_permissions.db
15120:
15121:
15122: =item *
15123:
15124: get_access_controls():
15125:
15126: Args:
15127: current_permissions: the hash ref returned from get_portfile_permissions()
15128: group: (optional) the group you want the files associated with
15129: file: (optional) the file you want access info on
15130:
15131: Returns:
1.749 raeburn 15132: a hash (keys are file names) of hashes containing
15133: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15134: values are XML containing access control settings (see below)
1.747 albertel 15135:
15136: Internal notes:
15137:
1.749 raeburn 15138: access controls are stored in file_permissions.db as key=value pairs.
15139: key -> path to file/file_name\0uniqueID:scope_end_start
15140: where scope -> public,guest,course,group,domains or users.
15141: end -> UNIX time for end of access (0 -> no end date)
15142: start -> UNIX time for start of access
15143:
15144: value -> XML description of access control
15145: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15146: <start></start>
15147: <end></end>
15148:
15149: <password></password> for scope type = guest
15150:
15151: <domain></domain> for scope type = course or group
15152: <number></number>
15153: <roles id="">
15154: <role></role>
15155: <access></access>
15156: <section></section>
15157: <group></group>
15158: </roles>
15159:
15160: <dom></dom> for scope type = domains
15161:
15162: <users> for scope type = users
15163: <user>
15164: <uname></uname>
15165: <udom></udom>
15166: </user>
15167: </users>
15168: </scope>
15169:
15170: Access data is also aggregated for each file in an additional key=value pair:
15171: key -> path to file/file_name\0accesscontrol
15172: value -> reference to hash
15173: hash contains key = value pairs
15174: where key = uniqueID:scope_end_start
15175: value = UNIX time record was last updated
15176:
15177: Used to improve speed of look-ups of access controls for each file.
15178:
15179: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15180:
1.1198 raeburn 15181: =item *
15182:
1.749 raeburn 15183: modify_access_controls():
15184:
15185: Modifies access controls for a portfolio file
15186: Args
15187: 1. file name
15188: 2. reference to hash of required changes,
15189: 3. domain
15190: 4. username
15191: where domain,username are the domain of the portfolio owner
15192: (either a user or a course)
15193:
15194: Returns:
15195: 1. result of additions or updates ('ok' or 'error', with error message).
15196: 2. result of deletions ('ok' or 'error', with error message).
15197: 3. reference to hash of any new or updated access controls.
15198: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15199: key = integer (inbound ID)
1.1198 raeburn 15200: value = uniqueID
15201:
15202: =item *
15203:
15204: get_timebased_id():
15205:
15206: Attempts to get a unique timestamp-based suffix for use with items added to a
15207: course via the Course Editor (e.g., folders, composite pages,
15208: group bulletin boards).
15209:
15210: Args: (first three required; six others optional)
15211:
15212: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15213: docssequence, or name of group
15214:
15215: 2. keyid (alphanumeric): name of temporary locking key in hash,
15216: e.g., num, boardids
15217:
15218: 3. namespace: name of gdbm file used to store suffixes already assigned;
15219: file will be named nohist_namespace.db
15220:
15221: 4. cdom: domain of course; default is current course domain from %env
15222:
15223: 5. cnum: course number; default is current course number from %env
15224:
15225: 6. idtype: set to concat if an additional digit is to be appended to the
15226: unix timestamp to form the suffix, if the plain timestamp is already
15227: in use. Default is to not do this, but simply increment the unix
15228: timestamp by 1 until a unique key is obtained.
15229:
15230: 7. who: holder of locking key; defaults to user:domain for user.
15231:
15232: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15233: retrying); default is 3.
15234:
15235: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15236:
15237: Returns:
15238:
15239: 1. suffix obtained (numeric)
15240:
15241: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15242:
15243: 3. error: contains (localized) error message if an error occurred.
15244:
1.747 albertel 15245:
1.608 albertel 15246: =back
15247:
1.243 albertel 15248: =head2 HTTP Helper Routines
15249:
15250: =over 4
15251:
1.191 harris41 15252: =item *
15253:
15254: escape() : unpack non-word characters into CGI-compatible hex codes
15255:
15256: =item *
15257:
15258: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15259:
1.243 albertel 15260: =back
15261:
15262: =head1 PRIVATE SUBROUTINES
15263:
15264: =head2 Underlying communication routines (Shouldn't call)
15265:
15266: =over 4
15267:
15268: =item *
15269:
15270: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15271:
15272: =item *
15273:
15274: reply() : uses subreply to send a message to remote machine, logs all failures
15275:
15276: =item *
15277:
15278: critical() : passes a critical message to another server; if cannot
15279: get through then place message in connection buffer directory and
15280: returns con_delayed, if incapable of saving message, returns
15281: con_failed
15282:
15283: =item *
15284:
15285: reconlonc() : tries to reconnect lonc client processes.
15286:
15287: =back
15288:
15289: =head2 Resource Access Logging
15290:
15291: =over 4
15292:
15293: =item *
15294:
15295: flushcourselogs() : flush (save) buffer logs and access logs
15296:
15297: =item *
15298:
15299: courselog($what) : save message for course in hash
15300:
15301: =item *
15302:
15303: courseacclog($what) : save message for course using &courselog(). Perform
15304: special processing for specific resource types (problems, exams, quizzes, etc).
15305:
1.191 harris41 15306: =item *
15307:
15308: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15309: as a PerlChildExitHandler
1.243 albertel 15310:
15311: =back
15312:
15313: =head2 Other
15314:
15315: =over 4
15316:
15317: =item *
15318:
15319: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15320:
15321: =back
15322:
15323: =cut
1.877 foxr 15324:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>