Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1336
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1336 ! raeburn 4: # $Id: lonnet.pm,v 1.1335 2017/01/28 21:35:54 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1182 foxr 78:
1.1173 foxr 79: use Encode;
80:
1.1245 raeburn 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
1.871 albertel 84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 88: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 89:
1.1 albertel 90: use IO::Socket;
1.31 www 91: use GDBM_File;
1.208 albertel 92: use HTML::LCParser;
1.88 www 93: use Fcntl qw(:flock);
1.870 albertel 94: use Storable qw(thaw nfreeze);
1.1289 damieng 95: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 96: use Cache::Memcached;
1.676 albertel 97: use Digest::MD5;
1.790 albertel 98: use Math::Random;
1.1024 raeburn 99: use File::MMagic;
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1167 droeschl 103: use LONCAPA::Lond;
1.1117 foxr 104:
1.1090 raeburn 105: use File::Copy;
1.676 albertel 106:
1.195 www 107: my $readit;
1.1288 damieng 108: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 109:
1.619 albertel 110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
1.449 matthew 115:
1.1187 raeburn 116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 117: {
118: my $logid;
1.1187 raeburn 119: sub write_log {
1.1188 raeburn 120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
1.957 raeburn 126: }
1.1184 raeburn 127: $logid ++;
1.957 raeburn 128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
1.1184 raeburn 130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 143: }
144: }
1.1 albertel 145:
1.163 harris41 146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
1.1 albertel 156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
1.448 albertel 161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
1.448 albertel 164: close($fh);
165: }
1.1 albertel 166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
1.448 albertel 174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
1.1 albertel 178: return 1;
179: }
180:
1.850 albertel 181: sub create_connection {
1.853 albertel 182: my ($hostname,$lonid) = @_;
1.851 albertel 183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
1.890 albertel 187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
1.983 raeburn 194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
1.850 albertel 208:
1.1106 raeburn 209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
1.1315 raeburn 232: sub get_servercerts_info {
233: my ($lonhost,$context) = @_;
234: my ($rep,$uselocal);
235: if (grep { $_ eq $lonhost } ¤t_machine_ids()) {
236: $uselocal = 1;
237: }
1.1316 raeburn 238: if (($context ne 'cgi') && ($uselocal)) {
1.1315 raeburn 239: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323 raeburn 240: if ($distro eq '') {
241: $uselocal = 0;
242: } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315 raeburn 243: if ($1 < 6) {
244: $uselocal = 0;
245: }
246: }
247: }
248: if ($uselocal) {
249: $rep = LONCAPA::Lond::server_certs(\%perlvar);
250: } else {
251: $rep=&reply('servercerts',$lonhost);
252: }
253: my ($result,%returnhash);
254: if (defined($lonhost)) {
255: if (!defined(&hostname($lonhost))) {
256: return;
257: }
258: }
259: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
260: ($rep eq 'unknown_cmd')) {
261: $result = $rep;
262: } else {
263: $result = 'ok';
264: my @pairs=split(/\&/,$rep);
265: foreach my $item (@pairs) {
266: my ($key,$value)=split(/=/,$item,2);
267: my $what = &unescape($key);
268: $returnhash{$what}=&thaw_unescape($value);
269: }
270: }
271: return ($result,\%returnhash);
272: }
273:
1.993 raeburn 274: sub get_server_loncaparev {
1.1073 raeburn 275: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 276: if (defined($lonhost)) {
277: if (!defined(&hostname($lonhost))) {
278: undef($lonhost);
279: }
280: }
281: if (!defined($lonhost)) {
282: if (defined(&domain($dom,'primary'))) {
283: $lonhost=&domain($dom,'primary');
284: if ($lonhost eq 'no_host') {
285: undef($lonhost);
286: }
287: }
288: }
289: if (defined($lonhost)) {
1.1073 raeburn 290: my $cachetime = 12*3600;
291: if (!$ignore_cache) {
292: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
293: if (defined($cached)) {
294: return $loncaparev;
295: }
296: }
297: my ($answer,$loncaparev);
298: my @ids=¤t_machine_ids();
299: if (grep(/^\Q$lonhost\E$/,@ids)) {
300: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 301: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 302: $loncaparev = $1;
303: }
304: } else {
305: $answer = &reply('serverloncaparev',$lonhost);
306: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
307: if ($caller eq 'loncron') {
308: my $ua=new LWP::UserAgent;
1.1082 raeburn 309: $ua->timeout(4);
1.1073 raeburn 310: my $protocol = $protocol{$lonhost};
311: $protocol = 'http' if ($protocol ne 'https');
312: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
313: my $request=new HTTP::Request('GET',$url);
314: my $response=$ua->request($request);
315: unless ($response->is_error()) {
316: my $content = $response->content;
1.1081 raeburn 317: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 318: $loncaparev = $1;
319: }
320: }
321: } else {
322: $loncaparev = $loncaparevs{$lonhost};
323: }
1.1081 raeburn 324: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 325: $loncaparev = $1;
326: }
1.993 raeburn 327: }
1.1073 raeburn 328: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 329: }
330: }
331:
1.1074 raeburn 332: sub get_server_homeID {
333: my ($hostname,$ignore_cache,$caller) = @_;
334: unless ($ignore_cache) {
335: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
336: if (defined($cached)) {
337: return $serverhomeID;
338: }
339: }
340: my $cachetime = 12*3600;
341: my $serverhomeID;
342: if ($caller eq 'loncron') {
343: my @machine_ids = &machine_ids($hostname);
344: foreach my $id (@machine_ids) {
345: my $response = &reply('serverhomeID',$id);
346: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
347: $serverhomeID = $response;
348: last;
349: }
350: }
351: if ($serverhomeID eq '') {
352: $serverhomeID = $machine_ids[-1];
353: }
354: } else {
355: $serverhomeID = $serverhomeIDs{$hostname};
356: }
357: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
358: }
359:
1.1121 raeburn 360: sub get_remote_globals {
361: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 362: my ($result,%returnhash,%whatneeded);
363: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 364: foreach my $what (sort(keys(%{$whathash}))) {
365: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 366: my ($response,$cached);
1.1121 raeburn 367: unless ($ignore_cache) {
1.1125 raeburn 368: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 369: }
370: if (defined($cached)) {
1.1125 raeburn 371: $returnhash{$what} = $response;
1.1121 raeburn 372: } else {
1.1125 raeburn 373: $whatneeded{$what} = 1;
1.1121 raeburn 374: }
375: }
1.1125 raeburn 376: if (keys(%whatneeded) == 0) {
377: $result = 'ok';
378: } else {
1.1121 raeburn 379: my $requested = &freeze_escape(\%whatneeded);
380: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 381: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
382: ($rep eq 'unknown_cmd')) {
383: $result = $rep;
384: } else {
385: $result = 'ok';
1.1121 raeburn 386: my @pairs=split(/\&/,$rep);
1.1125 raeburn 387: foreach my $item (@pairs) {
388: my ($key,$value)=split(/=/,$item,2);
389: my $what = &unescape($key);
390: my $hashid = $lonhost.'-'.$what;
391: $returnhash{$what}=&thaw_unescape($value);
392: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 393: }
394: }
395: }
396: }
1.1125 raeburn 397: return ($result,\%returnhash);
1.1121 raeburn 398: }
399:
1.1124 raeburn 400: sub remote_devalidate_cache {
1.1241 raeburn 401: my ($lonhost,$cachekeys) = @_;
402: my $items;
403: return unless (ref($cachekeys) eq 'ARRAY');
404: my $cachestr = join('&',@{$cachekeys});
405: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 406: return $response;
407: }
408:
1.1 albertel 409: # -------------------------------------------------- Non-critical communication
410: sub subreply {
411: my ($cmd,$server)=@_;
1.838 albertel 412: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 413: #
414: # With loncnew process trimming, there's a timing hole between lonc server
415: # process exit and the master server picking up the listen on the AF_UNIX
416: # socket. In that time interval, a lock file will exist:
417:
418: my $lockfile=$peerfile.".lock";
419: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1289 damieng 420: sleep(0.1);
1.549 foxr 421: }
422: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 423: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 424: #
1.550 foxr 425: # We'll give the connection a few tries before abandoning it. If
426: # connection is not possible, we'll con_lost back to the client.
427: #
428: my $client;
429: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
430: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
431: Type => SOCK_STREAM,
432: Timeout => 10);
1.869 albertel 433: if ($client) {
1.550 foxr 434: last; # Connected!
1.850 albertel 435: } else {
1.853 albertel 436: &create_connection(&hostname($server),$server);
1.550 foxr 437: }
1.1289 damieng 438: sleep(0.1); # Try again later if failed connection.
1.550 foxr 439: }
440: my $answer;
441: if ($client) {
1.704 albertel 442: print $client "sethost:$server:$cmd\n";
1.550 foxr 443: $answer=<$client>;
444: if (!$answer) { $answer="con_lost"; }
445: chomp($answer);
446: } else {
447: $answer = 'con_lost'; # Failed connection.
448: }
1.1 albertel 449: return $answer;
450: }
451:
452: sub reply {
453: my ($cmd,$server)=@_;
1.838 albertel 454: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 455: my $answer=subreply($cmd,$server);
1.65 www 456: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 457: &logthis("<font color=\"blue\">WARNING:".
1.12 www 458: " $cmd to $server returned $answer</font>");
459: }
1.1 albertel 460: return $answer;
461: }
462:
463: # ----------------------------------------------------------- Send USR1 to lonc
464:
465: sub reconlonc {
1.891 albertel 466: my ($lonid) = @_;
467: if ($lonid) {
1.1295 raeburn 468: my $hostname = &hostname($lonid);
1.891 albertel 469: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
470: if ($hostname && -e $peerfile) {
471: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
472: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
473: Type => SOCK_STREAM,
474: Timeout => 10);
475: if ($client) {
476: print $client ("reset_retries\n");
477: my $answer=<$client>;
478: #reset just this one.
479: }
480: }
481: return;
482: }
483:
1.836 www 484: &logthis("Trying to reconnect lonc");
1.1 albertel 485: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 486: if (open(my $fh,"<$loncfile")) {
1.1 albertel 487: my $loncpid=<$fh>;
488: chomp($loncpid);
489: if (kill 0 => $loncpid) {
490: &logthis("lonc at pid $loncpid responding, sending USR1");
491: kill USR1 => $loncpid;
492: sleep 1;
1.1295 raeburn 493: } else {
1.12 www 494: &logthis(
1.672 albertel 495: "<font color=\"blue\">WARNING:".
1.12 www 496: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 497: }
498: } else {
1.836 www 499: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 500: }
501: }
502:
503: # ------------------------------------------------------ Critical communication
1.12 www 504:
1.1 albertel 505: sub critical {
506: my ($cmd,$server)=@_;
1.838 albertel 507: unless (&hostname($server)) {
1.672 albertel 508: &logthis("<font color=\"blue\">WARNING:".
1.89 www 509: " Critical message to unknown server ($server)</font>");
510: return 'no_such_host';
511: }
1.1 albertel 512: my $answer=reply($cmd,$server);
513: if ($answer eq 'con_lost') {
1.1295 raeburn 514: &reconlonc($server);
1.589 albertel 515: my $answer=reply($cmd,$server);
1.1 albertel 516: if ($answer eq 'con_lost') {
517: my $now=time;
518: my $middlename=$cmd;
1.5 www 519: $middlename=substr($middlename,0,16);
1.1 albertel 520: $middlename=~s/\W//g;
521: my $dfilename=
1.305 www 522: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
523: $dumpcount++;
1.1 albertel 524: {
1.448 albertel 525: my $dfh;
526: if (open($dfh,">$dfilename")) {
527: print $dfh "$cmd\n";
528: close($dfh);
529: }
1.1 albertel 530: }
1.1288 damieng 531: sleep 1;
1.1 albertel 532: my $wcmd='';
533: {
1.448 albertel 534: my $dfh;
535: if (open($dfh,"<$dfilename")) {
536: $wcmd=<$dfh>;
537: close($dfh);
538: }
1.1 albertel 539: }
540: chomp($wcmd);
1.7 www 541: if ($wcmd eq $cmd) {
1.672 albertel 542: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 543: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 544: &logperm("D:$server:$cmd");
545: return 'con_delayed';
546: } else {
1.672 albertel 547: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 548: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 549: &logperm("F:$server:$cmd");
550: return 'con_failed';
551: }
552: }
553: }
554: return $answer;
1.405 albertel 555: }
556:
1.755 albertel 557: # ------------------------------------------- check if return value is an error
558:
559: sub error {
560: my ($result) = @_;
1.756 albertel 561: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 562: if ($2 == 2) { return undef; }
563: return $1;
564: }
565: return undef;
566: }
567:
1.783 albertel 568: sub convert_and_load_session_env {
569: my ($lonidsdir,$handle)=@_;
570: my @profile;
571: {
1.917 albertel 572: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
573: if (!$opened) {
1.915 albertel 574: return 0;
575: }
1.783 albertel 576: flock($idf,LOCK_SH);
577: @profile=<$idf>;
578: close($idf);
579: }
580: my %temp_env;
581: foreach my $line (@profile) {
1.786 albertel 582: if ($line !~ m/=/) {
583: return 0;
584: }
1.783 albertel 585: chomp($line);
586: my ($envname,$envvalue)=split(/=/,$line,2);
587: $temp_env{&unescape($envname)} = &unescape($envvalue);
588: }
589: unlink("$lonidsdir/$handle.id");
590: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
591: 0640)) {
592: %disk_env = %temp_env;
593: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
594: untie(%disk_env);
595: }
1.786 albertel 596: return 1;
1.783 albertel 597: }
598:
1.374 www 599: # ------------------------------------------- Transfer profile into environment
1.780 albertel 600: my $env_loaded;
601: sub transfer_profile_to_env {
1.788 albertel 602: my ($lonidsdir,$handle,$force_transfer) = @_;
603: if (!$force_transfer && $env_loaded) { return; }
1.374 www 604:
1.720 albertel 605: if (!defined($lonidsdir)) {
606: $lonidsdir = $perlvar{'lonIDsDir'};
607: }
608: if (!defined($handle)) {
609: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
610: }
611:
1.786 albertel 612: my $convert;
613: {
1.917 albertel 614: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
615: if (!$opened) {
1.915 albertel 616: return;
617: }
1.786 albertel 618: flock($idf,LOCK_SH);
619: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
620: &GDBM_READER(),0640)) {
621: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
622: untie(%disk_env);
623: } else {
624: $convert = 1;
625: }
626: }
627: if ($convert) {
628: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
629: &logthis("Failed to load session, or convert session.");
630: }
1.374 www 631: }
1.783 albertel 632:
1.786 albertel 633: my %remove;
1.783 albertel 634: while ( my $envname = each(%env) ) {
1.433 matthew 635: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
636: if ($time < time-300) {
1.783 albertel 637: $remove{$key}++;
1.433 matthew 638: }
639: }
640: }
1.783 albertel 641:
1.619 albertel 642: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 643: $env_loaded=1;
1.783 albertel 644: foreach my $expired_key (keys(%remove)) {
1.433 matthew 645: &delenv($expired_key);
1.374 www 646: }
1.1 albertel 647: }
648:
1.916 albertel 649: # ---------------------------------------------------- Check for valid session
650: sub check_for_valid_session {
1.1245 raeburn 651: my ($r,$name,$userhashref) = @_;
1.916 albertel 652: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 653: if ($name eq '') {
654: $name = 'lonID';
655: }
656: my $lonid=$cookies{$name};
1.916 albertel 657: return undef if (!$lonid);
658:
659: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 660: my $lonidsdir;
661: if ($name eq 'lonDAV') {
662: $lonidsdir=$r->dir_config('lonDAVsessDir');
663: } else {
664: $lonidsdir=$r->dir_config('lonIDsDir');
665: }
1.916 albertel 666: return undef if (!-e "$lonidsdir/$handle.id");
667:
1.917 albertel 668: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
669: return undef if (!$opened);
1.916 albertel 670:
671: flock($idf,LOCK_SH);
672: my %disk_env;
673: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
674: &GDBM_READER(),0640)) {
675: return undef;
676: }
677:
678: if (!defined($disk_env{'user.name'})
679: || !defined($disk_env{'user.domain'})) {
680: return undef;
681: }
1.1245 raeburn 682:
683: if (ref($userhashref) eq 'HASH') {
684: $userhashref->{'name'} = $disk_env{'user.name'};
685: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 686: }
1.1245 raeburn 687:
1.916 albertel 688: return $handle;
689: }
690:
1.830 albertel 691: sub timed_flock {
692: my ($file,$lock_type) = @_;
693: my $failed=0;
694: eval {
695: local $SIG{__DIE__}='DEFAULT';
696: local $SIG{ALRM}=sub {
697: $failed=1;
698: die("failed lock");
699: };
700: alarm(13);
701: flock($file,$lock_type);
702: alarm(0);
703: };
704: if ($failed) {
705: return undef;
706: } else {
707: return 1;
708: }
709: }
710:
1.5 www 711: # ---------------------------------------------------------- Append Environment
712:
713: sub appenv {
1.949 raeburn 714: my ($newenv,$roles) = @_;
715: if (ref($newenv) eq 'HASH') {
716: foreach my $key (keys(%{$newenv})) {
717: my $refused = 0;
718: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
719: $refused = 1;
720: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 721: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 722: if (grep(/^\Q$role\E$/,@{$roles})) {
723: $refused = 0;
724: }
725: }
726: }
727: if ($refused) {
728: &logthis("<font color=\"blue\">WARNING: ".
729: "Attempt to modify environment ".$key." to ".$newenv->{$key}
730: .'</font>');
731: delete($newenv->{$key});
732: } else {
733: $env{$key}=$newenv->{$key};
734: }
735: }
736: my $opened = open(my $env_file,'+<',$env{'user.environment'});
737: if ($opened
738: && &timed_flock($env_file,LOCK_EX)
739: &&
740: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
741: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
742: while (my ($key,$value) = each(%{$newenv})) {
743: $disk_env{$key} = $value;
744: }
745: untie(%disk_env);
1.35 www 746: }
1.191 harris41 747: }
1.56 www 748: return 'ok';
749: }
750: # ----------------------------------------------------- Delete from Environment
751:
752: sub delenv {
1.1104 raeburn 753: my ($delthis,$regexp,$roles) = @_;
754: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
755: my $refused = 1;
756: if (ref($roles) eq 'ARRAY') {
757: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
758: if (grep(/^\Q$role\E$/,@{$roles})) {
759: $refused = 0;
760: }
761: }
762: if ($refused) {
763: &logthis("<font color=\"blue\">WARNING: ".
764: "Attempt to delete from environment ".$delthis);
765: return 'error';
766: }
1.56 www 767: }
1.917 albertel 768: my $opened = open(my $env_file,'+<',$env{'user.environment'});
769: if ($opened
1.915 albertel 770: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 771: &&
772: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
773: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 774: foreach my $key (keys(%disk_env)) {
1.987 raeburn 775: if ($regexp) {
776: if ($key=~/^$delthis/) {
777: delete($env{$key});
778: delete($disk_env{$key});
779: }
780: } else {
781: if ($key=~/^\Q$delthis\E/) {
782: delete($env{$key});
783: delete($disk_env{$key});
784: }
785: }
1.448 albertel 786: }
1.783 albertel 787: untie(%disk_env);
1.5 www 788: }
789: return 'ok';
1.369 albertel 790: }
791:
1.790 albertel 792: sub get_env_multiple {
793: my ($name) = @_;
794: my @values;
795: if (defined($env{$name})) {
796: # exists is it an array
797: if (ref($env{$name})) {
798: @values=@{ $env{$name} };
799: } else {
800: $values[0]=$env{$name};
801: }
802: }
803: return(@values);
804: }
805:
1.958 www 806: # ------------------------------------------------------------------- Locking
807:
808: sub set_lock {
809: my ($text)=@_;
810: $locknum++;
811: my $id=$$.'-'.$locknum;
812: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
813: 'session.lock.'.$id => $text});
814: return $id;
815: }
816:
817: sub get_locks {
818: my $num=0;
819: my %texts=();
820: foreach my $lock (split(/\,/,$env{'session.locks'})) {
821: if ($lock=~/\w/) {
822: $num++;
823: $texts{$lock}=$env{'session.lock.'.$lock};
824: }
825: }
826: return ($num,%texts);
827: }
828:
829: sub remove_lock {
830: my ($id)=@_;
831: my $newlocks='';
832: foreach my $lock (split(/\,/,$env{'session.locks'})) {
833: if (($lock=~/\w/) && ($lock ne $id)) {
834: $newlocks.=','.$lock;
835: }
836: }
837: &appenv({'session.locks' => $newlocks});
838: &delenv('session.lock.'.$id);
839: }
840:
841: sub remove_all_locks {
842: my $activelocks=$env{'session.locks'};
843: foreach my $lock (split(/\,/,$env{'session.locks'})) {
844: if ($lock=~/\w/) {
845: &remove_lock($lock);
846: }
847: }
848: }
849:
850:
1.369 albertel 851: # ------------------------------------------ Find out current server userload
852: sub userload {
853: my $numusers=0;
854: {
855: opendir(LONIDS,$perlvar{'lonIDsDir'});
856: my $filename;
857: my $curtime=time;
858: while ($filename=readdir(LONIDS)) {
1.925 albertel 859: next if ($filename eq '.' || $filename eq '..');
860: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 861: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 862: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 863: }
864: closedir(LONIDS);
865: }
866: my $userloadpercent=0;
867: my $maxuserload=$perlvar{'lonUserLoadLim'};
868: if ($maxuserload) {
1.371 albertel 869: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 870: }
1.372 albertel 871: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 872: return $userloadpercent;
1.283 www 873: }
874:
1.1 albertel 875: # ------------------------------ Find server with least workload from spare.tab
1.11 www 876:
1.1 albertel 877: sub spareserver {
1.1083 raeburn 878: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 879: my $spare_server;
1.370 albertel 880: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 881: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
882: : $userloadpercent;
1.1083 raeburn 883: my ($uint_dom,$remotesessions);
884: if (($udom ne '') && (&domain($udom) ne '')) {
885: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
886: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
887: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
888: $remotesessions = $udomdefaults{'remotesessions'};
889: }
1.1123 raeburn 890: my $spareshash = &this_host_spares($udom);
891: if (ref($spareshash) eq 'HASH') {
892: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
893: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 894: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
895: $try_server));
1.1123 raeburn 896: ($spare_server, $lowest_load) =
897: &compare_server_load($try_server, $spare_server, $lowest_load);
898: }
1.1083 raeburn 899: }
1.784 albertel 900:
1.1123 raeburn 901: my $found_server = ($spare_server ne '' && $lowest_load < 100);
902:
903: if (!$found_server) {
904: if (ref($spareshash->{'default'}) eq 'ARRAY') {
905: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 906: next unless (&spare_can_host($udom,$uint_dom,
907: $remotesessions,$try_server));
1.1123 raeburn 908: ($spare_server, $lowest_load) =
909: &compare_server_load($try_server, $spare_server, $lowest_load);
910: }
911: }
912: }
1.784 albertel 913: }
914:
915: if (!$want_server_name) {
1.968 raeburn 916: my $protocol = 'http';
917: if ($protocol{$spare_server} eq 'https') {
918: $protocol = $protocol{$spare_server};
919: }
1.1001 raeburn 920: if (defined($spare_server)) {
921: my $hostname = &hostname($spare_server);
1.1083 raeburn 922: if (defined($hostname)) {
1.1001 raeburn 923: $spare_server = $protocol.'://'.$hostname;
924: }
925: }
1.784 albertel 926: }
927: return $spare_server;
928: }
929:
930: sub compare_server_load {
1.1253 raeburn 931: my ($try_server, $spare_server, $lowest_load, $required) = @_;
932:
933: if ($required) {
934: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
935: my $remoterev = &get_server_loncaparev(undef,$try_server);
936: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
937: if (($major eq '' && $minor eq '') ||
938: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
939: return ($spare_server,$lowest_load);
940: }
941: }
1.784 albertel 942:
943: my $loadans = &reply('load', $try_server);
944: my $userloadans = &reply('userload',$try_server);
945:
946: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 947: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 948: }
949:
950: my $load;
951: if ($loadans =~ /\d/) {
952: if ($userloadans =~ /\d/) {
953: #both are numbers, pick the bigger one
954: $load = ($loadans > $userloadans) ? $loadans
955: : $userloadans;
1.411 albertel 956: } else {
1.784 albertel 957: $load = $loadans;
1.411 albertel 958: }
1.784 albertel 959: } else {
960: $load = $userloadans;
961: }
962:
963: if (($load =~ /\d/) && ($load < $lowest_load)) {
964: $spare_server = $try_server;
965: $lowest_load = $load;
1.370 albertel 966: }
1.784 albertel 967: return ($spare_server,$lowest_load);
1.202 matthew 968: }
1.914 albertel 969:
970: # --------------------------- ask offload servers if user already has a session
971: sub find_existing_session {
972: my ($udom,$uname) = @_;
1.1123 raeburn 973: my $spareshash = &this_host_spares($udom);
974: if (ref($spareshash) eq 'HASH') {
975: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
976: foreach my $try_server (@{ $spareshash->{'primary'} }) {
977: return $try_server if (&has_user_session($try_server, $udom, $uname));
978: }
979: }
980: if (ref($spareshash->{'default'}) eq 'ARRAY') {
981: foreach my $try_server (@{ $spareshash->{'default'} }) {
982: return $try_server if (&has_user_session($try_server, $udom, $uname));
983: }
984: }
1.914 albertel 985: }
986: return;
987: }
988:
989: # -------------------------------- ask if server already has a session for user
990: sub has_user_session {
991: my ($lonid,$udom,$uname) = @_;
992: my $result = &reply(join(':','userhassession',
993: map {&escape($_)} ($udom,$uname)),$lonid);
994: return 1 if ($result eq 'ok');
995:
996: return 0;
997: }
998:
1.1076 raeburn 999: # --------- determine least loaded server in a user's domain which allows login
1000:
1001: sub choose_server {
1.1259 raeburn 1002: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1003: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1004: my %servers = &get_servers($udom);
1.1076 raeburn 1005: my $lowest_load = 30000;
1.1259 raeburn 1006: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1007: if ($skiploadbal) {
1008: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1009: unless (defined($cached)) {
1010: my $cachetime = 60*60*24;
1011: my %domconfig =
1012: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1013: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1014: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1015: $cachetime);
1016: }
1017: }
1018: }
1.1076 raeburn 1019: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1020: if ($skiploadbal) {
1021: if (ref($balancers) eq 'HASH') {
1022: next if (exists($balancers->{$lonhost}));
1023: }
1024: }
1.1115 raeburn 1025: my $loginvia;
1026: if ($checkloginvia) {
1027: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1028: if ($loginvia) {
1029: my ($server,$path) = split(/:/,$loginvia);
1030: ($login_host, $lowest_load) =
1.1253 raeburn 1031: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1032: if ($login_host eq $server) {
1033: $portal_path = $path;
1.1151 raeburn 1034: $isredirect = 1;
1.1116 raeburn 1035: }
1036: } else {
1037: ($login_host, $lowest_load) =
1.1253 raeburn 1038: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1039: if ($login_host eq $lonhost) {
1040: $portal_path = '';
1.1151 raeburn 1041: $isredirect = '';
1.1116 raeburn 1042: }
1043: }
1044: } else {
1.1076 raeburn 1045: ($login_host, $lowest_load) =
1.1253 raeburn 1046: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1047: }
1048: }
1049: if ($login_host ne '') {
1.1116 raeburn 1050: $hostname = &hostname($login_host);
1.1076 raeburn 1051: }
1.1331 raeburn 1052: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1053: }
1054:
1.202 matthew 1055: # --------------------------------------------- Try to change a user's password
1056:
1057: sub changepass {
1.799 raeburn 1058: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1059: $currentpass = &escape($currentpass);
1060: $newpass = &escape($newpass);
1.1030 raeburn 1061: my $lonhost = $perlvar{'lonHostID'};
1062: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1063: $server);
1064: if (! $answer) {
1065: &logthis("No reply on password change request to $server ".
1066: "by $uname in domain $udom.");
1067: } elsif ($answer =~ "^ok") {
1068: &logthis("$uname in $udom successfully changed their password ".
1069: "on $server.");
1070: } elsif ($answer =~ "^pwchange_failure") {
1071: &logthis("$uname in $udom was unable to change their password ".
1072: "on $server. The action was blocked by either lcpasswd ".
1073: "or pwchange");
1074: } elsif ($answer =~ "^non_authorized") {
1075: &logthis("$uname in $udom did not get their password correct when ".
1076: "attempting to change it on $server.");
1077: } elsif ($answer =~ "^auth_mode_error") {
1078: &logthis("$uname in $udom attempted to change their password despite ".
1079: "not being locally or internally authenticated on $server.");
1080: } elsif ($answer =~ "^unknown_user") {
1081: &logthis("$uname in $udom attempted to change their password ".
1082: "on $server but were unable to because $server is not ".
1083: "their home server.");
1084: } elsif ($answer =~ "^refused") {
1085: &logthis("$server refused to change $uname in $udom password because ".
1086: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1087: } elsif ($answer =~ "invalid_client") {
1088: &logthis("$server refused to change $uname in $udom password because ".
1089: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1090: }
1091: return $answer;
1.1 albertel 1092: }
1093:
1.169 harris41 1094: # ----------------------- Try to determine user's current authentication scheme
1095:
1096: sub queryauthenticate {
1097: my ($uname,$udom)=@_;
1.456 albertel 1098: my $uhome=&homeserver($uname,$udom);
1099: if (!$uhome) {
1100: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1101: return 'no_host';
1102: }
1103: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1104: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1105: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1106: }
1.456 albertel 1107: return $answer;
1.169 harris41 1108: }
1109:
1.1 albertel 1110: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1111:
1.1 albertel 1112: sub authenticate {
1.1073 raeburn 1113: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1114: $upass=&escape($upass);
1115: $uname= &LONCAPA::clean_username($uname);
1.836 www 1116: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1117: my $newhome;
1.836 www 1118: if ((!$uhome) || ($uhome eq 'no_host')) {
1119: # Maybe the machine was offline and only re-appeared again recently?
1120: &reconlonc();
1121: # One more
1.952 raeburn 1122: $uhome=&homeserver($uname,$udom,1);
1123: if (($uhome eq 'no_host') && $checkdefauth) {
1124: if (defined(&domain($udom,'primary'))) {
1125: $newhome=&domain($udom,'primary');
1126: }
1127: if ($newhome ne '') {
1128: $uhome = $newhome;
1129: }
1130: }
1.836 www 1131: if ((!$uhome) || ($uhome eq 'no_host')) {
1132: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1133: return 'no_host';
1134: }
1.1 albertel 1135: }
1.1073 raeburn 1136: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1137: if ($answer eq 'authorized') {
1.952 raeburn 1138: if ($newhome) {
1139: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1140: return 'no_account_on_host';
1141: } else {
1142: &logthis("User $uname at $udom authorized by $uhome");
1143: return $uhome;
1144: }
1.471 albertel 1145: }
1146: if ($answer eq 'non_authorized') {
1147: &logthis("User $uname at $udom rejected by $uhome");
1148: return 'no_host';
1.9 www 1149: }
1.471 albertel 1150: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1151: return 'no_host';
1152: }
1153:
1.1073 raeburn 1154: sub can_host_session {
1.1074 raeburn 1155: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1156: my $canhost = 1;
1.1074 raeburn 1157: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1158: if (ref($remotesessions) eq 'HASH') {
1159: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1160: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1161: $canhost = 0;
1162: } else {
1163: $canhost = 1;
1164: }
1165: }
1166: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1167: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1168: $canhost = 1;
1169: } else {
1170: $canhost = 0;
1171: }
1172: }
1173: if ($canhost) {
1174: if ($remotesessions->{'version'} ne '') {
1175: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1176: if ($reqmajor ne '' && $reqminor ne '') {
1177: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1178: my $major = $1;
1179: my $minor = $2;
1180: if (($major < $reqmajor ) ||
1181: (($major == $reqmajor) && ($minor < $reqminor))) {
1182: $canhost = 0;
1183: }
1184: } else {
1185: $canhost = 0;
1186: }
1187: }
1188: }
1189: }
1190: }
1191: if ($canhost) {
1192: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1193: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1194: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1195: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1196: if (($uint_dom ne '') &&
1197: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1198: $canhost = 0;
1199: } else {
1200: $canhost = 1;
1201: }
1202: }
1203: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1204: if (($uint_dom ne '') &&
1205: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1206: $canhost = 1;
1207: } else {
1208: $canhost = 0;
1209: }
1210: }
1211: }
1212: }
1213: return $canhost;
1214: }
1215:
1.1083 raeburn 1216: sub spare_can_host {
1217: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1218: my $canhost=1;
1.1279 raeburn 1219: my $try_server_hostname = &hostname($try_server);
1220: my $serverhomeID = &get_server_homeID($try_server_hostname);
1221: my $serverhomedom = &host_domain($serverhomeID);
1222: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1223: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1224: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1225: $canhost = 0;
1226: }
1227: }
1228: if (($canhost) && ($uint_dom)) {
1229: my @intdoms;
1230: my $internet_names = &get_internet_names($try_server);
1231: if (ref($internet_names) eq 'ARRAY') {
1232: @intdoms = @{$internet_names};
1233: }
1234: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1235: my $remoterev = &get_server_loncaparev(undef,$try_server);
1236: $canhost = &can_host_session($udom,$try_server,$remoterev,
1237: $remotesessions,
1238: $defdomdefaults{'hostedsessions'});
1239: }
1.1083 raeburn 1240: }
1241: return $canhost;
1242: }
1243:
1.1123 raeburn 1244: sub this_host_spares {
1245: my ($dom) = @_;
1.1126 raeburn 1246: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1247: my @hosts = ¤t_machine_ids();
1248: foreach my $lonhost (@hosts) {
1249: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1250: $dom_in_use = $dom;
1251: $lonhost_in_use = $lonhost;
1.1123 raeburn 1252: last;
1253: }
1254: }
1.1126 raeburn 1255: if ($dom_in_use ne '') {
1256: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1257: }
1258: if (ref($result) ne 'HASH') {
1259: $lonhost_in_use = $perlvar{'lonHostID'};
1260: $dom_in_use = &host_domain($lonhost_in_use);
1261: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1262: if (ref($result) ne 'HASH') {
1263: $result = \%spareid;
1264: }
1265: }
1266: return $result;
1267: }
1268:
1269: sub spares_for_offload {
1270: my ($dom_in_use,$lonhost_in_use) = @_;
1271: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1272: if (defined($cached)) {
1273: return $result;
1274: } else {
1.1126 raeburn 1275: my $cachetime = 60*60*24;
1276: my %domconfig =
1277: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1278: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1279: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1280: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1281: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1282: }
1283: }
1284: }
1285: }
1.1126 raeburn 1286: return;
1.1123 raeburn 1287: }
1288:
1.1129 raeburn 1289: sub get_lonbalancer_config {
1290: my ($servers) = @_;
1291: my ($currbalancer,$currtargets);
1292: if (ref($servers) eq 'HASH') {
1293: foreach my $server (keys(%{$servers})) {
1294: my %what = (
1295: spareid => 1,
1296: perlvar => 1,
1297: );
1298: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1299: if ($result eq 'ok') {
1300: if (ref($returnhash) eq 'HASH') {
1301: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1302: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1303: $currbalancer = $server;
1304: $currtargets = {};
1305: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1306: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1307: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1308: }
1309: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1310: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1311: }
1312: }
1313: last;
1314: }
1315: }
1316: }
1317: }
1318: }
1319: }
1320: return ($currbalancer,$currtargets);
1321: }
1322:
1323: sub check_loadbalancing {
1.1331 raeburn 1324: my ($uname,$udom,$caller) = @_;
1.1191 raeburn 1325: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1326: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1327: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1328: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1329: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1330: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1331: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1332: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1333: my $domneedscache;
1.1129 raeburn 1334: my $cachetime = 60*60*24;
1335:
1336: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1337: $dom_in_use = $udom;
1338: $homeintdom = 1;
1339: } else {
1340: $dom_in_use = $serverhomedom;
1341: }
1342: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1343: unless (defined($cached)) {
1344: my %domconfig =
1345: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1346: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1347: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1348: } else {
1349: $domneedscache = $dom_in_use;
1.1129 raeburn 1350: }
1351: }
1352: if (ref($result) eq 'HASH') {
1.1191 raeburn 1353: ($is_balancer,$currtargets,$currrules) =
1354: &check_balancer_result($result,@hosts);
1.1129 raeburn 1355: if ($is_balancer) {
1356: if (ref($currrules) eq 'HASH') {
1357: if ($homeintdom) {
1358: if ($uname ne '') {
1359: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1360: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1361: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1362: $rule_in_effect = $currrules->{'_LC_author'};
1363: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1364: $rule_in_effect = $currrules->{'_LC_adv'}
1365: }
1366: }
1367: if ($rule_in_effect eq '') {
1368: my %userenv = &userenvironment($udom,$uname,'inststatus');
1369: if ($userenv{'inststatus'} ne '') {
1370: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1371: my ($othertitle,$usertypes,$types) =
1372: &Apache::loncommon::sorted_inst_types($udom);
1373: if (ref($types) eq 'ARRAY') {
1374: foreach my $type (@{$types}) {
1375: if (grep(/^\Q$type\E$/,@statuses)) {
1376: if (exists($currrules->{$type})) {
1377: $rule_in_effect = $currrules->{$type};
1378: }
1379: }
1380: }
1381: }
1382: } else {
1383: if (exists($currrules->{'default'})) {
1384: $rule_in_effect = $currrules->{'default'};
1385: }
1386: }
1387: }
1388: } else {
1389: if (exists($currrules->{'default'})) {
1390: $rule_in_effect = $currrules->{'default'};
1391: }
1392: }
1393: } else {
1394: if ($currrules->{'_LC_external'} ne '') {
1395: $rule_in_effect = $currrules->{'_LC_external'};
1396: }
1397: }
1398: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1399: $uname,$udom);
1400: }
1401: }
1402: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1403: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1404: unless (defined($cached)) {
1405: my %domconfig =
1406: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1407: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1408: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1409: } else {
1410: $domneedscache = $serverhomedom;
1.1129 raeburn 1411: }
1412: }
1413: if (ref($result) eq 'HASH') {
1.1191 raeburn 1414: ($is_balancer,$currtargets,$currrules) =
1415: &check_balancer_result($result,@hosts);
1416: if ($is_balancer) {
1.1129 raeburn 1417: if (ref($currrules) eq 'HASH') {
1418: if ($currrules->{'_LC_internetdom'} ne '') {
1419: $rule_in_effect = $currrules->{'_LC_internetdom'};
1420: }
1421: }
1422: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1423: $uname,$udom);
1424: }
1425: } else {
1426: if ($perlvar{'lonBalancer'} eq 'yes') {
1427: $is_balancer = 1;
1428: $offloadto = &this_host_spares($dom_in_use);
1429: }
1.1307 raeburn 1430: unless (defined($cached)) {
1431: $domneedscache = $serverhomedom;
1432: }
1.1129 raeburn 1433: }
1434: } else {
1435: if ($perlvar{'lonBalancer'} eq 'yes') {
1436: $is_balancer = 1;
1437: $offloadto = &this_host_spares($dom_in_use);
1438: }
1.1307 raeburn 1439: unless (defined($cached)) {
1440: $domneedscache = $serverhomedom;
1441: }
1442: }
1443: if ($domneedscache) {
1444: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1445: }
1.1176 raeburn 1446: if ($is_balancer) {
1447: my $lowest_load = 30000;
1448: if (ref($offloadto) eq 'HASH') {
1449: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1450: foreach my $try_server (@{$offloadto->{'primary'}}) {
1451: ($otherserver,$lowest_load) =
1452: &compare_server_load($try_server,$otherserver,$lowest_load);
1453: }
1.1129 raeburn 1454: }
1.1176 raeburn 1455: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1456:
1.1176 raeburn 1457: if (!$found_server) {
1458: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1459: foreach my $try_server (@{$offloadto->{'default'}}) {
1460: ($otherserver,$lowest_load) =
1461: &compare_server_load($try_server,$otherserver,$lowest_load);
1462: }
1463: }
1464: }
1465: } elsif (ref($offloadto) eq 'ARRAY') {
1466: if (@{$offloadto} == 1) {
1467: $otherserver = $offloadto->[0];
1468: } elsif (@{$offloadto} > 1) {
1469: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1470: ($otherserver,$lowest_load) =
1471: &compare_server_load($try_server,$otherserver,$lowest_load);
1472: }
1473: }
1474: }
1.1331 raeburn 1475: unless ($caller eq 'login') {
1476: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1477: $is_balancer = 0;
1478: if ($uname ne '' && $udom ne '') {
1479: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1176 raeburn 1480:
1.1331 raeburn 1481: &appenv({'user.loadbalexempt' => $lonhost,
1482: 'user.loadbalcheck.time' => time});
1483: }
1.1176 raeburn 1484: }
1.1129 raeburn 1485: }
1486: }
1487: }
1488: return ($is_balancer,$otherserver);
1489: }
1490:
1.1191 raeburn 1491: sub check_balancer_result {
1492: my ($result,@hosts) = @_;
1493: my ($is_balancer,$currtargets,$currrules);
1494: if (ref($result) eq 'HASH') {
1495: if ($result->{'lonhost'} ne '') {
1496: my $currbalancer = $result->{'lonhost'};
1497: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1498: $is_balancer = 1;
1499: $currtargets = $result->{'targets'};
1500: $currrules = $result->{'rules'};
1501: }
1502: } else {
1503: foreach my $key (keys(%{$result})) {
1504: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1505: (ref($result->{$key}) eq 'HASH')) {
1506: $is_balancer = 1;
1507: $currrules = $result->{$key}{'rules'};
1508: $currtargets = $result->{$key}{'targets'};
1509: last;
1510: }
1511: }
1512: }
1513: }
1514: return ($is_balancer,$currtargets,$currrules);
1515: }
1516:
1.1129 raeburn 1517: sub get_loadbalancer_targets {
1518: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1519: my $offloadto;
1.1175 raeburn 1520: if ($rule_in_effect eq 'none') {
1521: return [$perlvar{'lonHostID'}];
1522: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1523: $offloadto = $currtargets;
1524: } else {
1525: if ($rule_in_effect eq 'homeserver') {
1526: my $homeserver = &homeserver($uname,$udom);
1527: if ($homeserver ne 'no_host') {
1528: $offloadto = [$homeserver];
1529: }
1530: } elsif ($rule_in_effect eq 'externalbalancer') {
1531: my %domconfig =
1532: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1533: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1534: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1535: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1536: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1537: }
1538: }
1539: } else {
1.1178 raeburn 1540: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1541: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1542: if (&hostname($remotebalancer) ne '') {
1543: $offloadto = [$remotebalancer];
1544: }
1545: }
1546: } elsif (&hostname($rule_in_effect) ne '') {
1547: $offloadto = [$rule_in_effect];
1548: }
1549: }
1550: return $offloadto;
1551: }
1552:
1.1127 raeburn 1553: sub internet_dom_servers {
1554: my ($dom) = @_;
1555: my (%uniqservers,%servers);
1556: my $primaryserver = &hostname(&domain($dom,'primary'));
1557: my @machinedoms = &machine_domains($primaryserver);
1558: foreach my $mdom (@machinedoms) {
1559: my %currservers = %servers;
1560: my %server = &get_servers($mdom);
1561: %servers = (%currservers,%server);
1562: }
1563: my %by_hostname;
1564: foreach my $id (keys(%servers)) {
1565: push(@{$by_hostname{$servers{$id}}},$id);
1566: }
1567: foreach my $hostname (sort(keys(%by_hostname))) {
1568: if (@{$by_hostname{$hostname}} > 1) {
1569: my $match = 0;
1570: foreach my $id (@{$by_hostname{$hostname}}) {
1571: if (&host_domain($id) eq $dom) {
1572: $uniqservers{$id} = $hostname;
1573: $match = 1;
1574: }
1575: }
1576: unless ($match) {
1577: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1578: }
1579: } else {
1580: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1581: }
1582: }
1583: return %uniqservers;
1584: }
1585:
1.1 albertel 1586: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1587:
1.599 albertel 1588: my %homecache;
1.1 albertel 1589: sub homeserver {
1.230 stredwic 1590: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1591: my $index="$uname:$udom";
1.426 albertel 1592:
1.599 albertel 1593: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1594:
1595: my %servers = &get_servers($udom,'library');
1596: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1597: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1598: exists($badServerCache{$tryserver}));
1.841 albertel 1599:
1600: my $answer=reply("home:$udom:$uname",$tryserver);
1601: if ($answer eq 'found') {
1602: delete($badServerCache{$tryserver});
1603: return $homecache{$index}=$tryserver;
1604: } elsif ($answer eq 'no_host') {
1605: $badServerCache{$tryserver}=1;
1606: }
1.1 albertel 1607: }
1608: return 'no_host';
1.70 www 1609: }
1610:
1.1300 raeburn 1611: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1612:
1613: sub idget {
1.1300 raeburn 1614: my ($udom,$idsref,$namespace)=@_;
1.70 www 1615: my %returnhash=();
1.1300 raeburn 1616: my @ids=();
1617: if (ref($idsref) eq 'ARRAY') {
1618: @ids = @{$idsref};
1619: } else {
1620: return %returnhash;
1621: }
1622: if ($namespace eq '') {
1623: $namespace = 'ids';
1624: }
1.70 www 1625:
1.841 albertel 1626: my %servers = &get_servers($udom,'library');
1627: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1628: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1629: if ($namespace eq 'ids') {
1630: $idlist=~tr/A-Z/a-z/;
1631: }
1632: my $reply;
1633: if ($namespace eq 'ids') {
1634: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1635: } else {
1636: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1637: }
1.841 albertel 1638: my @answer=();
1639: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1640: @answer=split(/\&/,$reply);
1641: } ;
1642: my $i;
1643: for ($i=0;$i<=$#ids;$i++) {
1644: if ($answer[$i]) {
1.1299 raeburn 1645: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1646: }
1.841 albertel 1647: }
1.1300 raeburn 1648: }
1.70 www 1649: return %returnhash;
1650: }
1651:
1652: # ------------------------------------- Find the IDs behind a list of usernames
1653:
1654: sub idrget {
1655: my ($udom,@unames)=@_;
1656: my %returnhash=();
1.800 albertel 1657: foreach my $uname (@unames) {
1658: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1659: }
1.70 www 1660: return %returnhash;
1661: }
1662:
1.1300 raeburn 1663: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 1664:
1665: sub idput {
1.1300 raeburn 1666: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 1667: my %servers=();
1.1300 raeburn 1668: my %ids=();
1669: my %byid = ();
1670: if (ref($idsref) eq 'HASH') {
1671: %ids=%{$idsref};
1672: }
1673: if ($namespace eq '') {
1674: $namespace = 'ids';
1675: }
1.800 albertel 1676: foreach my $uname (keys(%ids)) {
1677: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 1678: if ($uhom eq '') {
1679: $uhom=&homeserver($uname,$udom);
1680: }
1.70 www 1681: if ($uhom ne 'no_host') {
1.800 albertel 1682: my $esc_unam=&escape($uname);
1.1300 raeburn 1683: if ($namespace eq 'ids') {
1684: my $id=&escape($ids{$uname});
1685: $id=~tr/A-Z/a-z/;
1686: my $esc_unam=&escape($uname);
1687: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 1688: } else {
1.1300 raeburn 1689: my @currids = split(/,/,$ids{$uname});
1690: foreach my $id (@currids) {
1691: $byid{$uhom}{$id} .= $uname.',';
1692: }
1693: }
1694: }
1695: }
1696: if ($namespace eq 'clickers') {
1697: foreach my $server (keys(%byid)) {
1698: if (ref($byid{$server}) eq 'HASH') {
1699: foreach my $id (keys(%{$byid{$server}})) {
1700: $byid{$server} =~ s/,$//;
1701: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
1702: }
1.70 www 1703: }
1704: }
1.191 harris41 1705: }
1.800 albertel 1706: foreach my $server (keys(%servers)) {
1.1300 raeburn 1707: $servers{$server} =~ s/\&$//;
1708: if ($namespace eq 'ids') {
1709: &critical('idput:'.$udom.':'.$servers{$server},$server);
1710: } else {
1711: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
1712: }
1.191 harris41 1713: }
1.344 www 1714: }
1715:
1.1300 raeburn 1716: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 1717:
1718: sub iddel {
1.1300 raeburn 1719: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 1720: my %result=();
1.1300 raeburn 1721: my %ids=();
1722: my %byid = ();
1723: if (ref($idshashref) eq 'HASH') {
1724: %ids=%{$idshashref};
1725: } else {
1.1231 raeburn 1726: return %result;
1727: }
1.1300 raeburn 1728: if ($namespace eq '') {
1729: $namespace = 'ids';
1730: }
1.1231 raeburn 1731: my %servers=();
1.1300 raeburn 1732: while (my ($id,$unamestr) = each(%ids)) {
1733: if ($namespace eq 'ids') {
1734: my $uhom = $uhome;
1735: if ($uhom eq '') {
1736: $uhom=&homeserver($unamestr,$udom);
1737: }
1738: if ($uhom ne 'no_host') {
1739: $servers{$uhom}.='&'.&escape($id);
1740: }
1741: } else {
1742: my @curritems = split(/,/,$ids{$id});
1743: foreach my $uname (@curritems) {
1744: my $uhom = $uhome;
1745: if ($uhom eq '') {
1746: $uhom=&homeserver($uname,$udom);
1747: }
1748: if ($uhom ne 'no_host') {
1749: $byid{$uhom}{$id} .= $uname.',';
1750: }
1751: }
1.1231 raeburn 1752: }
1.1300 raeburn 1753: }
1754: if ($namespace eq 'clickers') {
1755: foreach my $server (keys(%byid)) {
1756: if (ref($byid{$server}) eq 'HASH') {
1757: foreach my $id (keys(%{$byid{$server}})) {
1758: $byid{$server}{$id} =~ s/,$//;
1759: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
1760: }
1.1231 raeburn 1761: }
1762: }
1763: }
1764: foreach my $server (keys(%servers)) {
1.1300 raeburn 1765: $servers{$server} =~ s/\&$//;
1766: if ($namespace eq 'ids') {
1767: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1768: } elsif ($namespace eq 'clickers') {
1769: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
1770: }
1.1231 raeburn 1771: }
1772: return %result;
1773: }
1774:
1.1300 raeburn 1775: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
1776:
1777: sub updateclickers {
1778: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
1779: my %clickers;
1780: if (ref($idshashref) eq 'HASH') {
1781: %clickers=%{$idshashref};
1782: } else {
1783: return;
1784: }
1785: my $items='';
1786: foreach my $item (keys(%clickers)) {
1787: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
1788: }
1789: $items=~s/\&$//;
1790: my $request = "updateclickers:$udom:$action:$items";
1791: if ($critical) {
1792: return &critical($request,$uhome);
1793: } else {
1794: return &reply($request,$uhome);
1795: }
1796: }
1797:
1.1023 raeburn 1798: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1799: sub dump_dom {
1.1165 droeschl 1800: my ($namespace, $udom, $regexp) = @_;
1801:
1802: $udom ||= $env{'user.domain'};
1803:
1804: return () unless $udom;
1805:
1806: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1807: }
1808:
1.1023 raeburn 1809: # ------------------------------------------ get items from domain db files
1.806 raeburn 1810:
1811: sub get_dom {
1.860 raeburn 1812: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1813: return if ($udom eq 'public');
1.806 raeburn 1814: my $items='';
1815: foreach my $item (@$storearr) {
1816: $items.=&escape($item).'&';
1817: }
1818: $items=~s/\&$//;
1.860 raeburn 1819: if (!$udom) {
1820: $udom=$env{'user.domain'};
1.1267 raeburn 1821: return if ($udom eq 'public');
1.860 raeburn 1822: if (defined(&domain($udom,'primary'))) {
1823: $uhome=&domain($udom,'primary');
1824: } else {
1.874 albertel 1825: undef($uhome);
1.860 raeburn 1826: }
1827: } else {
1828: if (!$uhome) {
1829: if (defined(&domain($udom,'primary'))) {
1830: $uhome=&domain($udom,'primary');
1831: }
1832: }
1833: }
1834: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1835: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1836: my %returnhash;
1.875 albertel 1837: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1838: return %returnhash;
1839: }
1.806 raeburn 1840: my @pairs=split(/\&/,$rep);
1841: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1842: return @pairs;
1843: }
1844: my $i=0;
1845: foreach my $item (@$storearr) {
1846: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1847: $i++;
1848: }
1849: return %returnhash;
1850: } else {
1.880 banghart 1851: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1852: }
1853: }
1854:
1855: # -------------------------------------------- put items in domain db files
1856:
1857: sub put_dom {
1.860 raeburn 1858: my ($namespace,$storehash,$udom,$uhome)=@_;
1859: if (!$udom) {
1860: $udom=$env{'user.domain'};
1861: if (defined(&domain($udom,'primary'))) {
1862: $uhome=&domain($udom,'primary');
1863: } else {
1.874 albertel 1864: undef($uhome);
1.860 raeburn 1865: }
1866: } else {
1867: if (!$uhome) {
1868: if (defined(&domain($udom,'primary'))) {
1869: $uhome=&domain($udom,'primary');
1870: }
1871: }
1872: }
1873: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1874: my $items='';
1875: foreach my $item (keys(%$storehash)) {
1876: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1877: }
1878: $items=~s/\&$//;
1879: return &reply("putdom:$udom:$namespace:$items",$uhome);
1880: } else {
1.860 raeburn 1881: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1882: }
1883: }
1884:
1.1023 raeburn 1885: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1886: sub newput_dom {
1.1023 raeburn 1887: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1888: my $result;
1889: if (!$udom) {
1890: $udom=$env{'user.domain'};
1891: }
1.1023 raeburn 1892: if ($udom) {
1893: my $uname = &get_domainconfiguser($udom);
1894: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1895: }
1896: return $result;
1897: }
1898:
1.1023 raeburn 1899: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1900: sub del_dom {
1.1023 raeburn 1901: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1902: if (ref($storearr) eq 'ARRAY') {
1903: if (!$udom) {
1904: $udom=$env{'user.domain'};
1905: }
1.1023 raeburn 1906: if ($udom) {
1907: my $uname = &get_domainconfiguser($udom);
1908: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1909: }
1910: }
1911: }
1912:
1.1023 raeburn 1913: # ----------------------------------construct domainconfig user for a domain
1914: sub get_domainconfiguser {
1915: my ($udom) = @_;
1916: return $udom.'-domainconfig';
1917: }
1918:
1.837 raeburn 1919: sub retrieve_inst_usertypes {
1920: my ($udom) = @_;
1921: my (%returnhash,@order);
1.989 raeburn 1922: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1923: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1924: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1925: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1926: } else {
1927: if (defined(&domain($udom,'primary'))) {
1928: my $uhome=&domain($udom,'primary');
1929: my $rep=&reply("inst_usertypes:$udom",$uhome);
1930: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1931: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1932: return (\%returnhash,\@order);
1933: }
1934: my ($hashitems,$orderitems) = split(/:/,$rep);
1935: my @pairs=split(/\&/,$hashitems);
1936: foreach my $item (@pairs) {
1937: my ($key,$value)=split(/=/,$item,2);
1938: $key = &unescape($key);
1939: next if ($key =~ /^error: 2 /);
1940: $returnhash{$key}=&thaw_unescape($value);
1941: }
1942: my @esc_order = split(/\&/,$orderitems);
1943: foreach my $item (@esc_order) {
1944: push(@order,&unescape($item));
1945: }
1946: } else {
1.1256 raeburn 1947: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1948: }
1.1256 raeburn 1949: return (\%returnhash,\@order);
1.837 raeburn 1950: }
1951: }
1952:
1.868 raeburn 1953: sub is_domainimage {
1954: my ($url) = @_;
1.1306 raeburn 1955: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1956: if (&domain($1) ne '') {
1957: return '1';
1958: }
1959: }
1960: return;
1961: }
1962:
1.899 raeburn 1963: sub inst_directory_query {
1964: my ($srch) = @_;
1965: my $udom = $srch->{'srchdomain'};
1966: my %results;
1967: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1968: my $outcome;
1.899 raeburn 1969: if ($homeserver ne '') {
1.904 albertel 1970: my $queryid=&reply("querysend:instdirsearch:".
1971: &escape($srch->{'srchby'}).':'.
1972: &escape($srch->{'srchterm'}).':'.
1973: &escape($srch->{'srchtype'}),$homeserver);
1974: my $host=&hostname($homeserver);
1975: if ($queryid !~/^\Q$host\E\_/) {
1976: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1977: return;
1978: }
1979: my $response = &get_query_reply($queryid);
1980: my $maxtries = 5;
1981: my $tries = 1;
1982: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1983: $response = &get_query_reply($queryid);
1984: $tries ++;
1985: }
1986:
1987: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1988: if ($response eq 'unavailable') {
1989: $outcome = $response;
1990: } else {
1991: $outcome = 'ok';
1992: my @matches = split(/\n/,$response);
1993: foreach my $match (@matches) {
1994: my ($key,$value) = split(/=/,$match);
1995: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1996: }
1.899 raeburn 1997: }
1998: }
1999: }
1.909 raeburn 2000: return ($outcome,%results);
1.899 raeburn 2001: }
2002:
2003: sub usersearch {
2004: my ($srch) = @_;
2005: my $dom = $srch->{'srchdomain'};
2006: my %results;
2007: my %libserv = &all_library();
2008: my $query = 'usersearch';
2009: foreach my $tryserver (keys(%libserv)) {
2010: if (&host_domain($tryserver) eq $dom) {
2011: my $host=&hostname($tryserver);
2012: my $queryid=
1.911 raeburn 2013: &reply("querysend:".&escape($query).':'.
2014: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2015: &escape($srch->{'srchtype'}).':'.
2016: &escape($srch->{'srchterm'}),$tryserver);
2017: if ($queryid !~/^\Q$host\E\_/) {
2018: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2019: next;
1.899 raeburn 2020: }
2021: my $reply = &get_query_reply($queryid);
2022: my $maxtries = 1;
2023: my $tries = 1;
2024: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2025: $reply = &get_query_reply($queryid);
2026: $tries ++;
2027: }
2028: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2029: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2030: } else {
1.911 raeburn 2031: my @matches;
2032: if ($reply =~ /\n/) {
2033: @matches = split(/\n/,$reply);
2034: } else {
2035: @matches = split(/\&/,$reply);
2036: }
1.899 raeburn 2037: foreach my $match (@matches) {
2038: my ($uname,$udom,%userhash);
1.911 raeburn 2039: foreach my $entry (split(/:/,$match)) {
2040: my ($key,$value) =
2041: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2042: $userhash{$key} = $value;
2043: if ($key eq 'username') {
2044: $uname = $value;
2045: } elsif ($key eq 'domain') {
2046: $udom = $value;
1.911 raeburn 2047: }
1.899 raeburn 2048: }
2049: $results{$uname.':'.$udom} = \%userhash;
2050: }
2051: }
2052: }
2053: }
2054: return %results;
2055: }
2056:
1.912 raeburn 2057: sub get_instuser {
2058: my ($udom,$uname,$id) = @_;
2059: my $homeserver = &domain($udom,'primary');
2060: my ($outcome,%results);
2061: if ($homeserver ne '') {
2062: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2063: &escape($id).':'.&escape($udom),$homeserver);
2064: my $host=&hostname($homeserver);
2065: if ($queryid !~/^\Q$host\E\_/) {
2066: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2067: return;
2068: }
2069: my $response = &get_query_reply($queryid);
2070: my $maxtries = 5;
2071: my $tries = 1;
2072: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2073: $response = &get_query_reply($queryid);
2074: $tries ++;
2075: }
2076: if (!&error($response) && $response ne 'refused') {
2077: if ($response eq 'unavailable') {
2078: $outcome = $response;
2079: } else {
2080: $outcome = 'ok';
2081: my @matches = split(/\n/,$response);
2082: foreach my $match (@matches) {
2083: my ($key,$value) = split(/=/,$match);
2084: $results{&unescape($key)} = &thaw_unescape($value);
2085: }
2086: }
2087: }
2088: }
2089: my %userinfo;
2090: if (ref($results{$uname}) eq 'HASH') {
2091: %userinfo = %{$results{$uname}};
2092: }
2093: return ($outcome,%userinfo);
2094: }
2095:
1.1290 raeburn 2096: sub get_multiple_instusers {
2097: my ($udom,$users,$caller) = @_;
2098: my ($outcome,$results);
2099: if (ref($users) eq 'HASH') {
2100: my $count = keys(%{$users});
2101: my $requested = &freeze_escape($users);
2102: my $homeserver = &domain($udom,'primary');
2103: if ($homeserver ne '') {
2104: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2105: my $host=&hostname($homeserver);
2106: if ($queryid !~/^\Q$host\E\_/) {
2107: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2108: ' for host: '.$homeserver.'in domain '.$udom);
2109: return ($outcome,$results);
2110: }
2111: my $response = &get_query_reply($queryid);
2112: my $maxtries = 5;
2113: if ($count > 100) {
2114: $maxtries = 1+int($count/20);
2115: }
2116: my $tries = 1;
2117: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2118: $response = &get_query_reply($queryid);
2119: $tries ++;
2120: }
2121: if ($response eq '') {
2122: $results = {};
2123: foreach my $key (keys(%{$users})) {
2124: my ($uname,$id);
2125: if ($caller eq 'id') {
2126: $id = $key;
2127: } else {
2128: $uname = $key;
2129: }
2130: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2131: $outcome = $resp;
1.1290 raeburn 2132: if ($resp eq 'ok') {
2133: %{$results} = (%{$results}, %info);
2134: } else {
2135: last;
2136: }
2137: }
2138: } elsif(!&error($response) && ($response ne 'refused')) {
2139: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2140: $outcome = $response;
2141: } else {
1.1291 raeburn 2142: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2143: if ($outcome eq 'ok') {
2144: $results = &thaw_unescape($userdata);
2145: }
2146: }
2147: }
2148: }
2149: }
2150: return ($outcome,$results);
2151: }
2152:
1.912 raeburn 2153: sub inst_rulecheck {
1.923 raeburn 2154: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2155: my %returnhash;
2156: if ($udom ne '') {
2157: if (ref($rules) eq 'ARRAY') {
2158: @{$rules} = map {&escape($_);} (@{$rules});
2159: my $rulestr = join(':',@{$rules});
2160: my $homeserver=&domain($udom,'primary');
2161: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2162: my $response;
2163: if ($item eq 'username') {
2164: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2165: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2166: $homeserver));
1.923 raeburn 2167: } elsif ($item eq 'id') {
2168: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2169: ':'.&escape($id).':'.$rulestr,
2170: $homeserver));
1.945 raeburn 2171: } elsif ($item eq 'selfcreate') {
2172: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2173: &escape($udom).':'.&escape($uname).
2174: ':'.$rulestr,$homeserver));
1.923 raeburn 2175: }
1.912 raeburn 2176: if ($response ne 'refused') {
2177: my @pairs=split(/\&/,$response);
2178: foreach my $item (@pairs) {
2179: my ($key,$value)=split(/=/,$item,2);
2180: $key = &unescape($key);
2181: next if ($key =~ /^error: 2 /);
2182: $returnhash{$key}=&thaw_unescape($value);
2183: }
2184: }
2185: }
2186: }
2187: }
2188: return %returnhash;
2189: }
2190:
2191: sub inst_userrules {
1.923 raeburn 2192: my ($udom,$check) = @_;
1.912 raeburn 2193: my (%ruleshash,@ruleorder);
2194: if ($udom ne '') {
2195: my $homeserver=&domain($udom,'primary');
2196: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2197: my $response;
2198: if ($check eq 'id') {
2199: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2200: $homeserver);
1.943 raeburn 2201: } elsif ($check eq 'email') {
2202: $response=&reply('instemailrules:'.&escape($udom),
2203: $homeserver);
1.923 raeburn 2204: } else {
2205: $response=&reply('instuserrules:'.&escape($udom),
2206: $homeserver);
2207: }
1.912 raeburn 2208: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2209: ($response ne 'unknown_cmd') &&
1.912 raeburn 2210: ($response ne 'no_such_host')) {
2211: my ($hashitems,$orderitems) = split(/:/,$response);
2212: my @pairs=split(/\&/,$hashitems);
2213: foreach my $item (@pairs) {
2214: my ($key,$value)=split(/=/,$item,2);
2215: $key = &unescape($key);
2216: next if ($key =~ /^error: 2 /);
2217: $ruleshash{$key}=&thaw_unescape($value);
2218: }
2219: my @esc_order = split(/\&/,$orderitems);
2220: foreach my $item (@esc_order) {
2221: push(@ruleorder,&unescape($item));
2222: }
2223: }
2224: }
2225: }
2226: return (\%ruleshash,\@ruleorder);
2227: }
2228:
1.976 raeburn 2229: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2230:
2231: sub get_domain_defaults {
1.1240 raeburn 2232: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2233: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2234: my $cachetime = 60*60*24;
1.1240 raeburn 2235: unless ($ignore_cache) {
2236: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2237: if (defined($cached)) {
2238: if (ref($result) eq 'HASH') {
2239: return %{$result};
2240: }
1.943 raeburn 2241: }
2242: }
2243: my %domdefaults;
2244: my %domconfig =
1.989 raeburn 2245: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2246: 'requestcourses','inststatus',
1.1183 raeburn 2247: 'coursedefaults','usersessions',
1.1258 raeburn 2248: 'requestauthor','selfenrollment',
1.1320 raeburn 2249: 'coursecategories','ssl','autoenroll',
1.1332 raeburn 2250: 'trust','helpsettings'],$domain);
1.1305 raeburn 2251: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2252: if (ref($domconfig{'defaults'}) eq 'HASH') {
2253: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2254: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2255: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2256: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2257: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2258: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2259: } else {
2260: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2261: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2262: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2263: }
1.976 raeburn 2264: if (ref($domconfig{'quotas'}) eq 'HASH') {
2265: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2266: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2267: } else {
2268: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2269: }
1.1177 raeburn 2270: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2271: foreach my $item (@usertools) {
2272: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2273: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2274: }
2275: }
1.1229 raeburn 2276: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2277: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2278: }
1.976 raeburn 2279: }
1.985 raeburn 2280: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2281: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2282: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2283: }
2284: }
1.1183 raeburn 2285: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2286: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2287: }
1.989 raeburn 2288: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2289: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2290: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2291: }
2292: }
1.1047 raeburn 2293: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2294: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2295: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2296: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2297: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2298: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2299: }
1.1254 raeburn 2300: foreach my $type (@coursetypes) {
2301: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2302: unless ($type eq 'community') {
2303: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2304: }
2305: }
2306: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2307: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2308: }
1.1277 raeburn 2309: if ($domdefaults{'postsubmit'} eq 'on') {
2310: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2311: $domdefaults{$type.'postsubtimeout'} =
2312: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2313: }
2314: }
1.1230 raeburn 2315: }
1.1286 raeburn 2316: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2317: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2318: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2319: if (@clonecodes) {
2320: $domdefaults{'canclone'} = join('+',@clonecodes);
2321: }
2322: }
2323: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2324: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2325: }
1.1047 raeburn 2326: }
1.1073 raeburn 2327: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2328: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2329: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2330: }
2331: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2332: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2333: }
1.1279 raeburn 2334: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2335: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2336: }
1.1073 raeburn 2337: }
1.1254 raeburn 2338: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2339: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2340: my @settings = ('types','registered','enroll_dates','access_dates','section',
2341: 'approval','limit');
2342: foreach my $type (@coursetypes) {
2343: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2344: my @mgrdc = ();
2345: foreach my $item (@settings) {
2346: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2347: push(@mgrdc,$item);
2348: }
2349: }
2350: if (@mgrdc) {
2351: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2352: }
2353: }
2354: }
2355: }
2356: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2357: foreach my $type (@coursetypes) {
2358: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2359: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2360: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2361: }
2362: }
2363: }
2364: }
2365: }
1.1258 raeburn 2366: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2367: $domdefaults{'catauth'} = 'std';
2368: $domdefaults{'catunauth'} = 'std';
2369: if ($domconfig{'coursecategories'}{'auth'}) {
2370: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2371: }
2372: if ($domconfig{'coursecategories'}{'unauth'}) {
2373: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2374: }
2375: }
1.1315 raeburn 2376: if (ref($domconfig{'ssl'}) eq 'HASH') {
2377: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2378: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2379: }
2380: if (ref($domconfig{'ssl'}{'connect'}) eq 'HASH') {
2381: $domdefaults{'connect'} = $domconfig{'ssl'}{'connect'};
2382: }
2383: }
1.1320 raeburn 2384: if (ref($domconfig{'trust'}) eq 'HASH') {
2385: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2386: foreach my $prefix (@prefixes) {
2387: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2388: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2389: }
2390: }
2391: }
1.1314 raeburn 2392: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2393: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2394: }
1.1332 raeburn 2395: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2396: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2397: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2398: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2399: }
2400: }
1.1219 raeburn 2401: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2402: return %domdefaults;
2403: }
2404:
1.1311 raeburn 2405: sub course_portal_url {
2406: my ($cnum,$cdom) = @_;
2407: my $chome = &homeserver($cnum,$cdom);
2408: my $hostname = &hostname($chome);
2409: my $protocol = $protocol{$chome};
2410: $protocol = 'http' if ($protocol ne 'https');
2411: my %domdefaults = &get_domain_defaults($cdom);
2412: my $firsturl;
2413: if ($domdefaults{'portal_def'}) {
2414: $firsturl = $domdefaults{'portal_def'};
2415: } else {
2416: $firsturl = $protocol.'://'.$hostname;
2417: }
2418: return $firsturl;
2419: }
2420:
1.344 www 2421: # --------------------------------------------------- Assign a key to a student
2422:
2423: sub assign_access_key {
1.364 www 2424: #
2425: # a valid key looks like uname:udom#comments
2426: # comments are being appended
2427: #
1.498 www 2428: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2429: $kdom=
1.620 albertel 2430: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2431: $knum=
1.620 albertel 2432: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2433: $cdom=
1.620 albertel 2434: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2435: $cnum=
1.620 albertel 2436: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2437: $udom=$env{'user.name'} unless (defined($udom));
2438: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2439: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2440: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2441: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2442: # assigned to this person
2443: # - this should not happen,
1.345 www 2444: # unless something went wrong
2445: # the first time around
2446: # ready to assign
1.364 www 2447: $logentry=$1.'; '.$logentry;
1.496 www 2448: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2449: $kdom,$knum) eq 'ok') {
1.345 www 2450: # key now belongs to user
1.346 www 2451: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2452: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2453: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2454: return 'ok';
2455: } else {
2456: return
2457: 'error: Count not permanently assign key, will need to be re-entered later.';
2458: }
2459: } else {
2460: return 'error: Could not assign key, try again later.';
2461: }
1.364 www 2462: } elsif (!$existing{$ckey}) {
1.345 www 2463: # the key does not exist
2464: return 'error: The key does not exist';
2465: } else {
2466: # the key is somebody else's
2467: return 'error: The key is already in use';
2468: }
1.344 www 2469: }
2470:
1.364 www 2471: # ------------------------------------------ put an additional comment on a key
2472:
2473: sub comment_access_key {
2474: #
2475: # a valid key looks like uname:udom#comments
2476: # comments are being appended
2477: #
2478: my ($ckey,$cdom,$cnum,$logentry)=@_;
2479: $cdom=
1.620 albertel 2480: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2481: $cnum=
1.620 albertel 2482: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2483: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2484: if ($existing{$ckey}) {
2485: $existing{$ckey}.='; '.$logentry;
2486: # ready to assign
1.367 www 2487: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2488: $cdom,$cnum) eq 'ok') {
2489: return 'ok';
2490: } else {
2491: return 'error: Count not store comment.';
2492: }
2493: } else {
2494: # the key does not exist
2495: return 'error: The key does not exist';
2496: }
2497: }
2498:
1.344 www 2499: # ------------------------------------------------------ Generate a set of keys
2500:
2501: sub generate_access_keys {
1.364 www 2502: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2503: $cdom=
1.620 albertel 2504: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2505: $cnum=
1.620 albertel 2506: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2507: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2508: unless (($cdom) && ($cnum)) { return 0; }
2509: if ($number>10000) { return 0; }
2510: sleep(2); # make sure don't get same seed twice
2511: srand(time()^($$+($$<<15))); # from "Programming Perl"
2512: my $total=0;
2513: for (my $i=1;$i<=$number;$i++) {
2514: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2515: sprintf("%lx",int(100000*rand)).'-'.
2516: sprintf("%lx",int(100000*rand));
2517: $newkey=~s/1/g/g; # folks mix up 1 and l
2518: $newkey=~s/0/h/g; # and also 0 and O
2519: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2520: if ($existing{$newkey}) {
2521: $i--;
2522: } else {
1.364 www 2523: if (&put('accesskeys',
2524: { $newkey => '# generated '.localtime().
1.620 albertel 2525: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2526: '; '.$logentry },
2527: $cdom,$cnum) eq 'ok') {
1.344 www 2528: $total++;
2529: }
2530: }
2531: }
1.620 albertel 2532: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2533: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2534: return $total;
2535: }
2536:
2537: # ------------------------------------------------------- Validate an accesskey
2538:
2539: sub validate_access_key {
2540: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2541: $cdom=
1.620 albertel 2542: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2543: $cnum=
1.620 albertel 2544: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2545: $udom=$env{'user.domain'} unless (defined($udom));
2546: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2547: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2548: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2549: }
2550:
2551: # ------------------------------------- Find the section of student in a course
1.652 albertel 2552: sub devalidate_getsection_cache {
2553: my ($udom,$unam,$courseid)=@_;
2554: my $hashid="$udom:$unam:$courseid";
2555: &devalidate_cache_new('getsection',$hashid);
2556: }
1.298 matthew 2557:
1.815 albertel 2558: sub courseid_to_courseurl {
2559: my ($courseid) = @_;
2560: #already url style courseid
2561: return $courseid if ($courseid =~ m{^/});
2562:
2563: if (exists($env{'course.'.$courseid.'.num'})) {
2564: my $cnum = $env{'course.'.$courseid.'.num'};
2565: my $cdom = $env{'course.'.$courseid.'.domain'};
2566: return "/$cdom/$cnum";
2567: }
2568:
2569: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2570: if (exists($courseinfo{'num'})) {
2571: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2572: }
2573:
2574: return undef;
2575: }
2576:
1.298 matthew 2577: sub getsection {
2578: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2579: my $cachetime=1800;
1.551 albertel 2580:
2581: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2582: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2583: if (defined($cached)) { return $result; }
2584:
1.298 matthew 2585: my %Pending;
2586: my %Expired;
2587: #
2588: # Each role can either have not started yet (pending), be active,
2589: # or have expired.
2590: #
2591: # If there is an active role, we are done.
2592: #
2593: # If there is more than one role which has not started yet,
2594: # choose the one which will start sooner
2595: # If there is one role which has not started yet, return it.
2596: #
2597: # If there is more than one expired role, choose the one which ended last.
2598: # If there is a role which has expired, return it.
2599: #
1.815 albertel 2600: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2601: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2602: foreach my $key (keys(%roleshash)) {
1.479 albertel 2603: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2604: my $section=$1;
2605: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2606: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2607: my $now=time;
1.548 albertel 2608: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2609: $Expired{$end}=$section;
2610: next;
2611: }
1.548 albertel 2612: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2613: $Pending{$start}=$section;
2614: next;
2615: }
1.599 albertel 2616: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2617: }
2618: #
2619: # Presumedly there will be few matching roles from the above
2620: # loop and the sorting time will be negligible.
2621: if (scalar(keys(%Pending))) {
2622: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2623: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2624: }
2625: if (scalar(keys(%Expired))) {
2626: my @sorted = sort {$a <=> $b} keys(%Expired);
2627: my $time = pop(@sorted);
1.599 albertel 2628: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2629: }
1.599 albertel 2630: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2631: }
1.70 www 2632:
1.599 albertel 2633: sub save_cache {
2634: &purge_remembered();
1.722 albertel 2635: #&Apache::loncommon::validate_page();
1.620 albertel 2636: undef(%env);
1.780 albertel 2637: undef($env_loaded);
1.599 albertel 2638: }
1.452 albertel 2639:
1.599 albertel 2640: my $to_remember=-1;
2641: my %remembered;
2642: my %accessed;
2643: my $kicks=0;
2644: my $hits=0;
1.849 albertel 2645: sub make_key {
2646: my ($name,$id) = @_;
1.872 albertel 2647: if (length($id) > 65
2648: && length(&escape($id)) > 200) {
2649: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2650: }
1.849 albertel 2651: return &escape($name.':'.$id);
2652: }
2653:
1.599 albertel 2654: sub devalidate_cache_new {
2655: my ($name,$id,$debug) = @_;
2656: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 2657: my $remembered_id=$name.':'.$id;
1.849 albertel 2658: $id=&make_key($name,$id);
1.599 albertel 2659: $memcache->delete($id);
1.1319 damieng 2660: delete($remembered{$remembered_id});
2661: delete($accessed{$remembered_id});
1.599 albertel 2662: }
2663:
2664: sub is_cached_new {
2665: my ($name,$id,$debug) = @_;
1.1319 damieng 2666: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
2667: if (exists($remembered{$remembered_id})) {
2668: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2669: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2670: $hits++;
1.1319 damieng 2671: return ($remembered{$remembered_id},1);
1.599 albertel 2672: }
1.1319 damieng 2673: $id=&make_key($name,$id);
1.599 albertel 2674: my $value = $memcache->get($id);
2675: if (!(defined($value))) {
2676: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2677: return (undef,undef);
1.416 albertel 2678: }
1.599 albertel 2679: if ($value eq '__undef__') {
2680: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2681: $value=undef;
2682: }
1.1319 damieng 2683: &make_room($remembered_id,$value,$debug);
1.599 albertel 2684: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2685: return ($value,1);
2686: }
2687:
2688: sub do_cache_new {
2689: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 2690: my $remembered_id=$name.':'.$id;
1.849 albertel 2691: $id=&make_key($name,$id);
1.599 albertel 2692: my $setvalue=$value;
2693: if (!defined($setvalue)) {
2694: $setvalue='__undef__';
2695: }
1.623 albertel 2696: if (!defined($time) ) {
2697: $time=600;
2698: }
1.599 albertel 2699: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2700: my $result = $memcache->set($id,$setvalue,$time);
2701: if (! $result) {
1.872 albertel 2702: &logthis("caching of id -> $id failed");
1.910 albertel 2703: $memcache->disconnect_all();
1.872 albertel 2704: }
1.600 albertel 2705: # need to make a copy of $value
1.1319 damieng 2706: &make_room($remembered_id,$value,$debug);
1.599 albertel 2707: return $value;
2708: }
2709:
2710: sub make_room {
1.1319 damieng 2711: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2712:
1.1319 damieng 2713: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2714: : $value;
1.599 albertel 2715: if ($to_remember<0) { return; }
1.1319 damieng 2716: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2717: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2718: my $to_kick;
2719: my $max_time=0;
2720: foreach my $other (keys(%accessed)) {
2721: if (&tv_interval($accessed{$other}) > $max_time) {
2722: $to_kick=$other;
2723: $max_time=&tv_interval($accessed{$other});
2724: }
2725: }
2726: delete($remembered{$to_kick});
2727: delete($accessed{$to_kick});
2728: $kicks++;
2729: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2730: return;
2731: }
2732:
1.599 albertel 2733: sub purge_remembered {
1.604 albertel 2734: #&logthis("Tossing ".scalar(keys(%remembered)));
2735: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2736: undef(%remembered);
2737: undef(%accessed);
1.428 albertel 2738: }
1.70 www 2739: # ------------------------------------- Read an entry from a user's environment
2740:
2741: sub userenvironment {
2742: my ($udom,$unam,@what)=@_;
1.976 raeburn 2743: my $items;
2744: foreach my $item (@what) {
2745: $items.=&escape($item).'&';
2746: }
2747: $items=~s/\&$//;
1.70 www 2748: my %returnhash=();
1.1009 raeburn 2749: my $uhome = &homeserver($unam,$udom);
2750: unless ($uhome eq 'no_host') {
2751: my @answer=split(/\&/,
2752: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2753: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2754: return %returnhash;
2755: }
1.1009 raeburn 2756: my $i;
2757: for ($i=0;$i<=$#what;$i++) {
2758: $returnhash{$what[$i]}=&unescape($answer[$i]);
2759: }
1.70 www 2760: }
2761: return %returnhash;
1.1 albertel 2762: }
2763:
1.617 albertel 2764: # ---------------------------------------------------------- Get a studentphoto
2765: sub studentphoto {
2766: my ($udom,$unam,$ext) = @_;
2767: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2768: if (defined($env{'request.course.id'})) {
1.708 raeburn 2769: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2770: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2771: return(&retrievestudentphoto($udom,$unam,$ext));
2772: } else {
2773: my ($result,$perm_reqd)=
1.707 albertel 2774: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2775: if ($result eq 'ok') {
2776: if (!($perm_reqd eq 'yes')) {
2777: return(&retrievestudentphoto($udom,$unam,$ext));
2778: }
2779: }
2780: }
2781: }
2782: } else {
2783: my ($result,$perm_reqd) =
1.707 albertel 2784: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2785: if ($result eq 'ok') {
2786: if (!($perm_reqd eq 'yes')) {
2787: return(&retrievestudentphoto($udom,$unam,$ext));
2788: }
2789: }
2790: }
2791: return '/adm/lonKaputt/lonlogo_broken.gif';
2792: }
2793:
2794: sub retrievestudentphoto {
2795: my ($udom,$unam,$ext,$type) = @_;
2796: my $home=&Apache::lonnet::homeserver($unam,$udom);
2797: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2798: if ($ret eq 'ok') {
2799: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2800: if ($type eq 'thumbnail') {
2801: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2802: }
2803: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2804: return $tokenurl;
2805: } else {
2806: if ($type eq 'thumbnail') {
2807: return '/adm/lonKaputt/genericstudent_tn.gif';
2808: } else {
2809: return '/adm/lonKaputt/lonlogo_broken.gif';
2810: }
1.617 albertel 2811: }
2812: }
2813:
1.263 www 2814: # -------------------------------------------------------------------- New chat
2815:
2816: sub chatsend {
1.724 raeburn 2817: my ($newentry,$anon,$group)=@_;
1.620 albertel 2818: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2819: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2820: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2821: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2822: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2823: &escape($newentry)).':'.$group,$chome);
1.292 www 2824: }
2825:
2826: # ------------------------------------------ Find current version of a resource
2827:
2828: sub getversion {
2829: my $fname=&clutter(shift);
1.1189 raeburn 2830: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2831: return ¤tversion(&filelocation('',$fname));
2832: }
2833:
2834: sub currentversion {
2835: my $fname=shift;
2836: my $author=$fname;
2837: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2838: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2839: my $home=&homeserver($uname,$udom);
1.292 www 2840: if ($home eq 'no_host') {
2841: return -1;
2842: }
1.1112 www 2843: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2844: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2845: return -1;
2846: }
1.1112 www 2847: return $answer;
1.263 www 2848: }
2849:
1.1111 www 2850: #
2851: # Return special version number of resource if set by override, empty otherwise
2852: #
2853: sub usedversion {
2854: my $fname=shift;
2855: unless ($fname) { $fname=$env{'request.uri'}; }
2856: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2857: if ($urlversion) { return $urlversion; }
2858: return '';
2859: }
2860:
1.1 albertel 2861: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2862:
1.1 albertel 2863: sub subscribe {
2864: my $fname=shift;
1.761 raeburn 2865: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2866: $fname=~s/[\n\r]//g;
1.1 albertel 2867: my $author=$fname;
2868: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2869: my ($udom,$uname)=split(/\//,$author);
2870: my $home=homeserver($uname,$udom);
1.335 albertel 2871: if ($home eq 'no_host') {
2872: return 'not_found';
1.1 albertel 2873: }
2874: my $answer=reply("sub:$fname",$home);
1.64 www 2875: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2876: $answer.=' by '.$home;
2877: }
1.1 albertel 2878: return $answer;
2879: }
2880:
1.8 www 2881: # -------------------------------------------------------------- Replicate file
2882:
2883: sub repcopy {
2884: my $filename=shift;
1.23 www 2885: $filename=~s/\/+/\//g;
1.1142 raeburn 2886: my $londocroot = $perlvar{'lonDocRoot'};
2887: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2888: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2889: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2890: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2891: return &repcopy_userfile($filename);
2892: }
1.532 albertel 2893: $filename=~s/[\n\r]//g;
1.8 www 2894: my $transname="$filename.in.transfer";
1.828 www 2895: # FIXME: this should flock
1.607 raeburn 2896: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2897: my $remoteurl=subscribe($filename);
1.64 www 2898: if ($remoteurl =~ /^con_lost by/) {
2899: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2900: return 'unavailable';
1.8 www 2901: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2902: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2903: return 'not_found';
1.64 www 2904: } elsif ($remoteurl =~ /^rejected by/) {
2905: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2906: return 'forbidden';
1.20 www 2907: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2908: return 'ok';
1.8 www 2909: } else {
1.290 www 2910: my $author=$filename;
2911: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2912: my ($udom,$uname)=split(/\//,$author);
2913: my $home=homeserver($uname,$udom);
2914: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2915: my @parts=split(/\//,$filename);
2916: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2917: if ($path ne "$londocroot/res") {
1.8 www 2918: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2919: return 'bad_request';
1.8 www 2920: }
2921: my $count;
2922: for ($count=5;$count<$#parts;$count++) {
2923: $path.="/$parts[$count]";
2924: if ((-e $path)!=1) {
2925: mkdir($path,0777);
2926: }
2927: }
2928: my $ua=new LWP::UserAgent;
2929: my $request=new HTTP::Request('GET',"$remoteurl");
2930: my $response=$ua->request($request,$transname);
2931: if ($response->is_error()) {
2932: unlink($transname);
2933: my $message=$response->status_line;
1.672 albertel 2934: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2935: ." LWP get: $message: $filename</font>");
1.607 raeburn 2936: return 'unavailable';
1.8 www 2937: } else {
1.16 www 2938: if ($remoteurl!~/\.meta$/) {
2939: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2940: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2941: if ($mresponse->is_error()) {
2942: unlink($filename.'.meta');
2943: &logthis(
1.672 albertel 2944: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2945: }
2946: }
1.8 www 2947: rename($transname,$filename);
1.607 raeburn 2948: return 'ok';
1.8 www 2949: }
1.290 www 2950: }
1.8 www 2951: }
1.330 www 2952: }
2953:
2954: # ------------------------------------------------ Get server side include body
2955: sub ssi_body {
1.381 albertel 2956: my ($filelink,%form)=@_;
1.606 matthew 2957: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2958: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2959: }
1.953 www 2960: my $output='';
2961: my $response;
1.980 raeburn 2962: if ($filelink=~/^https?\:/) {
1.954 raeburn 2963: ($output,$response)=&externalssi($filelink);
1.953 www 2964: } else {
1.1004 droeschl 2965: $filelink .= $filelink=~/\?/ ? '&' : '?';
2966: $filelink .= 'inhibitmenu=yes';
1.953 www 2967: ($output,$response)=&ssi($filelink,%form);
2968: }
1.778 albertel 2969: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2970: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2971: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2972: if (wantarray) {
2973: return ($output, $response);
2974: } else {
2975: return $output;
2976: }
1.8 www 2977: }
2978:
1.15 www 2979: # --------------------------------------------------------- Server Side Include
2980:
1.782 albertel 2981: sub absolute_url {
2982: my ($host_name) = @_;
2983: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2984: if ($host_name eq '') {
2985: $host_name = $ENV{'SERVER_NAME'};
2986: }
2987: return $protocol.$host_name;
2988: }
2989:
1.942 foxr 2990: #
2991: # Server side include.
2992: # Parameters:
2993: # fn Possibly encrypted resource name/id.
2994: # form Hash that describes how the rendering should be done
2995: # and other things.
1.944 foxr 2996: # Returns:
1.950 raeburn 2997: # Scalar context: The content of the response.
2998: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2999: #
1.15 www 3000: sub ssi {
3001:
1.944 foxr 3002: my ($fn,%form)=@_;
1.15 www 3003: my $ua=new LWP::UserAgent;
1.23 www 3004: my $request;
1.711 albertel 3005:
3006: $form{'no_update_last_known'}=1;
1.895 albertel 3007: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3008: if (%form) {
1.782 albertel 3009: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 3010: $request->content(join('&',map {
3011: my $name = escape($_);
3012: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3013: ? join("&$name=", map {escape($_) } @{$form{$_}})
3014: : &escape($form{$_}) );
3015: } keys(%form)));
1.23 www 3016: } else {
1.782 albertel 3017: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3018: }
3019:
1.15 www 3020: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 3021: my $response= $ua->request($request);
1.1182 foxr 3022: my $content = $response->content;
3023:
3024:
1.944 foxr 3025: if (wantarray) {
1.1173 foxr 3026: return ($content, $response);
1.944 foxr 3027: } else {
1.1173 foxr 3028: return $content;
1.942 foxr 3029: }
1.324 www 3030: }
3031:
3032: sub externalssi {
3033: my ($url)=@_;
3034: my $ua=new LWP::UserAgent;
3035: my $request=new HTTP::Request('GET',$url);
3036: my $response=$ua->request($request);
1.954 raeburn 3037: if (wantarray) {
3038: return ($response->content, $response);
3039: } else {
3040: return $response->content;
3041: }
1.15 www 3042: }
1.254 www 3043:
1.492 albertel 3044: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3045:
3046: sub allowuploaded {
3047: my ($srcurl,$url)=@_;
3048: $url=&clutter(&declutter($url));
3049: my $dir=$url;
3050: $dir=~s/\/[^\/]+$//;
3051: my %httpref=();
3052: my $httpurl=&hreflocation('',$url);
3053: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3054: &Apache::lonnet::appenv(\%httpref);
1.254 www 3055: }
1.477 raeburn 3056:
1.1193 raeburn 3057: #
3058: # Determine if the current user should be able to edit a particular resource,
3059: # when viewing in course context.
3060: # (a) When viewing resource used to determine if "Edit" item is included in
3061: # Functions.
3062: # (b) When displaying folder contents in course editor, used to determine if
3063: # "Edit" link will be displayed alongside resource.
3064: #
1.1196 raeburn 3065: # input: six args -- filename (decluttered), course number, course domain,
3066: # url, symb (if registered) and group (if this is a group
3067: # item -- e.g., bulletin board, group page etc.).
3068: # output: array of five scalars --
1.1193 raeburn 3069: # $cfile -- url for file editing if editable on current server
3070: # $home -- homeserver of resource (i.e., for author if published,
3071: # or course if uploaded.).
3072: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3073: # $forceedit -- 1 if icon/link should be to go to edit mode
3074: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3075: #
3076:
3077: sub can_edit_resource {
1.1194 raeburn 3078: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3079: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3080: #
3081: # For aboutme pages user can only edit his/her own.
3082: #
1.1199 raeburn 3083: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3084: my ($sdom,$sname) = ($1,$2);
3085: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3086: $home = $env{'user.home'};
3087: $cfile = $resurl;
3088: if ($env{'form.forceedit'}) {
3089: $forceview = 1;
3090: } else {
3091: $forceedit = 1;
3092: }
3093: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3094: } else {
3095: return;
3096: }
3097: }
3098:
3099: if ($env{'request.course.id'}) {
3100: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3101: if ($group ne '') {
3102: # if this is a group homepage or group bulletin board, check group privs
3103: my $allowed = 0;
1.1197 raeburn 3104: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3105: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3106: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3107: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3108: $allowed = 1;
3109: }
1.1197 raeburn 3110: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3111: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3112: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3113: $allowed = 1;
3114: }
3115: }
3116: if ($allowed) {
3117: $home=&homeserver($cnum,$cdom);
3118: if ($env{'form.forceedit'}) {
3119: $forceview = 1;
3120: } else {
3121: $forceedit = 1;
3122: }
3123: $cfile = $resurl;
3124: } else {
3125: return;
3126: }
3127: } else {
1.1208 raeburn 3128: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3129: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3130: return;
3131: }
3132: } elsif (!$crsedit) {
1.1194 raeburn 3133: #
3134: # No edit allowed where CC has switched to student role.
3135: #
3136: return;
3137: }
3138: }
3139: }
3140:
1.1193 raeburn 3141: if ($file ne '') {
3142: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3143: if (&is_course_upload($file,$cnum,$cdom)) {
3144: $uploaded = 1;
3145: $incourse = 1;
1.1193 raeburn 3146: if ($file =~/\.(htm|html|css|js|txt)$/) {
3147: $cfile = &hreflocation('',$file);
1.1201 raeburn 3148: if ($env{'form.forceedit'}) {
3149: $forceview = 1;
3150: } else {
3151: $forceedit = 1;
3152: }
1.1194 raeburn 3153: }
3154: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3155: $incourse = 1;
3156: if ($env{'form.forceedit'}) {
3157: $forceview = 1;
3158: } else {
3159: $forceedit = 1;
3160: }
3161: $cfile = $resurl;
3162: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3163: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3164: $incourse = 1;
3165: if ($env{'form.forceedit'}) {
3166: $forceview = 1;
3167: } else {
3168: $forceedit = 1;
3169: }
3170: $cfile = $resurl;
1.1199 raeburn 3171: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3172: $incourse = 1;
3173: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3174: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3175: $incourse = 1;
1.1199 raeburn 3176: if ($env{'form.forceedit'}) {
3177: $forceview = 1;
3178: } else {
3179: $forceedit = 1;
3180: }
3181: $cfile = $resurl;
1.1298 raeburn 3182: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
3183: $incourse = 1;
3184: if ($env{'form.forceedit'}) {
3185: $forceview = 1;
3186: } else {
3187: $forceedit = 1;
3188: }
3189: $cfile = $resurl;
1.1208 raeburn 3190: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3191: $incourse = 1;
3192: if ($env{'form.forceedit'}) {
3193: $forceview = 1;
3194: } else {
3195: $forceedit = 1;
3196: }
3197: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3198: }
3199: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3200: my $template = '/res/lib/templates/simpleproblem.problem';
3201: if (&is_on_map($template)) {
3202: $incourse = 1;
3203: $forceview = 1;
3204: $cfile = $template;
1.1193 raeburn 3205: }
1.1199 raeburn 3206: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3207: $incourse = 1;
3208: if ($env{'form.forceedit'}) {
3209: $forceview = 1;
3210: } else {
3211: $forceedit = 1;
3212: }
3213: $cfile = $resurl;
1.1298 raeburn 3214: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3215: $incourse = 1;
3216: if ($env{'form.forceedit'}) {
3217: $forceview = 1;
3218: } else {
3219: $forceedit = 1;
3220: }
3221: $cfile = $resurl;
1.1199 raeburn 3222: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3223: $incourse = 1;
3224: $forceview = 1;
3225: if ($symb) {
3226: my ($map,$id,$res)=&decode_symb($symb);
3227: $env{'request.symb'} = $symb;
3228: $cfile = &clutter($res);
3229: } else {
3230: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3231: my $escfile = &unescape($cfile);
3232: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
3233: $cfile = '/adm/wrapper'.$escfile;
3234: } else {
3235: $escfile =~ s{^http://}{};
3236: $cfile = &escape("/adm/wrapper/ext/$escfile");
3237: }
1.1199 raeburn 3238: }
1.1234 raeburn 3239: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3240: if ($env{'form.forceedit'}) {
3241: $forceview = 1;
3242: } else {
3243: $forceedit = 1;
3244: }
3245: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3246: }
3247: }
1.1194 raeburn 3248: if ($uploaded || $incourse) {
3249: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3250: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3251: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3252: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3253: # Check that the user has permission to edit this resource
3254: my $setpriv = 1;
3255: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3256: if (defined($cfudom)) {
3257: $home=&homeserver($cfuname,$cfudom);
3258: $cfile=$file;
3259: }
3260: }
1.1194 raeburn 3261: if (($cfile ne '') && (!$incourse || $uploaded) &&
3262: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3263: my @ids=¤t_machine_ids();
3264: unless (grep(/^\Q$home\E$/,@ids)) {
3265: $switchserver=1;
3266: }
3267: }
3268: }
1.1194 raeburn 3269: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3270: }
3271:
3272: sub is_course_upload {
3273: my ($file,$cnum,$cdom) = @_;
3274: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3275: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3276: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3277: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3278: return 1;
3279: }
3280: return;
3281: }
3282:
1.1194 raeburn 3283: sub in_course {
1.1195 raeburn 3284: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3285: if ($hideprivileged) {
3286: my $skipuser;
1.1219 raeburn 3287: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3288: my @possdoms = ($cdom);
3289: if ($coursehash{'checkforpriv'}) {
3290: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3291: }
3292: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3293: $skipuser = 1;
3294: if ($coursehash{'nothideprivileged'}) {
3295: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3296: my $user;
3297: if ($item =~ /:/) {
3298: $user = $item;
3299: } else {
3300: $user = join(':',split(/[\@]/,$item));
3301: }
3302: if ($user eq $uname.':'.$udom) {
3303: undef($skipuser);
3304: last;
3305: }
3306: }
3307: }
3308: if ($skipuser) {
3309: return 0;
3310: }
3311: }
3312: }
1.1194 raeburn 3313: $type ||= 'any';
3314: if (!defined($cdom) || !defined($cnum)) {
3315: my $cid = $env{'request.course.id'};
3316: $cdom = $env{'course.'.$cid.'.domain'};
3317: $cnum = $env{'course.'.$cid.'.num'};
3318: }
3319: my $typesref;
1.1195 raeburn 3320: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3321: $typesref = ['active','previous','future'];
3322: } elsif ($type eq 'previous' || $type eq 'future') {
3323: $typesref = [$type];
3324: }
3325: my %roles = &get_my_roles($uname,$udom,'userroles',
3326: $typesref,undef,[$cdom]);
3327: my ($tmp) = keys(%roles);
3328: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3329: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3330: if (@course_roles > 0) {
3331: return 1;
3332: }
3333: return 0;
3334: }
3335:
1.478 albertel 3336: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3337: # input: action, courseID, current domain, intended
1.637 raeburn 3338: # path to file, source of file, instruction to parse file for objects,
3339: # ref to hash for embedded objects,
3340: # ref to hash for codebase of java objects.
1.1095 raeburn 3341: # reference to scalar to accommodate mime type determined
3342: # from File::MMagic if $parser = parse.
1.637 raeburn 3343: #
1.485 raeburn 3344: # output: url to file (if action was uploaddoc),
3345: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3346: #
1.478 albertel 3347: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3348: # course.
1.477 raeburn 3349: #
1.478 albertel 3350: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3351: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3352: # course's home server.
1.477 raeburn 3353: #
1.478 albertel 3354: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3355: # be copied from $source (current location) to
3356: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3357: # and will then be copied to
3358: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3359: # course's home server.
1.485 raeburn 3360: #
1.481 raeburn 3361: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3362: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3363: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3364: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3365: # in course's home server.
1.637 raeburn 3366: #
1.477 raeburn 3367:
3368: sub process_coursefile {
1.1095 raeburn 3369: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3370: $mimetype)=@_;
1.477 raeburn 3371: my $fetchresult;
1.638 albertel 3372: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3373: if ($action eq 'propagate') {
1.638 albertel 3374: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3375: $home);
1.481 raeburn 3376: } else {
1.477 raeburn 3377: my $fpath = '';
3378: my $fname = $file;
1.478 albertel 3379: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3380: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3381: my $filepath = &build_filepath($fpath);
1.481 raeburn 3382: if ($action eq 'copy') {
3383: if ($source eq '') {
3384: $fetchresult = 'no source file';
3385: return $fetchresult;
3386: } else {
3387: my $destination = $filepath.'/'.$fname;
3388: rename($source,$destination);
3389: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3390: $home);
1.481 raeburn 3391: }
3392: } elsif ($action eq 'uploaddoc') {
3393: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3394: print $fh $env{'form.'.$source};
1.481 raeburn 3395: close($fh);
1.637 raeburn 3396: if ($parser eq 'parse') {
1.1024 raeburn 3397: my $mm = new File::MMagic;
1.1095 raeburn 3398: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3399: if ($type eq 'text/html') {
1.1024 raeburn 3400: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3401: unless ($parse_result eq 'ok') {
3402: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3403: }
1.637 raeburn 3404: }
1.1095 raeburn 3405: if (ref($mimetype)) {
3406: $$mimetype = $type;
3407: }
1.637 raeburn 3408: }
1.477 raeburn 3409: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3410: $home);
1.481 raeburn 3411: if ($fetchresult eq 'ok') {
3412: return '/uploaded/'.$fpath.'/'.$fname;
3413: } else {
3414: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3415: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3416: return '/adm/notfound.html';
3417: }
1.477 raeburn 3418: }
3419: }
1.485 raeburn 3420: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3421: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3422: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3423: }
3424: return $fetchresult;
3425: }
3426:
1.637 raeburn 3427: sub build_filepath {
3428: my ($fpath) = @_;
3429: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3430: unless ($fpath eq '') {
3431: my @parts=split('/',$fpath);
3432: foreach my $part (@parts) {
3433: $filepath.= '/'.$part;
3434: if ((-e $filepath)!=1) {
3435: mkdir($filepath,0777);
3436: }
3437: }
3438: }
3439: return $filepath;
3440: }
3441:
3442: sub store_edited_file {
1.638 albertel 3443: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3444: my $file = $primary_url;
3445: $file =~ s#^/uploaded/$docudom/$docuname/##;
3446: my $fpath = '';
3447: my $fname = $file;
3448: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3449: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3450: my $filepath = &build_filepath($fpath);
3451: open(my $fh,'>'.$filepath.'/'.$fname);
3452: print $fh $content;
3453: close($fh);
1.638 albertel 3454: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3455: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3456: $home);
1.637 raeburn 3457: if ($$fetchresult eq 'ok') {
3458: return '/uploaded/'.$fpath.'/'.$fname;
3459: } else {
1.638 albertel 3460: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3461: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3462: return '/adm/notfound.html';
3463: }
3464: }
3465:
1.531 albertel 3466: sub clean_filename {
1.831 albertel 3467: my ($fname,$args)=@_;
1.315 www 3468: # Replace Windows backslashes by forward slashes
1.257 www 3469: $fname=~s/\\/\//g;
1.831 albertel 3470: if (!$args->{'keep_path'}) {
3471: # Get rid of everything but the actual filename
3472: $fname=~s/^.*\/([^\/]+)$/$1/;
3473: }
1.315 www 3474: # Replace spaces by underscores
3475: $fname=~s/\s+/\_/g;
3476: # Replace all other weird characters by nothing
1.831 albertel 3477: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3478: # Replace all .\d. sequences with _\d. so they no longer look like version
3479: # numbers
3480: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3481: return $fname;
3482: }
1.1051 raeburn 3483: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3484: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3485: # image with the same aspect ratio as the original, but with dimensions which do
3486: # not exceed $resizewidth and $resizeheight.
3487:
1.984 neumanie 3488: sub resizeImage {
1.1051 raeburn 3489: my ($img_path,$resizewidth,$resizeheight) = @_;
3490: my $ima = Image::Magick->new;
3491: my $resized;
3492: if (-e $img_path) {
3493: $ima->Read($img_path);
3494: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3495: my $width = $ima->Get('width');
3496: my $height = $ima->Get('height');
3497: if ($width > $resizewidth) {
3498: my $factor = $width/$resizewidth;
3499: my $newheight = $height/$factor;
3500: $ima->Scale(width=>$resizewidth,height=>$newheight);
3501: $resized = 1;
3502: }
3503: }
3504: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3505: my $width = $ima->Get('width');
3506: my $height = $ima->Get('height');
3507: if ($height > $resizeheight) {
3508: my $factor = $height/$resizeheight;
3509: my $newwidth = $width/$factor;
3510: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3511: $resized = 1;
3512: }
3513: }
3514: if ($resized) {
3515: $ima->Write($img_path);
3516: }
3517: }
3518: return;
1.977 amueller 3519: }
3520:
1.608 albertel 3521: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3522: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3523: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3524: # $context - possible values: coursedoc, existingfile, overwrite,
3525: # canceloverwrite, or ''.
3526: # if 'coursedoc': upload to the current course
3527: # if 'existingfile': write file to tmp/overwrites directory
3528: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3529: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3530: # $subdir - directory in userfile to store the file into
1.858 raeburn 3531: # $parser - instruction to parse file for objects ($parser = parse)
3532: # $allfiles - reference to hash for embedded objects
3533: # $codebase - reference to hash for codebase of java objects
3534: # $desuname - username for permanent storage of uploaded file
3535: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3536: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3537: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3538: # $resizewidth - width (pixels) to which to resize uploaded image
3539: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3540: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3541: # from File::MMagic.
1.858 raeburn 3542: #
1.686 albertel 3543: # output: url of file in userspace, or error: <message>
3544: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3545:
1.531 albertel 3546: sub userfileupload {
1.1090 raeburn 3547: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3548: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3549: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3550: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3551: $fname=&clean_filename($fname);
1.1090 raeburn 3552: # See if there is anything left
1.257 www 3553: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3554: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3555: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3556: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3557: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3558: my $now = time;
1.1090 raeburn 3559: my $filepath;
1.1095 raeburn 3560: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3561: $filepath = 'tmp/helprequests/'.$now;
3562: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3563: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3564: '_'.$env{'user.domain'}.'/pending';
3565: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3566: my ($docuname,$docudom);
3567: if ($destudom) {
3568: $docudom = $destudom;
3569: } else {
3570: $docudom = $env{'user.domain'};
3571: }
3572: if ($destuname) {
3573: $docuname = $destuname;
3574: } else {
3575: $docuname = $env{'user.name'};
3576: }
3577: if (exists($env{'form.group'})) {
3578: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3579: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3580: }
3581: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3582: if ($context eq 'canceloverwrite') {
3583: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3584: if (-e $tempfile) {
3585: my @info = stat($tempfile);
3586: if ($info[9] eq $env{'form.timestamp'}) {
3587: unlink($tempfile);
3588: }
3589: }
3590: return;
1.523 raeburn 3591: }
3592: }
1.1090 raeburn 3593: # Create the directory if not present
1.741 raeburn 3594: my @parts=split(/\//,$filepath);
3595: my $fullpath = $perlvar{'lonDaemons'};
3596: for (my $i=0;$i<@parts;$i++) {
3597: $fullpath .= '/'.$parts[$i];
3598: if ((-e $fullpath)!=1) {
3599: mkdir($fullpath,0777);
3600: }
3601: }
3602: open(my $fh,'>'.$fullpath.'/'.$fname);
3603: print $fh $env{'form.'.$formname};
3604: close($fh);
1.1090 raeburn 3605: if ($context eq 'existingfile') {
3606: my @info = stat($fullpath.'/'.$fname);
3607: return ($fullpath.'/'.$fname,$info[9]);
3608: } else {
3609: return $fullpath.'/'.$fname;
3610: }
1.523 raeburn 3611: }
1.995 raeburn 3612: if ($subdir eq 'scantron') {
3613: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3614: } else {
1.995 raeburn 3615: $fname="$subdir/$fname";
3616: }
1.1090 raeburn 3617: if ($context eq 'coursedoc') {
1.638 albertel 3618: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3619: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3620: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3621: return &finishuserfileupload($docuname,$docudom,
3622: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3623: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3624: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3625: } else {
1.1218 raeburn 3626: if ($env{'form.folder'}) {
3627: $fname=$env{'form.folder'}.'/'.$fname;
3628: }
1.638 albertel 3629: return &process_coursefile('uploaddoc',$docuname,$docudom,
3630: $fname,$formname,$parser,
1.1095 raeburn 3631: $allfiles,$codebase,$mimetype);
1.481 raeburn 3632: }
1.719 banghart 3633: } elsif (defined($destuname)) {
3634: my $docuname=$destuname;
3635: my $docudom=$destudom;
1.860 raeburn 3636: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3637: $parser,$allfiles,$codebase,
1.1051 raeburn 3638: $thumbwidth,$thumbheight,
1.1095 raeburn 3639: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3640: } else {
1.638 albertel 3641: my $docuname=$env{'user.name'};
3642: my $docudom=$env{'user.domain'};
1.1220 raeburn 3643: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3644: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3645: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3646: }
1.860 raeburn 3647: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3648: $parser,$allfiles,$codebase,
1.1051 raeburn 3649: $thumbwidth,$thumbheight,
1.1095 raeburn 3650: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3651: }
1.271 www 3652: }
3653:
3654: sub finishuserfileupload {
1.860 raeburn 3655: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3656: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3657: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3658: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3659:
1.860 raeburn 3660: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3661: $file=$fname;
3662: if ($fname=~m|/|) {
3663: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3664: $path.=$fnamepath.'/';
3665: }
1.259 www 3666: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3667: my $count;
3668: for ($count=4;$count<=$#parts;$count++) {
3669: $filepath.="/$parts[$count]";
3670: if ((-e $filepath)!=1) {
3671: mkdir($filepath,0777);
3672: }
3673: }
1.984 neumanie 3674:
1.258 www 3675: # Save the file
3676: {
1.701 albertel 3677: if (!open(FH,'>'.$filepath.'/'.$file)) {
3678: &logthis('Failed to create '.$filepath.'/'.$file);
3679: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3680: return '/adm/notfound.html';
3681: }
1.1090 raeburn 3682: if ($context eq 'overwrite') {
1.1117 foxr 3683: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3684: my $target = $filepath.'/'.$file;
3685: if (-e $source) {
3686: my @info = stat($source);
3687: if ($info[9] eq $env{'form.timestamp'}) {
3688: unless (&File::Copy::move($source,$target)) {
3689: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3690: return "Moving from $source failed";
3691: }
3692: } else {
3693: return "Temporary file: $source had unexpected date/time for last modification";
3694: }
3695: } else {
3696: return "Temporary file: $source missing";
3697: }
3698: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3699: &logthis('Failed to write to '.$filepath.'/'.$file);
3700: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3701: return '/adm/notfound.html';
3702: }
1.570 albertel 3703: close(FH);
1.1051 raeburn 3704: if ($resizewidth && $resizeheight) {
3705: my $mm = new File::MMagic;
3706: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3707: if ($mime_type =~ m{^image/}) {
3708: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3709: }
1.977 amueller 3710: }
1.258 www 3711: }
1.1152 raeburn 3712: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3713: if (ref($mimetype)) {
3714: if ($$mimetype eq '') {
3715: my $mm = new File::MMagic;
3716: my $type = $mm->checktype_filename($filepath.'/'.$file);
3717: $$mimetype = $type;
3718: }
3719: }
3720: }
1.637 raeburn 3721: if ($parser eq 'parse') {
1.1152 raeburn 3722: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3723: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3724: $allfiles,$codebase);
3725: unless ($parse_result eq 'ok') {
3726: &logthis('Failed to parse '.$filepath.$file.
3727: ' for embedded media: '.$parse_result);
3728: }
1.637 raeburn 3729: }
3730: }
1.860 raeburn 3731: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3732: my $input = $filepath.'/'.$file;
3733: my $output = $filepath.'/'.'tn-'.$file;
3734: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3735: system("convert -sample $thumbsize $input $output");
3736: if (-e $filepath.'/'.'tn-'.$file) {
3737: $fetchthumb = 1;
3738: }
3739: }
1.858 raeburn 3740:
1.259 www 3741: # Notify homeserver to grep it
3742: #
1.984 neumanie 3743: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3744: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3745: if ($fetchresult eq 'ok') {
1.860 raeburn 3746: if ($fetchthumb) {
3747: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3748: if ($thumbresult ne 'ok') {
3749: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3750: $docuhome.': '.$thumbresult);
3751: }
3752: }
1.259 www 3753: #
1.258 www 3754: # Return the URL to it
1.494 albertel 3755: return '/uploaded/'.$path.$file;
1.263 www 3756: } else {
1.494 albertel 3757: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3758: ': '.$fetchresult);
1.263 www 3759: return '/adm/notfound.html';
1.858 raeburn 3760: }
1.493 albertel 3761: }
3762:
1.637 raeburn 3763: sub extract_embedded_items {
1.961 raeburn 3764: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3765: my @state = ();
1.1164 raeburn 3766: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3767: my %javafiles = (
3768: codebase => '',
3769: code => '',
3770: archive => ''
3771: );
3772: my %mediafiles = (
3773: src => '',
3774: movie => '',
3775: );
1.648 raeburn 3776: my $p;
3777: if ($content) {
3778: $p = HTML::LCParser->new($content);
3779: } else {
1.961 raeburn 3780: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3781: }
1.641 albertel 3782: while (my $t=$p->get_token()) {
1.640 albertel 3783: if ($t->[0] eq 'S') {
3784: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3785: push(@state, $tagname);
1.648 raeburn 3786: if (lc($tagname) eq 'allow') {
3787: &add_filetype($allfiles,$attr->{'src'},'src');
3788: }
1.640 albertel 3789: if (lc($tagname) eq 'img') {
3790: &add_filetype($allfiles,$attr->{'src'},'src');
3791: }
1.886 albertel 3792: if (lc($tagname) eq 'a') {
1.1222 raeburn 3793: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3794: &add_filetype($allfiles,$attr->{'href'},'href');
3795: }
1.886 albertel 3796: }
1.645 raeburn 3797: if (lc($tagname) eq 'script') {
1.1164 raeburn 3798: my $src;
1.645 raeburn 3799: if ($attr->{'archive'} =~ /\.jar$/i) {
3800: &add_filetype($allfiles,$attr->{'archive'},'archive');
3801: } else {
1.1164 raeburn 3802: if ($attr->{'src'} ne '') {
3803: $src = $attr->{'src'};
3804: &add_filetype($allfiles,$src,'src');
3805: }
3806: }
3807: my $text = $p->get_trimmed_text();
3808: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3809: my @swfargs = split(/,/,$1);
3810: foreach my $item (@swfargs) {
3811: $item =~ s/["']//g;
3812: $item =~ s/^\s+//;
3813: $item =~ s/\s+$//;
3814: }
3815: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3816: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3817: push(@{$related{$swfargs[0]}},$swfargs[2]);
3818: } else {
3819: $related{$swfargs[0]} = [$swfargs[2]];
3820: }
3821: }
1.645 raeburn 3822: }
3823: }
3824: if (lc($tagname) eq 'link') {
3825: if (lc($attr->{'rel'}) eq 'stylesheet') {
3826: &add_filetype($allfiles,$attr->{'href'},'href');
3827: }
3828: }
1.640 albertel 3829: if (lc($tagname) eq 'object' ||
3830: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3831: foreach my $item (keys(%javafiles)) {
3832: $javafiles{$item} = '';
3833: }
1.1164 raeburn 3834: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3835: $lastids{lc($tagname)} = $attr->{'id'};
3836: }
1.640 albertel 3837: }
3838: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3839: my $name = lc($attr->{'name'});
3840: foreach my $item (keys(%javafiles)) {
3841: if ($name eq $item) {
3842: $javafiles{$item} = $attr->{'value'};
3843: last;
3844: }
3845: }
1.1164 raeburn 3846: my $pathfrom;
1.640 albertel 3847: foreach my $item (keys(%mediafiles)) {
3848: if ($name eq $item) {
1.1164 raeburn 3849: $pathfrom = $attr->{'value'};
3850: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3851: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3852: last;
3853: }
3854: }
1.1164 raeburn 3855: if ($name eq 'flashvars') {
3856: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3857: }
3858: if ($pathfrom ne '') {
3859: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3860: $pathfrom);
3861: }
1.640 albertel 3862: }
3863: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3864: foreach my $item (keys(%javafiles)) {
3865: if ($attr->{$item}) {
3866: $javafiles{$item} = $attr->{$item};
3867: last;
3868: }
3869: }
3870: foreach my $item (keys(%mediafiles)) {
3871: if ($attr->{$item}) {
3872: &add_filetype($allfiles,$attr->{$item},$item);
3873: last;
3874: }
3875: }
1.1164 raeburn 3876: if (lc($tagname) eq 'embed') {
3877: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3878: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3879: $attr->{'src'});
3880: }
3881: }
1.640 albertel 3882: }
1.1243 raeburn 3883: if (lc($tagname) eq 'iframe') {
3884: my $src = $attr->{'src'} ;
3885: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3886: &add_filetype($allfiles,$src,'src');
3887: } elsif ($src =~ m{^/}) {
3888: if ($env{'request.course.id'}) {
3889: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3890: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3891: my $url = &hreflocation('',$fullpath);
3892: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3893: my $relpath = $1;
3894: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3895: &add_filetype($allfiles,$1,'src');
3896: }
3897: }
3898: }
3899: }
3900: }
1.1164 raeburn 3901: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3902: pop(@state);
1.1164 raeburn 3903: }
1.640 albertel 3904: } elsif ($t->[0] eq 'E') {
3905: my ($tagname) = ($t->[1]);
3906: if ($javafiles{'codebase'} ne '') {
3907: $javafiles{'codebase'} .= '/';
3908: }
3909: if (lc($tagname) eq 'applet' ||
3910: lc($tagname) eq 'object' ||
3911: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3912: ) {
3913: foreach my $item (keys(%javafiles)) {
3914: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3915: my $file=$javafiles{'codebase'}.$javafiles{$item};
3916: &add_filetype($allfiles,$file,$item);
3917: }
3918: }
3919: }
3920: pop @state;
3921: }
3922: }
1.1164 raeburn 3923: foreach my $id (sort(keys(%flashvars))) {
3924: if ($shockwave{$id} ne '') {
3925: my @pairs = split(/\&/,$flashvars{$id});
3926: foreach my $pair (@pairs) {
3927: my ($key,$value) = split(/\=/,$pair);
3928: if ($key eq 'thumb') {
3929: &add_filetype($allfiles,$value,$key);
3930: } elsif ($key eq 'content') {
3931: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3932: my ($ext) = ($value =~ /\.([^.]+)$/);
3933: if ($ext ne '') {
3934: &add_filetype($allfiles,$path.$value,$ext);
3935: }
3936: }
3937: }
3938: }
3939: }
1.637 raeburn 3940: return 'ok';
3941: }
3942:
1.639 albertel 3943: sub add_filetype {
3944: my ($allfiles,$file,$type)=@_;
3945: if (exists($allfiles->{$file})) {
3946: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3947: push(@{$allfiles->{$file}}, &escape($type));
3948: }
3949: } else {
3950: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3951: }
3952: }
3953:
1.1164 raeburn 3954: sub embedded_dependency {
3955: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3956: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3957: if (($identifier ne '') &&
3958: (ref($related->{$identifier}) eq 'ARRAY') &&
3959: ($pathfrom ne '')) {
3960: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3961: foreach my $dep (@{$related->{$identifier}}) {
3962: &add_filetype($allfiles,$path.$dep,'object');
3963: }
3964: }
3965: }
3966: return;
3967: }
3968:
1.493 albertel 3969: sub removeuploadedurl {
1.984 neumanie 3970: my ($url)=@_;
3971: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3972: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3973: }
3974:
3975: sub removeuserfile {
3976: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3977: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3978: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3979: if ($result eq 'ok') {
1.798 raeburn 3980: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3981: my $metafile = $fname.'.meta';
3982: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3983: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3984: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3985: my $sqlresult =
1.823 albertel 3986: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3987: 'portfolio_metadata',$group,
3988: 'delete');
1.798 raeburn 3989: }
3990: }
3991: return $result;
1.257 www 3992: }
1.15 www 3993:
1.530 albertel 3994: sub mkdiruserfile {
3995: my ($docuname,$docudom,$dir)=@_;
3996: my $home=&homeserver($docuname,$docudom);
3997: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3998: }
3999:
1.531 albertel 4000: sub renameuserfile {
4001: my ($docuname,$docudom,$old,$new)=@_;
4002: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4003: my $result = &reply("renameuserfile:$docudom:$docuname:".
4004: &escape("$old").':'.&escape("$new"),$home);
4005: if ($result eq 'ok') {
4006: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4007: my $oldmeta = $old.'.meta';
4008: my $newmeta = $new.'.meta';
4009: my $metaresult =
4010: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4011: my $url = "/uploaded/$docudom/$docuname/$old";
4012: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4013: my $sqlresult =
1.823 albertel 4014: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4015: 'portfolio_metadata',$group,
4016: 'delete');
1.798 raeburn 4017: }
4018: }
4019: return $result;
1.531 albertel 4020: }
4021:
1.14 www 4022: # ------------------------------------------------------------------------- Log
4023:
4024: sub log {
4025: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4026: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4027: }
4028:
4029: # ------------------------------------------------------------------ Course Log
1.352 www 4030: #
4031: # This routine flushes several buffers of non-mission-critical nature
4032: #
1.157 www 4033:
4034: sub flushcourselogs {
1.352 www 4035: &logthis('Flushing log buffers');
4036: #
4037: # course logs
4038: # This is a log of all transactions in a course, which can be used
4039: # for data mining purposes
4040: #
4041: # It also collects the courseid database, which lists last transaction
4042: # times and course titles for all courseids
4043: #
4044: my %courseidbuffer=();
1.921 raeburn 4045: foreach my $crsid (keys(%courselogs)) {
1.352 www 4046: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4047: &escape($courselogs{$crsid}),
4048: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4049: delete $courselogs{$crsid};
4050: } else {
4051: &logthis('Failed to flush log buffer for '.$crsid);
4052: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4053: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4054: " exceeded maximum size, deleting.</font>");
4055: delete $courselogs{$crsid};
4056: }
1.352 www 4057: }
1.920 raeburn 4058: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4059: 'description' => $coursedescrbuf{$crsid},
4060: 'inst_code' => $courseinstcodebuf{$crsid},
4061: 'type' => $coursetypebuf{$crsid},
4062: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4063: };
1.191 harris41 4064: }
1.352 www 4065: #
4066: # Write course id database (reverse lookup) to homeserver of courses
4067: # Is used in pickcourse
4068: #
1.840 albertel 4069: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4070: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4071: $courseidbuffer{$crs_home},
4072: $crs_home,'timeonly');
1.352 www 4073: }
4074: #
4075: # File accesses
4076: # Writes to the dynamic metadata of resources to get hit counts, etc.
4077: #
1.449 matthew 4078: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4079: if ($entry =~ /___count$/) {
4080: my ($dom,$name);
1.807 albertel 4081: ($dom,$name,undef)=
1.811 albertel 4082: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4083: if (! defined($dom) || $dom eq '' ||
4084: ! defined($name) || $name eq '') {
1.620 albertel 4085: my $cid = $env{'request.course.id'};
4086: $dom = $env{'request.'.$cid.'.domain'};
4087: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4088: }
1.450 matthew 4089: my $value = $accesshash{$entry};
4090: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4091: my %temphash=($url => $value);
1.449 matthew 4092: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4093: if ($result eq 'ok') {
4094: delete $accesshash{$entry};
4095: }
4096: } else {
1.811 albertel 4097: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4098: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4099: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4100: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4101: delete $accesshash{$entry};
4102: }
1.185 www 4103: }
1.191 harris41 4104: }
1.352 www 4105: #
4106: # Roles
4107: # Reverse lookup of user roles for course faculty/staff and co-authorship
4108: #
1.800 albertel 4109: foreach my $entry (keys(%userrolehash)) {
1.351 www 4110: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4111: split(/\:/,$entry);
4112: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4113: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4114: $rudom,$runame) eq 'ok') {
4115: delete $userrolehash{$entry};
4116: }
4117: }
1.662 raeburn 4118: #
1.1334 raeburn 4119: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4120: #
4121: my %domrolebuffer = ();
1.1000 raeburn 4122: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4123: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4124: if ($domrolebuffer{$rudom}) {
4125: $domrolebuffer{$rudom}.='&'.&escape($entry).
4126: '='.&escape($domainrolehash{$entry});
4127: } else {
4128: $domrolebuffer{$rudom}.=&escape($entry).
4129: '='.&escape($domainrolehash{$entry});
4130: }
4131: delete $domainrolehash{$entry};
4132: }
4133: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 4134: my %servers;
4135: if (defined(&domain($dom,'primary'))) {
4136: my $primary=&domain($dom,'primary');
4137: my $hostname=&hostname($primary);
4138: $servers{$primary} = $hostname;
4139: } else {
4140: %servers = &get_servers($dom,'library');
4141: }
1.841 albertel 4142: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 4143: if (&reply('domroleput:'.$dom.':'.
4144: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4145: last;
4146: } else {
1.841 albertel 4147: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4148: }
1.662 raeburn 4149: }
4150: }
1.186 www 4151: $dumpcount++;
1.157 www 4152: }
4153:
4154: sub courselog {
4155: my $what=shift;
1.158 www 4156: $what=time.':'.$what;
1.620 albertel 4157: unless ($env{'request.course.id'}) { return ''; }
4158: $coursedombuf{$env{'request.course.id'}}=
4159: $env{'course.'.$env{'request.course.id'}.'.domain'};
4160: $coursenumbuf{$env{'request.course.id'}}=
4161: $env{'course.'.$env{'request.course.id'}.'.num'};
4162: $coursehombuf{$env{'request.course.id'}}=
4163: $env{'course.'.$env{'request.course.id'}.'.home'};
4164: $coursedescrbuf{$env{'request.course.id'}}=
4165: $env{'course.'.$env{'request.course.id'}.'.description'};
4166: $courseinstcodebuf{$env{'request.course.id'}}=
4167: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4168: $courseownerbuf{$env{'request.course.id'}}=
4169: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4170: $coursetypebuf{$env{'request.course.id'}}=
4171: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4172: if (defined $courselogs{$env{'request.course.id'}}) {
4173: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4174: } else {
1.620 albertel 4175: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4176: }
1.620 albertel 4177: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4178: &flushcourselogs();
4179: }
1.158 www 4180: }
4181:
4182: sub courseacclog {
4183: my $fnsymb=shift;
1.620 albertel 4184: unless ($env{'request.course.id'}) { return ''; }
4185: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4186: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4187: $what.=':POST';
1.583 matthew 4188: # FIXME: Probably ought to escape things....
1.800 albertel 4189: foreach my $key (keys(%env)) {
4190: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4191: my $formitem = $1;
4192: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4193: $what.=':'.$formitem.'='.$env{$key};
4194: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4195: $what.=':'.$formitem.'='.$env{$key};
4196: }
1.158 www 4197: }
1.191 harris41 4198: }
1.583 matthew 4199: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4200: # FIXME: We should not be depending on a form parameter that someone
4201: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4202: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4203: $what.= ':POST';
4204: # FIXME: Probably ought to escape things....
4205: foreach my $element ('courseexp','crsfulltext','crsrelated',
4206: 'crsdiscuss') {
1.620 albertel 4207: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4208: }
4209: }
1.158 www 4210: }
4211: &courselog($what);
1.149 www 4212: }
4213:
1.185 www 4214: sub countacc {
4215: my $url=&declutter(shift);
1.458 matthew 4216: return if (! defined($url) || $url eq '');
1.620 albertel 4217: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4218: #
4219: # Mark that this url was used in this course
4220: #
1.620 albertel 4221: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4222: #
4223: # Increase the access count for this resource in this child process
4224: #
1.281 www 4225: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4226: $accesshash{$key}++;
1.185 www 4227: }
1.349 www 4228:
1.361 www 4229: sub linklog {
4230: my ($from,$to)=@_;
4231: $from=&declutter($from);
4232: $to=&declutter($to);
4233: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4234: $accesshash{$to.'___'.$from.'___goto'}=1;
4235: }
1.1160 www 4236:
4237: sub statslog {
4238: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4239: if ($users<2) { return; }
4240: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4241: 'course' => $env{'request.course.id'},
4242: 'sections' => '"all"',
4243: 'num_students' => $users,
4244: 'part' => $part,
4245: 'symb' => $symb,
4246: 'mean_tries' => $av_attempts,
4247: 'deg_of_diff' => $degdiff});
4248: foreach my $key (keys(%dynstore)) {
4249: $accesshash{$key}=$dynstore{$key};
4250: }
4251: }
1.361 www 4252:
1.349 www 4253: sub userrolelog {
4254: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4255: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4256: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4257: $userrolehash
4258: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4259: =$tend.':'.$tstart;
1.662 raeburn 4260: }
1.1169 droeschl 4261: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4262: $userrolehash
4263: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4264: =$tend.':'.$tstart;
4265: }
1.1334 raeburn 4266: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4267: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4268: $domainrolehash
4269: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4270: = $tend.':'.$tstart;
4271: }
1.351 www 4272: }
4273:
1.957 raeburn 4274: sub courserolelog {
4275: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 4276: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4277: my $cdom = $1;
4278: my $cnum = $2;
4279: my $sec = $3;
4280: my $namespace = 'rolelog';
4281: my %storehash = (
4282: role => $trole,
4283: start => $tstart,
4284: end => $tend,
4285: selfenroll => $selfenroll,
4286: context => $context,
4287: );
4288: if ($trole eq 'gr') {
4289: $namespace = 'groupslog';
4290: $storehash{'group'} = $sec;
4291: } else {
4292: $storehash{'section'} = $sec;
4293: }
1.1188 raeburn 4294: &write_log('course',$namespace,\%storehash,$delflag,$username,
4295: $domain,$cnum,$cdom);
1.1184 raeburn 4296: if (($trole ne 'st') || ($sec ne '')) {
4297: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4298: }
4299: }
4300: return;
4301: }
4302:
1.1184 raeburn 4303: sub domainrolelog {
4304: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4305: if ($area =~ m{^/($match_domain)/$}) {
4306: my $cdom = $1;
4307: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4308: my $namespace = 'rolelog';
4309: my %storehash = (
4310: role => $trole,
4311: start => $tstart,
4312: end => $tend,
4313: context => $context,
4314: );
1.1188 raeburn 4315: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4316: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4317: }
4318: return;
4319:
4320: }
4321:
4322: sub coauthorrolelog {
4323: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4324: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4325: my $audom = $1;
4326: my $auname = $2;
4327: my $namespace = 'rolelog';
4328: my %storehash = (
4329: role => $trole,
4330: start => $tstart,
4331: end => $tend,
4332: context => $context,
4333: );
1.1188 raeburn 4334: &write_log('author',$namespace,\%storehash,$delflag,$username,
4335: $domain,$auname,$audom);
1.1184 raeburn 4336: }
4337: return;
4338: }
4339:
1.351 www 4340: sub get_course_adv_roles {
1.948 raeburn 4341: my ($cid,$codes) = @_;
1.620 albertel 4342: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4343: my %coursehash=&coursedescription($cid);
1.988 raeburn 4344: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4345: my %nothide=();
1.800 albertel 4346: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4347: if ($user !~ /:/) {
4348: $nothide{join(':',split(/[\@]/,$user))}=1;
4349: } else {
4350: $nothide{$user}=1;
4351: }
1.470 www 4352: }
1.1219 raeburn 4353: my @possdoms = ($coursehash{'domain'});
4354: if ($coursehash{'checkforpriv'}) {
4355: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4356: }
1.351 www 4357: my %returnhash=();
4358: my %dumphash=
4359: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4360: my $now=time;
1.997 raeburn 4361: my %privileged;
1.1000 raeburn 4362: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4363: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4364: if (($tstart) && ($tstart<0)) { next; }
4365: if (($tend) && ($tend<$now)) { next; }
4366: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4367: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4368: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4369: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4370: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4371: if ($role eq 'cr') { next; }
1.948 raeburn 4372: if ($codes) {
4373: if ($section) { $role .= ':'.$section; }
4374: if ($returnhash{$role}) {
4375: $returnhash{$role}.=','.$username.':'.$domain;
4376: } else {
4377: $returnhash{$role}=$username.':'.$domain;
4378: }
1.351 www 4379: } else {
1.988 raeburn 4380: my $key=&plaintext($role,$crstype);
1.973 bisitz 4381: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4382: if ($returnhash{$key}) {
4383: $returnhash{$key}.=','.$username.':'.$domain;
4384: } else {
4385: $returnhash{$key}=$username.':'.$domain;
4386: }
1.351 www 4387: }
1.948 raeburn 4388: }
1.400 www 4389: return %returnhash;
4390: }
4391:
4392: sub get_my_roles {
1.937 raeburn 4393: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4394: unless (defined($uname)) { $uname=$env{'user.name'}; }
4395: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4396: my (%dumphash,%nothide);
1.1086 raeburn 4397: if ($context eq 'userroles') {
1.1166 raeburn 4398: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4399: } else {
1.1219 raeburn 4400: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4401: if ($hidepriv) {
4402: my %coursehash=&coursedescription($udom.'_'.$uname);
4403: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4404: if ($user !~ /:/) {
4405: $nothide{join(':',split(/[\@]/,$user))} = 1;
4406: } else {
4407: $nothide{$user} = 1;
4408: }
4409: }
4410: }
1.858 raeburn 4411: }
1.400 www 4412: my %returnhash=();
4413: my $now=time;
1.999 raeburn 4414: my %privileged;
1.800 albertel 4415: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4416: my ($role,$tend,$tstart);
4417: if ($context eq 'userroles') {
1.1149 raeburn 4418: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4419: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4420: } else {
4421: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4422: }
1.400 www 4423: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4424: my $status = 'active';
1.939 raeburn 4425: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4426: $status = 'previous';
4427: }
4428: if (($tstart) && ($now<$tstart)) {
4429: $status = 'future';
4430: }
4431: if (ref($types) eq 'ARRAY') {
4432: if (!grep(/^\Q$status\E$/,@{$types})) {
4433: next;
4434: }
4435: } else {
4436: if ($status ne 'active') {
4437: next;
4438: }
4439: }
1.867 raeburn 4440: my ($rolecode,$username,$domain,$section,$area);
4441: if ($context eq 'userroles') {
1.1186 raeburn 4442: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4443: (undef,$domain,$username,$section) = split(/\//,$area);
4444: } else {
4445: ($role,$username,$domain,$section) = split(/\:/,$entry);
4446: }
1.832 raeburn 4447: if (ref($roledoms) eq 'ARRAY') {
4448: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4449: next;
4450: }
4451: }
4452: if (ref($roles) eq 'ARRAY') {
4453: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4454: if ($role =~ /^cr\//) {
4455: if (!grep(/^cr$/,@{$roles})) {
4456: next;
4457: }
1.1104 raeburn 4458: } elsif ($role =~ /^gr\//) {
4459: if (!grep(/^gr$/,@{$roles})) {
4460: next;
4461: }
1.922 raeburn 4462: } else {
4463: next;
4464: }
1.832 raeburn 4465: }
1.867 raeburn 4466: }
1.937 raeburn 4467: if ($hidepriv) {
1.1219 raeburn 4468: my @privroles = ('dc','su');
1.999 raeburn 4469: if ($context eq 'userroles') {
1.1219 raeburn 4470: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4471: } else {
1.1219 raeburn 4472: my $possdoms = [$domain];
4473: if (ref($roledoms) eq 'ARRAY') {
4474: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4475: }
1.1219 raeburn 4476: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4477: if (!$nothide{$username.':'.$domain}) {
4478: next;
4479: }
4480: }
1.937 raeburn 4481: }
4482: }
1.933 raeburn 4483: if ($withsec) {
4484: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4485: $tstart.':'.$tend;
4486: } else {
4487: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4488: }
1.832 raeburn 4489: }
1.373 www 4490: return %returnhash;
1.399 www 4491: }
4492:
1.1333 raeburn 4493: sub get_all_adhocroles {
4494: my ($dom) = @_;
4495: my @roles_by_num = ();
4496: my %domdefaults = &get_domain_defaults($dom);
4497: my (%description,%access_in_dom,%access_info);
4498: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4499: my $count = 0;
4500: my %domcurrent = %{$domdefaults{'adhocroles'}};
4501: my %ordered;
4502: foreach my $role (sort(keys(%domcurrent))) {
4503: my ($order,$desc,$access_in_dom);
4504: if (ref($domcurrent{$role}) eq 'HASH') {
4505: $order = $domcurrent{$role}{'order'};
4506: $desc = $domcurrent{$role}{'desc'};
4507: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4508: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4509: }
4510: if ($order eq '') {
4511: $order = $count;
4512: }
4513: $ordered{$order} = $role;
4514: if ($desc ne '') {
4515: $description{$role} = $desc;
4516: } else {
4517: $description{$role}= $role;
4518: }
4519: $count++;
4520: }
4521: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4522: push(@roles_by_num,$ordered{$item});
4523: }
4524: }
4525: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4526: }
4527:
1.1332 raeburn 4528: sub get_my_adhocroles {
1.1333 raeburn 4529: my ($cid,$checkreg) = @_;
4530: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4531: if ($env{'request.course.id'} eq $cid) {
4532: $cdom = $env{'course.'.$cid.'.domain'};
4533: $cnum = $env{'course.'.$cid.'.num'};
4534: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4535: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4536: $cdom = $1;
4537: $cnum = $2;
4538: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4539: $cdom,$cnum);
4540: }
4541: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4542: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4543: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4544: if ($rosterhash{$user} ne '') {
4545: my $type = (split(/:/,$rosterhash{$user}))[5];
4546: return ([],{}) if ($type eq 'auto');
4547: }
4548: }
4549: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 4550: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 4551: my $then=$env{'user.login.time'};
4552: my $update=$env{'user.update.time'};
1.1335 raeburn 4553: if (!$update) {
4554: $update = $then;
4555: }
4556: my @liveroles;
1.1334 raeburn 4557: foreach my $role ('dh','da') {
4558: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 4559: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 4560: my $limit = $update;
4561: if ($env{'request.role'} eq "$role./$cdom/") {
4562: $limit = $then;
4563: }
1.1335 raeburn 4564: my $activerole = 1;
4565: if ($tstart && $tstart>$limit) { $activerole = 0; }
4566: if ($tend && $tend <$limit) { $activerole = 0; }
4567: if ($activerole) {
4568: push(@liveroles,$role);
4569: }
1.1334 raeburn 4570: }
1.1332 raeburn 4571: }
1.1335 raeburn 4572: if (@liveroles) {
1.1332 raeburn 4573: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 4574: my ($accessref,$accessinfo,%access_in_dom);
4575: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
4576: if (ref($roles_by_num) eq 'ARRAY') {
4577: if (@{$roles_by_num}) {
1.1332 raeburn 4578: my %settings;
4579: if ($env{'request.course.id'} eq $cid) {
4580: foreach my $envkey (keys(%env)) {
4581: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
4582: $settings{$1} = $env{$envkey};
4583: }
4584: }
4585: } else {
4586: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
4587: }
4588: my %setincrs;
4589: if ($settings{'internal.adhocaccess'}) {
4590: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
4591: }
4592: my @statuses;
4593: if ($env{'environment.inststatus'}) {
4594: @statuses = split(/,/,$env{'environment.inststatus'});
4595: }
4596: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 4597: if (ref($accessref) eq 'HASH') {
4598: %access_in_dom = %{$accessref};
4599: }
4600: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 4601: my ($curraccess,@okstatus,@personnel);
4602: if ($setincrs{$role}) {
4603: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
4604: if ($curraccess eq 'status') {
4605: @okstatus = split(/\&/,$rest);
4606: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4607: @personnel = split(/\&/,$rest);
4608: }
4609: } else {
4610: $curraccess = $access_in_dom{$role};
1.1333 raeburn 4611: if (ref($accessinfo) eq 'HASH') {
4612: if ($curraccess eq 'status') {
4613: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4614: @okstatus = @{$accessinfo->{$role}};
4615: }
4616: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4617: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4618: @personnel = @{$accessinfo->{$role}};
4619: }
1.1332 raeburn 4620: }
4621: }
4622: }
4623: if ($curraccess eq 'none') {
4624: next;
4625: } elsif ($curraccess eq 'all') {
4626: push(@possroles,$role);
1.1336 ! raeburn 4627: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 4628: if (grep(/^dh$/,@liveroles)) {
4629: push(@possroles,$role);
4630: } else {
4631: next;
4632: }
1.1336 ! raeburn 4633: } elsif ($curraccess eq 'da') {
1.1335 raeburn 4634: if (grep(/^da$/,@liveroles)) {
4635: push(@possroles,$role);
4636: } else {
4637: next;
4638: }
1.1332 raeburn 4639: } elsif ($curraccess eq 'status') {
4640: if (@okstatus) {
4641: if (!@statuses) {
4642: if (grep(/^default$/,@okstatus)) {
4643: push(@possroles,$role);
4644: }
4645: } else {
4646: foreach my $status (@okstatus) {
4647: if (grep(/^\Q$status\E$/,@statuses)) {
4648: push(@possroles,$role);
4649: last;
4650: }
4651: }
4652: }
4653: }
4654: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4655: if (grep(/^\Q$user\E$/,@personnel)) {
4656: if ($curraccess eq 'exc') {
4657: push(@possroles,$role);
4658: }
4659: } elsif ($curraccess eq 'inc') {
4660: push(@possroles,$role);
4661: }
4662: }
4663: }
4664: }
4665: }
4666: }
4667: }
4668: }
4669: }
1.1333 raeburn 4670: unless (ref($description) eq 'HASH') {
4671: if (ref($roles_by_num) eq 'ARRAY') {
4672: my %desc;
4673: map { $desc{$_} = $_; } (@{$roles_by_num});
4674: $description = \%desc;
4675: } else {
4676: $description = {};
4677: }
4678: }
4679: return (\@possroles,$description);
1.1332 raeburn 4680: }
4681:
1.399 www 4682: # ----------------------------------------------------- Frontpage Announcements
4683: #
4684: #
4685:
4686: sub postannounce {
4687: my ($server,$text)=@_;
1.844 albertel 4688: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4689: unless ($text=~/\w/) { $text=''; }
4690: return &reply('setannounce:'.&escape($text),$server);
4691: }
4692:
4693: sub getannounce {
1.448 albertel 4694:
4695: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4696: my $announcement='';
1.800 albertel 4697: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4698: close($fh);
1.399 www 4699: if ($announcement=~/\w/) {
4700: return
4701: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4702: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4703: } else {
4704: return '';
4705: }
4706: } else {
4707: return '';
4708: }
1.351 www 4709: }
1.353 www 4710:
4711: # ---------------------------------------------------------- Course ID routines
4712: # Deal with domain's nohist_courseid.db files
4713: #
4714:
4715: sub courseidput {
1.921 raeburn 4716: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4717: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4718: my $outcome;
4719: if ($caller eq 'timeonly') {
4720: my $cids = '';
4721: foreach my $item (keys(%$storehash)) {
4722: $cids.=&escape($item).'&';
4723: }
4724: $cids=~s/\&$//;
4725: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4726: $coursehome);
4727: } else {
4728: my $items = '';
4729: foreach my $item (keys(%$storehash)) {
4730: $items.= &escape($item).'='.
4731: &freeze_escape($$storehash{$item}).'&';
4732: }
4733: $items=~s/\&$//;
4734: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4735: $coursehome);
1.918 raeburn 4736: }
4737: if ($outcome eq 'unknown_cmd') {
4738: my $what;
4739: foreach my $cid (keys(%$storehash)) {
4740: $what .= &escape($cid).'=';
1.921 raeburn 4741: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4742: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4743: }
4744: $what =~ s/\:$/&/;
4745: }
4746: $what =~ s/\&$//;
4747: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4748: } else {
4749: return $outcome;
4750: }
1.353 www 4751: }
4752:
4753: sub courseiddump {
1.921 raeburn 4754: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4755: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4756: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4757: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 4758: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4759: my $as_hash = 1;
4760: my %returnhash;
4761: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4762: my %libserv = &all_library();
4763: foreach my $tryserver (keys(%libserv)) {
4764: if ( ( $hostidflag == 1
4765: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4766: || (!defined($hostidflag)) ) {
4767:
1.918 raeburn 4768: if (($domfilter eq '') ||
4769: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4770: my $rep;
4771: if (grep { $_ eq $tryserver } current_machine_ids()) {
4772: $rep = LONCAPA::Lond::dump_course_id_handler(
4773: join(":", (&host_domain($tryserver), $sincefilter,
4774: &escape($descfilter), &escape($instcodefilter),
4775: &escape($ownerfilter), &escape($coursefilter),
4776: &escape($typefilter), &escape($regexp_ok),
4777: $as_hash, &escape($selfenrollonly),
4778: &escape($catfilter), $showhidden, $caller,
4779: &escape($cloner), &escape($cc_clone), $cloneonly,
4780: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 4781: &escape($creationcontext),$domcloner,$hasuniquecode,
4782: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 4783: } else {
4784: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4785: $sincefilter.':'.&escape($descfilter).':'.
4786: &escape($instcodefilter).':'.&escape($ownerfilter).
4787: ':'.&escape($coursefilter).':'.&escape($typefilter).
4788: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4789: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4790: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4791: &escape($cc_clone).':'.$cloneonly.':'.
4792: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 4793: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4794: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 4795: }
4796:
1.918 raeburn 4797: my @pairs=split(/\&/,$rep);
4798: foreach my $item (@pairs) {
4799: my ($key,$value)=split(/\=/,$item,2);
4800: $key = &unescape($key);
4801: next if ($key =~ /^error: 2 /);
4802: my $result = &thaw_unescape($value);
4803: if (ref($result) eq 'HASH') {
4804: $returnhash{$key}=$result;
4805: } else {
1.921 raeburn 4806: my @responses = split(/:/,$value);
4807: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4808: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4809: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4810: }
1.1008 raeburn 4811: }
1.353 www 4812: }
4813: }
4814: }
4815: }
4816: return %returnhash;
4817: }
4818:
1.1055 raeburn 4819: sub courselastaccess {
4820: my ($cdom,$cnum,$hostidref) = @_;
4821: my %returnhash;
4822: if ($cdom && $cnum) {
4823: my $chome = &homeserver($cnum,$cdom);
4824: if ($chome ne 'no_host') {
4825: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4826: &extract_lastaccess(\%returnhash,$rep);
4827: }
4828: } else {
4829: if (!$cdom) { $cdom=''; }
4830: my %libserv = &all_library();
4831: foreach my $tryserver (keys(%libserv)) {
4832: if (ref($hostidref) eq 'ARRAY') {
4833: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4834: }
4835: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4836: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4837: &extract_lastaccess(\%returnhash,$rep);
4838: }
4839: }
4840: }
4841: return %returnhash;
4842: }
4843:
4844: sub extract_lastaccess {
4845: my ($returnhash,$rep) = @_;
4846: if (ref($returnhash) eq 'HASH') {
4847: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4848: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4849: $rep eq '') {
4850: my @pairs=split(/\&/,$rep);
4851: foreach my $item (@pairs) {
4852: my ($key,$value)=split(/\=/,$item,2);
4853: $key = &unescape($key);
4854: next if ($key =~ /^error: 2 /);
4855: $returnhash->{$key} = &thaw_unescape($value);
4856: }
4857: }
4858: }
4859: return;
4860: }
4861:
1.658 raeburn 4862: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4863:
4864: sub dcmailput {
1.685 raeburn 4865: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4866: my $status = &Apache::lonnet::critical(
1.740 www 4867: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4868: &escape($message),$server);
1.662 raeburn 4869: return $status;
4870: }
4871:
1.658 raeburn 4872: sub dcmaildump {
4873: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4874: my %returnhash=();
1.846 albertel 4875:
4876: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4877: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4878: &escape($enddate).':';
4879: my @esc_senders=map { &escape($_)} @$senders;
4880: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4881: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4882: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4883: if (($key) && ($value)) {
4884: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4885: }
4886: }
4887: }
4888: return %returnhash;
4889: }
1.662 raeburn 4890: # ---------------------------------------------------------- Domain roles
4891:
4892: sub get_domain_roles {
4893: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4894: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4895: $startdate = '.';
4896: }
1.1018 raeburn 4897: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4898: $enddate = '.';
4899: }
1.922 raeburn 4900: my $rolelist;
4901: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4902: $rolelist = join('&',@{$roles});
1.922 raeburn 4903: }
1.662 raeburn 4904: my %personnel = ();
1.841 albertel 4905:
4906: my %servers = &get_servers($dom,'library');
4907: foreach my $tryserver (keys(%servers)) {
4908: %{$personnel{$tryserver}}=();
4909: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4910: &escape($startdate).':'.
4911: &escape($enddate).':'.
4912: &escape($rolelist), $tryserver))) {
4913: my ($key,$value) = split(/\=/,$line,2);
4914: if (($key) && ($value)) {
4915: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4916: }
4917: }
1.662 raeburn 4918: }
4919: return %personnel;
4920: }
1.658 raeburn 4921:
1.1332 raeburn 4922: sub get_active_domroles {
4923: my ($dom,$roles) = @_;
4924: return () unless (ref($roles) eq 'ARRAY');
4925: my $now = time;
4926: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
4927: my %domroles;
4928: foreach my $server (keys(%dompersonnel)) {
4929: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
4930: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
4931: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
4932: }
4933: }
4934: return %domroles;
4935: }
4936:
1.1057 www 4937: # ----------------------------------------------------------- Interval timing
1.149 www 4938:
1.1153 www 4939: {
4940: # Caches needed for speedup of navmaps
4941: # We don't want to cache this for very long at all (5 seconds at most)
4942: #
4943: # The user for whom we cache
4944: my $cachedkey='';
4945: # The cached times for this user
4946: my %cachedtimes=();
4947: # When this was last done
1.1282 raeburn 4948: my $cachedtime='';
1.1153 www 4949:
4950: sub load_all_first_access {
1.1308 raeburn 4951: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 4952: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 4953: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
4954: (!$ignorecache)) {
1.1154 raeburn 4955: return;
4956: }
4957: $cachedtime=time;
4958: $cachedkey=$uname.':'.$udom;
4959: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4960: }
4961:
1.504 albertel 4962: sub get_first_access {
1.1308 raeburn 4963: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 4964: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4965: if ($argsymb) { $symb=$argsymb; }
4966: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4967: if ($argmap) { $map = $argmap; }
1.926 albertel 4968: if ($type eq 'course') {
4969: $res='course';
4970: } elsif ($type eq 'map') {
1.588 albertel 4971: $res=&symbread($map);
4972: } else {
4973: $res=$symb;
4974: }
1.1308 raeburn 4975: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 4976: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4977: }
4978:
4979: sub set_first_access {
1.1162 raeburn 4980: my ($type,$interval)=@_;
1.790 albertel 4981: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4982: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4983: if ($type eq 'course') {
4984: $res='course';
4985: } elsif ($type eq 'map') {
1.588 albertel 4986: $res=&symbread($map);
4987: } else {
4988: $res=$symb;
4989: }
1.1153 www 4990: $cachedkey='';
1.1162 raeburn 4991: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4992: if (!$firstaccess) {
1.1162 raeburn 4993: my $start = time;
4994: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4995: $udom,$uname);
4996: if ($putres eq 'ok') {
4997: &put('timerinterval',{"$courseid\0$res"=>$interval},
4998: $udom,$uname);
4999: &appenv(
5000: {
5001: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5002: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5003: }
5004: );
5005: }
5006: return $putres;
1.505 albertel 5007: }
5008: return 'already_set';
1.504 albertel 5009: }
1.1153 www 5010: }
1.1282 raeburn 5011:
1.110 www 5012: # --------------------------------------------- Set Expire Date for Spreadsheet
5013:
5014: sub expirespread {
5015: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5016: my $cid=$env{'request.course.id'};
1.110 www 5017: if ($cid) {
5018: my $now=time;
5019: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5020: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5021: $env{'course.'.$cid.'.num'}.
1.110 www 5022: ':nohist_expirationdates:'.
5023: &escape($key).'='.$now,
1.620 albertel 5024: $env{'course.'.$cid.'.home'})
1.110 www 5025: }
5026: return 'ok';
1.14 www 5027: }
5028:
1.109 www 5029: # ----------------------------------------------------- Devalidate Spreadsheets
5030:
5031: sub devalidate {
1.325 www 5032: my ($symb,$uname,$udom)=@_;
1.620 albertel 5033: my $cid=$env{'request.course.id'};
1.109 www 5034: if ($cid) {
1.391 matthew 5035: # delete the stored spreadsheets for
5036: # - the student level sheet of this user in course's homespace
5037: # - the assessment level sheet for this resource
5038: # for this user in user's homespace
1.553 albertel 5039: # - current conditional state info
1.325 www 5040: my $key=$uname.':'.$udom.':';
1.109 www 5041: my $status=
1.299 matthew 5042: &del('nohist_calculatedsheets',
1.391 matthew 5043: [$key.'studentcalc:'],
1.620 albertel 5044: $env{'course.'.$cid.'.domain'},
5045: $env{'course.'.$cid.'.num'})
1.133 albertel 5046: .' '.
5047: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5048: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5049: unless ($status eq 'ok ok') {
5050: &logthis('Could not devalidate spreadsheet '.
1.325 www 5051: $uname.' at '.$udom.' for '.
1.109 www 5052: $symb.': '.$status);
1.133 albertel 5053: }
1.553 albertel 5054: &delenv('user.state.'.$cid);
1.109 www 5055: }
5056: }
5057:
1.265 albertel 5058: sub get_scalar {
5059: my ($string,$end) = @_;
5060: my $value;
5061: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5062: $value = $1;
5063: } elsif ($$string =~ s/^([^&]*?)&//) {
5064: $value = $1;
5065: }
5066: return &unescape($value);
5067: }
5068:
5069: sub array2str {
5070: my (@array) = @_;
5071: my $result=&arrayref2str(\@array);
5072: $result=~s/^__ARRAY_REF__//;
5073: $result=~s/__END_ARRAY_REF__$//;
5074: return $result;
5075: }
5076:
1.204 albertel 5077: sub arrayref2str {
5078: my ($arrayref) = @_;
1.265 albertel 5079: my $result='__ARRAY_REF__';
1.204 albertel 5080: foreach my $elem (@$arrayref) {
1.265 albertel 5081: if(ref($elem) eq 'ARRAY') {
5082: $result.=&arrayref2str($elem).'&';
5083: } elsif(ref($elem) eq 'HASH') {
5084: $result.=&hashref2str($elem).'&';
5085: } elsif(ref($elem)) {
5086: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5087: } else {
5088: $result.=&escape($elem).'&';
5089: }
5090: }
5091: $result=~s/\&$//;
1.265 albertel 5092: $result .= '__END_ARRAY_REF__';
1.204 albertel 5093: return $result;
5094: }
5095:
1.168 albertel 5096: sub hash2str {
1.204 albertel 5097: my (%hash) = @_;
5098: my $result=&hashref2str(\%hash);
1.265 albertel 5099: $result=~s/^__HASH_REF__//;
5100: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5101: return $result;
5102: }
5103:
5104: sub hashref2str {
5105: my ($hashref)=@_;
1.265 albertel 5106: my $result='__HASH_REF__';
1.800 albertel 5107: foreach my $key (sort(keys(%$hashref))) {
5108: if (ref($key) eq 'ARRAY') {
5109: $result.=&arrayref2str($key).'=';
5110: } elsif (ref($key) eq 'HASH') {
5111: $result.=&hashref2str($key).'=';
5112: } elsif (ref($key)) {
1.265 albertel 5113: $result.='=';
1.800 albertel 5114: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5115: } else {
1.1132 raeburn 5116: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5117: }
5118:
1.800 albertel 5119: if(ref($hashref->{$key}) eq 'ARRAY') {
5120: $result.=&arrayref2str($hashref->{$key}).'&';
5121: } elsif(ref($hashref->{$key}) eq 'HASH') {
5122: $result.=&hashref2str($hashref->{$key}).'&';
5123: } elsif(ref($hashref->{$key})) {
1.265 albertel 5124: $result.='&';
1.800 albertel 5125: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5126: } else {
1.800 albertel 5127: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5128: }
5129: }
1.168 albertel 5130: $result=~s/\&$//;
1.265 albertel 5131: $result .= '__END_HASH_REF__';
1.168 albertel 5132: return $result;
5133: }
5134:
5135: sub str2hash {
1.265 albertel 5136: my ($string)=@_;
5137: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5138: return %$hash;
5139: }
5140:
5141: sub str2hashref {
1.168 albertel 5142: my ($string) = @_;
1.265 albertel 5143:
5144: my %hash;
5145:
5146: if($string !~ /^__HASH_REF__/) {
5147: if (! ($string eq '' || !defined($string))) {
5148: $hash{'error'}='Not hash reference';
5149: }
5150: return (\%hash, $string);
5151: }
5152:
5153: $string =~ s/^__HASH_REF__//;
5154:
5155: while($string !~ /^__END_HASH_REF__/) {
5156: #key
5157: my $key='';
5158: if($string =~ /^__HASH_REF__/) {
5159: ($key, $string)=&str2hashref($string);
5160: if(defined($key->{'error'})) {
5161: $hash{'error'}='Bad data';
5162: return (\%hash, $string);
5163: }
5164: } elsif($string =~ /^__ARRAY_REF__/) {
5165: ($key, $string)=&str2arrayref($string);
5166: if($key->[0] eq 'Array reference error') {
5167: $hash{'error'}='Bad data';
5168: return (\%hash, $string);
5169: }
5170: } else {
5171: $string =~ s/^(.*?)=//;
1.267 albertel 5172: $key=&unescape($1);
1.265 albertel 5173: }
5174: $string =~ s/^=//;
5175:
5176: #value
5177: my $value='';
5178: if($string =~ /^__HASH_REF__/) {
5179: ($value, $string)=&str2hashref($string);
5180: if(defined($value->{'error'})) {
5181: $hash{'error'}='Bad data';
5182: return (\%hash, $string);
5183: }
5184: } elsif($string =~ /^__ARRAY_REF__/) {
5185: ($value, $string)=&str2arrayref($string);
5186: if($value->[0] eq 'Array reference error') {
5187: $hash{'error'}='Bad data';
5188: return (\%hash, $string);
5189: }
5190: } else {
5191: $value=&get_scalar(\$string,'__END_HASH_REF__');
5192: }
5193: $string =~ s/^&//;
5194:
5195: $hash{$key}=$value;
1.204 albertel 5196: }
1.265 albertel 5197:
5198: $string =~ s/^__END_HASH_REF__//;
5199:
5200: return (\%hash, $string);
1.204 albertel 5201: }
5202:
5203: sub str2array {
1.265 albertel 5204: my ($string)=@_;
5205: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5206: return @$array;
5207: }
5208:
5209: sub str2arrayref {
1.204 albertel 5210: my ($string) = @_;
1.265 albertel 5211: my @array;
5212:
5213: if($string !~ /^__ARRAY_REF__/) {
5214: if (! ($string eq '' || !defined($string))) {
5215: $array[0]='Array reference error';
5216: }
5217: return (\@array, $string);
5218: }
5219:
5220: $string =~ s/^__ARRAY_REF__//;
5221:
5222: while($string !~ /^__END_ARRAY_REF__/) {
5223: my $value='';
5224: if($string =~ /^__HASH_REF__/) {
5225: ($value, $string)=&str2hashref($string);
5226: if(defined($value->{'error'})) {
5227: $array[0] ='Array reference error';
5228: return (\@array, $string);
5229: }
5230: } elsif($string =~ /^__ARRAY_REF__/) {
5231: ($value, $string)=&str2arrayref($string);
5232: if($value->[0] eq 'Array reference error') {
5233: $array[0] ='Array reference error';
5234: return (\@array, $string);
5235: }
5236: } else {
5237: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5238: }
5239: $string =~ s/^&//;
5240:
5241: push(@array, $value);
1.191 harris41 5242: }
1.265 albertel 5243:
5244: $string =~ s/^__END_ARRAY_REF__//;
5245:
5246: return (\@array, $string);
1.168 albertel 5247: }
5248:
1.167 albertel 5249: # -------------------------------------------------------------------Temp Store
5250:
1.168 albertel 5251: sub tmpreset {
5252: my ($symb,$namespace,$domain,$stuname) = @_;
5253: if (!$symb) {
5254: $symb=&symbread();
1.620 albertel 5255: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5256: }
5257: $symb=escape($symb);
5258:
1.620 albertel 5259: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5260: $namespace=~s/\//\_/g;
5261: $namespace=~s/\W//g;
5262:
1.620 albertel 5263: if (!$domain) { $domain=$env{'user.domain'}; }
5264: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5265: if ($domain eq 'public' && $stuname eq 'public') {
5266: $stuname=$ENV{'REMOTE_ADDR'};
5267: }
1.1117 foxr 5268: my $path=LONCAPA::tempdir();
1.168 albertel 5269: my %hash;
5270: if (tie(%hash,'GDBM_File',
5271: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5272: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5273: foreach my $key (keys(%hash)) {
1.180 albertel 5274: if ($key=~ /:$symb/) {
1.168 albertel 5275: delete($hash{$key});
5276: }
5277: }
5278: }
5279: }
5280:
1.167 albertel 5281: sub tmpstore {
1.168 albertel 5282: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5283:
5284: if (!$symb) {
5285: $symb=&symbread();
1.620 albertel 5286: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5287: }
5288: $symb=escape($symb);
5289:
5290: if (!$namespace) {
5291: # I don't think we would ever want to store this for a course.
5292: # it seems this will only be used if we don't have a course.
1.620 albertel 5293: #$namespace=$env{'request.course.id'};
1.168 albertel 5294: #if (!$namespace) {
1.620 albertel 5295: $namespace=$env{'request.state'};
1.168 albertel 5296: #}
5297: }
5298: $namespace=~s/\//\_/g;
5299: $namespace=~s/\W//g;
1.620 albertel 5300: if (!$domain) { $domain=$env{'user.domain'}; }
5301: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5302: if ($domain eq 'public' && $stuname eq 'public') {
5303: $stuname=$ENV{'REMOTE_ADDR'};
5304: }
1.168 albertel 5305: my $now=time;
5306: my %hash;
1.1117 foxr 5307: my $path=LONCAPA::tempdir();
1.168 albertel 5308: if (tie(%hash,'GDBM_File',
5309: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5310: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5311: $hash{"version:$symb"}++;
5312: my $version=$hash{"version:$symb"};
5313: my $allkeys='';
5314: foreach my $key (keys(%$storehash)) {
5315: $allkeys.=$key.':';
1.591 albertel 5316: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5317: }
5318: $hash{"$version:$symb:timestamp"}=$now;
5319: $allkeys.='timestamp';
5320: $hash{"$version:keys:$symb"}=$allkeys;
5321: if (untie(%hash)) {
5322: return 'ok';
5323: } else {
5324: return "error:$!";
5325: }
5326: } else {
5327: return "error:$!";
5328: }
5329: }
1.167 albertel 5330:
1.168 albertel 5331: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5332:
1.168 albertel 5333: sub tmprestore {
5334: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5335:
1.168 albertel 5336: if (!$symb) {
5337: $symb=&symbread();
1.620 albertel 5338: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5339: }
5340: $symb=escape($symb);
5341:
1.620 albertel 5342: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5343:
1.620 albertel 5344: if (!$domain) { $domain=$env{'user.domain'}; }
5345: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5346: if ($domain eq 'public' && $stuname eq 'public') {
5347: $stuname=$ENV{'REMOTE_ADDR'};
5348: }
1.168 albertel 5349: my %returnhash;
5350: $namespace=~s/\//\_/g;
5351: $namespace=~s/\W//g;
5352: my %hash;
1.1117 foxr 5353: my $path=LONCAPA::tempdir();
1.168 albertel 5354: if (tie(%hash,'GDBM_File',
5355: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5356: &GDBM_READER(),0640)) {
1.168 albertel 5357: my $version=$hash{"version:$symb"};
5358: $returnhash{'version'}=$version;
5359: my $scope;
5360: for ($scope=1;$scope<=$version;$scope++) {
5361: my $vkeys=$hash{"$scope:keys:$symb"};
5362: my @keys=split(/:/,$vkeys);
5363: my $key;
5364: $returnhash{"$scope:keys"}=$vkeys;
5365: foreach $key (@keys) {
1.591 albertel 5366: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5367: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5368: }
5369: }
1.168 albertel 5370: if (!(untie(%hash))) {
5371: return "error:$!";
5372: }
5373: } else {
5374: return "error:$!";
5375: }
5376: return %returnhash;
1.167 albertel 5377: }
5378:
1.9 www 5379: # ----------------------------------------------------------------------- Store
5380:
5381: sub store {
1.1269 raeburn 5382: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5383: my $home='';
5384:
1.168 albertel 5385: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5386:
1.213 www 5387: $symb=&symbclean($symb);
1.122 albertel 5388: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5389:
1.620 albertel 5390: if (!$domain) { $domain=$env{'user.domain'}; }
5391: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5392:
5393: &devalidate($symb,$stuname,$domain);
1.109 www 5394:
5395: $symb=escape($symb);
1.187 www 5396: if (!$namespace) {
1.620 albertel 5397: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5398: return '';
5399: }
5400: }
1.620 albertel 5401: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5402:
5403: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5404: $$storehash{'host'}=$perlvar{'lonHostID'};
5405:
1.12 www 5406: my $namevalue='';
1.800 albertel 5407: foreach my $key (keys(%$storehash)) {
5408: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5409: }
1.12 www 5410: $namevalue=~s/\&$//;
1.187 www 5411: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 5412: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5413: }
5414:
1.47 www 5415: # -------------------------------------------------------------- Critical Store
5416:
5417: sub cstore {
1.1269 raeburn 5418: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5419: my $home='';
5420:
1.168 albertel 5421: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5422:
1.213 www 5423: $symb=&symbclean($symb);
1.122 albertel 5424: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5425:
1.620 albertel 5426: if (!$domain) { $domain=$env{'user.domain'}; }
5427: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5428:
5429: &devalidate($symb,$stuname,$domain);
1.109 www 5430:
5431: $symb=escape($symb);
1.187 www 5432: if (!$namespace) {
1.620 albertel 5433: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5434: return '';
5435: }
5436: }
1.620 albertel 5437: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5438:
5439: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5440: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5441:
1.47 www 5442: my $namevalue='';
1.800 albertel 5443: foreach my $key (keys(%$storehash)) {
5444: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5445: }
1.47 www 5446: $namevalue=~s/\&$//;
1.187 www 5447: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5448: return critical
1.1269 raeburn 5449: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5450: }
5451:
1.9 www 5452: # --------------------------------------------------------------------- Restore
5453:
5454: sub restore {
1.124 www 5455: my ($symb,$namespace,$domain,$stuname) = @_;
5456: my $home='';
5457:
1.168 albertel 5458: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5459:
1.122 albertel 5460: if (!$symb) {
1.1224 raeburn 5461: return if ($namespace eq 'courserequests');
5462: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5463: } else {
1.1224 raeburn 5464: unless ($namespace eq 'courserequests') {
5465: $symb=&escape(&symbclean($symb));
5466: }
1.122 albertel 5467: }
1.188 www 5468: if (!$namespace) {
1.620 albertel 5469: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5470: return '';
5471: }
5472: }
1.620 albertel 5473: if (!$domain) { $domain=$env{'user.domain'}; }
5474: if (!$stuname) { $stuname=$env{'user.name'}; }
5475: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5476: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5477:
1.12 www 5478: my %returnhash=();
1.800 albertel 5479: foreach my $line (split(/\&/,$answer)) {
5480: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5481: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5482: }
1.75 www 5483: my $version;
5484: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5485: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5486: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5487: }
1.75 www 5488: }
1.13 www 5489: return %returnhash;
1.34 www 5490: }
5491:
5492: # ---------------------------------------------------------- Course Description
1.1118 foxr 5493: #
5494: #
1.34 www 5495:
5496: sub coursedescription {
1.731 albertel 5497: my ($courseid,$args)=@_;
1.34 www 5498: $courseid=~s/^\///;
1.49 www 5499: $courseid=~s/\_/\//g;
1.34 www 5500: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5501: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5502: my $normalid=$cdomain.'_'.$cnum;
5503: # need to always cache even if we get errors otherwise we keep
5504: # trying and trying and trying to get the course description.
5505: my %envhash=();
5506: my %returnhash=();
1.731 albertel 5507:
5508: my $expiretime=600;
5509: if ($env{'request.course.id'} eq $normalid) {
5510: $expiretime=120;
5511: }
5512:
5513: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5514: if (!$args->{'freshen_cache'}
5515: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5516: foreach my $key (keys(%env)) {
5517: next if ($key !~ /^\Q$prefix\E(.*)/);
5518: my ($setting) = $1;
5519: $returnhash{$setting} = $env{$key};
5520: }
5521: return %returnhash;
5522: }
5523:
1.1118 foxr 5524: # get the data again
5525:
1.731 albertel 5526: if (!$args->{'one_time'}) {
5527: $envhash{'course.'.$normalid.'.last_cache'}=time;
5528: }
1.811 albertel 5529:
1.34 www 5530: if ($chome ne 'no_host') {
1.302 albertel 5531: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5532: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5533: my $username = $env{'user.name'}; # Defult username
5534: if(defined $args->{'user'}) {
5535: $username = $args->{'user'};
5536: }
1.129 albertel 5537: $returnhash{'home'}= $chome;
5538: $returnhash{'domain'} = $cdomain;
5539: $returnhash{'num'} = $cnum;
1.741 raeburn 5540: if (!defined($returnhash{'type'})) {
5541: $returnhash{'type'} = 'Course';
5542: }
1.130 albertel 5543: while (my ($name,$value) = each %returnhash) {
1.53 www 5544: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5545: }
1.270 www 5546: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5547: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5548: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5549: $envhash{'course.'.$normalid.'.home'}=$chome;
5550: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5551: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5552: }
5553: }
1.731 albertel 5554: if (!$args->{'one_time'}) {
1.949 raeburn 5555: &appenv(\%envhash);
1.731 albertel 5556: }
1.302 albertel 5557: return %returnhash;
1.461 www 5558: }
5559:
1.1080 raeburn 5560: sub update_released_required {
5561: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5562: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5563: $cid = $env{'request.course.id'};
5564: $cdom = $env{'course.'.$cid.'.domain'};
5565: $cnum = $env{'course.'.$cid.'.num'};
5566: $chome = $env{'course.'.$cid.'.home'};
5567: }
5568: if ($needsrelease) {
5569: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5570: my $needsupdate;
5571: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5572: $needsupdate = 1;
5573: } else {
5574: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5575: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5576: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5577: $needsupdate = 1;
5578: }
5579: }
5580: if ($needsupdate) {
5581: my %needshash = (
5582: 'internal.releaserequired' => $needsrelease,
5583: );
5584: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5585: if ($putresult eq 'ok') {
5586: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5587: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5588: if (ref($crsinfo{$cid}) eq 'HASH') {
5589: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5590: &courseidput($cdom,\%crsinfo,$chome,'notime');
5591: }
5592: }
5593: }
5594: }
5595: return;
5596: }
5597:
1.461 www 5598: # -------------------------------------------------See if a user is privileged
5599:
5600: sub privileged {
1.1219 raeburn 5601: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5602: my $now = time;
1.1219 raeburn 5603: my $roles;
5604: if (ref($possroles) eq 'ARRAY') {
5605: $roles = $possroles;
5606: } else {
5607: $roles = ['dc','su'];
5608: }
5609: if (ref($possdomains) eq 'ARRAY') {
5610: my %privileged = &privileged_by_domain($possdomains,$roles);
5611: foreach my $dom (@{$possdomains}) {
5612: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5613: (ref($privileged{$dom}) eq 'HASH')) {
5614: foreach my $role (@{$roles}) {
5615: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5616: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5617: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5618: return 1 unless (($end && $end < $now) ||
5619: ($start && $start > $now));
5620: }
5621: }
5622: }
5623: }
5624: }
5625: } else {
5626: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5627: my $now = time;
1.1170 droeschl 5628:
1.1275 musolffc 5629: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5630: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5631: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5632: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5633: or ($tstart && $tstart > $now);
1.1170 droeschl 5634: }
1.1219 raeburn 5635: }
5636: }
5637: return 0;
5638: }
1.1170 droeschl 5639:
1.1219 raeburn 5640: sub privileged_by_domain {
5641: my ($domains,$roles) = @_;
5642: my %privileged = ();
5643: my $cachetime = 60*60*24;
5644: my $now = time;
5645: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5646: return %privileged;
5647: }
5648: foreach my $dom (@{$domains}) {
5649: next if (ref($privileged{$dom}) eq 'HASH');
5650: my $needroles;
5651: foreach my $role (@{$roles}) {
5652: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5653: if (defined($cached)) {
5654: if (ref($result) eq 'HASH') {
5655: $privileged{$dom}{$role} = $result;
5656: }
5657: } else {
5658: $needroles = 1;
5659: }
5660: }
5661: if ($needroles) {
5662: my %dompersonnel = &get_domain_roles($dom,$roles);
5663: $privileged{$dom} = {};
5664: foreach my $server (keys(%dompersonnel)) {
5665: if (ref($dompersonnel{$server}) eq 'HASH') {
5666: foreach my $item (keys(%{$dompersonnel{$server}})) {
5667: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5668: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5669: next if ($end && $end < $now);
5670: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5671: $dompersonnel{$server}{$item};
5672: }
5673: }
5674: }
5675: if (ref($privileged{$dom}) eq 'HASH') {
5676: foreach my $role (@{$roles}) {
5677: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5678: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5679: } else {
5680: my %hash = ();
5681: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5682: }
5683: }
5684: }
5685: }
5686: }
5687: return %privileged;
1.9 www 5688: }
1.1 albertel 5689:
1.103 harris41 5690: # -------------------------------------------------------- Get user privileges
1.11 www 5691:
5692: sub rolesinit {
1.1169 droeschl 5693: my ($domain, $username) = @_;
5694: my %userroles = ('user.login.time' => time);
5695: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5696:
5697: # firstaccess and timerinterval are related to timed maps/resources.
5698: # also, blocking can be triggered by an activating timer
5699: # it's saved in the user's %env.
5700: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5701: my %timerinterval = &dump('timerinterval', $domain, $username);
5702: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5703: %timerintchk, %timerintenv);
5704:
1.1162 raeburn 5705: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5706: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5707: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5708: }
1.1169 droeschl 5709:
1.1162 raeburn 5710: foreach my $key (keys(%timerinterval)) {
5711: my ($cid,$rest) = split(/\0/,$key);
5712: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5713: }
1.1169 droeschl 5714:
1.11 www 5715: my %allroles=();
1.1162 raeburn 5716: my %allgroups=();
1.11 www 5717:
1.1274 raeburn 5718: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5719: my $role = $rolesdump{$area};
5720: $area =~ s/\_\w\w$//;
5721:
5722: my ($trole, $tend, $tstart, $group_privs);
5723:
5724: if ($role =~ /^cr/) {
5725: # Custom role, defined by a user
5726: # e.g., user.role.cr/msu/smith/mynewrole
5727: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5728: $trole = $1;
5729: ($tend, $tstart) = split('_', $2);
5730: } else {
5731: $trole = $role;
5732: }
5733: } elsif ($role =~ m|^gr/|) {
5734: # Role of member in a group, defined within a course/community
5735: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5736: ($trole, $tend, $tstart) = split(/_/, $role);
5737: next if $tstart eq '-1';
5738: ($trole, $group_privs) = split(/\//, $trole);
5739: $group_privs = &unescape($group_privs);
5740: } else {
5741: # Just a normal role, defined in roles.tab
5742: ($trole, $tend, $tstart) = split(/_/,$role);
5743: }
5744:
5745: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5746: $username);
5747: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5748:
5749: # role expired or not available yet?
5750: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5751: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5752:
5753: next if $area eq '' or $trole eq '';
5754:
5755: my $spec = "$trole.$area";
5756: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5757:
5758: if ($trole =~ /^cr\//) {
5759: # Custom role, defined by a user
5760: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5761: } elsif ($trole eq 'gr') {
5762: # Role of a member in a group, defined within a course/community
5763: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5764: next;
5765: } else {
5766: # Normal role, defined in roles.tab
5767: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5768: }
5769:
5770: my $cid = $tdomain.'_'.$trest;
5771: unless ($firstaccchk{$cid}) {
5772: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5773: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5774: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5775: $coursetimerstarts{$cid}{$item};
5776: }
5777: }
5778: $firstaccchk{$cid} = 1;
5779: }
5780: unless ($timerintchk{$cid}) {
5781: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5782: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5783: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5784: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5785: }
1.12 www 5786: }
1.1169 droeschl 5787: $timerintchk{$cid} = 1;
1.191 harris41 5788: }
1.11 www 5789: }
1.1169 droeschl 5790:
5791: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5792: \%allroles, \%allgroups);
5793: $env{'user.adv'} = $userroles{'user.adv'};
5794:
1.1162 raeburn 5795: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5796: }
5797:
1.567 raeburn 5798: sub set_arearole {
1.1215 raeburn 5799: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5800: unless ($nolog) {
1.567 raeburn 5801: # log the associated role with the area
1.1215 raeburn 5802: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5803: }
1.743 albertel 5804: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5805: }
5806:
5807: sub custom_roleprivs {
5808: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5809: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5810: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5811: if (&hostname($homsvr) ne '') {
1.567 raeburn 5812: my ($rdummy,$roledef)=
5813: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5814: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5815: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5816: if (defined($syspriv)) {
1.1043 raeburn 5817: if ($trest =~ /^$match_community$/) {
5818: $syspriv =~ s/bre\&S//;
5819: }
1.567 raeburn 5820: $$allroles{'cm./'}.=':'.$syspriv;
5821: $$allroles{$spec.'./'}.=':'.$syspriv;
5822: }
5823: if ($tdomain ne '') {
5824: if (defined($dompriv)) {
5825: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5826: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5827: }
5828: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 5829: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
5830: my $rolename = $1;
5831: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
5832: }
1.567 raeburn 5833: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5834: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5835: }
5836: }
5837: }
5838: }
5839: }
5840:
1.1332 raeburn 5841: sub course_adhocrole_privs {
5842: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
5843: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
5844: if ($overrides{"internal.adhocpriv.$rolename"}) {
5845: my (%currprivs,%storeprivs);
5846: foreach my $item (split(/:/,$coursepriv)) {
5847: my ($priv,$restrict) = split(/\&/,$item);
5848: $currprivs{$priv} = $restrict;
5849: }
5850: my (%possadd,%possremove,%full);
5851: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
5852: my ($priv,$restrict)=split(/\&/,$item);
5853: $full{$priv} = $restrict;
5854: }
5855: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
5856: next if ($item eq '');
5857: my ($rule,$rest) = split(/=/,$item);
5858: next unless (($rule eq 'off') || ($rule eq 'on'));
5859: foreach my $priv (split(/:/,$rest)) {
5860: if ($priv ne '') {
5861: if ($rule eq 'off') {
5862: $possremove{$priv} = 1;
5863: } else {
5864: $possadd{$priv} = 1;
5865: }
5866: }
5867: }
5868: }
5869: foreach my $priv (sort(keys(%full))) {
5870: if (exists($currprivs{$priv})) {
5871: unless (exists($possremove{$priv})) {
5872: $storeprivs{$priv} = $currprivs{$priv};
5873: }
5874: } elsif (exists($possadd{$priv})) {
5875: $storeprivs{$priv} = $full{$priv};
5876: }
5877: }
5878: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
5879: }
5880: return $coursepriv;
5881: }
5882:
1.678 raeburn 5883: sub group_roleprivs {
5884: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5885: my $access = 1;
5886: my $now = time;
5887: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5888: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5889: if ($access) {
1.811 albertel 5890: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5891: $$allgroups{$course}{$group} .=':'.$group_privs;
5892: }
5893: }
1.567 raeburn 5894:
5895: sub standard_roleprivs {
5896: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5897: if (defined($pr{$trole.':s'})) {
5898: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5899: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5900: }
5901: if ($tdomain ne '') {
5902: if (defined($pr{$trole.':d'})) {
5903: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5904: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5905: }
5906: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5907: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5908: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5909: }
5910: }
5911: }
5912:
5913: sub set_userprivs {
1.1064 raeburn 5914: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5915: my $author=0;
5916: my $adv=0;
1.678 raeburn 5917: my %grouproles = ();
5918: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5919: my @groupkeys;
1.1000 raeburn 5920: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5921: push(@groupkeys,$role);
5922: }
5923: if (ref($groups_roles) eq 'HASH') {
5924: foreach my $key (keys(%{$groups_roles})) {
5925: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5926: push(@groupkeys,$key);
5927: }
5928: }
5929: }
5930: if (@groupkeys > 0) {
5931: foreach my $role (@groupkeys) {
5932: my ($trole,$area,$sec,$extendedarea);
5933: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5934: $trole = $1;
5935: $area = $2;
5936: $sec = $3;
5937: $extendedarea = $area.$sec;
5938: if (exists($$allgroups{$area})) {
5939: foreach my $group (keys(%{$$allgroups{$area}})) {
5940: my $spec = $trole.'.'.$extendedarea;
5941: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5942: $$allgroups{$area}{$group};
1.1064 raeburn 5943: }
1.678 raeburn 5944: }
5945: }
5946: }
5947: }
5948: }
1.800 albertel 5949: foreach my $group (keys(%grouproles)) {
5950: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5951: }
1.800 albertel 5952: foreach my $role (keys(%{$allroles})) {
5953: my %thesepriv;
1.941 raeburn 5954: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5955: foreach my $item (split(/:/,$$allroles{$role})) {
5956: if ($item ne '') {
5957: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5958: if ($restrictions eq '') {
5959: $thesepriv{$privilege}='F';
5960: } elsif ($thesepriv{$privilege} ne 'F') {
5961: $thesepriv{$privilege}.=$restrictions;
5962: }
5963: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5964: }
5965: }
5966: my $thesestr='';
1.1104 raeburn 5967: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5968: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5969: }
5970: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5971: }
5972: return ($author,$adv);
5973: }
5974:
1.994 raeburn 5975: sub role_status {
1.1104 raeburn 5976: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5977: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5978: my ($one,$two) = split(m{\./},$rolekey,2);
5979: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5980: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5981: $$where = '/'.$two;
1.994 raeburn 5982: $$trolecode=$$role.'.'.$$where;
5983: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5984: $$tstatus='is';
1.1104 raeburn 5985: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5986: $$tstatus='future';
1.1034 raeburn 5987: if ($$tstart<$now) {
5988: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5989: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5990: my (%allroles,%allgroups,$group_privs,
5991: %groups_roles,@rolecodes);
1.1002 raeburn 5992: my %userroles = (
5993: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5994: );
1.1064 raeburn 5995: @rolecodes = ('cm');
1.1002 raeburn 5996: my $spec=$$role.'.'.$$where;
5997: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5998: if ($$role =~ /^cr\//) {
5999: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6000: push(@rolecodes,'cr');
1.1002 raeburn 6001: } elsif ($$role eq 'gr') {
1.1064 raeburn 6002: push(@rolecodes,$$role);
1.1002 raeburn 6003: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6004: $env{'user.name'});
1.1064 raeburn 6005: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6006: (undef,my $group_privs) = split(/\//,$trole);
6007: $group_privs = &unescape($group_privs);
6008: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6009: 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 6010: &get_groups_roles($tdomain,$trest,
6011: \%course_roles,\@rolecodes,
6012: \%groups_roles);
1.1002 raeburn 6013: } else {
1.1064 raeburn 6014: push(@rolecodes,$$role);
1.1002 raeburn 6015: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6016: }
1.1064 raeburn 6017: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
6018: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 6019: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
6020: }
6021: }
1.1034 raeburn 6022: $$tstatus = 'is';
1.1002 raeburn 6023: }
1.994 raeburn 6024: }
6025: if ($$tend) {
1.1104 raeburn 6026: if ($$tend<$update) {
1.994 raeburn 6027: $$tstatus='expired';
6028: } elsif ($$tend<$now) {
6029: $$tstatus='will_not';
6030: }
6031: }
6032: }
6033: }
6034: }
6035:
1.1104 raeburn 6036: sub get_groups_roles {
6037: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6038: return unless((ref($cdom_courseroles) eq 'HASH') &&
6039: (ref($rolecodes) eq 'ARRAY') &&
6040: (ref($groups_roles) eq 'HASH'));
6041: if (keys(%{$cdom_courseroles}) > 0) {
6042: my ($cnum) = ($rest =~ /^($match_courseid)/);
6043: if ($cdom ne '' && $cnum ne '') {
6044: foreach my $key (keys(%{$cdom_courseroles})) {
6045: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6046: my $crsrole = $1;
6047: my $crssec = $2;
6048: if ($crsrole =~ /^cr/) {
6049: unless (grep(/^cr$/,@{$rolecodes})) {
6050: push(@{$rolecodes},'cr');
6051: }
6052: } else {
6053: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6054: push(@{$rolecodes},$crsrole);
6055: }
6056: }
6057: my $rolekey = "$crsrole./$cdom/$cnum";
6058: if ($crssec ne '') {
6059: $rolekey .= "/$crssec";
6060: }
6061: $rolekey .= './';
6062: $groups_roles->{$rolekey} = $rolecodes;
6063: }
6064: }
6065: }
6066: }
6067: return;
6068: }
6069:
6070: sub delete_env_groupprivs {
6071: my ($where,$courseroles,$possroles) = @_;
6072: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6073: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6074: unless (ref($courseroles->{$udom}) eq 'HASH') {
6075: %{$courseroles->{$udom}} =
6076: &get_my_roles('','','userroles',['active'],
6077: $possroles,[$udom],1);
6078: }
6079: if (ref($courseroles->{$udom}) eq 'HASH') {
6080: foreach my $item (keys(%{$courseroles->{$udom}})) {
6081: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6082: my $area = '/'.$cdom.'/'.$cnum;
6083: my $privkey = "user.priv.$crsrole.$area";
6084: if ($crssec ne '') {
6085: $privkey .= '/'.$crssec;
6086: }
6087: $privkey .= ".$area/$group";
6088: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6089: }
6090: }
6091: return;
6092: }
6093:
1.994 raeburn 6094: sub check_adhoc_privs {
1.1329 raeburn 6095: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6096: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 6097: if ($sec) {
6098: $cckey .= '/'.$sec;
6099: }
1.1185 raeburn 6100: my $setprivs;
1.994 raeburn 6101: if ($env{$cckey}) {
6102: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6103: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6104: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 6105: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6106: $setprivs = 1;
1.994 raeburn 6107: }
6108: } else {
1.1330 raeburn 6109: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6110: $setprivs = 1;
1.994 raeburn 6111: }
1.1185 raeburn 6112: return $setprivs;
1.994 raeburn 6113: }
6114:
6115: sub set_adhoc_privileges {
1.1326 raeburn 6116: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 6117: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6118: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 6119: if ($sec ne '') {
6120: $area .= '/'.$sec;
6121: }
1.994 raeburn 6122: my $spec = $role.'.'.$area;
6123: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 6124: $env{'user.name'},1);
1.1326 raeburn 6125: my %rolehash = ();
1.1332 raeburn 6126: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6127: my $rolename = $1;
1.1326 raeburn 6128: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 6129: my %domdef = &get_domain_defaults($dcdom);
6130: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6131: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6132: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6133: }
6134: }
1.1326 raeburn 6135: } else {
6136: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6137: }
6138: my ($author,$adv)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6139: &appenv(\%userroles,[$role,'cm']);
6140: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 6141: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6142: &appenv( {'request.role' => $spec,
6143: 'request.role.domain' => $dcdom,
1.1332 raeburn 6144: 'request.course.sec' => $sec,
1.1088 raeburn 6145: }
6146: );
6147: my $tadv=0;
6148: if (&allowed('adv') eq 'F') { $tadv=1; }
6149: &appenv({'request.role.adv' => $tadv});
6150: }
1.994 raeburn 6151: }
6152:
1.12 www 6153: # --------------------------------------------------------------- get interface
6154:
6155: sub get {
1.131 albertel 6156: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6157: my $items='';
1.800 albertel 6158: foreach my $item (@$storearr) {
6159: $items.=&escape($item).'&';
1.191 harris41 6160: }
1.12 www 6161: $items=~s/\&$//;
1.620 albertel 6162: if (!$udomain) { $udomain=$env{'user.domain'}; }
6163: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6164: my $uhome=&homeserver($uname,$udomain);
6165:
1.133 albertel 6166: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6167: my @pairs=split(/\&/,$rep);
1.273 albertel 6168: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6169: return @pairs;
6170: }
1.15 www 6171: my %returnhash=();
1.42 www 6172: my $i=0;
1.800 albertel 6173: foreach my $item (@$storearr) {
6174: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6175: $i++;
1.191 harris41 6176: }
1.15 www 6177: return %returnhash;
1.27 www 6178: }
6179:
6180: # --------------------------------------------------------------- del interface
6181:
6182: sub del {
1.133 albertel 6183: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6184: my $items='';
1.800 albertel 6185: foreach my $item (@$storearr) {
6186: $items.=&escape($item).'&';
1.191 harris41 6187: }
1.984 neumanie 6188:
1.27 www 6189: $items=~s/\&$//;
1.620 albertel 6190: if (!$udomain) { $udomain=$env{'user.domain'}; }
6191: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6192: my $uhome=&homeserver($uname,$udomain);
6193: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6194: }
6195:
6196: # -------------------------------------------------------------- dump interface
6197:
1.1180 droeschl 6198: sub unserialize {
6199: my ($rep, $escapedkeys) = @_;
6200:
6201: return {} if $rep =~ /^error/;
6202:
6203: my %returnhash=();
1.1252 raeburn 6204: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 6205: my ($key, $value) = split(/=/, $item, 2);
6206: $key = unescape($key) unless $escapedkeys;
6207: next if $key =~ /^error: 2 /;
1.1252 raeburn 6208: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 6209: }
6210: #return %returnhash;
6211: return \%returnhash;
6212: }
6213:
6214: # see Lond::dump_with_regexp
6215: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6216: sub dump {
1.1180 droeschl 6217: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6218: if (!$udomain) { $udomain=$env{'user.domain'}; }
6219: if (!$uname) { $uname=$env{'user.name'}; }
6220: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6221:
1.1266 raeburn 6222: if ($regexp) {
6223: $regexp=&escape($regexp);
6224: } else {
6225: $regexp='.';
6226: }
1.1180 droeschl 6227: if (grep { $_ eq $uhome } current_machine_ids()) {
6228: # user is hosted on this machine
1.1266 raeburn 6229: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 6230: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 6231: return %{unserialize($reply, $escapedkeys)};
6232: }
1.1166 raeburn 6233: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6234: my @pairs=split(/\&/,$rep);
6235: my %returnhash=();
1.1098 foxr 6236: if (!($rep =~ /^error/ )) {
6237: foreach my $item (@pairs) {
6238: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 6239: $key = unescape($key) unless $escapedkeys;
6240: #$key = &unescape($key);
1.1098 foxr 6241: next if ($key =~ /^error: 2 /);
6242: $returnhash{$key}=&thaw_unescape($value);
6243: }
1.755 albertel 6244: }
6245: return %returnhash;
1.407 www 6246: }
6247:
1.1098 foxr 6248:
1.717 albertel 6249: # --------------------------------------------------------- dumpstore interface
6250:
6251: sub dumpstore {
6252: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 6253: # same as dump but keys must be escaped. They may contain colon separated
6254: # lists of values that may themself contain colons (e.g. symbs).
6255: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6256: }
6257:
1.407 www 6258: # -------------------------------------------------------------- keys interface
6259:
6260: sub getkeys {
6261: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6262: if (!$udomain) { $udomain=$env{'user.domain'}; }
6263: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6264: my $uhome=&homeserver($uname,$udomain);
6265: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6266: my @keyarray=();
1.800 albertel 6267: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6268: next if ($key =~ /^error: 2 /);
1.800 albertel 6269: push(@keyarray,&unescape($key));
1.407 www 6270: }
6271: return @keyarray;
1.318 matthew 6272: }
6273:
1.319 matthew 6274: # --------------------------------------------------------------- currentdump
6275: sub currentdump {
1.328 matthew 6276: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6277: $courseid = $env{'request.course.id'} if (! defined($courseid));
6278: $sdom = $env{'user.domain'} if (! defined($sdom));
6279: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6280: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 6281: my $rep;
6282:
6283: if (grep { $_ eq $uhome } current_machine_ids()) {
6284: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6285: $courseid)));
6286: } else {
6287: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6288: }
6289:
1.318 matthew 6290: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6291: #
1.318 matthew 6292: my %returnhash=();
1.319 matthew 6293: #
6294: if ($rep eq "unknown_cmd") {
6295: # an old lond will not know currentdump
6296: # Do a dump and make it look like a currentdump
1.822 albertel 6297: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6298: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6299: my %hash = @tmp;
6300: @tmp=();
1.424 matthew 6301: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6302: } else {
6303: my @pairs=split(/\&/,$rep);
1.800 albertel 6304: foreach my $pair (@pairs) {
6305: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6306: my ($symb,$param) = split(/:/,$key);
6307: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6308: &thaw_unescape($value);
1.319 matthew 6309: }
1.191 harris41 6310: }
1.12 www 6311: return %returnhash;
1.424 matthew 6312: }
6313:
6314: sub convert_dump_to_currentdump{
6315: my %hash = %{shift()};
6316: my %returnhash;
6317: # Code ripped from lond, essentially. The only difference
6318: # here is the unescaping done by lonnet::dump(). Conceivably
6319: # we might run in to problems with parameter names =~ /^v\./
6320: while (my ($key,$value) = each(%hash)) {
6321: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6322: $symb = &unescape($symb);
6323: $param = &unescape($param);
1.424 matthew 6324: next if ($v eq 'version' || $symb eq 'keys');
6325: next if (exists($returnhash{$symb}) &&
6326: exists($returnhash{$symb}->{$param}) &&
6327: $returnhash{$symb}->{'v.'.$param} > $v);
6328: $returnhash{$symb}->{$param}=$value;
6329: $returnhash{$symb}->{'v.'.$param}=$v;
6330: }
6331: #
6332: # Remove all of the keys in the hashes which keep track of
6333: # the version of the parameter.
6334: while (my ($symb,$param_hash) = each(%returnhash)) {
6335: # use a foreach because we are going to delete from the hash.
6336: foreach my $key (keys(%$param_hash)) {
6337: delete($param_hash->{$key}) if ($key =~ /^v\./);
6338: }
6339: }
6340: return \%returnhash;
1.12 www 6341: }
6342:
1.627 albertel 6343: # ------------------------------------------------------ critical inc interface
6344:
6345: sub cinc {
6346: return &inc(@_,'critical');
6347: }
6348:
1.449 matthew 6349: # --------------------------------------------------------------- inc interface
6350:
6351: sub inc {
1.627 albertel 6352: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6353: if (!$udomain) { $udomain=$env{'user.domain'}; }
6354: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6355: my $uhome=&homeserver($uname,$udomain);
6356: my $items='';
6357: if (! ref($store)) {
6358: # got a single value, so use that instead
6359: $items = &escape($store).'=&';
6360: } elsif (ref($store) eq 'SCALAR') {
6361: $items = &escape($$store).'=&';
6362: } elsif (ref($store) eq 'ARRAY') {
6363: $items = join('=&',map {&escape($_);} @{$store});
6364: } elsif (ref($store) eq 'HASH') {
6365: while (my($key,$value) = each(%{$store})) {
6366: $items.= &escape($key).'='.&escape($value).'&';
6367: }
6368: }
6369: $items=~s/\&$//;
1.627 albertel 6370: if ($critical) {
6371: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6372: } else {
6373: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6374: }
1.449 matthew 6375: }
6376:
1.12 www 6377: # --------------------------------------------------------------- put interface
6378:
6379: sub put {
1.134 albertel 6380: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6381: if (!$udomain) { $udomain=$env{'user.domain'}; }
6382: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6383: my $uhome=&homeserver($uname,$udomain);
1.12 www 6384: my $items='';
1.800 albertel 6385: foreach my $item (keys(%$storehash)) {
6386: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6387: }
1.12 www 6388: $items=~s/\&$//;
1.134 albertel 6389: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6390: }
6391:
1.631 albertel 6392: # ------------------------------------------------------------ newput interface
6393:
6394: sub newput {
6395: my ($namespace,$storehash,$udomain,$uname)=@_;
6396: if (!$udomain) { $udomain=$env{'user.domain'}; }
6397: if (!$uname) { $uname=$env{'user.name'}; }
6398: my $uhome=&homeserver($uname,$udomain);
6399: my $items='';
6400: foreach my $key (keys(%$storehash)) {
6401: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6402: }
6403: $items=~s/\&$//;
6404: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6405: }
6406:
6407: # --------------------------------------------------------- putstore interface
6408:
1.524 raeburn 6409: sub putstore {
1.1269 raeburn 6410: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6411: if (!$udomain) { $udomain=$env{'user.domain'}; }
6412: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6413: my $uhome=&homeserver($uname,$udomain);
6414: my $items='';
1.715 albertel 6415: foreach my $key (keys(%$storehash)) {
6416: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6417: }
1.715 albertel 6418: $items=~s/\&$//;
1.716 albertel 6419: my $esc_symb=&escape($symb);
6420: my $esc_v=&escape($version);
1.715 albertel 6421: my $reply =
1.716 albertel 6422: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6423: $uhome);
1.1269 raeburn 6424: if (($tolog) && ($reply eq 'ok')) {
6425: my $namevalue='';
6426: foreach my $key (keys(%{$storehash})) {
6427: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6428: }
6429: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6430: '&host='.&escape($perlvar{'lonHostID'}).
6431: '&version='.$esc_v.
6432: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6433: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6434: }
1.715 albertel 6435: if ($reply eq 'unknown_cmd') {
1.716 albertel 6436: # gfall back to way things use to be done
1.715 albertel 6437: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6438: $uname);
1.524 raeburn 6439: }
1.715 albertel 6440: return $reply;
6441: }
6442:
6443: sub old_putstore {
1.716 albertel 6444: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6445: if (!$udomain) { $udomain=$env{'user.domain'}; }
6446: if (!$uname) { $uname=$env{'user.name'}; }
6447: my $uhome=&homeserver($uname,$udomain);
6448: my %newstorehash;
1.800 albertel 6449: foreach my $item (keys(%$storehash)) {
6450: my $key = $version.':'.&escape($symb).':'.$item;
6451: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6452: }
6453: my $items='';
6454: my %allitems = ();
1.800 albertel 6455: foreach my $item (keys(%newstorehash)) {
6456: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6457: my $key = $1.':keys:'.$2;
6458: $allitems{$key} .= $3.':';
6459: }
1.800 albertel 6460: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6461: }
1.800 albertel 6462: foreach my $item (keys(%allitems)) {
6463: $allitems{$item} =~ s/\:$//;
6464: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6465: }
6466: $items=~s/\&$//;
6467: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6468: }
6469:
1.47 www 6470: # ------------------------------------------------------ critical put interface
6471:
6472: sub cput {
1.134 albertel 6473: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6474: if (!$udomain) { $udomain=$env{'user.domain'}; }
6475: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6476: my $uhome=&homeserver($uname,$udomain);
1.47 www 6477: my $items='';
1.800 albertel 6478: foreach my $item (keys(%$storehash)) {
6479: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6480: }
1.47 www 6481: $items=~s/\&$//;
1.134 albertel 6482: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6483: }
6484:
6485: # -------------------------------------------------------------- eget interface
6486:
6487: sub eget {
1.133 albertel 6488: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6489: my $items='';
1.800 albertel 6490: foreach my $item (@$storearr) {
6491: $items.=&escape($item).'&';
1.191 harris41 6492: }
1.12 www 6493: $items=~s/\&$//;
1.620 albertel 6494: if (!$udomain) { $udomain=$env{'user.domain'}; }
6495: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6496: my $uhome=&homeserver($uname,$udomain);
6497: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6498: my @pairs=split(/\&/,$rep);
6499: my %returnhash=();
1.42 www 6500: my $i=0;
1.800 albertel 6501: foreach my $item (@$storearr) {
6502: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6503: $i++;
1.191 harris41 6504: }
1.12 www 6505: return %returnhash;
6506: }
6507:
1.667 albertel 6508: # ------------------------------------------------------------ tmpput interface
6509: sub tmpput {
1.802 raeburn 6510: my ($storehash,$server,$context)=@_;
1.667 albertel 6511: my $items='';
1.800 albertel 6512: foreach my $item (keys(%$storehash)) {
6513: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6514: }
6515: $items=~s/\&$//;
1.802 raeburn 6516: if (defined($context)) {
6517: $items .= ':'.&escape($context);
6518: }
1.667 albertel 6519: return &reply("tmpput:$items",$server);
6520: }
6521:
6522: # ------------------------------------------------------------ tmpget interface
6523: sub tmpget {
1.688 albertel 6524: my ($token,$server)=@_;
6525: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6526: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6527: my %returnhash;
1.1328 raeburn 6528: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6529: return %returnhash;
6530: }
1.667 albertel 6531: foreach my $item (split(/\&/,$rep)) {
6532: my ($key,$value)=split(/=/,$item);
6533: $returnhash{&unescape($key)}=&thaw_unescape($value);
6534: }
6535: return %returnhash;
6536: }
6537:
1.1113 raeburn 6538: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6539: sub tmpdel {
6540: my ($token,$server)=@_;
6541: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6542: return &reply("tmpdel:$token",$server);
6543: }
6544:
1.1198 raeburn 6545: # ------------------------------------------------------------ get_timebased_id
6546:
6547: sub get_timebased_id {
6548: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6549: $maxtries) = @_;
6550: my ($newid,$error,$dellock);
6551: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6552: return ('','ok','invalid call to get suffix');
6553: }
6554:
6555: # set defaults for any optional args for which values were not supplied
6556: if ($who eq '') {
6557: $who = $env{'user.name'}.':'.$env{'user.domain'};
6558: }
6559: if (!$locktries) {
6560: $locktries = 3;
6561: }
6562: if (!$maxtries) {
6563: $maxtries = 10;
6564: }
6565:
6566: if (($cdom eq '') || ($cnum eq '')) {
6567: if ($env{'request.course.id'}) {
6568: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6569: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6570: }
6571: if (($cdom eq '') || ($cnum eq '')) {
6572: return ('','ok','call to get suffix not in course context');
6573: }
6574: }
6575:
6576: # construct locking item
6577: my $lockhash = {
6578: $prefix."\0".'locked_'.$keyid => $who,
6579: };
6580: my $tries = 0;
6581:
6582: # attempt to get lock on nohist_$namespace file
6583: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6584: while (($gotlock ne 'ok') && $tries <$locktries) {
6585: $tries ++;
6586: sleep 1;
6587: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6588: }
6589:
6590: # attempt to get unique identifier, based on current timestamp
6591: if ($gotlock eq 'ok') {
6592: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6593: my $id = time;
6594: $newid = $id;
1.1268 raeburn 6595: if ($idtype eq 'addcode') {
6596: $newid .= &sixnum_code();
6597: }
1.1198 raeburn 6598: my $idtries = 0;
6599: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6600: if ($idtype eq 'concat') {
6601: $newid = $id.$idtries;
1.1268 raeburn 6602: } elsif ($idtype eq 'addcode') {
6603: $newid = $newid.&sixnum_code();
1.1198 raeburn 6604: } else {
6605: $newid ++;
6606: }
6607: $idtries ++;
6608: }
6609: if (!exists($inuse{$prefix."\0".$newid})) {
6610: my %new_item = (
6611: $prefix."\0".$newid => $who,
6612: );
6613: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6614: $cdom,$cnum);
6615: if ($putresult ne 'ok') {
6616: undef($newid);
6617: $error = 'error saving new item: '.$putresult;
6618: }
6619: } else {
1.1268 raeburn 6620: undef($newid);
1.1198 raeburn 6621: $error = ('error: no unique suffix available for the new item ');
6622: }
6623: # remove lock
6624: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6625: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6626: } else {
6627: $error = "error: could not obtain lockfile\n";
6628: $dellock = 'ok';
1.1276 raeburn 6629: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6630: $dellock = 'nolock';
6631: }
1.1198 raeburn 6632: }
6633: return ($newid,$dellock,$error);
6634: }
6635:
1.1268 raeburn 6636: sub sixnum_code {
6637: my $code;
6638: for (0..6) {
6639: $code .= int( rand(9) );
6640: }
6641: return $code;
6642: }
6643:
1.765 albertel 6644: # -------------------------------------------------- portfolio access checking
6645:
6646: sub portfolio_access {
1.1270 raeburn 6647: my ($requrl,$clientip) = @_;
1.765 albertel 6648: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6649: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6650: if ($result) {
6651: my %setters;
6652: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6653: my ($startblock,$endblock) =
6654: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6655: if ($startblock && $endblock) {
6656: return 'B';
6657: }
6658: } else {
6659: my ($startblock,$endblock) =
6660: &Apache::loncommon::blockcheck(\%setters,'port');
6661: if ($startblock && $endblock) {
6662: return 'B';
6663: }
6664: }
6665: }
1.765 albertel 6666: if ($result eq 'ok') {
1.766 albertel 6667: return 'F';
1.765 albertel 6668: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6669: return 'A';
1.765 albertel 6670: }
1.766 albertel 6671: return '';
1.765 albertel 6672: }
6673:
6674: sub get_portfolio_access {
1.1270 raeburn 6675: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6676:
6677: if (!ref($access_hash)) {
6678: my $current_perms = &get_portfile_permissions($udom,$unum);
6679: my %access_controls = &get_access_controls($current_perms,$group,
6680: $file_name);
6681: $access_hash = $access_controls{$file_name};
6682: }
6683:
1.1270 raeburn 6684: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6685: my $now = time;
6686: if (ref($access_hash) eq 'HASH') {
6687: foreach my $key (keys(%{$access_hash})) {
6688: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6689: if ($start > $now) {
6690: next;
6691: }
6692: if ($end && $end<$now) {
6693: next;
6694: }
6695: if ($scope eq 'public') {
6696: $public = $key;
6697: last;
6698: } elsif ($scope eq 'guest') {
6699: $guest = $key;
6700: } elsif ($scope eq 'domains') {
6701: push(@domains,$key);
6702: } elsif ($scope eq 'users') {
6703: push(@users,$key);
6704: } elsif ($scope eq 'course') {
6705: push(@courses,$key);
6706: } elsif ($scope eq 'group') {
6707: push(@groups,$key);
1.1270 raeburn 6708: } elsif ($scope eq 'ip') {
6709: push(@ips,$key);
1.765 albertel 6710: }
6711: }
6712: if ($public) {
6713: return 'ok';
1.1270 raeburn 6714: } elsif (@ips > 0) {
6715: my $allowed;
6716: foreach my $ipkey (@ips) {
6717: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6718: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6719: $allowed = 1;
6720: last;
6721: }
6722: }
6723: }
6724: if ($allowed) {
6725: return 'ok';
6726: }
1.765 albertel 6727: }
6728: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6729: if ($guest) {
6730: return $guest;
6731: }
6732: } else {
6733: if (@domains > 0) {
6734: foreach my $domkey (@domains) {
6735: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6736: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6737: return 'ok';
6738: }
6739: }
6740: }
6741: }
6742: if (@users > 0) {
6743: foreach my $userkey (@users) {
1.865 raeburn 6744: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6745: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6746: if (ref($item) eq 'HASH') {
6747: if (($item->{'uname'} eq $env{'user.name'}) &&
6748: ($item->{'udom'} eq $env{'user.domain'})) {
6749: return 'ok';
6750: }
6751: }
6752: }
6753: }
1.765 albertel 6754: }
6755: }
6756: my %roleshash;
6757: my @courses_and_groups = @courses;
6758: push(@courses_and_groups,@groups);
6759: if (@courses_and_groups > 0) {
6760: my (%allgroups,%allroles);
6761: my ($start,$end,$role,$sec,$group);
6762: foreach my $envkey (%env) {
1.1060 raeburn 6763: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6764: my $cid = $2.'_'.$3;
6765: if ($1 eq 'gr') {
6766: $group = $4;
6767: $allgroups{$cid}{$group} = $env{$envkey};
6768: } else {
6769: if ($4 eq '') {
6770: $sec = 'none';
6771: } else {
6772: $sec = $4;
6773: }
6774: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6775: }
1.811 albertel 6776: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6777: my $cid = $2.'_'.$3;
6778: if ($4 eq '') {
6779: $sec = 'none';
6780: } else {
6781: $sec = $4;
6782: }
6783: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6784: }
6785: }
6786: if (keys(%allroles) == 0) {
6787: return;
6788: }
6789: foreach my $key (@courses_and_groups) {
6790: my %content = %{$$access_hash{$key}};
6791: my $cnum = $content{'number'};
6792: my $cdom = $content{'domain'};
6793: my $cid = $cdom.'_'.$cnum;
6794: if (!exists($allroles{$cid})) {
6795: next;
6796: }
6797: foreach my $role_id (keys(%{$content{'roles'}})) {
6798: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6799: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6800: my @status = @{$content{'roles'}{$role_id}{'access'}};
6801: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6802: foreach my $role (keys(%{$allroles{$cid}})) {
6803: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6804: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6805: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6806: if (grep/^all$/,@sections) {
6807: return 'ok';
6808: } else {
6809: if (grep/^$sec$/,@sections) {
6810: return 'ok';
6811: }
6812: }
6813: }
6814: }
6815: if (keys(%{$allgroups{$cid}}) == 0) {
6816: if (grep/^none$/,@groups) {
6817: return 'ok';
6818: }
6819: } else {
6820: if (grep/^all$/,@groups) {
6821: return 'ok';
6822: }
6823: foreach my $group (keys(%{$allgroups{$cid}})) {
6824: if (grep/^$group$/,@groups) {
6825: return 'ok';
6826: }
6827: }
6828: }
6829: }
6830: }
6831: }
6832: }
6833: }
6834: if ($guest) {
6835: return $guest;
6836: }
6837: }
6838: }
6839: return;
6840: }
6841:
6842: sub course_group_datechecker {
6843: my ($dates,$now,$status) = @_;
6844: my ($start,$end) = split(/\./,$dates);
6845: if (!$start && !$end) {
6846: return 'ok';
6847: }
6848: if (grep/^active$/,@{$status}) {
6849: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6850: return 'ok';
6851: }
6852: }
6853: if (grep/^previous$/,@{$status}) {
6854: if ($end > $now ) {
6855: return 'ok';
6856: }
6857: }
6858: if (grep/^future$/,@{$status}) {
6859: if ($start > $now) {
6860: return 'ok';
6861: }
6862: }
6863: return;
6864: }
6865:
6866: sub parse_portfolio_url {
6867: my ($url) = @_;
6868:
6869: my ($type,$udom,$unum,$group,$file_name);
6870:
1.823 albertel 6871: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6872: $type = 1;
6873: $udom = $1;
6874: $unum = $2;
6875: $file_name = $3;
1.823 albertel 6876: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6877: $type = 2;
6878: $udom = $1;
6879: $unum = $2;
6880: $group = $3;
6881: $file_name = $3.'/'.$4;
6882: }
6883: if (wantarray) {
6884: return ($type,$udom,$unum,$file_name,$group);
6885: }
6886: return $type;
6887: }
6888:
6889: sub is_portfolio_url {
6890: my ($url) = @_;
6891: return scalar(&parse_portfolio_url($url));
6892: }
6893:
1.798 raeburn 6894: sub is_portfolio_file {
6895: my ($file) = @_;
1.820 raeburn 6896: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6897: return 1;
6898: }
6899: return;
6900: }
6901:
1.976 raeburn 6902: sub usertools_access {
1.1084 raeburn 6903: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6904: my ($access,%tools);
6905: if ($context eq '') {
6906: $context = 'tools';
6907: }
6908: if ($context eq 'requestcourses') {
6909: %tools = (
6910: official => 1,
6911: unofficial => 1,
1.1006 raeburn 6912: community => 1,
1.1246 raeburn 6913: textbook => 1,
1.1305 raeburn 6914: placement => 1,
1.985 raeburn 6915: );
1.1183 raeburn 6916: } elsif ($context eq 'requestauthor') {
6917: %tools = (
6918: requestauthor => 1,
6919: );
1.985 raeburn 6920: } else {
6921: %tools = (
6922: aboutme => 1,
6923: blog => 1,
1.1177 raeburn 6924: webdav => 1,
1.985 raeburn 6925: portfolio => 1,
6926: );
6927: }
1.976 raeburn 6928: return if (!defined($tools{$tool}));
6929:
1.1242 raeburn 6930: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6931: $udom = $env{'user.domain'};
6932: $uname = $env{'user.name'};
6933: }
6934:
1.978 raeburn 6935: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6936: if ($action ne 'reload') {
1.985 raeburn 6937: if ($context eq 'requestcourses') {
6938: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6939: } elsif ($context eq 'requestauthor') {
6940: return $env{'environment.canrequest.author'};
1.985 raeburn 6941: } else {
6942: return $env{'environment.availabletools.'.$tool};
6943: }
6944: }
1.976 raeburn 6945: }
6946:
1.1183 raeburn 6947: my ($toolstatus,$inststatus,$envkey);
6948: if ($context eq 'requestauthor') {
6949: $envkey = $context;
6950: } else {
6951: $envkey = $context.'.'.$tool;
6952: }
1.976 raeburn 6953:
1.985 raeburn 6954: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6955: ($action ne 'reload')) {
1.1183 raeburn 6956: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6957: $inststatus = $env{'environment.inststatus'};
6958: } else {
1.1084 raeburn 6959: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6960: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6961: $inststatus = $userenvref->{'inststatus'};
6962: } else {
1.1183 raeburn 6963: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6964: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6965: $inststatus = $userenv{'inststatus'};
6966: }
1.976 raeburn 6967: }
6968:
6969: if ($toolstatus ne '') {
6970: if ($toolstatus) {
6971: $access = 1;
6972: } else {
6973: $access = 0;
6974: }
6975: return $access;
6976: }
6977:
1.1084 raeburn 6978: my ($is_adv,%domdef);
6979: if (ref($is_advref) eq 'HASH') {
6980: $is_adv = $is_advref->{'is_adv'};
6981: } else {
6982: $is_adv = &is_advanced_user($udom,$uname);
6983: }
6984: if (ref($domdefref) eq 'HASH') {
6985: %domdef = %{$domdefref};
6986: } else {
6987: %domdef = &get_domain_defaults($udom);
6988: }
1.976 raeburn 6989: if (ref($domdef{$tool}) eq 'HASH') {
6990: if ($is_adv) {
6991: if ($domdef{$tool}{'_LC_adv'} ne '') {
6992: if ($domdef{$tool}{'_LC_adv'}) {
6993: $access = 1;
6994: } else {
6995: $access = 0;
6996: }
6997: return $access;
6998: }
6999: }
7000: if ($inststatus ne '') {
7001: my ($hasaccess,$hasnoaccess);
7002: foreach my $affiliation (split(/:/,$inststatus)) {
7003: if ($domdef{$tool}{$affiliation} ne '') {
7004: if ($domdef{$tool}{$affiliation}) {
7005: $hasaccess = 1;
7006: } else {
7007: $hasnoaccess = 1;
7008: }
7009: }
7010: }
7011: if ($hasaccess || $hasnoaccess) {
7012: if ($hasaccess) {
7013: $access = 1;
7014: } elsif ($hasnoaccess) {
7015: $access = 0;
7016: }
7017: return $access;
7018: }
7019: } else {
7020: if ($domdef{$tool}{'default'} ne '') {
7021: if ($domdef{$tool}{'default'}) {
7022: $access = 1;
7023: } elsif ($domdef{$tool}{'default'} == 0) {
7024: $access = 0;
7025: }
7026: return $access;
7027: }
7028: }
7029: } else {
1.1177 raeburn 7030: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7031: $access = 1;
7032: } else {
7033: $access = 0;
7034: }
1.976 raeburn 7035: return $access;
7036: }
7037: }
7038:
1.1050 raeburn 7039: sub is_course_owner {
7040: my ($cdom,$cnum,$udom,$uname) = @_;
7041: if (($udom eq '') || ($uname eq '')) {
7042: $udom = $env{'user.domain'};
7043: $uname = $env{'user.name'};
7044: }
7045: unless (($udom eq '') || ($uname eq '')) {
7046: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7047: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7048: return 1;
7049: } else {
7050: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7051: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7052: return 1;
7053: }
7054: }
7055: }
7056: }
7057: return;
7058: }
7059:
1.976 raeburn 7060: sub is_advanced_user {
7061: my ($udom,$uname) = @_;
1.1085 raeburn 7062: if ($udom ne '' && $uname ne '') {
7063: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7064: if (wantarray) {
7065: return ($env{'user.adv'},$env{'user.author'});
7066: } else {
7067: return $env{'user.adv'};
7068: }
1.1085 raeburn 7069: }
7070: }
1.976 raeburn 7071: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7072: my %allroles;
1.1128 raeburn 7073: my ($is_adv,$is_author);
1.976 raeburn 7074: foreach my $role (keys(%roleshash)) {
7075: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7076: my $area = '/'.$tdomain.'/'.$trest;
7077: if ($sec ne '') {
7078: $area .= '/'.$sec;
7079: }
7080: if (($area ne '') && ($trole ne '')) {
7081: my $spec=$trole.'.'.$area;
7082: if ($trole =~ /^cr\//) {
7083: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7084: } elsif ($trole ne 'gr') {
7085: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7086: }
1.1128 raeburn 7087: if ($trole eq 'au') {
7088: $is_author = 1;
7089: }
1.976 raeburn 7090: }
7091: }
7092: foreach my $role (keys(%allroles)) {
7093: last if ($is_adv);
7094: foreach my $item (split(/:/,$allroles{$role})) {
7095: if ($item ne '') {
7096: my ($privilege,$restrictions)=split(/&/,$item);
7097: if ($privilege eq 'adv') {
7098: $is_adv = 1;
7099: last;
7100: }
7101: }
7102: }
7103: }
1.1128 raeburn 7104: if (wantarray) {
7105: return ($is_adv,$is_author);
7106: }
1.976 raeburn 7107: return $is_adv;
7108: }
1.798 raeburn 7109:
1.1035 raeburn 7110: sub check_can_request {
1.1036 raeburn 7111: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7112: my $canreq = 0;
7113: my ($types,$typename) = &Apache::loncommon::course_types();
7114: my @options = ('approval','validate','autolimit');
7115: my $optregex = join('|',@options);
7116: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7117: foreach my $type (@{$types}) {
7118: if (&usertools_access($env{'user.name'},
7119: $env{'user.domain'},
7120: $type,undef,'requestcourses')) {
7121: $canreq ++;
1.1036 raeburn 7122: if (ref($request_domains) eq 'HASH') {
7123: push(@{$request_domains->{$type}},$env{'user.domain'});
7124: }
1.1035 raeburn 7125: if ($dom eq $env{'user.domain'}) {
7126: $can_request->{$type} = 1;
7127: }
7128: }
7129: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7130: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7131: if (@curr > 0) {
1.1036 raeburn 7132: foreach my $item (@curr) {
7133: if (ref($request_domains) eq 'HASH') {
7134: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7135: if ($otherdom ne '') {
7136: if (ref($request_domains->{$type}) eq 'ARRAY') {
7137: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7138: push(@{$request_domains->{$type}},$otherdom);
7139: }
7140: } else {
7141: push(@{$request_domains->{$type}},$otherdom);
7142: }
7143: }
7144: }
7145: }
7146: unless($dom eq $env{'user.domain'}) {
7147: $canreq ++;
1.1035 raeburn 7148: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7149: $can_request->{$type} = 1;
7150: }
7151: }
7152: }
7153: }
7154: }
7155: }
7156: return $canreq;
7157: }
7158:
1.341 www 7159: # ---------------------------------------------- Custom access rule evaluation
7160:
7161: sub customaccess {
7162: my ($priv,$uri)=@_;
1.807 albertel 7163: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7164: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7165: $udom = &LONCAPA::clean_domain($udom);
7166: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7167: my $access=0;
1.800 albertel 7168: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7169: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7170: if ($type eq 'user') {
7171: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7172: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7173: if ($tdom) {
7174: if ($tdom ne $env{'user.domain'}) { next; }
7175: }
1.896 albertel 7176: if ($tuname) {
7177: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7178: }
7179: $access=($effect eq 'allow');
7180: last;
7181: }
7182: } else {
7183: if ($role) {
7184: if ($role ne $urole) { next; }
7185: }
7186: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7187: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7188: if ($tdom) {
7189: if ($tdom ne $udom) { next; }
7190: }
7191: if ($tcrs) {
7192: if ($tcrs ne $ucrs) { next; }
7193: }
7194: if ($tsec) {
7195: if ($tsec ne $usec) { next; }
7196: }
7197: $access=($effect eq 'allow');
7198: last;
7199: }
7200: if ($realm eq '' && $role eq '') {
7201: $access=($effect eq 'allow');
7202: }
1.402 bowersj2 7203: }
1.341 www 7204: }
7205: return $access;
7206: }
7207:
1.103 harris41 7208: # ------------------------------------------------- Check for a user privilege
1.12 www 7209:
7210: sub allowed {
1.1281 raeburn 7211: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7212: my $ver_orguri=$uri;
1.439 www 7213: $uri=&deversion($uri);
1.152 www 7214: my $orguri=$uri;
1.52 www 7215: $uri=&declutter($uri);
1.809 raeburn 7216:
1.810 raeburn 7217: if ($priv eq 'evb') {
7218: # Evade communication block restrictions for specified role in a course
7219: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7220: return $1;
7221: } else {
7222: return;
7223: }
7224: }
7225:
1.620 albertel 7226: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7227: # Free bre access to adm and meta resources
1.775 albertel 7228: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 7229: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7230: && ($priv eq 'bre')) {
1.14 www 7231: return 'F';
1.159 www 7232: }
7233:
1.545 banghart 7234: # Free bre access to user's own portfolio contents
1.714 raeburn 7235: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7236: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7237: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7238: my %setters;
7239: my ($startblock,$endblock) =
7240: &Apache::loncommon::blockcheck(\%setters,'port');
7241: if ($startblock && $endblock) {
7242: return 'B';
7243: } else {
7244: return 'F';
7245: }
1.545 banghart 7246: }
7247:
1.762 raeburn 7248: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7249: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7250: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7251: if (exists($env{'request.course.id'})) {
7252: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7253: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7254: if (($domain eq $cdom) && ($name eq $cnum)) {
7255: my $courseprivid=$env{'request.course.id'};
7256: $courseprivid=~s/\_/\//;
7257: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7258: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7259: return $1;
1.762 raeburn 7260: } else {
7261: if ($env{'request.course.sec'}) {
7262: $courseprivid.='/'.$env{'request.course.sec'};
7263: }
7264: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7265: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7266: return $2;
7267: }
1.714 raeburn 7268: }
7269: }
7270: }
7271: }
7272:
1.159 www 7273: # Free bre to public access
7274:
7275: if ($priv eq 'bre') {
1.238 www 7276: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7277: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7278: return 'F';
7279: }
1.238 www 7280: if ($copyright eq 'priv') {
7281: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7282: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7283: return '';
7284: }
7285: }
7286: if ($copyright eq 'domain') {
7287: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7288: unless (($env{'user.domain'} eq $1) ||
7289: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7290: return '';
7291: }
1.262 matthew 7292: }
1.620 albertel 7293: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7294: # Library role, so allow browsing of resources in this domain.
7295: return 'F';
1.238 www 7296: }
1.341 www 7297: if ($copyright eq 'custom') {
7298: unless (&customaccess($priv,$uri)) { return ''; }
7299: }
1.14 www 7300: }
1.264 matthew 7301: # Domain coordinator is trying to create a course
1.620 albertel 7302: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7303: # uri is the requested domain in this case.
7304: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7305: # a role of dc for the domain in question.
1.620 albertel 7306: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7307: }
1.29 www 7308:
1.52 www 7309: my $thisallowed='';
7310: my $statecond=0;
7311: my $courseprivid='';
7312:
1.1039 raeburn 7313: my $ownaccess;
1.1043 raeburn 7314: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7315: if (($priv eq 'bro') && ($env{'user.author'})) {
7316: if ($uri eq '') {
7317: $ownaccess = 1;
7318: } else {
7319: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7320: my $udom = $env{'user.domain'};
7321: my $uname = $env{'user.name'};
7322: if ($uri =~ m{^\Q$udom\E/?$}) {
7323: $ownaccess = 1;
1.1040 raeburn 7324: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7325: unless ($uri =~ m{\.\./}) {
7326: $ownaccess = 1;
7327: }
7328: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7329: my $now = time;
7330: if ($uri =~ m{^([^/]+)/?$}) {
7331: my $adom = $1;
7332: foreach my $key (keys(%env)) {
1.1042 raeburn 7333: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7334: my ($start,$end) = split('.',$env{$key});
7335: if (($now >= $start) && (!$end || $end < $now)) {
7336: $ownaccess = 1;
7337: last;
7338: }
7339: }
7340: }
7341: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7342: my $adom = $1;
7343: my $aname = $2;
1.1042 raeburn 7344: foreach my $role ('ca','aa') {
7345: if ($env{"user.role.$role./$adom/$aname"}) {
7346: my ($start,$end) =
7347: split('.',$env{"user.role.$role./$adom/$aname"});
7348: if (($now >= $start) && (!$end || $end < $now)) {
7349: $ownaccess = 1;
7350: last;
7351: }
1.1039 raeburn 7352: }
7353: }
7354: }
7355: }
7356: }
7357: }
7358: }
7359:
1.52 www 7360: # Course
7361:
1.620 albertel 7362: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7363: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7364: $thisallowed.=$1;
7365: }
1.52 www 7366: }
1.29 www 7367:
1.52 www 7368: # Domain
7369:
1.620 albertel 7370: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7371: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7372: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7373: $thisallowed.=$1;
7374: }
1.12 www 7375: }
1.52 www 7376:
1.1141 raeburn 7377: # User who is not author or co-author might still be able to edit
7378: # resource of an author in the domain (e.g., if Domain Coordinator).
7379: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7380: (&allowed('mdc',$env{'request.course.id'}))) {
7381: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7382: $thisallowed.=$1;
7383: }
7384: }
7385:
1.52 www 7386: # Course: uri itself is a course
1.66 www 7387: my $courseuri=$uri;
7388: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7389: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7390:
1.620 albertel 7391: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7392: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7393: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7394: $thisallowed.=$1;
7395: }
1.12 www 7396: }
1.29 www 7397:
1.665 albertel 7398: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7399: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7400: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7401: $thisallowed='';
1.671 raeburn 7402: my ($match)=&is_on_map($uri);
7403: if ($match) {
7404: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7405: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 7406: my $value = $1;
7407: if ($noblockcheck) {
7408: $thisallowed.=$value;
1.1162 raeburn 7409: } else {
1.1281 raeburn 7410: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7411: if (@blockers > 0) {
7412: $thisallowed = 'B';
7413: } else {
7414: $thisallowed.=$value;
7415: }
1.1162 raeburn 7416: }
1.671 raeburn 7417: }
7418: } else {
1.705 albertel 7419: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7420: if ($refuri) {
7421: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7422: $thisallowed='F';
1.671 raeburn 7423: } else {
7424: $refuri=&declutter($refuri);
7425: my ($match) = &is_on_map($refuri);
7426: if ($match) {
1.1281 raeburn 7427: if ($noblockcheck) {
7428: $thisallowed='F';
1.1162 raeburn 7429: } else {
1.1281 raeburn 7430: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7431: if (@blockers > 0) {
7432: $thisallowed = 'B';
7433: } else {
7434: $thisallowed='F';
7435: }
1.1162 raeburn 7436: }
1.671 raeburn 7437: }
1.669 raeburn 7438: }
1.671 raeburn 7439: }
7440: }
1.314 www 7441: }
1.492 albertel 7442:
1.766 albertel 7443: if ($priv eq 'bre'
7444: && $thisallowed ne 'F'
7445: && $thisallowed ne '2'
7446: && &is_portfolio_url($uri)) {
1.1270 raeburn 7447: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7448: }
1.1250 raeburn 7449:
1.52 www 7450: # Full access at system, domain or course-wide level? Exit.
1.29 www 7451: if ($thisallowed=~/F/) {
7452: return 'F';
7453: }
7454:
1.52 www 7455: # If this is generating or modifying users, exit with special codes
1.29 www 7456:
1.643 www 7457: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7458: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7459: my ($audom,$auname)=split('/',$uri);
1.643 www 7460: # no author name given, so this just checks on the general right to make a co-author in this domain
7461: unless ($auname) { return $thisallowed; }
7462: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7463: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7464: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7465: ($audom ne $env{'request.role.domain'}))) { return ''; }
7466: }
1.52 www 7467: return $thisallowed;
7468: }
7469: #
1.103 harris41 7470: # Gathered so far: system, domain and course wide privileges
1.52 www 7471: #
7472: # Course: See if uri or referer is an individual resource that is part of
7473: # the course
7474:
1.620 albertel 7475: if ($env{'request.course.id'}) {
1.232 www 7476:
1.620 albertel 7477: $courseprivid=$env{'request.course.id'};
7478: if ($env{'request.course.sec'}) {
7479: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7480: }
7481: $courseprivid=~s/\_/\//;
7482: my $checkreferer=1;
1.232 www 7483: my ($match,$cond)=&is_on_map($uri);
7484: if ($match) {
7485: $statecond=$cond;
1.620 albertel 7486: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7487: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7488: my $value = $1;
7489: if ($priv eq 'bre') {
1.1281 raeburn 7490: if ($noblockcheck) {
7491: $thisallowed.=$value;
1.1162 raeburn 7492: } else {
1.1281 raeburn 7493: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7494: if (@blockers > 0) {
7495: $thisallowed = 'B';
7496: } else {
7497: $thisallowed.=$value;
7498: }
1.1162 raeburn 7499: }
7500: } else {
7501: $thisallowed.=$value;
7502: }
1.52 www 7503: $checkreferer=0;
7504: }
1.29 www 7505: }
1.83 www 7506:
1.148 www 7507: if ($checkreferer) {
1.620 albertel 7508: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7509: unless ($refuri) {
1.800 albertel 7510: foreach my $key (keys(%env)) {
7511: if ($key=~/^httpref\..*\*/) {
7512: my $pattern=$key;
1.156 www 7513: $pattern=~s/^httpref\.\/res\///;
1.148 www 7514: $pattern=~s/\*/\[\^\/\]\+/g;
7515: $pattern=~s/\//\\\//g;
1.152 www 7516: if ($orguri=~/$pattern/) {
1.800 albertel 7517: $refuri=$env{$key};
1.148 www 7518: }
7519: }
1.191 harris41 7520: }
1.148 www 7521: }
1.232 www 7522:
1.148 www 7523: if ($refuri) {
1.152 www 7524: $refuri=&declutter($refuri);
1.232 www 7525: my ($match,$cond)=&is_on_map($refuri);
7526: if ($match) {
7527: my $refstatecond=$cond;
1.620 albertel 7528: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7529: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7530: my $value = $1;
7531: if ($priv eq 'bre') {
1.1281 raeburn 7532: if ($noblockcheck) {
7533: $thisallowed.=$value;
1.1162 raeburn 7534: } else {
1.1281 raeburn 7535: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7536: if (@blockers > 0) {
7537: $thisallowed = 'B';
7538: } else {
7539: $thisallowed.=$value;
7540: }
1.1162 raeburn 7541: }
7542: } else {
7543: $thisallowed.=$value;
7544: }
1.53 www 7545: $uri=$refuri;
7546: $statecond=$refstatecond;
1.52 www 7547: }
7548: }
1.148 www 7549: }
1.29 www 7550: }
1.52 www 7551: }
1.29 www 7552:
1.52 www 7553: #
1.103 harris41 7554: # Gathered now: all privileges that could apply, and condition number
1.52 www 7555: #
7556: #
7557: # Full or no access?
7558: #
1.29 www 7559:
1.52 www 7560: if ($thisallowed=~/F/) {
7561: return 'F';
7562: }
1.29 www 7563:
1.52 www 7564: unless ($thisallowed) {
7565: return '';
7566: }
1.29 www 7567:
1.52 www 7568: # Restrictions exist, deal with them
7569: #
7570: # C:according to course preferences
7571: # R:according to resource settings
7572: # L:unless locked
7573: # X:according to user session state
7574: #
7575:
7576: # Possibly locked functionality, check all courses
1.54 www 7577: # Locks might take effect only after 10 minutes cache expiration for other
7578: # courses, and 2 minutes for current course
1.52 www 7579:
7580: my $envkey;
7581: if ($thisallowed=~/L/) {
1.1000 raeburn 7582: foreach $envkey (keys(%env)) {
1.54 www 7583: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7584: my $courseid=$2;
7585: my $roleid=$1.'.'.$2;
1.92 www 7586: $courseid=~s/^\///;
1.54 www 7587: my $expiretime=600;
1.620 albertel 7588: if ($env{'request.role'} eq $roleid) {
1.54 www 7589: $expiretime=120;
7590: }
7591: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7592: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7593: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7594: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7595: }
1.620 albertel 7596: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7597: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7598: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7599: &log($env{'user.domain'},$env{'user.name'},
7600: $env{'user.home'},
1.57 www 7601: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7602: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7603: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7604: return '';
7605: }
7606: }
1.620 albertel 7607: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7608: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7609: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7610: &log($env{'user.domain'},$env{'user.name'},
7611: $env{'user.home'},
1.57 www 7612: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7613: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7614: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7615: return '';
7616: }
7617: }
7618: }
1.29 www 7619: }
1.52 www 7620: }
7621:
7622: #
7623: # Rest of the restrictions depend on selected course
7624: #
7625:
1.620 albertel 7626: unless ($env{'request.course.id'}) {
1.766 albertel 7627: if ($thisallowed eq 'A') {
7628: return 'A';
1.814 raeburn 7629: } elsif ($thisallowed eq 'B') {
7630: return 'B';
1.766 albertel 7631: } else {
7632: return '1';
7633: }
1.52 www 7634: }
1.29 www 7635:
1.52 www 7636: #
7637: # Now user is definitely in a course
7638: #
1.53 www 7639:
7640:
7641: # Course preferences
7642:
7643: if ($thisallowed=~/C/) {
1.620 albertel 7644: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7645: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7646: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7647: =~/\Q$rolecode\E/) {
1.1304 raeburn 7648: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7649: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7650: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7651: $env{'request.course.id'});
7652: }
1.237 www 7653: return '';
7654: }
7655:
1.620 albertel 7656: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7657: =~/\Q$unamedom\E/) {
1.1304 raeburn 7658: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7659: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7660: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7661: $env{'request.course.id'});
7662: }
1.54 www 7663: return '';
7664: }
1.53 www 7665: }
7666:
7667: # Resource preferences
7668:
7669: if ($thisallowed=~/R/) {
1.620 albertel 7670: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7671: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7672: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7673: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7674: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7675: }
7676: return '';
1.54 www 7677: }
1.53 www 7678: }
1.30 www 7679:
1.246 www 7680: # Restricted by state or randomout?
1.30 www 7681:
1.52 www 7682: if ($thisallowed=~/X/) {
1.620 albertel 7683: if ($env{'acc.randomout'}) {
1.579 albertel 7684: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7685: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7686: return '';
7687: }
1.247 www 7688: }
7689: if (&condval($statecond)) {
1.52 www 7690: return '2';
7691: } else {
7692: return '';
7693: }
7694: }
1.30 www 7695:
1.766 albertel 7696: if ($thisallowed eq 'A') {
7697: return 'A';
1.814 raeburn 7698: } elsif ($thisallowed eq 'B') {
7699: return 'B';
1.766 albertel 7700: }
1.52 www 7701: return 'F';
1.232 www 7702: }
1.1162 raeburn 7703:
1.1192 raeburn 7704: # ------------------------------------------- Check construction space access
7705:
7706: sub constructaccess {
7707: my ($url,$setpriv)=@_;
7708:
7709: # We do not allow editing of previous versions of files
7710: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7711:
7712: # Get username and domain from URL
7713: my ($ownername,$ownerdomain,$ownerhome);
7714:
7715: ($ownerdomain,$ownername) =
1.1325 raeburn 7716: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 7717:
7718: # The URL does not really point to any authorspace, forget it
7719: unless (($ownername) && ($ownerdomain)) { return ''; }
7720:
7721: # Now we need to see if the user has access to the authorspace of
7722: # $ownername at $ownerdomain
7723:
7724: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7725: # Real author for this?
7726: $ownerhome = $env{'user.home'};
7727: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7728: return ($ownername,$ownerdomain,$ownerhome);
7729: }
7730: } else {
7731: # Co-author for this?
7732: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7733: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7734: $ownerhome = &homeserver($ownername,$ownerdomain);
7735: return ($ownername,$ownerdomain,$ownerhome);
7736: }
1.1312 raeburn 7737: if ($env{'request.course.id'}) {
7738: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
7739: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
7740: if (&allowed('mdc',$env{'request.course.id'})) {
7741: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
7742: return ($ownername,$ownerdomain,$ownerhome);
7743: }
7744: }
7745: }
1.1192 raeburn 7746: }
7747:
7748: # We don't have any access right now. If we are not possibly going to do anything about this,
7749: # we might as well leave
7750: unless ($setpriv) { return ''; }
7751:
7752: # Backdoor access?
7753: my $allowed=&allowed('eco',$ownerdomain);
7754: # Nope
7755: unless ($allowed) { return ''; }
7756: # Looks like we may have access, but could be locked by the owner of the construction space
7757: if ($allowed eq 'U') {
7758: my %blocked=&get('environment',['domcoord.author'],
7759: $ownerdomain,$ownername);
7760: # Is blocked by owner
7761: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7762: }
7763: if (($allowed eq 'F') || ($allowed eq 'U')) {
7764: # Grant temporary access
7765: my $then=$env{'user.login.time'};
1.1209 raeburn 7766: my $update=$env{'user.update.time'};
1.1192 raeburn 7767: if (!$update) { $update = $then; }
7768: my $refresh=$env{'user.refresh.time'};
7769: if (!$refresh) { $refresh = $update; }
7770: my $now = time;
7771: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7772: $now,'ca','constructaccess');
7773: $ownerhome = &homeserver($ownername,$ownerdomain);
7774: return($ownername,$ownerdomain,$ownerhome);
7775: }
7776: # No business here
7777: return '';
7778: }
7779:
1.1282 raeburn 7780: # ----------------------------------------------------------- Content Blocking
7781:
7782: {
7783: # Caches for faster Course Contents display where content blocking
7784: # is in operation (i.e., interval param set) for timed quiz.
7785: #
7786: # User for whom data are being temporarily cached.
7787: my $cacheduser='';
7788: # Cached blockers for this user (a hash of blocking items).
7789: my %cachedblockers=();
7790: # When the data were last cached.
7791: my $cachedlast='';
7792:
7793: sub load_all_blockers {
7794: my ($uname,$udom,$blocks)=@_;
7795: if (($uname ne '') && ($udom ne '')) {
7796: if (($cacheduser eq $uname.':'.$udom) &&
7797: (abs($cachedlast-time)<5)) {
7798: return;
7799: }
7800: }
7801: $cachedlast=time;
7802: $cacheduser=$uname.':'.$udom;
7803: %cachedblockers = &get_commblock_resources($blocks);
7804: }
7805:
1.1162 raeburn 7806: sub get_comm_blocks {
7807: my ($cdom,$cnum) = @_;
7808: if ($cdom eq '' || $cnum eq '') {
7809: return unless ($env{'request.course.id'});
7810: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7811: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7812: }
7813: my %commblocks;
7814: my $hashid=$cdom.'_'.$cnum;
7815: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7816: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7817: %commblocks = %{$blocksref};
7818: } else {
7819: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7820: my $cachetime = 600;
7821: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7822: }
7823: return %commblocks;
7824: }
7825:
1.1282 raeburn 7826: sub get_commblock_resources {
7827: my ($blocks) = @_;
7828: my %blockers = ();
7829: return %blockers unless ($env{'request.course.id'});
7830: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7831: my %commblocks;
7832: if (ref($blocks) eq 'HASH') {
7833: %commblocks = %{$blocks};
7834: } else {
7835: %commblocks = &get_comm_blocks();
7836: }
1.1282 raeburn 7837: return %blockers unless (keys(%commblocks) > 0);
7838: my $navmap = Apache::lonnavmaps::navmap->new();
7839: return %blockers unless (ref($navmap));
1.1162 raeburn 7840: my $now = time;
7841: foreach my $block (keys(%commblocks)) {
7842: if ($block =~ /^(\d+)____(\d+)$/) {
7843: my ($start,$end) = ($1,$2);
7844: if ($start <= $now && $end >= $now) {
7845: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7846: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7847: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 7848: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7849: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7850: }
7851: }
7852: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 7853: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7854: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7855: }
7856: }
7857: }
7858: }
7859: }
7860: } elsif ($block =~ /^firstaccess____(.+)$/) {
7861: my $item = $1;
1.1163 raeburn 7862: my @to_test;
1.1162 raeburn 7863: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7864: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 7865: my @interval;
7866: my $type = 'map';
7867: if ($item eq 'course') {
7868: $type = 'course';
7869: @interval=&EXT("resource.0.interval");
7870: } else {
7871: if ($item =~ /___\d+___/) {
7872: $type = 'resource';
7873: @interval=&EXT("resource.0.interval",$item);
7874: if (ref($navmap)) {
7875: my $res = $navmap->getBySymb($item);
7876: push(@to_test,$res);
7877: }
1.1162 raeburn 7878: } else {
1.1282 raeburn 7879: my $mapsymb = &symbread($item,1);
7880: if ($mapsymb) {
7881: if (ref($navmap)) {
7882: my $mapres = $navmap->getBySymb($mapsymb);
7883: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7884: foreach my $res (@to_test) {
7885: my $symb = $res->symb();
7886: next if ($symb eq $mapsymb);
7887: if ($symb ne '') {
7888: @interval=&EXT("resource.0.interval",$symb);
7889: if ($interval[1] eq 'map') {
7890: last;
1.1162 raeburn 7891: }
7892: }
7893: }
7894: }
7895: }
7896: }
1.1282 raeburn 7897: }
1.1310 raeburn 7898: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 7899: my $timelimit = $1;
1.1282 raeburn 7900: my $first_access;
7901: if ($type eq 'resource') {
7902: $first_access=&get_first_access($interval[1],$item);
7903: } elsif ($type eq 'map') {
7904: $first_access=&get_first_access($interval[1],undef,$item);
7905: } else {
7906: $first_access=&get_first_access($interval[1]);
7907: }
7908: if ($first_access) {
1.1292 raeburn 7909: my $timesup = $first_access+$timelimit;
1.1282 raeburn 7910: if ($timesup > $now) {
7911: my $activeblock;
7912: foreach my $res (@to_test) {
1.1283 raeburn 7913: if ($res->answerable()) {
1.1282 raeburn 7914: $activeblock = 1;
7915: last;
7916: }
7917: }
7918: if ($activeblock) {
7919: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7920: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7921: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7922: }
7923: }
7924: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7925: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7926: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7927: }
1.1162 raeburn 7928: }
7929: }
7930: }
7931: }
7932: }
7933: }
7934: }
7935: }
7936: }
1.1282 raeburn 7937: return %blockers;
1.1162 raeburn 7938: }
7939:
1.1282 raeburn 7940: sub has_comm_blocking {
7941: my ($priv,$symb,$uri,$blocks) = @_;
7942: my @blockers;
7943: return unless ($env{'request.course.id'});
7944: return unless ($priv eq 'bre');
7945: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7946: return if ($env{'request.state'} eq 'construct');
7947: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7948: return unless (keys(%cachedblockers) > 0);
7949: my (%possibles,@symbs);
7950: if (!$symb) {
7951: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7952: }
1.1282 raeburn 7953: if ($symb) {
7954: @symbs = ($symb);
7955: } elsif (keys(%possibles)) {
7956: @symbs = keys(%possibles);
7957: }
7958: my $noblock;
7959: foreach my $symb (@symbs) {
7960: last if ($noblock);
7961: my ($map,$resid,$resurl)=&decode_symb($symb);
7962: foreach my $block (keys(%cachedblockers)) {
7963: if ($block =~ /^firstaccess____(.+)$/) {
7964: my $item = $1;
7965: if (($item eq $map) || ($item eq $symb)) {
7966: $noblock = 1;
7967: last;
7968: }
7969: }
7970: if (ref($cachedblockers{$block}) eq 'HASH') {
7971: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7972: if ($cachedblockers{$block}{'resources'}{$symb}) {
7973: unless (grep(/^\Q$block\E$/,@blockers)) {
7974: push(@blockers,$block);
7975: }
7976: }
7977: }
1.1162 raeburn 7978: }
1.1282 raeburn 7979: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7980: if ($cachedblockers{$block}{'maps'}{$map}) {
7981: unless (grep(/^\Q$block\E$/,@blockers)) {
7982: push(@blockers,$block);
7983: }
7984: }
1.1162 raeburn 7985: }
7986: }
7987: }
1.1282 raeburn 7988: return if ($noblock);
7989: return @blockers;
7990: }
1.1162 raeburn 7991: }
7992:
1.1282 raeburn 7993: # -------------------------------- Deversion and split uri into path an filename
7994:
1.1133 foxr 7995: #
1.1282 raeburn 7996: # Removes the version from a URI and
1.1133 foxr 7997: # splits it in to its filename and path to the filename.
7998: # Seems like File::Basename could have done this more clearly.
7999: # Parameters:
8000: # $uri - input URI
8001: # Returns:
8002: # Two element list consisting of
8003: # $pathname - the URI up to and excluding the trailing /
8004: # $filename - The part of the URI following the last /
8005: # NOTE:
8006: # Another realization of this is simply:
8007: # use File::Basename;
8008: # ...
8009: # $uri = shift;
8010: # $filename = basename($uri);
8011: # $path = dirname($uri);
8012: # return ($filename, $path);
8013: #
8014: # The implementation below is probably faster however.
8015: #
1.710 albertel 8016: sub split_uri_for_cond {
8017: my $uri=&deversion(&declutter(shift));
8018: my @uriparts=split(/\//,$uri);
8019: my $filename=pop(@uriparts);
8020: my $pathname=join('/',@uriparts);
8021: return ($pathname,$filename);
8022: }
1.232 www 8023: # --------------------------------------------------- Is a resource on the map?
8024:
8025: sub is_on_map {
1.710 albertel 8026: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8027: #Trying to find the conditional for the file
1.620 albertel 8028: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8029: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8030: if ($match) {
1.289 bowersj2 8031: return (1,$1);
8032: } else {
1.434 www 8033: return (0,0);
1.289 bowersj2 8034: }
1.12 www 8035: }
8036:
1.427 www 8037: # --------------------------------------------------------- Get symb from alias
8038:
8039: sub get_symb_from_alias {
8040: my $symb=shift;
8041: my ($map,$resid,$url)=&decode_symb($symb);
8042: # Already is a symb
8043: if ($url) { return $symb; }
8044: # Must be an alias
8045: my $aliassymb='';
8046: my %bighash;
1.620 albertel 8047: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8048: &GDBM_READER(),0640)) {
8049: my $rid=$bighash{'mapalias_'.$symb};
8050: if ($rid) {
8051: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8052: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8053: $resid,$bighash{'src_'.$rid});
1.427 www 8054: }
8055: untie %bighash;
8056: }
8057: return $aliassymb;
8058: }
8059:
1.12 www 8060: # ----------------------------------------------------------------- Define Role
8061:
8062: sub definerole {
8063: if (allowed('mcr','/')) {
1.1326 raeburn 8064: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8065: foreach my $role (split(':',$sysrole)) {
8066: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8067: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8068: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8069: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8070: return "refused:s:$crole&$cqual";
8071: }
8072: }
1.191 harris41 8073: }
1.800 albertel 8074: foreach my $role (split(':',$domrole)) {
8075: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8076: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8077: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8078: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8079: return "refused:d:$crole&$cqual";
8080: }
8081: }
1.191 harris41 8082: }
1.800 albertel 8083: foreach my $role (split(':',$courole)) {
8084: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8085: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8086: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8087: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8088: return "refused:c:$crole&$cqual";
8089: }
8090: }
1.191 harris41 8091: }
1.1326 raeburn 8092: my $uhome;
8093: if (($uname ne '') && ($udom ne '')) {
8094: $uhome = &homeserver($uname,$udom);
8095: return $uhome if ($uhome eq 'no_host');
8096: } else {
8097: $uname = $env{'user.name'};
8098: $udom = $env{'user.domain'};
8099: $uhome = $env{'user.home'};
8100: }
1.620 albertel 8101: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 8102: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8103: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 8104: return reply($command,$uhome);
1.12 www 8105: } else {
8106: return 'refused';
8107: }
1.105 harris41 8108: }
8109:
8110: # ---------------- Make a metadata query against the network of library servers
8111:
8112: sub metadata_query {
1.1237 raeburn 8113: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8114: my %rhash;
1.845 albertel 8115: my %libserv = &all_library();
1.244 matthew 8116: my @server_list = (defined($server_array) ? @$server_array
8117: : keys(%libserv) );
8118: for my $server (@server_list) {
1.1237 raeburn 8119: my $domains = '';
8120: if (ref($domains_hash) eq 'HASH') {
8121: $domains = $domains_hash->{$server};
8122: }
1.118 harris41 8123: unless ($custom or $customshow) {
1.1237 raeburn 8124: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8125: $rhash{$server}=$reply;
8126: }
8127: else {
8128: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 8129: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8130: $server);
8131: $rhash{$server}=$reply;
8132: }
1.112 harris41 8133: }
1.118 harris41 8134: return \%rhash;
1.240 www 8135: }
8136:
8137: # ----------------------------------------- Send log queries and wait for reply
8138:
8139: sub log_query {
8140: my ($uname,$udom,$query,%filters)=@_;
8141: my $uhome=&homeserver($uname,$udom);
8142: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8143: my $uhost=&hostname($uhome);
1.800 albertel 8144: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8145: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8146: $uhome);
1.479 albertel 8147: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8148: return get_query_reply($queryid);
8149: }
8150:
1.818 raeburn 8151: # -------------------------- Update MySQL table for portfolio file
8152:
8153: sub update_portfolio_table {
1.821 raeburn 8154: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8155: if ($group ne '') {
8156: $file_name =~s /^\Q$group\E//;
8157: }
1.818 raeburn 8158: my $homeserver = &homeserver($uname,$udom);
8159: my $queryid=
1.821 raeburn 8160: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8161: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8162: my $reply = &get_query_reply($queryid);
8163: return $reply;
8164: }
8165:
1.899 raeburn 8166: # -------------------------- Update MySQL allusers table
8167:
8168: sub update_allusers_table {
8169: my ($uname,$udom,$names) = @_;
8170: my $homeserver = &homeserver($uname,$udom);
8171: my $queryid=
8172: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8173: 'lastname='.&escape($names->{'lastname'}).'%%'.
8174: 'firstname='.&escape($names->{'firstname'}).'%%'.
8175: 'middlename='.&escape($names->{'middlename'}).'%%'.
8176: 'generation='.&escape($names->{'generation'}).'%%'.
8177: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8178: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8179: return;
1.899 raeburn 8180: }
8181:
1.508 raeburn 8182: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8183:
8184: sub fetch_enrollment_query {
1.511 raeburn 8185: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 8186: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8187: my $maxtries = 1;
1.508 raeburn 8188: if ($context eq 'automated') {
8189: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 8190: $sleep = 2;
8191: $loopmax = 100;
1.547 raeburn 8192: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8193: } else {
8194: $homeserver = &homeserver($cnum,$dom);
8195: }
1.838 albertel 8196: my $host=&hostname($homeserver);
1.506 raeburn 8197: my $cmd = '';
1.1000 raeburn 8198: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8199: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8200: }
8201: $cmd =~ s/%%$//;
8202: $cmd = &escape($cmd);
8203: my $query = 'fetchenrollment';
1.620 albertel 8204: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8205: unless ($queryid=~/^\Q$host\E\_/) {
8206: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8207: return 'error: '.$queryid;
8208: }
1.1317 raeburn 8209: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8210: my $tries = 1;
8211: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 8212: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8213: $tries ++;
8214: }
1.526 raeburn 8215: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8216: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8217: } else {
1.901 albertel 8218: my @responses = split(/:/,$reply);
1.1322 raeburn 8219: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8220: foreach my $line (@responses) {
8221: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8222: $$replyref{$key} = $value;
8223: }
8224: } else {
1.1117 foxr 8225: my $pathname = LONCAPA::tempdir();
1.800 albertel 8226: foreach my $line (@responses) {
8227: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8228: $$replyref{$key} = $value;
8229: if ($value > 0) {
1.800 albertel 8230: foreach my $item (@{$$affiliatesref{$key}}) {
8231: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8232: my $destname = $pathname.'/'.$filename;
8233: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8234: if ($xml_classlist =~ /^error/) {
8235: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8236: } else {
1.506 raeburn 8237: if ( open(FILE,">$destname") ) {
8238: print FILE &unescape($xml_classlist);
8239: close(FILE);
1.526 raeburn 8240: } else {
8241: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8242: }
8243: }
8244: }
8245: }
8246: }
8247: }
8248: return 'ok';
8249: }
8250: return 'error';
8251: }
8252:
1.242 www 8253: sub get_query_reply {
1.1317 raeburn 8254: my ($queryid,$sleep,$loopmax) = @_;;
8255: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8256: $sleep = 0.2;
8257: }
8258: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8259: $loopmax = 100;
8260: }
1.1117 foxr 8261: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8262: my $reply='';
1.1317 raeburn 8263: for (1..$loopmax) {
8264: sleep($sleep);
1.240 www 8265: if (-e $replyfile.'.end') {
1.448 albertel 8266: if (open(my $fh,$replyfile)) {
1.904 albertel 8267: $reply = join('',<$fh>);
8268: close($fh);
1.240 www 8269: } else { return 'error: reply_file_error'; }
1.242 www 8270: return &unescape($reply);
8271: }
1.240 www 8272: }
1.242 www 8273: return 'timeout:'.$queryid;
1.240 www 8274: }
8275:
8276: sub courselog_query {
1.241 www 8277: #
8278: # possible filters:
8279: # url: url or symb
8280: # username
8281: # domain
8282: # action: view, submit, grade
8283: # start: timestamp
8284: # end: timestamp
8285: #
1.240 www 8286: my (%filters)=@_;
1.620 albertel 8287: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8288: if ($filters{'url'}) {
8289: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8290: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8291: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8292: }
1.620 albertel 8293: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8294: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8295: return &log_query($cname,$cdom,'courselog',%filters);
8296: }
8297:
8298: sub userlog_query {
1.858 raeburn 8299: #
8300: # possible filters:
8301: # action: log check role
8302: # start: timestamp
8303: # end: timestamp
8304: #
1.240 www 8305: my ($uname,$udom,%filters)=@_;
8306: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8307: }
8308:
1.506 raeburn 8309: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8310:
8311: sub auto_run {
1.508 raeburn 8312: my ($cnum,$cdom) = @_;
1.876 raeburn 8313: my $response = 0;
8314: my $settings;
8315: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8316: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8317: $settings = $domconfig{'autoenroll'};
8318: if ($settings->{'run'} eq '1') {
8319: $response = 1;
8320: }
8321: } else {
1.934 raeburn 8322: my $homeserver;
8323: if (&is_course($cdom,$cnum)) {
8324: $homeserver = &homeserver($cnum,$cdom);
8325: } else {
8326: $homeserver = &domain($cdom,'primary');
8327: }
8328: if ($homeserver ne 'no_host') {
8329: $response = &reply('autorun:'.$cdom,$homeserver);
8330: }
1.876 raeburn 8331: }
1.506 raeburn 8332: return $response;
8333: }
1.776 albertel 8334:
1.506 raeburn 8335: sub auto_get_sections {
1.508 raeburn 8336: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8337: my $homeserver;
8338: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8339: $homeserver = &homeserver($cnum,$cdom);
8340: }
8341: if (!defined($homeserver)) {
8342: if ($cdom =~ /^$match_domain$/) {
8343: $homeserver = &domain($cdom,'primary');
8344: }
8345: }
8346: my @secs;
8347: if (defined($homeserver)) {
8348: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8349: unless ($response eq 'refused') {
8350: @secs = split(/:/,$response);
8351: }
1.506 raeburn 8352: }
8353: return @secs;
8354: }
1.776 albertel 8355:
1.506 raeburn 8356: sub auto_new_course {
1.1099 raeburn 8357: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8358: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8359: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8360: return $response;
8361: }
1.776 albertel 8362:
1.506 raeburn 8363: sub auto_validate_courseID {
1.508 raeburn 8364: my ($cnum,$cdom,$inst_course_id) = @_;
8365: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8366: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8367: return $response;
8368: }
1.776 albertel 8369:
1.1007 raeburn 8370: sub auto_validate_instcode {
1.1020 raeburn 8371: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8372: my ($homeserver,$response);
8373: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8374: $homeserver = &homeserver($cnum,$cdom);
8375: }
8376: if (!defined($homeserver)) {
8377: if ($cdom =~ /^$match_domain$/) {
8378: $homeserver = &domain($cdom,'primary');
8379: }
8380: }
1.1065 raeburn 8381: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8382: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 8383: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8384: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8385: }
8386:
1.506 raeburn 8387: sub auto_create_password {
1.873 raeburn 8388: my ($cnum,$cdom,$authparam,$udom) = @_;
8389: my ($homeserver,$response);
1.506 raeburn 8390: my $create_passwd = 0;
8391: my $authchk = '';
1.873 raeburn 8392: if ($udom =~ /^$match_domain$/) {
8393: $homeserver = &domain($udom,'primary');
8394: }
8395: if ($homeserver eq '') {
8396: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8397: $homeserver = &homeserver($cnum,$cdom);
8398: }
8399: }
8400: if ($homeserver eq '') {
8401: $authchk = 'nodomain';
1.506 raeburn 8402: } else {
1.873 raeburn 8403: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8404: if ($response eq 'refused') {
8405: $authchk = 'refused';
8406: } else {
1.901 albertel 8407: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8408: }
1.506 raeburn 8409: }
8410: return ($authparam,$create_passwd,$authchk);
8411: }
8412:
1.706 raeburn 8413: sub auto_photo_permission {
8414: my ($cnum,$cdom,$students) = @_;
8415: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8416: my ($outcome,$perm_reqd,$conditions) =
8417: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8418: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8419: return (undef,undef);
8420: }
1.706 raeburn 8421: return ($outcome,$perm_reqd,$conditions);
8422: }
8423:
8424: sub auto_checkphotos {
8425: my ($uname,$udom,$pid) = @_;
8426: my $homeserver = &homeserver($uname,$udom);
8427: my ($result,$resulttype);
8428: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8429: &escape($uname).':'.&escape($pid),
8430: $homeserver));
1.709 albertel 8431: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8432: return (undef,undef);
8433: }
1.706 raeburn 8434: if ($outcome) {
8435: ($result,$resulttype) = split(/:/,$outcome);
8436: }
8437: return ($result,$resulttype);
8438: }
8439:
8440: sub auto_photochoice {
8441: my ($cnum,$cdom) = @_;
8442: my $homeserver = &homeserver($cnum,$cdom);
8443: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8444: &escape($cdom),
8445: $homeserver)));
1.709 albertel 8446: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8447: return (undef,undef);
8448: }
1.706 raeburn 8449: return ($update,$comment);
8450: }
8451:
8452: sub auto_photoupdate {
8453: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8454: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8455: my $host=&hostname($homeserver);
1.706 raeburn 8456: my $cmd = '';
8457: my $maxtries = 1;
1.800 albertel 8458: foreach my $affiliate (keys(%{$affiliatesref})) {
8459: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8460: }
8461: $cmd =~ s/%%$//;
8462: $cmd = &escape($cmd);
8463: my $query = 'institutionalphotos';
8464: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8465: unless ($queryid=~/^\Q$host\E\_/) {
8466: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8467: return 'error: '.$queryid;
8468: }
8469: my $reply = &get_query_reply($queryid);
8470: my $tries = 1;
8471: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8472: $reply = &get_query_reply($queryid);
8473: $tries ++;
8474: }
8475: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8476: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8477: } else {
8478: my @responses = split(/:/,$reply);
8479: my $outcome = shift(@responses);
8480: foreach my $item (@responses) {
8481: my ($key,$value) = split(/=/,$item);
8482: $$photo{$key} = $value;
8483: }
8484: return $outcome;
8485: }
8486: return 'error';
8487: }
8488:
1.521 raeburn 8489: sub auto_instcode_format {
1.793 albertel 8490: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8491: $cat_order) = @_;
1.521 raeburn 8492: my $courses = '';
1.772 raeburn 8493: my @homeservers;
1.521 raeburn 8494: if ($caller eq 'global') {
1.841 albertel 8495: my %servers = &get_servers($codedom,'library');
8496: foreach my $tryserver (keys(%servers)) {
8497: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8498: push(@homeservers,$tryserver);
8499: }
1.584 raeburn 8500: }
1.1022 raeburn 8501: } elsif ($caller eq 'requests') {
8502: if ($codedom =~ /^$match_domain$/) {
8503: my $chome = &domain($codedom,'primary');
8504: unless ($chome eq 'no_host') {
8505: push(@homeservers,$chome);
8506: }
8507: }
1.521 raeburn 8508: } else {
1.772 raeburn 8509: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8510: }
1.793 albertel 8511: foreach my $code (keys(%{$instcodes})) {
8512: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8513: }
8514: chop($courses);
1.772 raeburn 8515: my $ok_response = 0;
8516: my $response;
8517: while (@homeservers > 0 && $ok_response == 0) {
8518: my $server = shift(@homeservers);
8519: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8520: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8521: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8522: split(/:/,$response);
1.772 raeburn 8523: %{$codes} = (%{$codes},&str2hash($codes_str));
8524: push(@{$codetitles},&str2array($codetitles_str));
8525: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8526: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8527: $ok_response = 1;
8528: }
8529: }
8530: if ($ok_response) {
1.521 raeburn 8531: return 'ok';
1.772 raeburn 8532: } else {
8533: return $response;
1.521 raeburn 8534: }
8535: }
8536:
1.792 raeburn 8537: sub auto_instcode_defaults {
8538: my ($domain,$returnhash,$code_order) = @_;
8539: my @homeservers;
1.841 albertel 8540:
8541: my %servers = &get_servers($domain,'library');
8542: foreach my $tryserver (keys(%servers)) {
8543: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8544: push(@homeservers,$tryserver);
8545: }
1.792 raeburn 8546: }
1.841 albertel 8547:
1.792 raeburn 8548: my $response;
1.841 albertel 8549: foreach my $server (@homeservers) {
1.792 raeburn 8550: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8551: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8552:
8553: foreach my $pair (split(/\&/,$response)) {
8554: my ($name,$value)=split(/\=/,$pair);
8555: if ($name eq 'code_order') {
8556: @{$code_order} = split(/\&/,&unescape($value));
8557: } else {
8558: $returnhash->{&unescape($name)}=&unescape($value);
8559: }
8560: }
8561: return 'ok';
1.792 raeburn 8562: }
1.841 albertel 8563:
8564: return $response;
1.1003 raeburn 8565: }
8566:
8567: sub auto_possible_instcodes {
1.1007 raeburn 8568: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8569: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8570: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8571: return;
8572: }
1.1003 raeburn 8573: my (@homeservers,$uhome);
8574: if (defined(&domain($domain,'primary'))) {
8575: $uhome=&domain($domain,'primary');
8576: push(@homeservers,&domain($domain,'primary'));
8577: } else {
8578: my %servers = &get_servers($domain,'library');
8579: foreach my $tryserver (keys(%servers)) {
8580: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8581: push(@homeservers,$tryserver);
8582: }
8583: }
8584: }
8585: my $response;
8586: foreach my $server (@homeservers) {
8587: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8588: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8589: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8590: split(':',$response);
8591: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8592: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8593: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8594: my ($name,$value)=split('=',$item);
8595: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8596: }
8597: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8598: my ($name,$value)=split('=',$item);
8599: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8600: }
8601: return 'ok';
8602: }
8603: return $response;
8604: }
1.792 raeburn 8605:
1.1010 raeburn 8606: sub auto_courserequest_checks {
8607: my ($dom) = @_;
1.1020 raeburn 8608: my ($homeserver,%validations);
8609: if ($dom =~ /^$match_domain$/) {
8610: $homeserver = &domain($dom,'primary');
8611: }
8612: unless ($homeserver eq 'no_host') {
8613: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8614: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8615: my @items = split(/&/,$response);
8616: foreach my $item (@items) {
8617: my ($key,$value) = split('=',$item);
8618: $validations{&unescape($key)} = &thaw_unescape($value);
8619: }
8620: }
8621: }
1.1010 raeburn 8622: return %validations;
8623: }
8624:
1.1020 raeburn 8625: sub auto_courserequest_validation {
1.1255 raeburn 8626: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8627: my ($homeserver,$response);
8628: if ($dom =~ /^$match_domain$/) {
8629: $homeserver = &domain($dom,'primary');
8630: }
1.1255 raeburn 8631: unless ($homeserver eq 'no_host') {
8632: my $customdata;
8633: if (ref($custominfo) eq 'HASH') {
8634: $customdata = &freeze_escape($custominfo);
8635: }
1.1020 raeburn 8636: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8637: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8638: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8639: $customdata,$homeserver));
1.1020 raeburn 8640: }
8641: return $response;
8642: }
8643:
1.777 albertel 8644: sub auto_validate_class_sec {
1.918 raeburn 8645: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8646: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8647: my $ownerlist;
8648: if (ref($owners) eq 'ARRAY') {
8649: $ownerlist = join(',',@{$owners});
8650: } else {
8651: $ownerlist = $owners;
8652: }
1.773 raeburn 8653: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8654: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8655: return $response;
8656: }
8657:
1.1248 raeburn 8658: sub auto_crsreq_update {
8659: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8660: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8661: my ($homeserver,%crsreqresponse);
8662: if ($cdom =~ /^$match_domain$/) {
8663: $homeserver = &domain($cdom,'primary');
8664: }
8665: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8666: my $info;
8667: if (ref($inbound) eq 'HASH') {
8668: $info = &freeze_escape($inbound);
8669: }
8670: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8671: ':'.&escape($action).':'.&escape($ownername).':'.
8672: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8673: &escape($title).':'.&escape($code).':'.
8674: &escape($accessstart).':'.&escape($accessend).':'.$info,
8675: $homeserver);
1.1248 raeburn 8676: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8677: my @items = split(/&/,$response);
8678: foreach my $item (@items) {
8679: my ($key,$value) = split('=',$item);
8680: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8681: }
8682: }
8683: }
8684: return \%crsreqresponse;
8685: }
8686:
1.1305 raeburn 8687: sub auto_export_grades {
1.1309 raeburn 8688: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8689: my ($homeserver,%exportresponse);
8690: if ($cdom =~ /^$match_domain$/) {
8691: $homeserver = &domain($cdom,'primary');
8692: }
8693: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8694: my $info;
8695: if (ref($inforef) eq 'HASH') {
8696: $info = &freeze_escape($inforef);
8697: }
8698: if (ref($gradesref) eq 'HASH') {
8699: my $grades = &freeze_escape($gradesref);
8700: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8701: $info.':'.$grades,$homeserver);
8702: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8703: my @items = split(/&/,$response);
8704: foreach my $item (@items) {
8705: my ($key,$value) = split('=',$item);
8706: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8707: }
8708: }
8709: }
8710: }
8711: return \%exportresponse;
1.1305 raeburn 8712: }
8713:
1.1287 raeburn 8714: sub check_instcode_cloning {
8715: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8716: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8717: return;
8718: }
8719: my $canclone;
8720: if (@{$code_order} > 0) {
8721: my $instcoderegexp ='^';
8722: my @clonecodes = split(/\&/,$cloner);
8723: foreach my $item (@{$code_order}) {
8724: if (grep(/^\Q$item\E=/,@clonecodes)) {
8725: foreach my $pair (@clonecodes) {
8726: my ($key,$val) = split(/\=/,$pair,2);
8727: $val = &unescape($val);
8728: if ($key eq $item) {
8729: $instcoderegexp .= '('.$val.')';
8730: last;
8731: }
8732: }
8733: } else {
8734: $instcoderegexp .= $codedefaults->{$item};
8735: }
8736: }
8737: $instcoderegexp .= '$';
8738: my (@from,@to);
8739: eval {
8740: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8741: (@to) = ($clonetocode =~ /$instcoderegexp/);
8742: };
8743: if ((@from > 0) && (@to > 0)) {
8744: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8745: if (!@diffs) {
8746: $canclone = 1;
8747: }
8748: }
8749: }
8750: return $canclone;
8751: }
8752:
8753: sub default_instcode_cloning {
8754: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8755: my (%codedefaults,@code_order,$canclone);
8756: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8757: %codedefaults = %{$codedefaultsref};
8758: @code_order = @{$codeorderref};
8759: } elsif ($clonedom) {
8760: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8761: }
8762: if (($domdefclone) && (@code_order)) {
8763: my @clonecodes = split(/\+/,$domdefclone);
8764: my $instcoderegexp ='^';
8765: foreach my $item (@code_order) {
8766: if (grep(/^\Q$item\E$/,@clonecodes)) {
8767: $instcoderegexp .= '('.$codedefaults{$item}.')';
8768: } else {
8769: $instcoderegexp .= $codedefaults{$item};
8770: }
8771: }
8772: $instcoderegexp .= '$';
8773: my (@from,@to);
8774: eval {
8775: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8776: (@to) = ($clonetocode =~ /$instcoderegexp/);
8777: };
8778: if ((@from > 0) && (@to > 0)) {
8779: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8780: if (!@diffs) {
8781: $canclone = 1;
8782: }
8783: }
8784: }
8785: return $canclone;
8786: }
8787:
1.679 raeburn 8788: # ------------------------------------------------------- Course Group routines
8789:
8790: sub get_coursegroups {
1.809 raeburn 8791: my ($cdom,$cnum,$group,$namespace) = @_;
8792: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8793: }
8794:
1.679 raeburn 8795: sub modify_coursegroup {
8796: my ($cdom,$cnum,$groupsettings) = @_;
8797: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8798: }
8799:
1.809 raeburn 8800: sub toggle_coursegroup_status {
8801: my ($cdom,$cnum,$group,$action) = @_;
8802: my ($from_namespace,$to_namespace);
8803: if ($action eq 'delete') {
8804: $from_namespace = 'coursegroups';
8805: $to_namespace = 'deleted_groups';
8806: } else {
8807: $from_namespace = 'deleted_groups';
8808: $to_namespace = 'coursegroups';
8809: }
8810: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8811: if (my $tmp = &error(%curr_group)) {
8812: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8813: return ('read error',$tmp);
8814: } else {
8815: my %savedsettings = %curr_group;
1.809 raeburn 8816: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8817: my $deloutcome;
8818: if ($result eq 'ok') {
1.809 raeburn 8819: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8820: } else {
8821: return ('write error',$result);
8822: }
8823: if ($deloutcome eq 'ok') {
8824: return 'ok';
8825: } else {
8826: return ('delete error',$deloutcome);
8827: }
8828: }
8829: }
8830:
1.679 raeburn 8831: sub modify_group_roles {
1.957 raeburn 8832: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8833: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8834: my $role = 'gr/'.&escape($userprivs);
8835: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8836: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8837: if ($result eq 'ok') {
8838: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8839: }
1.679 raeburn 8840: return $result;
8841: }
8842:
8843: sub modify_coursegroup_membership {
8844: my ($cdom,$cnum,$membership) = @_;
8845: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8846: return $result;
8847: }
8848:
1.682 raeburn 8849: sub get_active_groups {
8850: my ($udom,$uname,$cdom,$cnum) = @_;
8851: my $now = time;
8852: my %groups = ();
8853: foreach my $key (keys(%env)) {
1.811 albertel 8854: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8855: my ($start,$end) = split(/\./,$env{$key});
8856: if (($end!=0) && ($end<$now)) { next; }
8857: if (($start!=0) && ($start>$now)) { next; }
8858: if ($1 eq $cdom && $2 eq $cnum) {
8859: $groups{$3} = $env{$key} ;
8860: }
8861: }
8862: }
8863: return %groups;
8864: }
8865:
1.683 raeburn 8866: sub get_group_membership {
8867: my ($cdom,$cnum,$group) = @_;
8868: return(&dump('groupmembership',$cdom,$cnum,$group));
8869: }
8870:
8871: sub get_users_groups {
8872: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8873: my @usersgroups;
1.683 raeburn 8874: my $cachetime=1800;
8875:
8876: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8877: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8878: if (defined($cached)) {
1.734 albertel 8879: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8880: } else {
8881: $grouplist = '';
1.816 raeburn 8882: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8883: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8884: my $access_end = $env{'course.'.$courseid.
8885: '.default_enrollment_end_date'};
8886: my $now = time;
8887: foreach my $key (keys(%roleshash)) {
8888: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8889: my $group = $1;
8890: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8891: my $start = $2;
8892: my $end = $1;
8893: if ($start == -1) { next; } # deleted from group
8894: if (($start!=0) && ($start>$now)) { next; }
8895: if (($end!=0) && ($end<$now)) {
8896: if ($access_end && $access_end < $now) {
8897: if ($access_end - $end < 86400) {
8898: push(@usersgroups,$group);
1.733 raeburn 8899: }
8900: }
1.817 raeburn 8901: next;
1.733 raeburn 8902: }
1.817 raeburn 8903: push(@usersgroups,$group);
1.683 raeburn 8904: }
8905: }
8906: }
1.817 raeburn 8907: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8908: $grouplist = join(':',@usersgroups);
8909: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8910: }
1.733 raeburn 8911: return @usersgroups;
1.683 raeburn 8912: }
8913:
8914: sub devalidate_getgroups_cache {
8915: my ($udom,$uname,$cdom,$cnum)=@_;
8916: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8917:
1.683 raeburn 8918: my $hashid="$udom:$uname:$courseid";
8919: &devalidate_cache_new('getgroups',$hashid);
8920: }
8921:
1.12 www 8922: # ------------------------------------------------------------------ Plain Text
8923:
8924: sub plaintext {
1.988 raeburn 8925: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8926: if ($short =~ m{^cr/}) {
1.758 albertel 8927: return (split('/',$short))[-1];
8928: }
1.742 raeburn 8929: if (!defined($cid)) {
8930: $cid = $env{'request.course.id'};
8931: }
8932: my %rolenames = (
1.1008 raeburn 8933: Course => 'std',
8934: Community => 'alt1',
1.1305 raeburn 8935: Placement => 'std',
1.742 raeburn 8936: );
1.1037 raeburn 8937: if ($cid ne '') {
8938: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8939: unless ($forcedefault) {
8940: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8941: &Apache::lonlocal::mt_escape(\$roletext);
8942: return &Apache::lonlocal::mt($roletext);
8943: }
8944: }
8945: }
8946: if ((defined($type)) && (defined($rolenames{$type})) &&
8947: (defined($rolenames{$type})) &&
8948: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8949: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8950: } elsif ($cid ne '') {
8951: my $crstype = $env{'course.'.$cid.'.type'};
8952: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8953: (defined($prp{$short}{$rolenames{$crstype}}))) {
8954: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8955: }
1.742 raeburn 8956: }
1.1037 raeburn 8957: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8958: }
8959:
8960: # ----------------------------------------------------------------- Assign Role
8961:
8962: sub assignrole {
1.957 raeburn 8963: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8964: $context)=@_;
1.21 www 8965: my $mrole;
8966: if ($role =~ /^cr\//) {
1.393 www 8967: my $cwosec=$url;
1.811 albertel 8968: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8969: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8970: my $refused = 1;
8971: if ($context eq 'requestcourses') {
8972: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8973: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8974: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8975: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8976: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8977: if ($crsenv{'internal.courseowner'} eq
8978: $env{'user.name'}.':'.$env{'user.domain'}) {
8979: $refused = '';
8980: }
8981: }
8982: }
8983: }
8984: }
8985: if ($refused) {
8986: &logthis('Refused custom assignrole: '.
8987: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8988: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8989: return 'refused';
8990: }
1.104 www 8991: }
1.21 www 8992: $mrole='cr';
1.678 raeburn 8993: } elsif ($role =~ /^gr\//) {
8994: my $cwogrp=$url;
1.811 albertel 8995: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8996: unless (&allowed('mdg',$cwogrp)) {
8997: &logthis('Refused group assignrole: '.
8998: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8999: $env{'user.name'}.' at '.$env{'user.domain'});
9000: return 'refused';
9001: }
9002: $mrole='gr';
1.21 www 9003: } else {
1.82 www 9004: my $cwosec=$url;
1.811 albertel 9005: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9006: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9007: my $refused;
9008: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9009: if (!(&allowed('c'.$role,$url))) {
9010: $refused = 1;
9011: }
9012: } else {
9013: $refused = 1;
9014: }
1.947 raeburn 9015: if ($refused) {
1.1045 raeburn 9016: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9017: if (!$selfenroll && $context eq 'course') {
9018: my %crsenv;
9019: if ($role eq 'cc' || $role eq 'co') {
9020: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9021: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9022: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9023: if ($crsenv{'internal.courseowner'} eq
9024: $env{'user.name'}.':'.$env{'user.domain'}) {
9025: $refused = '';
9026: }
9027: }
9028: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9029: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9030: if ($crsenv{'internal.courseowner'} eq
9031: $env{'user.name'}.':'.$env{'user.domain'}) {
9032: $refused = '';
9033: }
9034: }
9035: }
9036: }
9037: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9038: $refused = '';
1.1017 raeburn 9039: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9040: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9041: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9042: my $wrongcc;
9043: if ($cnum =~ /^$match_community$/) {
9044: $wrongcc = 1 if ($role eq 'cc');
9045: } else {
9046: $wrongcc = 1 if ($role eq 'co');
9047: }
9048: unless ($wrongcc) {
9049: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9050: if ($crsenv{'internal.courseowner'} eq
9051: $env{'user.name'}.':'.$env{'user.domain'}) {
9052: $refused = '';
9053: }
1.1017 raeburn 9054: }
9055: }
1.1183 raeburn 9056: } elsif ($context eq 'requestauthor') {
9057: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9058: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9059: if ($env{'environment.requestauthor'} eq 'automatic') {
9060: $refused = '';
9061: } else {
9062: my %domdefaults = &get_domain_defaults($udom);
9063: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9064: my $checkbystatus;
9065: if ($env{'user.adv'}) {
9066: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9067: if ($disposition eq 'automatic') {
9068: $refused = '';
9069: } elsif ($disposition eq '') {
9070: $checkbystatus = 1;
9071: }
9072: } else {
9073: $checkbystatus = 1;
9074: }
9075: if ($checkbystatus) {
9076: if ($env{'environment.inststatus'}) {
9077: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9078: foreach my $type (@inststatuses) {
9079: if (($type ne '') &&
9080: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9081: $refused = '';
9082: }
9083: }
9084: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9085: $refused = '';
9086: }
9087: }
9088: }
9089: }
9090: }
1.1017 raeburn 9091: }
9092: if ($refused) {
1.947 raeburn 9093: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9094: ' '.$role.' '.$end.' '.$start.' by '.
9095: $env{'user.name'}.' at '.$env{'user.domain'});
9096: return 'refused';
9097: }
1.932 raeburn 9098: }
1.1131 raeburn 9099: } elsif ($role eq 'au') {
9100: if ($url ne '/'.$udom.'/') {
9101: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9102: ' to assign author role for '.$uname.':'.$udom.
9103: ' in domain: '.$url.' refused (wrong domain).');
9104: return 'refused';
9105: }
1.104 www 9106: }
1.21 www 9107: $mrole=$role;
9108: }
1.620 albertel 9109: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9110: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9111: if ($end) { $command.='_'.$end; }
1.21 www 9112: if ($start) {
9113: if ($end) {
1.81 www 9114: $command.='_'.$start;
1.21 www 9115: } else {
1.81 www 9116: $command.='_0_'.$start;
1.21 www 9117: }
9118: }
1.739 raeburn 9119: my $origstart = $start;
9120: my $origend = $end;
1.957 raeburn 9121: my $delflag;
1.357 www 9122: # actually delete
9123: if ($deleteflag) {
1.373 www 9124: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9125: # modify command to delete the role
1.620 albertel 9126: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9127: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9128: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9129: # set start and finish to negative values for userrolelog
9130: $start=-1;
9131: $end=-1;
1.957 raeburn 9132: $delflag = 1;
1.357 www 9133: }
9134: }
9135: # send command
1.349 www 9136: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9137: # log new user role if status is ok
1.349 www 9138: if ($answer eq 'ok') {
1.663 raeburn 9139: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 9140: if (($role eq 'cc') || ($role eq 'in') ||
9141: ($role eq 'ep') || ($role eq 'ad') ||
9142: ($role eq 'ta') || ($role eq 'st') ||
9143: ($role=~/^cr/) || ($role eq 'gr') ||
9144: ($role eq 'co')) {
1.1200 raeburn 9145: # for course roles, perform group memberships changes triggered by role change.
9146: unless ($role =~ /^gr/) {
9147: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9148: $origstart,$selfenroll,$context);
9149: }
1.1184 raeburn 9150: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9151: $selfenroll,$context);
9152: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 9153: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9154: ($role eq 'da')) {
1.1184 raeburn 9155: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9156: $context);
9157: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9158: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9159: $context);
9160: }
1.1053 raeburn 9161: if ($role eq 'cc') {
9162: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9163: }
1.349 www 9164: }
9165: return $answer;
1.169 harris41 9166: }
9167:
1.1053 raeburn 9168: sub autoupdate_coowners {
9169: my ($url,$end,$start,$uname,$udom) = @_;
9170: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9171: if (($cdom ne '') && ($cnum ne '')) {
9172: my $now = time;
9173: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9174: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9175: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9176: my $instcode = $coursehash{'internal.coursecode'};
9177: if ($instcode ne '') {
1.1056 raeburn 9178: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9179: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9180: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9181: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9182: if ($result eq 'valid') {
9183: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9184: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9185: push(@newcoowners,$coowner);
9186: }
9187: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9188: push(@newcoowners,$uname.':'.$udom);
9189: }
9190: @newcoowners = sort(@newcoowners);
9191: } else {
9192: push(@newcoowners,$uname.':'.$udom);
9193: }
9194: } else {
9195: if ($coursehash{'internal.co-owners'}) {
9196: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9197: unless ($coowner eq $uname.':'.$udom) {
9198: push(@newcoowners,$coowner);
9199: }
9200: }
9201: unless (@newcoowners > 0) {
9202: $delcoowners = 1;
9203: $coowners = '';
9204: }
9205: }
9206: }
9207: if (@newcoowners || $delcoowners) {
9208: &store_coowners($cdom,$cnum,$coursehash{'home'},
9209: $delcoowners,@newcoowners);
9210: }
9211: }
9212: }
9213: }
9214: }
9215: }
9216: }
9217:
9218: sub store_coowners {
9219: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9220: my $cid = $cdom.'_'.$cnum;
9221: my ($coowners,$delresult,$putresult);
9222: if (@newcoowners) {
9223: $coowners = join(',',@newcoowners);
9224: my %coownershash = (
9225: 'internal.co-owners' => $coowners,
9226: );
9227: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9228: if ($putresult eq 'ok') {
9229: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9230: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9231: }
9232: }
9233: }
9234: if ($delcoowners) {
9235: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9236: if ($delresult eq 'ok') {
9237: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9238: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9239: }
9240: }
9241: }
9242: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9243: my %crsinfo =
9244: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9245: if (ref($crsinfo{$cid}) eq 'HASH') {
9246: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9247: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9248: }
9249: }
9250: }
9251:
1.169 harris41 9252: # -------------------------------------------------- Modify user authentication
1.197 www 9253: # Overrides without validation
9254:
1.169 harris41 9255: sub modifyuserauth {
9256: my ($udom,$uname,$umode,$upass)=@_;
9257: my $uhome=&homeserver($uname,$udom);
1.197 www 9258: unless (&allowed('mau',$udom)) { return 'refused'; }
9259: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9260: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9261: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9262: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9263: &escape($upass),$uhome);
1.620 albertel 9264: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9265: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9266: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9267: &log($udom,,$uname,$uhome,
1.620 albertel 9268: 'Authentication changed by '.$env{'user.domain'}.', '.
9269: $env{'user.name'}.', '.$umode.
1.197 www 9270: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9271: unless ($reply eq 'ok') {
1.197 www 9272: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9273: return 'error: '.$reply;
9274: }
1.170 harris41 9275: return 'ok';
1.80 www 9276: }
9277:
1.81 www 9278: # --------------------------------------------------------------- Modify a user
1.80 www 9279:
1.81 www 9280: sub modifyuser {
1.206 matthew 9281: my ($udom, $uname, $uid,
9282: $umode, $upass, $first,
9283: $middle, $last, $gene,
1.1058 raeburn 9284: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9285: $udom= &LONCAPA::clean_domain($udom);
9286: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9287: my $showcandelete = 'none';
9288: if (ref($candelete) eq 'ARRAY') {
9289: if (@{$candelete} > 0) {
9290: $showcandelete = join(', ',@{$candelete});
9291: }
9292: }
1.81 www 9293: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9294: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9295: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9296: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9297: ' desiredhome not specified').
1.620 albertel 9298: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9299: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9300: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9301: my $newuser;
9302: if ($uhome eq 'no_host') {
9303: $newuser = 1;
9304: }
1.80 www 9305: # ----------------------------------------------------------------- Create User
1.406 albertel 9306: if (($uhome eq 'no_host') &&
9307: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9308: my $unhome='';
1.844 albertel 9309: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9310: $unhome = $desiredhome;
1.620 albertel 9311: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9312: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9313: } else { # load balancing routine for determining $unhome
1.81 www 9314: my $loadm=10000000;
1.841 albertel 9315: my %servers = &get_servers($udom,'library');
9316: foreach my $tryserver (keys(%servers)) {
9317: my $answer=reply('load',$tryserver);
9318: if (($answer=~/\d+/) && ($answer<$loadm)) {
9319: $loadm=$answer;
9320: $unhome=$tryserver;
9321: }
1.80 www 9322: }
9323: }
9324: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9325: return 'error: unable to find a home server for '.$uname.
9326: ' in domain '.$udom;
1.80 www 9327: }
9328: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9329: &escape($upass),$unhome);
9330: unless ($reply eq 'ok') {
9331: return 'error: '.$reply;
9332: }
1.230 stredwic 9333: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9334: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9335: return 'error: unable verify users home machine.';
1.80 www 9336: }
1.209 matthew 9337: } # End of creation of new user
1.80 www 9338: # ---------------------------------------------------------------------- Add ID
9339: if ($uid) {
9340: $uid=~tr/A-Z/a-z/;
9341: my %uidhash=&idrget($udom,$uname);
1.196 www 9342: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9343: && (!$forceid)) {
1.80 www 9344: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9345: return 'error: user id "'.$uid.'" does not match '.
9346: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9347: }
9348: } else {
1.1300 raeburn 9349: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 9350: }
9351: }
9352: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9353: my @tmp=&get('environment',
1.899 raeburn 9354: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9355: 'permanentemail','inststatus'],
1.134 albertel 9356: $udom,$uname);
1.1075 raeburn 9357: my (%names,%oldnames);
1.313 matthew 9358: if ($tmp[0] =~ m/^error:.*/) {
9359: %names=();
9360: } else {
9361: %names = @tmp;
1.1075 raeburn 9362: %oldnames = %names;
1.313 matthew 9363: }
1.388 www 9364: #
1.1058 raeburn 9365: # If name, email and/or uid are blank (e.g., because an uploaded file
9366: # of users did not contain them), do not overwrite existing values
9367: # unless field is in $candelete array ref.
9368: #
9369:
9370: my @fields = ('firstname','middlename','lastname','generation',
9371: 'permanentemail','id');
9372: my %newvalues;
9373: if (ref($candelete) eq 'ARRAY') {
9374: foreach my $field (@fields) {
9375: if (grep(/^\Q$field\E$/,@{$candelete})) {
9376: if ($field eq 'firstname') {
9377: $names{$field} = $first;
9378: } elsif ($field eq 'middlename') {
9379: $names{$field} = $middle;
9380: } elsif ($field eq 'lastname') {
9381: $names{$field} = $last;
9382: } elsif ($field eq 'generation') {
9383: $names{$field} = $gene;
9384: } elsif ($field eq 'permanentemail') {
9385: $names{$field} = $email;
9386: } elsif ($field eq 'id') {
9387: $names{$field} = $uid;
9388: }
9389: }
9390: }
9391: }
1.388 www 9392: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9393: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9394: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9395: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9396: if ($email) {
9397: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9398: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9399: }
1.899 raeburn 9400: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9401: if (defined($inststatus)) {
9402: $names{'inststatus'} = '';
9403: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9404: if (ref($usertypes) eq 'HASH') {
9405: my @okstatuses;
9406: foreach my $item (split(/:/,$inststatus)) {
9407: if (defined($usertypes->{$item})) {
9408: push(@okstatuses,$item);
9409: }
9410: }
9411: if (@okstatuses) {
9412: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9413: }
9414: }
9415: }
1.1075 raeburn 9416: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9417: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9418: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9419: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9420: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9421: } else {
9422: $logmsg .= ' during self creation';
9423: }
1.1075 raeburn 9424: my $changed;
9425: if ($newuser) {
9426: $changed = 1;
9427: } else {
9428: foreach my $field (@fields) {
9429: if ($names{$field} ne $oldnames{$field}) {
9430: $changed = 1;
9431: last;
9432: }
9433: }
9434: }
9435: unless ($changed) {
9436: $logmsg = 'No changes in user information needed for: '.$logmsg;
9437: &logthis($logmsg);
9438: return 'ok';
9439: }
9440: my $reply = &put('environment', \%names, $udom,$uname);
9441: if ($reply ne 'ok') {
9442: return 'error: '.$reply;
9443: }
1.1087 raeburn 9444: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9445: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9446: }
1.1075 raeburn 9447: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9448: &devalidate_cache_new('namescache',$uname.':'.$udom);
9449: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9450: &logthis($logmsg);
1.134 albertel 9451: return 'ok';
1.80 www 9452: }
9453:
1.81 www 9454: # -------------------------------------------------------------- Modify student
1.80 www 9455:
1.81 www 9456: sub modifystudent {
9457: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9458: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 9459: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9460: if (!$cid) {
1.620 albertel 9461: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9462: return 'not_in_class';
9463: }
1.80 www 9464: }
9465: # --------------------------------------------------------------- Make the user
1.81 www 9466: my $reply=&modifyuser
1.209 matthew 9467: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9468: $desiredhome,$email,$inststatus);
1.80 www 9469: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9470: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 9471: # student's environment
1.297 matthew 9472: $uid = undef if (!$forceid);
1.455 albertel 9473: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 9474: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 9475: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9476: return $reply;
9477: }
9478:
9479: sub modify_student_enrollment {
1.1216 raeburn 9480: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 9481: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9482: my ($cdom,$cnum,$chome);
9483: if (!$cid) {
1.620 albertel 9484: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9485: return 'not_in_class';
9486: }
1.620 albertel 9487: $cdom=$env{'course.'.$cid.'.domain'};
9488: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9489: } else {
9490: ($cdom,$cnum)=split(/_/,$cid);
9491: }
1.620 albertel 9492: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9493: if (!$chome) {
1.457 raeburn 9494: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9495: }
1.455 albertel 9496: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9497: # Make sure the user exists
1.81 www 9498: my $uhome=&homeserver($uname,$udom);
9499: if (($uhome eq '') || ($uhome eq 'no_host')) {
9500: return 'error: no such user';
9501: }
1.297 matthew 9502: # Get student data if we were not given enough information
9503: if (!defined($first) || $first eq '' ||
9504: !defined($last) || $last eq '' ||
9505: !defined($uid) || $uid eq '' ||
9506: !defined($middle) || $middle eq '' ||
9507: !defined($gene) || $gene eq '') {
1.294 matthew 9508: # They did not supply us with enough data to enroll the student, so
9509: # we need to pick up more information.
1.297 matthew 9510: my %tmp = &get('environment',
1.294 matthew 9511: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9512: ,$udom,$uname);
9513:
1.800 albertel 9514: #foreach my $key (keys(%tmp)) {
9515: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9516: #}
1.294 matthew 9517: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9518: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9519: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9520: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9521: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9522: }
1.556 albertel 9523: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9524: my $user = "$uname:$udom";
9525: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9526: my $reply=cput('classlist',
1.1148 raeburn 9527: {$user =>
1.1314 raeburn 9528: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9529: $cdom,$cnum);
1.1148 raeburn 9530: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9531: &devalidate_getsection_cache($udom,$uname,$cid);
9532: } else {
1.81 www 9533: return 'error: '.$reply;
9534: }
1.297 matthew 9535: # Add student role to user
1.83 www 9536: my $uurl='/'.$cid;
1.81 www 9537: $uurl=~s/\_/\//g;
9538: if ($usec) {
9539: $uurl.='/'.$usec;
9540: }
1.1148 raeburn 9541: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9542: $selfenroll,$context);
9543: if ($result ne 'ok') {
9544: if ($old_entry{$user} ne '') {
9545: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9546: } else {
9547: $reply = &del('classlist',[$user],$cdom,$cnum);
9548: }
9549: }
9550: return $result;
1.21 www 9551: }
9552:
1.556 albertel 9553: sub format_name {
9554: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9555: my $name;
9556: if ($first ne 'lastname') {
9557: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9558: } else {
9559: if ($lastname=~/\S/) {
9560: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9561: $name=~s/\s+,/,/;
9562: } else {
9563: $name.= $firstname.' '.$middlename.' '.$generation;
9564: }
9565: }
9566: $name=~s/^\s+//;
9567: $name=~s/\s+$//;
9568: $name=~s/\s+/ /g;
9569: return $name;
9570: }
9571:
1.84 www 9572: # ------------------------------------------------- Write to course preferences
9573:
9574: sub writecoursepref {
9575: my ($courseid,%prefs)=@_;
9576: $courseid=~s/^\///;
9577: $courseid=~s/\_/\//g;
9578: my ($cdomain,$cnum)=split(/\//,$courseid);
9579: my $chome=homeserver($cnum,$cdomain);
9580: if (($chome eq '') || ($chome eq 'no_host')) {
9581: return 'error: no such course';
9582: }
9583: my $cstring='';
1.800 albertel 9584: foreach my $pref (keys(%prefs)) {
9585: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9586: }
1.84 www 9587: $cstring=~s/\&$//;
9588: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9589: }
9590:
9591: # ---------------------------------------------------------- Make/modify course
9592:
9593: sub createcourse {
1.741 raeburn 9594: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9595: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9596: $url=&declutter($url);
9597: my $cid='';
1.1028 raeburn 9598: if ($context eq 'requestcourses') {
9599: my $can_create = 0;
9600: my ($ownername,$ownerdom) = split(':',$course_owner);
9601: if ($udom eq $ownerdom) {
9602: if (&usertools_access($ownername,$ownerdom,$category,undef,
9603: $context)) {
9604: $can_create = 1;
9605: }
9606: } else {
9607: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9608: $category);
9609: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9610: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9611: if (@curr > 0) {
9612: my @options = qw(approval validate autolimit);
9613: my $optregex = join('|',@options);
9614: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9615: $can_create = 1;
9616: }
9617: }
9618: }
9619: }
9620: if ($can_create) {
9621: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9622: unless (&allowed('ccc',$udom)) {
9623: return 'refused';
9624: }
1.1017 raeburn 9625: }
9626: } else {
9627: return 'refused';
9628: }
1.1028 raeburn 9629: } elsif (!&allowed('ccc',$udom)) {
9630: return 'refused';
1.84 www 9631: }
1.1011 raeburn 9632: # --------------------------------------------------------------- Get Unique ID
9633: my $uname;
9634: if ($cnum =~ /^$match_courseid$/) {
9635: my $chome=&homeserver($cnum,$udom,'true');
9636: if (($chome eq '') || ($chome eq 'no_host')) {
9637: $uname = $cnum;
9638: } else {
1.1038 raeburn 9639: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9640: }
9641: } else {
1.1038 raeburn 9642: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9643: }
9644: return $uname if ($uname =~ /^error/);
9645: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9646: if (!defined($course_server)) {
9647: if (defined(&domain($udom,'primary'))) {
9648: $course_server = &domain($udom,'primary');
9649: } else {
9650: $course_server = $env{'user.home'};
9651: }
9652: }
9653: my %host_servers =
9654: &Apache::lonnet::get_servers($udom,'library');
9655: unless ($host_servers{$course_server}) {
9656: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9657: }
1.84 www 9658: # ------------------------------------------------------------- Make the course
9659: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9660: $course_server);
1.84 www 9661: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9662: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9663: if (($uhome eq '') || ($uhome eq 'no_host')) {
9664: return 'error: no such course';
9665: }
1.271 www 9666: # ----------------------------------------------------------------- Course made
1.516 raeburn 9667: # log existence
1.1029 raeburn 9668: my $now = time;
1.918 raeburn 9669: my $newcourse = {
9670: $udom.'_'.$uname => {
1.921 raeburn 9671: description => $description,
9672: inst_code => $inst_code,
9673: owner => $course_owner,
9674: type => $crstype,
1.1029 raeburn 9675: creator => $env{'user.name'}.':'.
9676: $env{'user.domain'},
9677: created => $now,
9678: context => $context,
1.918 raeburn 9679: },
9680: };
1.921 raeburn 9681: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9682: # set toplevel url
1.271 www 9683: my $topurl=$url;
9684: unless ($nonstandard) {
9685: # ------------------------------------------ For standard courses, make top url
9686: my $mapurl=&clutter($url);
1.278 www 9687: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9688: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9689: <map>
9690: <resource id="1" type="start"></resource>
9691: <resource id="2" src="$mapurl"></resource>
9692: <resource id="3" type="finish"></resource>
9693: <link index="1" from="1" to="2"></link>
9694: <link index="2" from="2" to="3"></link>
9695: </map>
9696: ENDINITMAP
9697: $topurl=&declutter(
1.638 albertel 9698: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9699: );
9700: }
9701: # ----------------------------------------------------------- Write preferences
1.84 www 9702: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9703: ('description' => $description,
9704: 'url' => $topurl,
9705: 'internal.creator' => $env{'user.name'}.':'.
9706: $env{'user.domain'},
9707: 'internal.created' => $now,
9708: 'internal.creationcontext' => $context)
9709: );
1.84 www 9710: return '/'.$udom.'/'.$uname;
9711: }
9712:
1.1011 raeburn 9713: # ------------------------------------------------------------------- Create ID
9714: sub generate_coursenum {
1.1038 raeburn 9715: my ($udom,$crstype) = @_;
1.1011 raeburn 9716: my $domdesc = &domain($udom);
9717: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9718: my $first;
9719: if ($crstype eq 'Community') {
9720: $first = '0';
9721: } else {
9722: $first = int(1+rand(9));
9723: }
9724: my $uname=$first.
1.1011 raeburn 9725: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9726: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9727: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9728: # ----------------------------------------------- Make sure that does not exist
9729: my $uhome=&homeserver($uname,$udom,'true');
9730: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9731: if ($crstype eq 'Community') {
9732: $first = '0';
9733: } else {
9734: $first = int(1+rand(9));
9735: }
9736: $uname=$first.
1.1011 raeburn 9737: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9738: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9739: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9740: $uhome=&homeserver($uname,$udom,'true');
9741: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9742: return 'error: unable to generate unique course-ID';
9743: }
9744: }
9745: return $uname;
9746: }
9747:
1.813 albertel 9748: sub is_course {
1.1167 droeschl 9749: my ($cdom, $cnum) = scalar(@_) == 1 ?
9750: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9751:
9752: return unless $cdom and $cnum;
9753:
9754: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9755: '.');
9756:
1.1219 raeburn 9757: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9758: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9759: }
9760:
1.1015 raeburn 9761: sub store_userdata {
9762: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9763: my $result;
1.1016 raeburn 9764: if ($datakey ne '') {
1.1013 raeburn 9765: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9766: if ($udom eq '' || $uname eq '') {
9767: $udom = $env{'user.domain'};
9768: $uname = $env{'user.name'};
9769: }
9770: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9771: if (($uhome eq '') || ($uhome eq 'no_host')) {
9772: $result = 'error: no_host';
9773: } else {
9774: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9775: $storehash->{'host'} = $perlvar{'lonHostID'};
9776:
9777: my $namevalue='';
9778: foreach my $key (keys(%{$storehash})) {
9779: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9780: }
9781: $namevalue=~s/\&$//;
1.1224 raeburn 9782: unless ($namespace eq 'courserequests') {
9783: $datakey = &escape($datakey);
9784: }
1.1105 raeburn 9785: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9786: $namevalue,$uhome);
1.1013 raeburn 9787: }
9788: } else {
9789: $result = 'error: data to store was not a hash reference';
9790: }
9791: } else {
9792: $result= 'error: invalid requestkey';
9793: }
9794: return $result;
9795: }
9796:
1.21 www 9797: # ---------------------------------------------------------- Assign Custom Role
9798:
9799: sub assigncustomrole {
1.957 raeburn 9800: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9801: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9802: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9803: }
9804:
9805: # ----------------------------------------------------------------- Revoke Role
9806:
9807: sub revokerole {
1.957 raeburn 9808: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9809: my $now=time;
1.965 raeburn 9810: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9811: }
9812:
9813: # ---------------------------------------------------------- Revoke Custom Role
9814:
9815: sub revokecustomrole {
1.957 raeburn 9816: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9817: my $now=time;
1.357 www 9818: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9819: $deleteflag,$selfenroll,$context);
1.17 www 9820: }
9821:
1.533 banghart 9822: # ------------------------------------------------------------ Disk usage
1.535 albertel 9823: sub diskusage {
1.955 raeburn 9824: my ($udom,$uname,$directorypath,$getpropath)=@_;
9825: $directorypath =~ s/\/$//;
9826: my $listing=&reply('du2:'.&escape($directorypath).':'
9827: .&escape($getpropath).':'.&escape($uname).':'
9828: .&escape($udom),homeserver($uname,$udom));
9829: if ($listing eq 'unknown_cmd') {
9830: if ($getpropath) {
9831: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9832: }
9833: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9834: }
1.514 albertel 9835: return $listing;
1.512 banghart 9836: }
9837:
1.566 banghart 9838: sub is_locked {
1.1096 raeburn 9839: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9840: my @check;
9841: my $is_locked;
1.1093 raeburn 9842: push (@check,$file_name);
1.613 albertel 9843: my %locked = &get('file_permissions',\@check,
1.620 albertel 9844: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9845: my ($tmp)=keys(%locked);
9846: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9847:
1.566 banghart 9848: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9849: $is_locked = 'false';
9850: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9851: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9852: $is_locked = 'true';
1.1096 raeburn 9853: if (ref($which) eq 'ARRAY') {
9854: push(@{$which},$entry);
9855: } else {
9856: last;
9857: }
1.745 raeburn 9858: }
9859: }
1.566 banghart 9860: } else {
9861: $is_locked = 'false';
9862: }
1.1093 raeburn 9863: return $is_locked;
1.566 banghart 9864: }
9865:
1.759 albertel 9866: sub declutter_portfile {
9867: my ($file) = @_;
1.833 albertel 9868: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9869: return $file;
9870: }
9871:
1.559 banghart 9872: # ------------------------------------------------------------- Mark as Read Only
9873:
9874: sub mark_as_readonly {
9875: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9876: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9877: my ($tmp)=keys(%current_permissions);
9878: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9879: foreach my $file (@{$files}) {
1.759 albertel 9880: $file = &declutter_portfile($file);
1.561 banghart 9881: push(@{$current_permissions{$file}},$what);
1.559 banghart 9882: }
1.613 albertel 9883: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9884: return;
9885: }
9886:
1.572 banghart 9887: # ------------------------------------------------------------Save Selected Files
9888:
9889: sub save_selected_files {
9890: my ($user, $path, @files) = @_;
9891: my $filename = $user."savedfiles";
1.573 banghart 9892: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9893: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9894: foreach my $file (@files) {
1.620 albertel 9895: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9896: }
9897: foreach my $file (@other_files) {
1.574 banghart 9898: print (OUT $file."\n");
1.572 banghart 9899: }
1.574 banghart 9900: close (OUT);
1.572 banghart 9901: return 'ok';
9902: }
9903:
1.574 banghart 9904: sub clear_selected_files {
9905: my ($user) = @_;
9906: my $filename = $user."savedfiles";
1.1117 foxr 9907: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9908: print (OUT undef);
9909: close (OUT);
9910: return ("ok");
9911: }
9912:
1.572 banghart 9913: sub files_in_path {
9914: my ($user, $path) = @_;
9915: my $filename = $user."savedfiles";
9916: my %return_files;
1.1117 foxr 9917: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9918: while (my $line_in = <IN>) {
1.574 banghart 9919: chomp ($line_in);
9920: my @paths_and_file = split (m!/!, $line_in);
9921: my $file_part = pop (@paths_and_file);
9922: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9923: $path_part.='/';
9924: my $path_and_file = $path_part.$file_part;
9925: if ($path_part eq $path) {
9926: $return_files{$file_part}= 'selected';
9927: }
9928: }
1.574 banghart 9929: close (IN);
9930: return (\%return_files);
1.572 banghart 9931: }
9932:
9933: # called in portfolio select mode, to show files selected NOT in current directory
9934: sub files_not_in_path {
9935: my ($user, $path) = @_;
9936: my $filename = $user."savedfiles";
9937: my @return_files;
9938: my $path_part;
1.1117 foxr 9939: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9940: while (my $line = <IN>) {
1.572 banghart 9941: #ok, I know it's clunky, but I want it to work
1.800 albertel 9942: my @paths_and_file = split(m|/|, $line);
9943: my $file_part = pop(@paths_and_file);
9944: chomp($file_part);
9945: my $path_part = join('/', @paths_and_file);
1.572 banghart 9946: $path_part .= '/';
9947: my $path_and_file = $path_part.$file_part;
9948: if ($path_part ne $path) {
1.800 albertel 9949: push(@return_files, ($path_and_file));
1.572 banghart 9950: }
9951: }
1.800 albertel 9952: close(OUT);
1.574 banghart 9953: return (@return_files);
1.572 banghart 9954: }
9955:
1.1273 raeburn 9956: #------------------------------Submitted/Handedback Portfolio Files Versioning
9957:
9958: sub portfiles_versioning {
9959: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9960: my $portfolio_root = '/userfiles/portfolio';
9961: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9962: foreach my $file (@{$portfiles}) {
9963: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9964: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9965: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9966: my $getpropath = 1;
9967: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9968: $stu_name,$getpropath);
9969: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9970: my $new_answer =
9971: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9972: if ($new_answer ne 'problem getting file') {
9973: push(@{$versioned_portfiles}, $directory.$new_answer);
9974: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9975: [$symb,$env{'request.course.id'},'graded']);
9976: }
9977: }
9978: }
9979:
9980: sub get_next_version {
9981: my ($answer_name, $answer_ext, $dir_list) = @_;
9982: my $version;
9983: if (ref($dir_list) eq 'ARRAY') {
9984: foreach my $row (@{$dir_list}) {
9985: my ($file) = split(/\&/,$row,2);
9986: my ($file_name,$file_version,$file_ext) =
9987: &file_name_version_ext($file);
9988: if (($file_name eq $answer_name) &&
9989: ($file_ext eq $answer_ext)) {
9990: # gets here if filename and extension match,
9991: # regardless of version
9992: if ($file_version ne '') {
9993: # a versioned file is found so save it for later
9994: if ($file_version > $version) {
9995: $version = $file_version;
9996: }
9997: }
9998: }
9999: }
10000: }
10001: $version ++;
10002: return($version);
10003: }
10004:
10005: sub version_selected_portfile {
10006: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10007: my ($answer_name,$answer_ver,$answer_ext) =
10008: &file_name_version_ext($file_name);
10009: my $new_answer;
10010: $env{'form.copy'} =
10011: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10012: if($env{'form.copy'} eq '-1') {
10013: $new_answer = 'problem getting file';
10014: } else {
10015: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10016: my $copy_result =
10017: &finishuserfileupload($stu_name,$domain,'copy',
10018: '/portfolio'.$directory.$new_answer);
10019: }
10020: undef($env{'form.copy'});
10021: return ($new_answer);
10022: }
10023:
10024: sub file_name_version_ext {
10025: my ($file)=@_;
10026: my @file_parts = split(/\./, $file);
10027: my ($name,$version,$ext);
10028: if (@file_parts > 1) {
10029: $ext=pop(@file_parts);
10030: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10031: $version=pop(@file_parts);
10032: }
10033: $name=join('.',@file_parts);
10034: } else {
10035: $name=join('.',@file_parts);
10036: }
10037: return($name,$version,$ext);
10038: }
10039:
1.745 raeburn 10040: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10041:
1.745 raeburn 10042: sub get_portfile_permissions {
10043: my ($domain,$user) = @_;
1.613 albertel 10044: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10045: my ($tmp)=keys(%current_permissions);
10046: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10047: return \%current_permissions;
10048: }
10049:
10050: #---------------------------------------------Get portfolio file access controls
10051:
1.749 raeburn 10052: sub get_access_controls {
1.745 raeburn 10053: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10054: my %access;
10055: my $real_file = $file;
10056: $file =~ s/\.meta$//;
1.745 raeburn 10057: if (defined($file)) {
1.749 raeburn 10058: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10059: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10060: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10061: }
10062: }
1.745 raeburn 10063: } else {
1.749 raeburn 10064: foreach my $key (keys(%{$current_permissions})) {
10065: if ($key =~ /\0accesscontrol$/) {
10066: if (defined($group)) {
10067: if ($key !~ m-^\Q$group\E/-) {
10068: next;
10069: }
10070: }
10071: my ($fullpath) = split(/\0/,$key);
10072: if (ref($$current_permissions{$key}) eq 'HASH') {
10073: foreach my $control (keys(%{$$current_permissions{$key}})) {
10074: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10075: }
10076: }
10077: }
10078: }
10079: }
10080: return %access;
10081: }
10082:
10083: sub modify_access_controls {
10084: my ($file_name,$changes,$domain,$user)=@_;
10085: my ($outcome,$deloutcome);
10086: my %store_permissions;
10087: my %new_values;
10088: my %new_control;
10089: my %translation;
10090: my @deletions = ();
10091: my $now = time;
10092: if (exists($$changes{'activate'})) {
10093: if (ref($$changes{'activate'}) eq 'HASH') {
10094: my @newitems = sort(keys(%{$$changes{'activate'}}));
10095: my $numnew = scalar(@newitems);
10096: for (my $i=0; $i<$numnew; $i++) {
10097: my $newkey = $newitems[$i];
10098: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10099: if ($newkey =~ /^\d+:/) {
10100: $newkey =~ s/^(\d+)/$newid/;
10101: $translation{$1} = $newid;
10102: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10103: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10104: $translation{$1} = $newid;
10105: }
1.749 raeburn 10106: $new_values{$file_name."\0".$newkey} =
10107: $$changes{'activate'}{$newitems[$i]};
10108: $new_control{$newkey} = $now;
10109: }
10110: }
10111: }
10112: my %todelete;
10113: my %changed_items;
10114: foreach my $action ('delete','update') {
10115: if (exists($$changes{$action})) {
10116: if (ref($$changes{$action}) eq 'HASH') {
10117: foreach my $key (keys(%{$$changes{$action}})) {
10118: my ($itemnum) = ($key =~ /^([^:]+):/);
10119: if ($action eq 'delete') {
10120: $todelete{$itemnum} = 1;
10121: } else {
10122: $changed_items{$itemnum} = $key;
10123: }
10124: }
1.745 raeburn 10125: }
10126: }
1.749 raeburn 10127: }
10128: # get lock on access controls for file.
10129: my $lockhash = {
10130: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10131: ':'.$env{'user.domain'},
10132: };
10133: my $tries = 0;
10134: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10135:
1.1288 damieng 10136: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10137: $tries ++;
1.1289 damieng 10138: sleep(0.1);
1.749 raeburn 10139: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10140: }
10141: if ($gotlock eq 'ok') {
10142: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10143: my ($tmp)=keys(%curr_permissions);
10144: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10145: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10146: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10147: if (ref($curr_controls) eq 'HASH') {
10148: foreach my $control_item (keys(%{$curr_controls})) {
10149: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10150: if (defined($todelete{$itemnum})) {
10151: push(@deletions,$file_name."\0".$control_item);
10152: } else {
10153: if (defined($changed_items{$itemnum})) {
10154: $new_control{$changed_items{$itemnum}} = $now;
10155: push(@deletions,$file_name."\0".$control_item);
10156: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10157: } else {
10158: $new_control{$control_item} = $$curr_controls{$control_item};
10159: }
10160: }
1.745 raeburn 10161: }
10162: }
10163: }
1.970 raeburn 10164: my ($group);
10165: if (&is_course($domain,$user)) {
10166: ($group,my $file) = split(/\//,$file_name,2);
10167: }
1.749 raeburn 10168: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10169: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10170: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10171: # remove lock
10172: my @del_lock = ($file_name."\0".'locked_access_records');
10173: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10174: my $sqlresult =
1.970 raeburn 10175: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10176: $group);
1.749 raeburn 10177: } else {
10178: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10179: }
1.749 raeburn 10180: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10181: }
10182:
1.827 raeburn 10183: sub make_public_indefinitely {
1.1271 raeburn 10184: my (@requrl) = @_;
10185: return &automated_portfile_access('public',\@requrl);
10186: }
10187:
10188: sub automated_portfile_access {
10189: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 10190: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10191: return 'invalid';
10192: }
1.1271 raeburn 10193: my %urls;
10194: if (ref($addsref) eq 'ARRAY') {
10195: foreach my $requrl (@{$addsref}) {
10196: if (&is_portfolio_url($requrl)) {
10197: unless (exists($urls{$requrl})) {
10198: $urls{$requrl} = 'add';
10199: }
10200: }
10201: }
10202: }
10203: if (ref($delsref) eq 'ARRAY') {
10204: foreach my $requrl (@{$delsref}) {
10205: if (&is_portfolio_url($requrl)) {
10206: unless (exists($urls{$requrl})) {
10207: $urls{$requrl} = 'delete';
10208: }
10209: }
10210: }
10211: }
10212: unless (keys(%urls)) {
10213: return 'invalid';
10214: }
10215: my $ip;
10216: if ($accesstype eq 'ip') {
10217: if (ref($info) eq 'HASH') {
10218: if ($info->{'ip'} ne '') {
10219: $ip = $info->{'ip'};
10220: }
10221: }
10222: if ($ip eq '') {
10223: return 'invalid';
10224: }
10225: }
10226: my $errors;
1.827 raeburn 10227: my $now = time;
1.1271 raeburn 10228: my %current_perms;
10229: foreach my $requrl (sort(keys(%urls))) {
10230: my $action;
10231: if ($urls{$requrl} eq 'add') {
10232: $action = 'activate';
10233: } else {
10234: $action = 'none';
10235: }
10236: my $aclnum = 0;
1.827 raeburn 10237: my (undef,$udom,$unum,$file_name,$group) =
10238: &parse_portfolio_url($requrl);
1.1271 raeburn 10239: unless (exists($current_perms{$unum.':'.$udom})) {
10240: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10241: }
10242: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 10243: $group,$file_name);
10244: foreach my $key (keys(%{$access_controls{$file_name}})) {
10245: my ($num,$scope,$end,$start) =
10246: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 10247: if ($scope eq $accesstype) {
10248: if (($start <= $now) && ($end == 0)) {
10249: if ($accesstype eq 'ip') {
10250: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10251: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10252: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10253: if ($urls{$requrl} eq 'add') {
10254: $action = 'none';
10255: last;
10256: } else {
10257: $action = 'delete';
10258: $aclnum = $num;
10259: last;
10260: }
10261: }
10262: }
10263: }
10264: } elsif ($accesstype eq 'public') {
10265: if ($urls{$requrl} eq 'add') {
10266: $action = 'none';
10267: last;
10268: } else {
10269: $action = 'delete';
10270: $aclnum = $num;
10271: last;
10272: }
10273: }
10274: } elsif ($accesstype eq 'public') {
1.827 raeburn 10275: $action = 'update';
10276: $aclnum = $num;
1.1271 raeburn 10277: last;
1.827 raeburn 10278: }
10279: }
10280: }
10281: if ($action eq 'none') {
1.1271 raeburn 10282: next;
1.827 raeburn 10283: } else {
10284: my %changes;
10285: my $newend = 0;
10286: my $newstart = $now;
1.1271 raeburn 10287: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 10288: $changes{$action}{$newkey} = {
1.1271 raeburn 10289: type => $accesstype,
1.827 raeburn 10290: time => {
10291: start => $newstart,
10292: end => $newend,
10293: },
10294: };
1.1271 raeburn 10295: if ($accesstype eq 'ip') {
10296: $changes{$action}{$newkey}{'ip'} = [$ip];
10297: }
1.827 raeburn 10298: my ($outcome,$deloutcome,$new_values,$translation) =
10299: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 10300: unless ($outcome eq 'ok') {
10301: $errors .= $outcome.' ';
10302: }
1.827 raeburn 10303: }
1.1271 raeburn 10304: }
10305: if ($errors) {
10306: $errors =~ s/\s$//;
10307: return $errors;
1.827 raeburn 10308: } else {
1.1271 raeburn 10309: return 'ok';
1.827 raeburn 10310: }
10311: }
10312:
1.745 raeburn 10313: #------------------------------------------------------Get Marked as Read Only
10314:
10315: sub get_marked_as_readonly {
10316: my ($domain,$user,$what,$group) = @_;
10317: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10318: my @readonly_files;
1.629 banghart 10319: my $cmp1=$what;
10320: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10321: while (my ($file_name,$value) = each(%{$current_permissions})) {
10322: if (defined($group)) {
10323: if ($file_name !~ m-^\Q$group\E/-) {
10324: next;
10325: }
10326: }
1.561 banghart 10327: if (ref($value) eq "ARRAY"){
10328: foreach my $stored_what (@{$value}) {
1.629 banghart 10329: my $cmp2=$stored_what;
1.759 albertel 10330: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10331: $cmp2=join('',@{$stored_what});
1.745 raeburn 10332: }
1.629 banghart 10333: if ($cmp1 eq $cmp2) {
1.561 banghart 10334: push(@readonly_files, $file_name);
1.745 raeburn 10335: last;
1.563 banghart 10336: } elsif (!defined($what)) {
10337: push(@readonly_files, $file_name);
1.745 raeburn 10338: last;
1.561 banghart 10339: }
10340: }
1.745 raeburn 10341: }
1.561 banghart 10342: }
10343: return @readonly_files;
10344: }
1.577 banghart 10345: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10346:
1.577 banghart 10347: sub get_marked_as_readonly_hash {
1.745 raeburn 10348: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10349: my %readonly_files;
1.745 raeburn 10350: while (my ($file_name,$value) = each(%{$current_permissions})) {
10351: if (defined($group)) {
10352: if ($file_name !~ m-^\Q$group\E/-) {
10353: next;
10354: }
10355: }
1.577 banghart 10356: if (ref($value) eq "ARRAY"){
10357: foreach my $stored_what (@{$value}) {
1.745 raeburn 10358: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10359: foreach my $lock_descriptor(@{$stored_what}) {
10360: if ($lock_descriptor eq 'graded') {
10361: $readonly_files{$file_name} = 'graded';
10362: } elsif ($lock_descriptor eq 'handback') {
10363: $readonly_files{$file_name} = 'handback';
10364: } else {
10365: if (!exists($readonly_files{$file_name})) {
10366: $readonly_files{$file_name} = 'locked';
10367: }
10368: }
1.745 raeburn 10369: }
1.750 banghart 10370: }
1.577 banghart 10371: }
10372: }
10373: }
10374: return %readonly_files;
10375: }
1.559 banghart 10376: # ------------------------------------------------------------ Unmark as Read Only
10377:
10378: sub unmark_as_readonly {
1.629 banghart 10379: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10380: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10381: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10382: $file_name = &declutter_portfile($file_name);
1.634 albertel 10383: my $symb_crs = $what;
10384: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10385: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10386: my ($tmp)=keys(%current_permissions);
10387: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10388: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10389: foreach my $file (@readonly_files) {
1.759 albertel 10390: my $clean_file = &declutter_portfile($file);
10391: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10392: my $current_locks = $current_permissions{$file};
1.563 banghart 10393: my @new_locks;
10394: my @del_keys;
10395: if (ref($current_locks) eq "ARRAY"){
10396: foreach my $locker (@{$current_locks}) {
1.632 albertel 10397: my $compare=$locker;
1.749 raeburn 10398: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10399: $compare=join('',@{$locker});
1.746 raeburn 10400: if ($compare ne $symb_crs) {
10401: push(@new_locks, $locker);
10402: }
1.563 banghart 10403: }
10404: }
1.650 albertel 10405: if (scalar(@new_locks) > 0) {
1.563 banghart 10406: $current_permissions{$file} = \@new_locks;
10407: } else {
10408: push(@del_keys, $file);
1.613 albertel 10409: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10410: delete($current_permissions{$file});
1.563 banghart 10411: }
10412: }
1.561 banghart 10413: }
1.613 albertel 10414: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10415: return;
10416: }
1.512 banghart 10417:
1.17 www 10418: # ------------------------------------------------------------ Directory lister
10419:
10420: sub dirlist {
1.955 raeburn 10421: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10422: $uri=~s/^\///;
10423: $uri=~s/\/$//;
1.253 stredwic 10424: my ($udom, $uname);
1.955 raeburn 10425: if ($getuserdir) {
1.253 stredwic 10426: $udom = $userdomain;
10427: $uname = $username;
1.955 raeburn 10428: } else {
10429: (undef,$udom,$uname)=split(/\//,$uri);
10430: if(defined($userdomain)) {
10431: $udom = $userdomain;
10432: }
10433: if(defined($username)) {
10434: $uname = $username;
10435: }
1.253 stredwic 10436: }
1.955 raeburn 10437: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10438:
1.955 raeburn 10439: $dirRoot = $perlvar{'lonDocRoot'};
10440: if (defined($getpropath)) {
10441: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10442: $dirRoot =~ s/\/$//;
1.955 raeburn 10443: } elsif (defined($getuserdir)) {
10444: my $subdir=$uname.'__';
10445: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10446: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10447: ."/$udom/$subdir/$uname";
10448: } elsif (defined($alternateRoot)) {
10449: $dirRoot = $alternateRoot;
1.751 banghart 10450: }
1.253 stredwic 10451:
10452: if($udom) {
10453: if($uname) {
1.1135 raeburn 10454: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10455: if ($uhome eq 'no_host') {
10456: return ([],'no_host');
10457: }
1.955 raeburn 10458: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10459: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10460: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10461: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10462: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10463: } else {
10464: @listing_results = map { &unescape($_); } split(/:/,$listing);
10465: }
1.605 matthew 10466: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10467: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10468: @listing_results = split(/:/,$listing);
10469: } else {
10470: @listing_results = map { &unescape($_); } split(/:/,$listing);
10471: }
1.1135 raeburn 10472: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10473: ($listing eq 'rejected') || ($listing eq 'refused') ||
10474: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10475: return ([],$listing);
10476: } else {
10477: return (\@listing_results);
1.1135 raeburn 10478: }
1.955 raeburn 10479: } elsif(!$alternateRoot) {
1.1136 raeburn 10480: my (%allusers,%listerror);
1.841 albertel 10481: my %servers = &get_servers($udom,'library');
1.955 raeburn 10482: foreach my $tryserver (keys(%servers)) {
10483: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10484: &escape($udom),$tryserver);
10485: if ($listing eq 'unknown_cmd') {
10486: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10487: $udom, $tryserver);
10488: } else {
10489: @listing_results = map { &unescape($_); } split(/:/,$listing);
10490: }
1.841 albertel 10491: if ($listing eq 'unknown_cmd') {
10492: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10493: $udom, $tryserver);
10494: @listing_results = split(/:/,$listing);
10495: } else {
10496: @listing_results =
10497: map { &unescape($_); } split(/:/,$listing);
10498: }
1.1136 raeburn 10499: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10500: ($listing eq 'rejected') || ($listing eq 'refused') ||
10501: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10502: $listerror{$tryserver} = $listing;
10503: } else {
1.841 albertel 10504: foreach my $line (@listing_results) {
10505: my ($entry) = split(/&/,$line,2);
10506: $allusers{$entry} = 1;
10507: }
10508: }
1.253 stredwic 10509: }
1.1136 raeburn 10510: my @alluserslist=();
1.800 albertel 10511: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10512: push(@alluserslist,$user.'&user');
1.253 stredwic 10513: }
1.1318 droeschl 10514:
10515: if (!%listerror) {
10516: # no errors
10517: return (\@alluserslist);
10518: } elsif (scalar(keys(%servers)) == 1) {
10519: # one library server, one error
10520: my ($key) = keys(%listerror);
10521: return (\@alluserslist, $listerror{$key});
10522: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10523: # con_lost indicates that we might miss data from at least one
10524: # library server
10525: return (\@alluserslist, 'con_lost');
10526: } else {
10527: # multiple library servers and no con_lost -> data should be
10528: # complete.
10529: return (\@alluserslist);
10530: }
10531:
1.253 stredwic 10532: } else {
1.1136 raeburn 10533: return ([],'missing username');
1.253 stredwic 10534: }
1.955 raeburn 10535: } elsif(!defined($getpropath)) {
1.1136 raeburn 10536: my $path = $perlvar{'lonDocRoot'}.'/res/';
10537: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10538: return (\@all_domains);
1.955 raeburn 10539: } else {
1.1136 raeburn 10540: return ([],'missing domain');
1.275 stredwic 10541: }
10542: }
10543:
10544: # --------------------------------------------- GetFileTimestamp
10545: # This function utilizes dirlist and returns the date stamp for
10546: # when it was last modified. It will also return an error of -1
10547: # if an error occurs
10548:
10549: sub GetFileTimestamp {
1.955 raeburn 10550: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10551: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10552: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10553: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10554: undef,$getuserdir);
10555: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10556: return -1;
10557: }
10558: if (ref($fileref) eq 'ARRAY') {
10559: my @stats = split('&',$fileref->[0]);
1.375 matthew 10560: # @stats contains first the filename, then the stat output
10561: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10562: } else {
10563: return -1;
1.253 stredwic 10564: }
1.26 www 10565: }
10566:
1.712 albertel 10567: sub stat_file {
10568: my ($uri) = @_;
1.787 albertel 10569: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10570:
1.955 raeburn 10571: my ($udom,$uname,$file);
1.712 albertel 10572: if ($uri =~ m-^/(uploaded|editupload)/-) {
10573: ($udom,$uname,$file) =
1.811 albertel 10574: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10575: $file = 'userfiles/'.$file;
10576: }
10577: if ($uri =~ m-^/res/-) {
10578: ($udom,$uname) =
1.807 albertel 10579: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10580: $file = $uri;
10581: }
10582:
10583: if (!$udom || !$uname || !$file) {
10584: # unable to handle the uri
10585: return ();
10586: }
1.956 raeburn 10587: my $getpropath;
10588: if ($file =~ /^userfiles\//) {
10589: $getpropath = 1;
10590: }
1.1136 raeburn 10591: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10592: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10593: return ();
10594: } else {
10595: if (ref($listref) eq 'ARRAY') {
10596: my @stats = split('&',$listref->[0]);
10597: shift(@stats); #filename is first
10598: return @stats;
10599: }
1.712 albertel 10600: }
10601: return ();
10602: }
10603:
1.1313 raeburn 10604: # --------------------------------------------------------- recursedirs
10605: # Recursive function to traverse either a specific user's Authoring Space
10606: # or corresponding Published Resource Space, and populate the hash ref:
10607: # $dirhashref with URLs of all directories, and if $filehashref hash
10608: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10609: # or .rights files in resource space, and .meta, .save, .log, and .bak
10610: # files in Authoring Space.
10611: #
10612: # Inputs:
10613: #
10614: # $is_home - true if current server is home server for user's space
10615: # $context - either: priv, or res respectively for Authoring or Resource Space.
10616: # $docroot - Document root (i.e., /home/httpd/html
10617: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10618: # $relpath - Current path (relative to top level).
10619: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10620: # $filehashref - reference to hash to populate with URLs of files (Optional)
10621: #
10622: # Returns: nothing
10623: #
10624: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10625: #
10626: # Currently used by interface/londocs.pm to create linked select boxes for
10627: # directory and filename to import a Course "Author" resource into a course, and
10628: # also to create linked select boxes for Authoring Space and Directory to choose
10629: # save location for creation of a new "standard" problem from the Course Editor.
10630: #
10631:
10632: sub recursedirs {
10633: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10634: return unless (ref($dirhashref) eq 'HASH');
10635: my $currpath = $docroot.$toppath;
10636: if ($relpath) {
10637: $currpath .= "/$relpath";
10638: }
10639: my $savefile;
10640: if (ref($filehashref)) {
10641: $savefile = 1;
10642: }
10643: if ($is_home) {
10644: if (opendir(my $dirh,$currpath)) {
10645: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10646: next if ($item eq '');
10647: if (-d "$currpath/$item") {
10648: my $newpath;
10649: if ($relpath) {
10650: $newpath = "$relpath/$item";
10651: } else {
10652: $newpath = $item;
10653: }
10654: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10655: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10656: } elsif ($savefile) {
10657: if ($context eq 'priv') {
10658: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10659: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10660: }
10661: } else {
10662: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10663: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10664: }
10665: }
10666: }
10667: }
10668: closedir($dirh);
10669: }
10670: } else {
10671: my ($dirlistref,$listerror) =
10672: &dirlist($toppath.$relpath);
10673: my @dir_lines;
10674: my $dirptr=16384;
10675: if (ref($dirlistref) eq 'ARRAY') {
10676: foreach my $dir_line (sort
10677: {
10678: my ($afile)=split('&',$a,2);
10679: my ($bfile)=split('&',$b,2);
10680: return (lc($afile) cmp lc($bfile));
10681: } (@{$dirlistref})) {
10682: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10683: split(/\&/,$dir_line,16);
10684: $item =~ s/\s+$//;
10685: next if (($item =~ /^\.\.?$/) || ($obs));
10686: if ($dirptr&$testdir) {
10687: my $newpath;
10688: if ($relpath) {
10689: $newpath = "$relpath/$item";
10690: } else {
10691: $relpath = '/';
10692: $newpath = $item;
10693: }
10694: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10695: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10696: } elsif ($savefile) {
10697: if ($context eq 'priv') {
10698: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10699: $filehashref->{$relpath}{$item} = 1;
10700: }
10701: } else {
10702: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10703: $filehashref->{$relpath}{$item} = 1;
10704: }
10705: }
10706: }
10707: }
10708: }
10709: }
10710: return;
10711: }
10712:
1.26 www 10713: # -------------------------------------------------------- Value of a Condition
10714:
1.713 albertel 10715: # gets the value of a specific preevaluated condition
10716: # stored in the string $env{user.state.<cid>}
10717: # or looks up a condition reference in the bighash and if if hasn't
10718: # already been evaluated recurses into docondval to get the value of
10719: # the condition, then memoizing it to
10720: # $env{user.state.<cid>.<condition>}
1.40 www 10721: sub directcondval {
10722: my $number=shift;
1.620 albertel 10723: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10724: &Apache::lonuserstate::evalstate();
10725: }
1.713 albertel 10726: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10727: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10728: } elsif ($number =~ /^_/) {
10729: my $sub_condition;
10730: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10731: &GDBM_READER(),0640)) {
10732: $sub_condition=$bighash{'conditions'.$number};
10733: untie(%bighash);
10734: }
10735: my $value = &docondval($sub_condition);
1.949 raeburn 10736: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10737: return $value;
10738: }
1.620 albertel 10739: if ($env{'user.state.'.$env{'request.course.id'}}) {
10740: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10741: } else {
10742: return 2;
10743: }
10744: }
10745:
1.713 albertel 10746: # get the collection of conditions for this resource
1.26 www 10747: sub condval {
10748: my $condidx=shift;
1.54 www 10749: my $allpathcond='';
1.713 albertel 10750: foreach my $cond (split(/\|/,$condidx)) {
10751: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10752: $allpathcond.=
10753: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10754: }
1.191 harris41 10755: }
1.54 www 10756: $allpathcond=~s/\|$//;
1.713 albertel 10757: return &docondval($allpathcond);
10758: }
10759:
10760: #evaluates an expression of conditions
10761: sub docondval {
10762: my ($allpathcond) = @_;
10763: my $result=0;
10764: if ($env{'request.course.id'}
10765: && defined($allpathcond)) {
10766: my $operand='|';
10767: my @stack;
10768: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10769: if ($chunk eq '(') {
10770: push @stack,($operand,$result);
10771: } elsif ($chunk eq ')') {
10772: my $before=pop @stack;
10773: if (pop @stack eq '&') {
10774: $result=$result>$before?$before:$result;
10775: } else {
10776: $result=$result>$before?$result:$before;
10777: }
10778: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10779: $operand=$chunk;
10780: } else {
10781: my $new=directcondval($chunk);
10782: if ($operand eq '&') {
10783: $result=$result>$new?$new:$result;
10784: } else {
10785: $result=$result>$new?$result:$new;
10786: }
10787: }
10788: }
1.26 www 10789: }
10790: return $result;
1.421 albertel 10791: }
10792:
10793: # ---------------------------------------------------- Devalidate courseresdata
10794:
10795: sub devalidatecourseresdata {
10796: my ($coursenum,$coursedomain)=@_;
10797: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10798: &devalidate_cache_new('courseres',$hashid);
1.28 www 10799: }
10800:
1.763 www 10801:
1.200 www 10802: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10803: #
10804: # Parameters:
10805: # $coursenum - Number of the course.
10806: # $coursedomain - Domain at which the course was created.
10807: # Returns:
10808: # A hash of the course parameters along (I think) with timestamps
10809: # and version info.
1.877 foxr 10810:
1.624 albertel 10811: sub get_courseresdata {
10812: my ($coursenum,$coursedomain)=@_;
1.200 www 10813: my $coursehom=&homeserver($coursenum,$coursedomain);
10814: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10815: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10816: my %dumpreply;
1.417 albertel 10817: unless (defined($cached)) {
1.624 albertel 10818: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10819: $result=\%dumpreply;
1.251 albertel 10820: my ($tmp) = keys(%dumpreply);
10821: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10822: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10823: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10824: return $tmp;
1.416 albertel 10825: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10826: $result=undef;
1.599 albertel 10827: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10828: }
10829: }
1.624 albertel 10830: return $result;
10831: }
10832:
1.633 albertel 10833: sub devalidateuserresdata {
10834: my ($uname,$udom)=@_;
10835: my $hashid="$udom:$uname";
10836: &devalidate_cache_new('userres',$hashid);
10837: }
10838:
1.624 albertel 10839: sub get_userresdata {
10840: my ($uname,$udom)=@_;
10841: #most student don\'t have any data set, check if there is some data
10842: if (&EXT_cache_status($udom,$uname)) { return undef; }
10843:
10844: my $hashid="$udom:$uname";
10845: my ($result,$cached)=&is_cached_new('userres',$hashid);
10846: if (!defined($cached)) {
10847: my %resourcedata=&dump('resourcedata',$udom,$uname);
10848: $result=\%resourcedata;
10849: &do_cache_new('userres',$hashid,$result,600);
10850: }
10851: my ($tmp)=keys(%$result);
10852: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10853: return $result;
10854: }
10855: #error 2 occurs when the .db doesn't exist
10856: if ($tmp!~/error: 2 /) {
1.1294 raeburn 10857: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10858: &logthis("<font color=\"blue\">WARNING:".
10859: " Trying to get resource data for ".
10860: $uname." at ".$udom.": ".
10861: $tmp."</font>");
10862: }
1.624 albertel 10863: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10864: #&EXT_cache_set($udom,$uname);
10865: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10866: undef($tmp); # not really an error so don't send it back
1.624 albertel 10867: }
10868: return $tmp;
10869: }
1.879 foxr 10870: #----------------------------------------------- resdata - return resource data
10871: # Purpose:
10872: # Return resource data for either users or for a course.
10873: # Parameters:
10874: # $name - Course/user name.
10875: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 10876: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 10877: # $mapp - decluttered URL of enclosing map
10878: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
10879: # $recurseup - Ref to array of map URLs, starting with map containing
10880: # $mapp up through hierarchy of nested maps to top level map.
10881: # $courseid - CourseID (first part of param identifier).
10882: # $modifier - Middle part of param identifier.
10883: # $what - Last part of param identifier.
1.879 foxr 10884: # @which - Array of names of resources desired.
10885: # Returns:
10886: # The value of the first reasource in @which that is found in the
10887: # resource hash.
10888: # Exceptional Conditions:
10889: # If the $type passed in is not valid (not the string 'course' or
10890: # 'user', an undefined reference is returned.
10891: # If none of the resources are found, an undef is returned
1.624 albertel 10892: sub resdata {
1.1301 raeburn 10893: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
10894: $modifier,$what,@which)=@_;
1.624 albertel 10895: my $result;
10896: if ($type eq 'course') {
10897: $result=&get_courseresdata($name,$domain);
10898: } elsif ($type eq 'user') {
10899: $result=&get_userresdata($name,$domain);
10900: }
10901: if (!ref($result)) { return $result; }
1.251 albertel 10902: foreach my $item (@which) {
1.1301 raeburn 10903: if ($item->[1] eq 'course') {
10904: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
10905: unless ($$recursed) {
1.1302 raeburn 10906: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 10907: $$recursed = 1;
10908: }
10909: foreach my $item (@${recurseup}) {
10910: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
10911: last if (defined($result->{$norecursechk}));
10912: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
10913: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
10914: }
10915: }
10916: }
10917: if (defined($result->{$item->[0]})) {
1.927 albertel 10918: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10919: }
1.250 albertel 10920: }
1.291 albertel 10921: return undef;
1.200 www 10922: }
10923:
1.1298 raeburn 10924: sub get_domain_ltitools {
10925: my ($cdom) = @_;
10926: my %ltitools;
10927: my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10928: if (defined($cached)) {
10929: if (ref($result) eq 'HASH') {
10930: %ltitools = %{$result};
10931: }
10932: } else {
10933: my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10934: if (ref($domconfig{'ltitools'}) eq 'HASH') {
10935: %ltitools = %{$domconfig{'ltitools'}};
10936: }
10937: my $cachetime = 24*60*60;
10938: &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10939: }
10940: return %ltitools;
10941: }
10942:
1.1236 raeburn 10943: sub get_numsuppfiles {
10944: my ($cnum,$cdom,$ignorecache)=@_;
10945: my $hashid=$cnum.':'.$cdom;
10946: my ($suppcount,$cached);
10947: unless ($ignorecache) {
10948: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10949: }
10950: unless (defined($cached)) {
10951: my $chome=&homeserver($cnum,$cdom);
10952: unless ($chome eq 'no_host') {
10953: ($suppcount,my $errors) = (0,0);
10954: my $suppmap = 'supplemental.sequence';
10955: ($suppcount,$errors) =
10956: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10957: }
10958: &do_cache_new('suppcount',$hashid,$suppcount,600);
10959: }
10960: return $suppcount;
10961: }
10962:
1.379 matthew 10963: #
10964: # EXT resource caching routines
10965: #
10966:
1.1302 raeburn 10967: {
10968: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
10969: #
10970: # The course for which we cache
10971: my $cachedmapkey='';
10972: # The cached recursive maps for this course
10973: my %cachedmaps=();
10974: # When this was last done
10975: my $cachedmaptime='';
10976:
1.379 matthew 10977: sub clear_EXT_cache_status {
1.383 albertel 10978: &delenv('cache.EXT.');
1.379 matthew 10979: }
10980:
10981: sub EXT_cache_status {
10982: my ($target_domain,$target_user) = @_;
1.383 albertel 10983: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10984: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10985: # We know already the user has no data
10986: return 1;
10987: } else {
10988: return 0;
10989: }
10990: }
10991:
10992: sub EXT_cache_set {
10993: my ($target_domain,$target_user) = @_;
1.383 albertel 10994: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10995: #&appenv({$cachename => time});
1.379 matthew 10996: }
10997:
1.28 www 10998: # --------------------------------------------------------- Value of a Variable
1.58 www 10999: sub EXT {
1.715 albertel 11000:
1.1228 raeburn 11001: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11002: unless ($varname) { return ''; }
1.218 albertel 11003: #get real user name/domain, courseid and symb
11004: my $courseid;
1.359 albertel 11005: my $publicuser;
1.427 www 11006: if ($symbparm) {
11007: $symbparm=&get_symb_from_alias($symbparm);
11008: }
1.218 albertel 11009: if (!($uname && $udom)) {
1.790 albertel 11010: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11011: if (!$symbparm) { $symbparm=$cursymb; }
11012: } else {
1.620 albertel 11013: $courseid=$env{'request.course.id'};
1.218 albertel 11014: }
1.48 www 11015: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11016: my $rest;
1.320 albertel 11017: if (defined($therest[0])) {
1.48 www 11018: $rest=join('.',@therest);
11019: } else {
11020: $rest='';
11021: }
1.320 albertel 11022:
1.57 www 11023: my $qualifierrest=$qualifier;
11024: if ($rest) { $qualifierrest.='.'.$rest; }
11025: my $spacequalifierrest=$space;
11026: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11027: if ($realm eq 'user') {
1.48 www 11028: # --------------------------------------------------------------- user.resource
11029: if ($space eq 'resource') {
1.651 albertel 11030: if ( (defined($Apache::lonhomework::parsing_a_problem)
11031: || defined($Apache::lonhomework::parsing_a_task))
11032: &&
1.744 albertel 11033: ($symbparm eq &symbread()) ) {
11034: # if we are in the middle of processing the resource the
11035: # get the value we are planning on committing
11036: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11037: return $Apache::lonhomework::results{$qualifierrest};
11038: } else {
11039: return $Apache::lonhomework::history{$qualifierrest};
11040: }
1.335 albertel 11041: } else {
1.359 albertel 11042: my %restored;
1.620 albertel 11043: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11044: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11045: } else {
11046: %restored=&restore($symbparm,$courseid,$udom,$uname);
11047: }
1.335 albertel 11048: return $restored{$qualifierrest};
11049: }
1.48 www 11050: # ----------------------------------------------------------------- user.access
11051: } elsif ($space eq 'access') {
1.218 albertel 11052: # FIXME - not supporting calls for a specific user
1.48 www 11053: return &allowed($qualifier,$rest);
11054: # ------------------------------------------ user.preferences, user.environment
11055: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11056: if (($uname eq $env{'user.name'}) &&
11057: ($udom eq $env{'user.domain'})) {
11058: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11059: } else {
1.359 albertel 11060: my %returnhash;
11061: if (!$publicuser) {
11062: %returnhash=&userenvironment($udom,$uname,
11063: $qualifierrest);
11064: }
1.218 albertel 11065: return $returnhash{$qualifierrest};
11066: }
1.48 www 11067: # ----------------------------------------------------------------- user.course
11068: } elsif ($space eq 'course') {
1.218 albertel 11069: # FIXME - not supporting calls for a specific user
1.620 albertel 11070: return $env{join('.',('request.course',$qualifier))};
1.48 www 11071: # ------------------------------------------------------------------- user.role
11072: } elsif ($space eq 'role') {
1.218 albertel 11073: # FIXME - not supporting calls for a specific user
1.620 albertel 11074: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11075: if ($qualifier eq 'value') {
11076: return $role;
11077: } elsif ($qualifier eq 'extent') {
11078: return $where;
11079: }
11080: # ----------------------------------------------------------------- user.domain
11081: } elsif ($space eq 'domain') {
1.218 albertel 11082: return $udom;
1.48 www 11083: # ------------------------------------------------------------------- user.name
11084: } elsif ($space eq 'name') {
1.218 albertel 11085: return $uname;
1.48 www 11086: # ---------------------------------------------------- Any other user namespace
1.29 www 11087: } else {
1.359 albertel 11088: my %reply;
11089: if (!$publicuser) {
11090: %reply=&get($space,[$qualifierrest],$udom,$uname);
11091: }
11092: return $reply{$qualifierrest};
1.48 www 11093: }
1.236 www 11094: } elsif ($realm eq 'query') {
11095: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11096: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11097: [$spacequalifierrest]);
1.620 albertel 11098: return $env{'form.'.$spacequalifierrest};
1.236 www 11099: } elsif ($realm eq 'request') {
1.48 www 11100: # ------------------------------------------------------------- request.browser
11101: if ($space eq 'browser') {
1.1145 bisitz 11102: return $env{'browser.'.$qualifier};
1.57 www 11103: # ------------------------------------------------------------ request.filename
11104: } else {
1.620 albertel 11105: return $env{'request.'.$spacequalifierrest};
1.29 www 11106: }
1.28 www 11107: } elsif ($realm eq 'course') {
1.48 www 11108: # ---------------------------------------------------------- course.description
1.620 albertel 11109: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11110: } elsif ($realm eq 'resource') {
1.165 www 11111:
1.620 albertel 11112: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11113: if (!$symbparm) { $symbparm=&symbread(); }
11114: }
1.693 albertel 11115:
1.1232 raeburn 11116: if ($qualifier eq '') {
11117: if ($space eq 'title') {
11118: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11119: return &gettitle($symbparm);
11120: }
1.693 albertel 11121:
1.1232 raeburn 11122: if ($space eq 'map') {
11123: my ($map) = &decode_symb($symbparm);
11124: return &symbread($map);
11125: }
11126: if ($space eq 'maptitle') {
11127: my ($map) = &decode_symb($symbparm);
11128: return &gettitle($map);
11129: }
11130: if ($space eq 'filename') {
11131: if ($symbparm) {
11132: return &clutter((&decode_symb($symbparm))[2]);
11133: }
11134: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11135: }
1.1232 raeburn 11136:
1.1233 raeburn 11137: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11138: if ($space eq 'visibleparts') {
11139: my $navmap = Apache::lonnavmaps::navmap->new();
11140: my $item;
11141: if (ref($navmap)) {
11142: my $res = $navmap->getBySymb($symbparm);
11143: my $parts = $res->parts();
11144: if (ref($parts) eq 'ARRAY') {
11145: $item = join(',',@{$parts});
11146: }
11147: undef($navmap);
1.1232 raeburn 11148: }
1.1233 raeburn 11149: return $item;
1.1232 raeburn 11150: }
11151: }
11152: }
1.693 albertel 11153:
1.1301 raeburn 11154: my ($section, $group, @groups, @recurseup, $recursed);
11155: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 11156: if (($courseid eq '') && ($cid)) {
11157: $courseid = $cid;
11158: }
11159: if (($symbparm && $courseid) &&
11160: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11161:
1.218 albertel 11162: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11163:
1.60 www 11164: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11165: my $symbp=$symbparm;
1.1301 raeburn 11166: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11167: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 11168: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 11169: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 11170: if (($env{'user.name'} eq $uname) &&
11171: ($env{'user.domain'} eq $udom)) {
11172: $section=$env{'request.course.sec'};
1.733 raeburn 11173: @groups = split(/:/,$env{'request.course.groups'});
11174: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11175: } else {
1.539 albertel 11176: if (! defined($usection)) {
1.551 albertel 11177: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11178: } else {
11179: $section = $usection;
11180: }
1.733 raeburn 11181: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11182: }
11183:
11184: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11185: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 11186: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 11187: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11188:
1.593 albertel 11189: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11190: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 11191: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 11192: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11193:
1.60 www 11194: # ----------------------------------------------------------- first, check user
1.624 albertel 11195:
1.1301 raeburn 11196: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11197: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 11198: ([$courselevelr,'resource'],
11199: [$courselevelm,'map' ],
1.1301 raeburn 11200: [$courseleveli,'map' ],
1.927 albertel 11201: [$courselevel, 'course' ]));
1.931 albertel 11202: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11203:
1.594 albertel 11204: # ------------------------------------------------ second, check some of course
1.684 raeburn 11205: my $coursereply;
1.691 raeburn 11206: if (@groups > 0) {
11207: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 11208: $recurseparm,$mapparm,$spacequalifierrest,
11209: $mapp,\$recursed,\@recurseup);
11210: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11211: }
1.96 www 11212:
1.684 raeburn 11213: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11214: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 11215: 'course',$mapp,\$recursed,\@recurseup,
11216: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 11217: ([$seclevelr, 'resource'],
11218: [$seclevelm, 'map' ],
1.1301 raeburn 11219: [$secleveli, 'map' ],
1.927 albertel 11220: [$seclevel, 'course' ],
11221: [$courselevelr,'resource']));
11222: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11223:
1.60 www 11224: # ------------------------------------------------------ third, check map parms
1.218 albertel 11225: my %parmhash=();
11226: my $thisparm='';
11227: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11228: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11229: &GDBM_READER(),0640)) {
1.218 albertel 11230: $thisparm=$parmhash{$symbparm};
11231: untie(%parmhash);
11232: }
1.927 albertel 11233: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11234: }
1.594 albertel 11235: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 11236:
11237: my $what = $spacequalifierrest;
11238: $what=~s/\./\_/;
1.282 albertel 11239: my $filename;
11240: if (!$symbparm) { $symbparm=&symbread(); }
11241: if ($symbparm) {
1.409 www 11242: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11243: } else {
1.620 albertel 11244: $filename=$env{'request.filename'};
1.282 albertel 11245: }
1.1301 raeburn 11246: my $metadata=&metadata($filename,$what);
1.927 albertel 11247: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301 raeburn 11248: $metadata=&metadata($filename,'parameter_'.$what);
1.927 albertel 11249: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11250:
1.1301 raeburn 11251: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 11252: if ($symbparm && defined($courseid) &&
1.620 albertel 11253: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11254: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11255: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 11256: 'course',$mapp,\$recursed,\@recurseup,
11257: $courseid,'.',$spacequalifierrest,
1.927 albertel 11258: ([$courselevelm,'map' ],
1.1301 raeburn 11259: [$courseleveli,'map' ],
1.927 albertel 11260: [$courselevel, 'course']));
11261: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11262: }
1.145 www 11263: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11264: unless ($space eq '0') {
1.336 albertel 11265: my @parts=split(/_/,$space);
11266: my $id=pop(@parts);
11267: my $part=join('_',@parts);
11268: if ($part eq '') { $part='0'; }
1.927 albertel 11269: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11270: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11271: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11272: }
1.395 albertel 11273: if ($recurse) { return undef; }
11274: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11275: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11276: # ---------------------------------------------------- Any other user namespace
11277: } elsif ($realm eq 'environment') {
11278: # ----------------------------------------------------------------- environment
1.620 albertel 11279: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11280: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11281: } else {
1.770 albertel 11282: if ($uname eq 'anonymous' && $udom eq '') {
11283: return '';
11284: }
1.219 albertel 11285: my %returnhash=&userenvironment($udom,$uname,
11286: $spacequalifierrest);
11287: return $returnhash{$spacequalifierrest};
11288: }
1.28 www 11289: } elsif ($realm eq 'system') {
1.48 www 11290: # ----------------------------------------------------------------- system.time
11291: if ($space eq 'time') {
11292: return time;
11293: }
1.696 albertel 11294: } elsif ($realm eq 'server') {
11295: # ----------------------------------------------------------------- system.time
11296: if ($space eq 'name') {
11297: return $ENV{'SERVER_NAME'};
11298: }
1.28 www 11299: }
1.48 www 11300: return '';
1.61 www 11301: }
11302:
1.927 albertel 11303: sub get_reply {
11304: my ($reply_value) = @_;
1.940 raeburn 11305: if (ref($reply_value) eq 'ARRAY') {
11306: if (wantarray) {
11307: return @$reply_value;
11308: }
11309: return $reply_value->[0];
11310: } else {
11311: return $reply_value;
1.927 albertel 11312: }
11313: }
11314:
1.691 raeburn 11315: sub check_group_parms {
1.1301 raeburn 11316: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11317: $recursed,$recurseupref) = @_;
11318: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11319: [$what,'course']);
11320: my $coursereply;
1.691 raeburn 11321: foreach my $group (@{$groups}) {
1.1301 raeburn 11322: my @groupitems = ();
1.691 raeburn 11323: foreach my $level (@levels) {
1.927 albertel 11324: my $item = $courseid.'.['.$group.'].'.$level->[0];
11325: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11326: }
1.1301 raeburn 11327: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11328: $env{'course.'.$courseid.'.domain'},
11329: 'course',$mapp,$recursed,$recurseupref,
11330: $courseid,'.['.$group.'].',$what,
11331: @groupitems);
11332: last if (defined($coursereply));
1.691 raeburn 11333: }
11334: return $coursereply;
11335: }
11336:
1.1301 raeburn 11337: sub get_map_hierarchy {
1.1302 raeburn 11338: my ($mapname,$courseid) = @_;
11339: my @recurseup = ();
1.1301 raeburn 11340: if ($mapname) {
1.1302 raeburn 11341: if (($cachedmapkey eq $courseid) &&
11342: (abs($cachedmaptime-time)<5)) {
11343: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11344: return @{$cachedmaps{$mapname}};
11345: }
11346: }
1.1301 raeburn 11347: my $navmap = Apache::lonnavmaps::navmap->new();
11348: if (ref($navmap)) {
11349: @recurseup = $navmap->recurseup_maps($mapname);
11350: undef($navmap);
1.1302 raeburn 11351: $cachedmaps{$mapname} = \@recurseup;
11352: $cachedmaptime=time;
11353: $cachedmapkey=$courseid;
1.1301 raeburn 11354: }
11355: }
11356: return @recurseup;
11357: }
11358:
1.1302 raeburn 11359: }
11360:
1.691 raeburn 11361: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11362: my ($courseid,@groups) = @_;
11363: @groups = sort(@groups);
1.691 raeburn 11364: return @groups;
11365: }
11366:
1.395 albertel 11367: sub packages_tab_default {
11368: my ($uri,$varname)=@_;
11369: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11370:
11371: my (@extension,@specifics,$do_default);
11372: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11373: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11374: if ($pack_type eq 'default') {
11375: $do_default=1;
11376: } elsif ($pack_type eq 'extension') {
11377: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11378: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11379: # only look at packages defaults for packages that this id is
1.738 albertel 11380: push(@specifics,[$package,$pack_type,$pack_part]);
11381: }
11382: }
11383: # first look for a package that matches the requested part id
11384: foreach my $package (@specifics) {
11385: my (undef,$pack_type,$pack_part)=@{$package};
11386: next if ($pack_part ne $part);
11387: if (defined($packagetab{"$pack_type&$name&default"})) {
11388: return $packagetab{"$pack_type&$name&default"};
11389: }
11390: }
11391: # look for any possible matching non extension_ package
11392: foreach my $package (@specifics) {
11393: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11394: if (defined($packagetab{"$pack_type&$name&default"})) {
11395: return $packagetab{"$pack_type&$name&default"};
11396: }
1.585 albertel 11397: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11398: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11399: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11400: }
11401: }
1.738 albertel 11402: # look for any posible extension_ match
11403: foreach my $package (@extension) {
11404: my ($package,$pack_type)=@{$package};
11405: if (defined($packagetab{"$pack_type&$name&default"})) {
11406: return $packagetab{"$pack_type&$name&default"};
11407: }
11408: if (defined($packagetab{$package."&$name&default"})) {
11409: return $packagetab{$package."&$name&default"};
11410: }
11411: }
11412: # look for a global default setting
11413: if ($do_default && defined($packagetab{"default&$name&default"})) {
11414: return $packagetab{"default&$name&default"};
11415: }
1.395 albertel 11416: return undef;
11417: }
11418:
1.334 albertel 11419: sub add_prefix_and_part {
11420: my ($prefix,$part)=@_;
11421: my $keyroot;
11422: if (defined($prefix) && $prefix !~ /^__/) {
11423: # prefix that has a part already
11424: $keyroot=$prefix;
11425: } elsif (defined($prefix)) {
11426: # prefix that is missing a part
11427: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11428: } else {
11429: # no prefix at all
11430: if (defined($part)) { $keyroot='_'.$part; }
11431: }
11432: return $keyroot;
11433: }
11434:
1.71 www 11435: # ---------------------------------------------------------------- Get metadata
11436:
1.599 albertel 11437: my %metaentry;
1.1070 www 11438: my %importedpartids;
1.71 www 11439: sub metadata {
1.176 www 11440: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11441: $uri=&declutter($uri);
1.288 albertel 11442: # if it is a non metadata possible uri return quickly
1.529 albertel 11443: if (($uri eq '') ||
11444: (($uri =~ m|^/*adm/|) &&
1.1298 raeburn 11445: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108 raeburn 11446: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11447: return undef;
11448: }
1.1261 raeburn 11449: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11450: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11451: return undef;
1.288 albertel 11452: }
1.73 www 11453: my $filename=$uri;
11454: $uri=~s/\.meta$//;
1.172 www 11455: #
11456: # Is the metadata already cached?
1.177 www 11457: # Look at timestamp of caching
1.172 www 11458: # Everything is cached by the main uri, libraries are never directly cached
11459: #
1.428 albertel 11460: if (!defined($liburi)) {
1.599 albertel 11461: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11462: if (defined($cached)) { return $result->{':'.$what}; }
11463: }
11464: {
1.1069 www 11465: # Imported parts would go here
1.1070 www 11466: my %importedids=();
11467: my @origfileimportpartids=();
1.1069 www 11468: my $importedparts=0;
1.172 www 11469: #
11470: # Is this a recursive call for a library?
11471: #
1.599 albertel 11472: # if (! exists($metacache{$uri})) {
11473: # $metacache{$uri}={};
11474: # }
1.924 albertel 11475: my $cachetime = 60*60;
1.171 www 11476: if ($liburi) {
11477: $liburi=&declutter($liburi);
11478: $filename=$liburi;
1.401 bowersj2 11479: } else {
1.599 albertel 11480: &devalidate_cache_new('meta',$uri);
11481: undef(%metaentry);
1.401 bowersj2 11482: }
1.140 www 11483: my %metathesekeys=();
1.73 www 11484: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11485: my $metastring;
1.1140 www 11486: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11487: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11488: $metastring =
1.929 albertel 11489: &Apache::lonnet::ssi_body($which,
1.924 albertel 11490: ('grade_target' => 'meta'));
11491: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11492: } elsif (($uri !~ m -^(editupload)/-) &&
11493: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11494: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11495: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11496: $metastring=&getfile($file);
1.489 albertel 11497: }
1.208 albertel 11498: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11499: my $token;
1.140 www 11500: undef %metathesekeys;
1.71 www 11501: while ($token=$parser->get_token) {
1.339 albertel 11502: if ($token->[0] eq 'S') {
11503: if (defined($token->[2]->{'package'})) {
1.172 www 11504: #
11505: # This is a package - get package info
11506: #
1.339 albertel 11507: my $package=$token->[2]->{'package'};
11508: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11509: if (defined($token->[2]->{'id'})) {
11510: $keyroot.='_'.$token->[2]->{'id'};
11511: }
1.599 albertel 11512: if ($metaentry{':packages'}) {
11513: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11514: } else {
1.599 albertel 11515: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11516: }
1.736 albertel 11517: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11518: my $part=$keyroot;
11519: $part=~s/^\_//;
1.736 albertel 11520: if ($pack_entry=~/^\Q$package\E\&/ ||
11521: $pack_entry=~/^\Q$package\E_0\&/) {
11522: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11523: # ignore package.tab specified default values
11524: # here &package_tab_default() will fetch those
11525: if ($subp eq 'default') { next; }
1.736 albertel 11526: my $value=$packagetab{$pack_entry};
1.432 albertel 11527: my $unikey;
11528: if ($pack =~ /_0$/) {
11529: $unikey='parameter_0_'.$name;
11530: $part=0;
11531: } else {
11532: $unikey='parameter'.$keyroot.'_'.$name;
11533: }
1.339 albertel 11534: if ($subp eq 'display') {
11535: $value.=' [Part: '.$part.']';
11536: }
1.599 albertel 11537: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11538: $metathesekeys{$unikey}=1;
1.599 albertel 11539: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11540: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11541: }
1.599 albertel 11542: if (defined($metaentry{':'.$unikey.'.default'})) {
11543: $metaentry{':'.$unikey}=
11544: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11545: }
1.339 albertel 11546: }
11547: }
11548: } else {
1.172 www 11549: #
11550: # This is not a package - some other kind of start tag
1.339 albertel 11551: #
11552: my $entry=$token->[1];
1.1068 www 11553: my $unikey='';
1.175 www 11554:
1.339 albertel 11555: if ($entry eq 'import') {
1.175 www 11556: #
11557: # Importing a library here
1.339 albertel 11558: #
1.1067 www 11559: my $location=$parser->get_text('/import');
11560: my $dir=$filename;
11561: $dir=~s|[^/]*$||;
11562: $location=&filelocation($dir,$location);
1.1069 www 11563:
1.1068 www 11564: my $importmode=$token->[2]->{'importmode'};
11565: if ($importmode eq 'problem') {
1.1069 www 11566: # Import as problem/response
1.1068 www 11567: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11568: } elsif ($importmode eq 'part') {
11569: # Import as part(s)
1.1069 www 11570: $importedparts=1;
11571: # We need to get the original file and the imported file to get the part order correct
11572: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11573: # Load and inspect original file
1.1070 www 11574: if ($#origfileimportpartids<0) {
11575: undef(%importedpartids);
11576: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11577: my $origfile=&getfile($origfilelocation);
11578: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11579: }
11580:
1.1069 www 11581: # Load and inspect imported file
11582: my $impfile=&getfile($location);
11583: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11584: if ($#impfilepartids>=0) {
11585: # This problem had parts
1.1070 www 11586: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11587: } else {
11588: # Importing by turning a single problem into a problem part
11589: # It gets the import-tags ID as part-ID
11590: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11591: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11592: }
1.1068 www 11593: } else {
11594: # Normal import
11595: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11596: if (defined($token->[2]->{'id'})) {
11597: $unikey.='_'.$token->[2]->{'id'};
11598: }
1.1067 www 11599: }
11600:
1.339 albertel 11601: if ($depthcount<20) {
1.736 albertel 11602: my $metadata =
11603: &metadata($uri,'keys', $location,$unikey,
11604: $depthcount+1);
11605: foreach my $meta (split(',',$metadata)) {
11606: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11607: $metathesekeys{$meta}=1;
1.339 albertel 11608: }
1.1068 www 11609:
11610: }
1.1067 www 11611: } else {
11612: #
11613: # Not importing, some other kind of non-package, non-library start tag
11614: #
11615: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11616: if (defined($token->[2]->{'id'})) {
11617: $unikey.='_'.$token->[2]->{'id'};
11618: }
1.339 albertel 11619: if (defined($token->[2]->{'name'})) {
11620: $unikey.='_'.$token->[2]->{'name'};
11621: }
11622: $metathesekeys{$unikey}=1;
1.736 albertel 11623: foreach my $param (@{$token->[3]}) {
11624: $metaentry{':'.$unikey.'.'.$param} =
11625: $token->[2]->{$param};
1.339 albertel 11626: }
11627: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11628: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11629: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11630: # only ws inside the tag, and not in default, so use default
11631: # as value
1.599 albertel 11632: $metaentry{':'.$unikey}=$default;
1.908 albertel 11633: } elsif ( $internaltext =~ /\S/ ) {
11634: # something interesting inside the tag
11635: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11636: } else {
1.908 albertel 11637: # no interesting values, don't set a default
1.339 albertel 11638: }
1.172 www 11639: # end of not-a-package not-a-library import
1.339 albertel 11640: }
1.172 www 11641: # end of not-a-package start tag
1.339 albertel 11642: }
1.172 www 11643: # the next is the end of "start tag"
1.339 albertel 11644: }
11645: }
1.483 albertel 11646: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11647: $extension = lc($extension);
11648: if ($extension eq 'htm') { $extension='html'; }
11649:
1.737 albertel 11650: foreach my $key (keys(%packagetab)) {
1.483 albertel 11651: #no specific packages #how's our extension
11652: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11653: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11654: \%metathesekeys);
11655: }
1.883 albertel 11656:
11657: if (!exists($metaentry{':packages'})
11658: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11659: foreach my $key (keys(%packagetab)) {
1.483 albertel 11660: #no specific packages well let's get default then
11661: if ($key!~/^default&/) { next; }
1.488 albertel 11662: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11663: \%metathesekeys);
11664: }
11665: }
1.338 www 11666: # are there custom rights to evaluate
1.599 albertel 11667: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11668:
1.338 www 11669: #
11670: # Importing a rights file here
1.339 albertel 11671: #
11672: unless ($depthcount) {
1.599 albertel 11673: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11674: my $dir=$filename;
11675: $dir=~s|[^/]*$||;
11676: $location=&filelocation($dir,$location);
1.736 albertel 11677: my $rights_metadata =
11678: &metadata($uri,'keys',$location,'_rights',
11679: $depthcount+1);
11680: foreach my $rights (split(',',$rights_metadata)) {
11681: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11682: $metathesekeys{$rights}=1;
1.339 albertel 11683: }
11684: }
11685: }
1.737 albertel 11686: # uniqifiy package listing
11687: my %seen;
11688: my @uniq_packages =
11689: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11690: $metaentry{':packages'} = join(',',@uniq_packages);
11691:
1.1070 www 11692: if ($importedparts) {
11693: # We had imported parts and need to rebuild partorder
11694: $metaentry{':partorder'}='';
11695: $metathesekeys{'partorder'}=1;
11696: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11697: if ($origfileimportpartids[$index] eq 'part') {
11698: # original part, part of the problem
11699: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11700: } else {
11701: # we have imported parts at this position
11702: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11703: }
11704: }
11705: $metaentry{':partorder'}=~s/^\,//;
11706: }
11707:
1.737 albertel 11708: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11709: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 11710: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11711: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11712: # this is the end of "was not already recently cached
1.71 www 11713: }
1.599 albertel 11714: return $metaentry{':'.$what};
1.261 albertel 11715: }
11716:
1.488 albertel 11717: sub metadata_create_package_def {
1.483 albertel 11718: my ($uri,$key,$package,$metathesekeys)=@_;
11719: my ($pack,$name,$subp)=split(/\&/,$key);
11720: if ($subp eq 'default') { next; }
11721:
1.599 albertel 11722: if (defined($metaentry{':packages'})) {
11723: $metaentry{':packages'}.=','.$package;
1.483 albertel 11724: } else {
1.599 albertel 11725: $metaentry{':packages'}=$package;
1.483 albertel 11726: }
11727: my $value=$packagetab{$key};
11728: my $unikey;
11729: $unikey='parameter_0_'.$name;
1.599 albertel 11730: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11731: $$metathesekeys{$unikey}=1;
1.599 albertel 11732: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11733: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11734: }
1.599 albertel 11735: if (defined($metaentry{':'.$unikey.'.default'})) {
11736: $metaentry{':'.$unikey}=
11737: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11738: }
11739: }
11740:
1.261 albertel 11741: sub metadata_generate_part0 {
11742: my ($metadata,$metacache,$uri) = @_;
11743: my %allnames;
1.737 albertel 11744: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11745: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11746: my $part=$$metacache{':'.$metakey.'.part'};
11747: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11748: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11749: $allnames{$name}=$part;
11750: }
11751: }
11752: }
11753: foreach my $name (keys(%allnames)) {
11754: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11755: my $key=":parameter_0_$name";
1.261 albertel 11756: $$metacache{"$key.part"}='0';
11757: $$metacache{"$key.name"}=$name;
1.428 albertel 11758: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11759: $allnames{$name}.'_'.$name.
11760: '.type'};
1.428 albertel 11761: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11762: '.display'};
1.644 www 11763: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11764: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11765: $$metacache{"$key.display"}=$olddis;
11766: }
1.71 www 11767: }
11768:
1.764 albertel 11769: # ------------------------------------------------------ Devalidate title cache
11770:
11771: sub devalidate_title_cache {
11772: my ($url)=@_;
11773: if (!$env{'request.course.id'}) { return; }
11774: my $symb=&symbread($url);
11775: if (!$symb) { return; }
11776: my $key=$env{'request.course.id'}."\0".$symb;
11777: &devalidate_cache_new('title',$key);
11778: }
11779:
1.1014 droeschl 11780: # ------------------------------------------------- Get the title of a course
11781:
11782: sub current_course_title {
11783: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11784: }
1.301 www 11785: # ------------------------------------------------- Get the title of a resource
11786:
11787: sub gettitle {
11788: my $urlsymb=shift;
11789: my $symb=&symbread($urlsymb);
1.534 albertel 11790: if ($symb) {
1.620 albertel 11791: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11792: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11793: if (defined($cached)) {
11794: return $result;
11795: }
1.534 albertel 11796: my ($map,$resid,$url)=&decode_symb($symb);
11797: my $title='';
1.907 albertel 11798: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11799: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11800: } else {
11801: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11802: &GDBM_READER(),0640)) {
11803: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11804: $title=$bighash{'title_'.$mapid.'.'.$resid};
11805: untie(%bighash);
11806: }
1.534 albertel 11807: }
11808: $title=~s/\&colon\;/\:/gs;
11809: if ($title) {
1.1159 www 11810: # Remember both $symb and $title for dynamic metadata
11811: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11812: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11813: # Cache this title and then return it
1.599 albertel 11814: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11815: }
11816: $urlsymb=$url;
11817: }
11818: my $title=&metadata($urlsymb,'title');
11819: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11820: return $title;
1.301 www 11821: }
1.613 albertel 11822:
1.614 albertel 11823: sub get_slot {
11824: my ($which,$cnum,$cdom)=@_;
11825: if (!$cnum || !$cdom) {
1.790 albertel 11826: (undef,my $courseid)=&whichuser();
1.620 albertel 11827: $cdom=$env{'course.'.$courseid.'.domain'};
11828: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11829: }
1.703 albertel 11830: my $key=join("\0",'slots',$cdom,$cnum,$which);
11831: my %slotinfo;
11832: if (exists($remembered{$key})) {
11833: $slotinfo{$which} = $remembered{$key};
11834: } else {
11835: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11836: &Apache::lonhomework::showhash(%slotinfo);
11837: my ($tmp)=keys(%slotinfo);
11838: if ($tmp=~/^error:/) { return (); }
11839: $remembered{$key} = $slotinfo{$which};
11840: }
1.616 albertel 11841: if (ref($slotinfo{$which}) eq 'HASH') {
11842: return %{$slotinfo{$which}};
11843: }
11844: return $slotinfo{$which};
1.614 albertel 11845: }
1.1150 raeburn 11846:
11847: sub get_reservable_slots {
11848: my ($cnum,$cdom,$uname,$udom) = @_;
11849: my $now = time;
11850: my $reservable_info;
11851: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11852: if (exists($remembered{$key})) {
11853: $reservable_info = $remembered{$key};
11854: } else {
11855: my %resv;
11856: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11857: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11858: $reservable_info = \%resv;
11859: $remembered{$key} = $reservable_info;
11860: }
11861: return $reservable_info;
11862: }
11863:
11864: sub get_course_slots {
11865: my ($cnum,$cdom) = @_;
11866: my $hashid=$cnum.':'.$cdom;
11867: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11868: if (defined($cached)) {
11869: if (ref($result) eq 'HASH') {
11870: return %{$result};
11871: }
11872: } else {
11873: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11874: my ($tmp) = keys(%slots);
11875: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 11876: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11877: return %slots;
11878: }
11879: }
11880: return;
11881: }
11882:
11883: sub devalidate_slots_cache {
11884: my ($cnum,$cdom)=@_;
11885: my $hashid=$cnum.':'.$cdom;
11886: &devalidate_cache_new('allslots',$hashid);
11887: }
11888:
1.1181 raeburn 11889: sub get_coursechange {
11890: my ($cdom,$cnum) = @_;
11891: if ($cdom eq '' || $cnum eq '') {
11892: return unless ($env{'request.course.id'});
11893: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11894: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11895: }
11896: my $hashid=$cdom.'_'.$cnum;
11897: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11898: if ((defined($cached)) && ($change ne '')) {
11899: return $change;
11900: } else {
11901: my %crshash;
11902: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11903: if ($crshash{'internal.contentchange'} eq '') {
11904: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11905: if ($change eq '') {
11906: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11907: $change = $crshash{'internal.created'};
11908: }
11909: } else {
11910: $change = $crshash{'internal.contentchange'};
11911: }
11912: my $cachetime = 600;
11913: &do_cache_new('crschange',$hashid,$change,$cachetime);
11914: }
11915: return $change;
11916: }
11917:
11918: sub devalidate_coursechange_cache {
11919: my ($cnum,$cdom)=@_;
11920: my $hashid=$cnum.':'.$cdom;
11921: &devalidate_cache_new('crschange',$hashid);
11922: }
11923:
1.31 www 11924: # ------------------------------------------------- Update symbolic store links
11925:
11926: sub symblist {
11927: my ($mapname,%newhash)=@_;
1.438 www 11928: $mapname=&deversion(&declutter($mapname));
1.31 www 11929: my %hash;
1.620 albertel 11930: if (($env{'request.course.fn'}) && (%newhash)) {
11931: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11932: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11933: foreach my $url (keys(%newhash)) {
1.711 albertel 11934: next if ($url eq 'last_known'
11935: && $env{'form.no_update_last_known'});
11936: $hash{declutter($url)}=&encode_symb($mapname,
11937: $newhash{$url}->[1],
11938: $newhash{$url}->[0]);
1.191 harris41 11939: }
1.31 www 11940: if (untie(%hash)) {
11941: return 'ok';
11942: }
11943: }
11944: }
11945: return 'error';
1.212 www 11946: }
11947:
11948: # --------------------------------------------------------------- Verify a symb
11949:
11950: sub symbverify {
1.1190 raeburn 11951: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11952: my $thisfn=$thisurl;
1.439 www 11953: $thisfn=&declutter($thisfn);
1.215 www 11954: # direct jump to resource in page or to a sequence - will construct own symbs
11955: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11956: # check URL part
1.409 www 11957: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11958:
1.431 www 11959: unless ($url eq $thisfn) { return 0; }
1.213 www 11960:
1.216 www 11961: $symb=&symbclean($symb);
1.510 www 11962: $thisurl=&deversion($thisurl);
1.439 www 11963: $thisfn=&deversion($thisfn);
1.213 www 11964:
11965: my %bighash;
11966: my $okay=0;
1.431 www 11967:
1.620 albertel 11968: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11969: &GDBM_READER(),0640)) {
1.1204 raeburn 11970: my $noclutter;
1.1032 raeburn 11971: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11972: $thisurl =~ s/\?.+$//;
1.1204 raeburn 11973: if ($map =~ m{^uploaded/.+\.page$}) {
11974: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11975: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11976: $noclutter = 1;
11977: }
11978: }
11979: my $ids;
11980: if ($noclutter) {
11981: $ids=$bighash{'ids_'.$thisurl};
11982: } else {
11983: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11984: }
1.1102 raeburn 11985: unless ($ids) {
11986: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
11987: $ids=$bighash{$idkey};
1.216 www 11988: }
11989: if ($ids) {
11990: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 11991: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 11992: $symb =~ s/\?.+$//;
1.1202 raeburn 11993: }
1.800 albertel 11994: foreach my $id (split(/\,/,$ids)) {
11995: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11996: if (
11997: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 11998: eq $symb) {
11999: if (ref($encstate)) {
12000: $$encstate = $bighash{'encrypted_'.$id};
12001: }
1.620 albertel 12002: if (($env{'request.role.adv'}) ||
1.1101 raeburn 12003: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12004: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 12005: $okay=1;
1.1202 raeburn 12006: last;
1.582 albertel 12007: }
12008: }
1.216 www 12009: }
12010: }
1.213 www 12011: untie(%bighash);
12012: }
12013: return $okay;
1.31 www 12014: }
12015:
1.210 www 12016: # --------------------------------------------------------------- Clean-up symb
12017:
12018: sub symbclean {
12019: my $symb=shift;
1.568 albertel 12020: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12021: # remove version from map
12022: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12023:
1.210 www 12024: # remove version from URL
12025: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12026:
1.507 www 12027: # remove wrapper
12028:
1.510 www 12029: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12030: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12031: return $symb;
1.409 www 12032: }
12033:
12034: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12035:
12036: sub encode_symb {
12037: my ($map,$resid,$url)=@_;
12038: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12039: }
1.409 www 12040:
12041: sub decode_symb {
1.568 albertel 12042: my $symb=shift;
12043: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12044: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12045: return (&fixversion($map),$resid,&fixversion($url));
12046: }
12047:
12048: sub fixversion {
12049: my $fn=shift;
1.609 banghart 12050: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12051: my %bighash;
12052: my $uri=&clutter($fn);
1.620 albertel 12053: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12054: # is this cached?
1.599 albertel 12055: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12056: if (defined($cached)) { return $result; }
12057: # unfortunately not cached, or expired
1.620 albertel 12058: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12059: &GDBM_READER(),0640)) {
12060: if ($bighash{'version_'.$uri}) {
12061: my $version=$bighash{'version_'.$uri};
1.444 www 12062: unless (($version eq 'mostrecent') ||
12063: ($version==&getversion($uri))) {
1.440 www 12064: $uri=~s/\.(\w+)$/\.$version\.$1/;
12065: }
12066: }
12067: untie %bighash;
1.413 www 12068: }
1.599 albertel 12069: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12070: }
12071:
12072: sub deversion {
12073: my $url=shift;
12074: $url=~s/\.\d+\.(\w+)$/\.$1/;
12075: return $url;
1.210 www 12076: }
12077:
1.31 www 12078: # ------------------------------------------------------ Return symb list entry
12079:
12080: sub symbread {
1.1282 raeburn 12081: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 12082: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 12083: if (defined($env{$cache_str})) {
12084: if ($ignorecachednull) {
12085: return $env{$cache_str} unless ($env{$cache_str} eq '');
12086: } else {
12087: return $env{$cache_str};
12088: }
12089: }
1.242 www 12090: # no filename provided? try from environment
1.1265 raeburn 12091: unless ($thisfn) {
1.620 albertel 12092: if ($env{'request.symb'}) {
12093: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 12094: }
1.620 albertel 12095: $thisfn=$env{'request.filename'};
1.44 www 12096: }
1.569 albertel 12097: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12098: # is that filename actually a symb? Verify, clean, and return
12099: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12100: if (&symbverify($thisfn,$1)) {
1.620 albertel 12101: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12102: }
1.242 www 12103: }
1.44 www 12104: $thisfn=declutter($thisfn);
1.31 www 12105: my %hash;
1.37 www 12106: my %bighash;
12107: my $syval='';
1.620 albertel 12108: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12109: my $targetfn = $thisfn;
1.609 banghart 12110: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12111: $targetfn = 'adm/wrapper/'.$thisfn;
12112: }
1.687 albertel 12113: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12114: $targetfn=$1;
12115: }
1.620 albertel 12116: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12117: &GDBM_READER(),0640)) {
1.481 raeburn 12118: $syval=$hash{$targetfn};
1.37 www 12119: untie(%hash);
12120: }
12121: # ---------------------------------------------------------- There was an entry
12122: if ($syval) {
1.601 albertel 12123: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12124: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12125: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12126: #return $env{$cache_str}='';
1.601 albertel 12127: #}
12128: #$syval.=$1;
12129: #}
1.37 www 12130: } else {
12131: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12132: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12133: &GDBM_READER(),0640)) {
1.37 www 12134: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12135: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12136: unless ($ids) {
12137: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12138: }
12139: unless ($ids) {
12140: # alias?
12141: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12142: }
1.37 www 12143: if ($ids) {
12144: # ------------------------------------------------------------------- Has ID(s)
12145: my @possibilities=split(/\,/,$ids);
1.39 www 12146: if ($#possibilities==0) {
12147: # ----------------------------------------------- There is only one possibility
1.37 www 12148: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12149: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12150: $resid,$thisfn);
1.1282 raeburn 12151: if (ref($possibles) eq 'HASH') {
12152: $possibles->{$syval} = 1;
12153: }
12154: if ($checkforblock) {
12155: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12156: if (@blockers) {
12157: $syval = '';
12158: return;
12159: }
12160: }
12161: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12162: # ------------------------------------------ There is more than one possibility
12163: my $realpossible=0;
1.800 albertel 12164: foreach my $id (@possibilities) {
12165: my $file=$bighash{'src_'.$id};
1.1282 raeburn 12166: my $canaccess;
12167: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12168: $canaccess = 1;
12169: } else {
12170: $canaccess = &allowed('bre',$file);
12171: }
12172: if ($canaccess) {
12173: my ($mapid,$resid)=split(/\./,$id);
12174: if ($bighash{'map_type_'.$mapid} ne 'page') {
12175: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12176: $resid,$thisfn);
12177: if (ref($possibles) eq 'HASH') {
12178: $possibles->{$syval} = 1;
12179: }
12180: if ($checkforblock) {
12181: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12182: unless (@blockers > 0) {
12183: $syval = $poss_syval;
12184: $realpossible++;
12185: }
12186: } else {
12187: $syval = $poss_syval;
12188: $realpossible++;
12189: }
12190: }
1.39 www 12191: }
1.191 harris41 12192: }
1.39 www 12193: if ($realpossible!=1) { $syval=''; }
1.249 www 12194: } else {
12195: $syval='';
1.37 www 12196: }
12197: }
1.1282 raeburn 12198: untie(%bighash);
1.481 raeburn 12199: }
1.31 www 12200: }
1.62 www 12201: if ($syval) {
1.620 albertel 12202: return $env{$cache_str}=$syval;
1.62 www 12203: }
1.31 www 12204: }
1.949 raeburn 12205: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12206: return $env{$cache_str}='';
1.31 www 12207: }
12208:
12209: # ---------------------------------------------------------- Return random seed
12210:
1.32 www 12211: sub numval {
12212: my $txt=shift;
12213: $txt=~tr/A-J/0-9/;
12214: $txt=~tr/a-j/0-9/;
12215: $txt=~tr/K-T/0-9/;
12216: $txt=~tr/k-t/0-9/;
12217: $txt=~tr/U-Z/0-5/;
12218: $txt=~tr/u-z/0-5/;
12219: $txt=~s/\D//g;
1.564 albertel 12220: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12221: return int($txt);
1.368 albertel 12222: }
12223:
1.484 albertel 12224: sub numval2 {
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;
12233: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12234: my $total;
12235: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12236: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12237: return int($total);
12238: }
12239:
1.575 albertel 12240: sub numval3 {
12241: use integer;
12242: my $txt=shift;
12243: $txt=~tr/A-J/0-9/;
12244: $txt=~tr/a-j/0-9/;
12245: $txt=~tr/K-T/0-9/;
12246: $txt=~tr/k-t/0-9/;
12247: $txt=~tr/U-Z/0-5/;
12248: $txt=~tr/u-z/0-5/;
12249: $txt=~s/\D//g;
12250: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12251: my $total;
12252: foreach my $val (@txts) { $total+=$val; }
12253: if ($_64bit) { $total=(($total<<32)>>32); }
12254: return $total;
12255: }
12256:
1.675 albertel 12257: sub digest {
12258: my ($data)=@_;
12259: my $digest=&Digest::MD5::md5($data);
12260: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12261: my ($e,$f);
12262: {
12263: use integer;
12264: $e=($a+$b);
12265: $f=($c+$d);
12266: if ($_64bit) {
12267: $e=(($e<<32)>>32);
12268: $f=(($f<<32)>>32);
12269: }
12270: }
12271: if (wantarray) {
12272: return ($e,$f);
12273: } else {
12274: my $g;
12275: {
12276: use integer;
12277: $g=($e+$f);
12278: if ($_64bit) {
12279: $g=(($g<<32)>>32);
12280: }
12281: }
12282: return $g;
12283: }
12284: }
12285:
1.368 albertel 12286: sub latest_rnd_algorithm_id {
1.675 albertel 12287: return '64bit5';
1.366 albertel 12288: }
1.32 www 12289:
1.503 albertel 12290: sub get_rand_alg {
12291: my ($courseid)=@_;
1.790 albertel 12292: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12293: if ($courseid) {
1.620 albertel 12294: return $env{"course.$courseid.rndseed"};
1.503 albertel 12295: }
12296: return &latest_rnd_algorithm_id();
12297: }
12298:
1.562 albertel 12299: sub validCODE {
12300: my ($CODE)=@_;
12301: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12302: return 0;
12303: }
12304:
1.491 albertel 12305: sub getCODE {
1.620 albertel 12306: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12307: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12308: defined($Apache::lonhomework::parsing_a_task) ) &&
12309: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12310: return $Apache::lonhomework::history{'resource.CODE'};
12311: }
12312: return undef;
12313: }
1.1133 foxr 12314: #
12315: # Determines the random seed for a specific context:
12316: #
12317: # parameters:
12318: # symb - in course context the symb for the seed.
12319: # course_id - The course id of the form domain_coursenum.
12320: # domain - Domain for the user.
12321: # course - Course for the user.
12322: # cenv - environment of the course.
12323: #
12324: # NOTE:
12325: # All parameters are picked out of the environment if missing
12326: # or not defined.
12327: # If a symb cannot be determined the current time is used instead.
12328: #
12329: # For a given well defined symb, courside, domain, username,
12330: # and course environment, the seed is reproducible.
12331: #
1.31 www 12332: sub rndseed {
1.1133 foxr 12333: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12334: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12335: if (!defined($symb)) {
1.366 albertel 12336: unless ($symb=$wsymb) { return time; }
12337: }
1.1146 foxr 12338: if (!defined $courseid) {
12339: $courseid=$wcourseid;
12340: }
12341: if (!defined $domain) { $domain=$wdomain; }
12342: if (!defined $username) { $username=$wusername }
1.1133 foxr 12343:
12344: my $which;
12345: if (defined($cenv->{'rndseed'})) {
12346: $which = $cenv->{'rndseed'};
12347: } else {
12348: $which =&get_rand_alg($courseid);
12349: }
1.491 albertel 12350: if (defined(&getCODE())) {
1.1133 foxr 12351:
1.675 albertel 12352: if ($which eq '64bit5') {
12353: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12354: } elsif ($which eq '64bit4') {
1.575 albertel 12355: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12356: } else {
12357: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12358: }
1.675 albertel 12359: } elsif ($which eq '64bit5') {
12360: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12361: } elsif ($which eq '64bit4') {
12362: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12363: } elsif ($which eq '64bit3') {
12364: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12365: } elsif ($which eq '64bit2') {
12366: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12367: } elsif ($which eq '64bit') {
12368: return &rndseed_64bit($symb,$courseid,$domain,$username);
12369: }
12370: return &rndseed_32bit($symb,$courseid,$domain,$username);
12371: }
12372:
12373: sub rndseed_32bit {
12374: my ($symb,$courseid,$domain,$username)=@_;
12375: {
12376: use integer;
12377: my $symbchck=unpack("%32C*",$symb) << 27;
12378: my $symbseed=numval($symb) << 22;
12379: my $namechck=unpack("%32C*",$username) << 17;
12380: my $nameseed=numval($username) << 12;
12381: my $domainseed=unpack("%32C*",$domain) << 7;
12382: my $courseseed=unpack("%32C*",$courseid);
12383: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12384: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12385: #&logthis("rndseed :$num:$symb");
1.564 albertel 12386: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12387: return $num;
12388: }
12389: }
12390:
12391: sub rndseed_64bit {
12392: my ($symb,$courseid,$domain,$username)=@_;
12393: {
12394: use integer;
12395: my $symbchck=unpack("%32S*",$symb) << 21;
12396: my $symbseed=numval($symb) << 10;
12397: my $namechck=unpack("%32S*",$username);
12398:
12399: my $nameseed=numval($username) << 21;
12400: my $domainseed=unpack("%32S*",$domain) << 10;
12401: my $courseseed=unpack("%32S*",$courseid);
12402:
12403: my $num1=$symbchck+$symbseed+$namechck;
12404: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12405: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12406: #&logthis("rndseed :$num:$symb");
1.564 albertel 12407: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12408: return "$num1,$num2";
1.155 albertel 12409: }
1.366 albertel 12410: }
12411:
1.443 albertel 12412: sub rndseed_64bit2 {
12413: my ($symb,$courseid,$domain,$username)=@_;
12414: {
12415: use integer;
12416: # strings need to be an even # of cahracters long, it it is odd the
12417: # last characters gets thrown away
12418: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12419: my $symbseed=numval($symb) << 10;
12420: my $namechck=unpack("%32S*",$username.' ');
12421:
12422: my $nameseed=numval($username) << 21;
1.501 albertel 12423: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12424: my $courseseed=unpack("%32S*",$courseid.' ');
12425:
12426: my $num1=$symbchck+$symbseed+$namechck;
12427: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12428: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12429: #&logthis("rndseed :$num:$symb");
1.803 albertel 12430: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12431: return "$num1,$num2";
12432: }
12433: }
12434:
12435: sub rndseed_64bit3 {
12436: my ($symb,$courseid,$domain,$username)=@_;
12437: {
12438: use integer;
12439: # strings need to be an even # of cahracters long, it it is odd the
12440: # last characters gets thrown away
12441: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12442: my $symbseed=numval2($symb) << 10;
12443: my $namechck=unpack("%32S*",$username.' ');
12444:
12445: my $nameseed=numval2($username) << 21;
1.443 albertel 12446: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12447: my $courseseed=unpack("%32S*",$courseid.' ');
12448:
12449: my $num1=$symbchck+$symbseed+$namechck;
12450: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12451: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12452: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12453: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12454:
1.503 albertel 12455: return "$num1:$num2";
1.443 albertel 12456: }
12457: }
12458:
1.575 albertel 12459: sub rndseed_64bit4 {
12460: my ($symb,$courseid,$domain,$username)=@_;
12461: {
12462: use integer;
12463: # strings need to be an even # of cahracters long, it it is odd the
12464: # last characters gets thrown away
12465: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12466: my $symbseed=numval3($symb) << 10;
12467: my $namechck=unpack("%32S*",$username.' ');
12468:
12469: my $nameseed=numval3($username) << 21;
12470: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12471: my $courseseed=unpack("%32S*",$courseid.' ');
12472:
12473: my $num1=$symbchck+$symbseed+$namechck;
12474: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12475: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12476: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12477: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12478:
1.575 albertel 12479: return "$num1:$num2";
12480: }
12481: }
12482:
1.675 albertel 12483: sub rndseed_64bit5 {
12484: my ($symb,$courseid,$domain,$username)=@_;
12485: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12486: return "$num1:$num2";
12487: }
12488:
1.366 albertel 12489: sub rndseed_CODE_64bit {
12490: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12491: {
1.366 albertel 12492: use integer;
1.443 albertel 12493: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12494: my $symbseed=numval2($symb);
1.491 albertel 12495: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12496: my $CODEseed=numval(&getCODE());
1.443 albertel 12497: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12498: my $num1=$symbseed+$CODEchck;
12499: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12500: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12501: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12502: if ($_64bit) { $num1=(($num1<<32)>>32); }
12503: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12504: return "$num1:$num2";
1.366 albertel 12505: }
12506: }
12507:
1.575 albertel 12508: sub rndseed_CODE_64bit4 {
12509: my ($symb,$courseid,$domain,$username)=@_;
12510: {
12511: use integer;
12512: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12513: my $symbseed=numval3($symb);
12514: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12515: my $CODEseed=numval3(&getCODE());
12516: my $courseseed=unpack("%32S*",$courseid.' ');
12517: my $num1=$symbseed+$CODEchck;
12518: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12519: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12520: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12521: if ($_64bit) { $num1=(($num1<<32)>>32); }
12522: if ($_64bit) { $num2=(($num2<<32)>>32); }
12523: return "$num1:$num2";
12524: }
12525: }
12526:
1.675 albertel 12527: sub rndseed_CODE_64bit5 {
12528: my ($symb,$courseid,$domain,$username)=@_;
12529: my $code = &getCODE();
12530: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12531: return "$num1:$num2";
12532: }
12533:
1.366 albertel 12534: sub setup_random_from_rndseed {
12535: my ($rndseed)=@_;
1.503 albertel 12536: if ($rndseed =~/([,:])/) {
1.1262 raeburn 12537: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12538: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12539: &Math::Random::random_set_seed_from_phrase($rndseed);
12540: } else {
12541: &Math::Random::random_set_seed($num1,$num2);
12542: }
1.366 albertel 12543: } else {
12544: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12545: }
1.36 albertel 12546: }
12547:
1.474 albertel 12548: sub latest_receipt_algorithm_id {
1.835 albertel 12549: return 'receipt3';
1.474 albertel 12550: }
12551:
1.480 www 12552: sub recunique {
12553: my $fucourseid=shift;
12554: my $unique;
1.835 albertel 12555: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12556: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12557: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12558: } else {
12559: $unique=$perlvar{'lonReceipt'};
12560: }
12561: return unpack("%32C*",$unique);
12562: }
12563:
12564: sub recprefix {
12565: my $fucourseid=shift;
12566: my $prefix;
1.835 albertel 12567: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12568: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12569: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12570: } else {
12571: $prefix=$perlvar{'lonHostID'};
12572: }
12573: return unpack("%32C*",$prefix);
12574: }
12575:
1.76 www 12576: sub ireceipt {
1.474 albertel 12577: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12578:
12579: my $return =&recprefix($fucourseid).'-';
12580:
12581: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12582: $env{'request.state'} eq 'construct') {
12583: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12584: return $return;
12585: }
12586:
1.76 www 12587: my $cuname=unpack("%32C*",$funame);
12588: my $cudom=unpack("%32C*",$fudom);
12589: my $cucourseid=unpack("%32C*",$fucourseid);
12590: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12591: my $cunique=&recunique($fucourseid);
1.474 albertel 12592: my $cpart=unpack("%32S*",$part);
1.835 albertel 12593: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12594:
1.790 albertel 12595: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12596:
12597: $return.= ($cunique%$cuname+
12598: $cunique%$cudom+
12599: $cusymb%$cuname+
12600: $cusymb%$cudom+
12601: $cucourseid%$cuname+
12602: $cucourseid%$cudom+
12603: $cpart%$cuname+
12604: $cpart%$cudom);
12605: } else {
12606: $return.= ($cunique%$cuname+
12607: $cunique%$cudom+
12608: $cusymb%$cuname+
12609: $cusymb%$cudom+
12610: $cucourseid%$cuname+
12611: $cucourseid%$cudom);
12612: }
12613: return $return;
1.76 www 12614: }
12615:
12616: sub receipt {
1.474 albertel 12617: my ($part)=@_;
1.790 albertel 12618: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12619: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12620: }
1.260 ng 12621:
1.790 albertel 12622: sub whichuser {
12623: my ($passedsymb)=@_;
12624: my ($symb,$courseid,$domain,$name,$publicuser);
12625: if (defined($env{'form.grade_symb'})) {
12626: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12627: my $allowed=&allowed('vgr',$tmp_courseid);
12628: if (!$allowed &&
12629: exists($env{'request.course.sec'}) &&
12630: $env{'request.course.sec'} !~ /^\s*$/) {
12631: $allowed=&allowed('vgr',$tmp_courseid.
12632: '/'.$env{'request.course.sec'});
12633: }
12634: if ($allowed) {
12635: ($symb)=&get_env_multiple('form.grade_symb');
12636: $courseid=$tmp_courseid;
12637: ($domain)=&get_env_multiple('form.grade_domain');
12638: ($name)=&get_env_multiple('form.grade_username');
12639: return ($symb,$courseid,$domain,$name,$publicuser);
12640: }
12641: }
12642: if (!$passedsymb) {
12643: $symb=&symbread();
12644: } else {
12645: $symb=$passedsymb;
12646: }
12647: $courseid=$env{'request.course.id'};
12648: $domain=$env{'user.domain'};
12649: $name=$env{'user.name'};
12650: if ($name eq 'public' && $domain eq 'public') {
12651: if (!defined($env{'form.username'})) {
12652: $env{'form.username'}.=time.rand(10000000);
12653: }
12654: $name.=$env{'form.username'};
12655: }
12656: return ($symb,$courseid,$domain,$name,$publicuser);
12657:
12658: }
12659:
1.36 albertel 12660: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12661: # returns either the contents of the file or
12662: # -1 if the file doesn't exist
1.481 raeburn 12663: #
12664: # if the target is a file that was uploaded via DOCS,
12665: # a check will be made to see if a current copy exists on the local server,
12666: # if it does this will be served, otherwise a copy will be retrieved from
12667: # the home server for the course and stored in /home/httpd/html/userfiles on
12668: # the local server.
1.472 albertel 12669:
1.36 albertel 12670: sub getfile {
1.538 albertel 12671: my ($file) = @_;
1.609 banghart 12672: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12673: &repcopy($file);
12674: return &readfile($file);
12675: }
12676:
12677: sub repcopy_userfile {
12678: my ($file)=@_;
1.1142 raeburn 12679: my $londocroot = $perlvar{'lonDocRoot'};
12680: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12681: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12682: my ($cdom,$cnum,$filename) =
1.811 albertel 12683: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12684: my $uri="/uploaded/$cdom/$cnum/$filename";
12685: if (-e "$file") {
1.828 www 12686: # we already have a local copy, check it out
1.538 albertel 12687: my @fileinfo = stat($file);
1.828 www 12688: my $rtncode;
12689: my $info;
1.538 albertel 12690: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12691: if ($lwpresp ne 'ok') {
1.828 www 12692: # there is no such file anymore, even though we had a local copy
1.482 albertel 12693: if ($rtncode eq '404') {
1.538 albertel 12694: unlink($file);
1.482 albertel 12695: }
12696: return -1;
12697: }
12698: if ($info < $fileinfo[9]) {
1.828 www 12699: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12700: return 'ok';
1.828 www 12701: } else {
12702: # the file is outdated, get rid of it
12703: unlink($file);
1.482 albertel 12704: }
1.828 www 12705: }
12706: # one way or the other, at this point, we don't have the file
12707: # construct the correct path for the file
12708: my @parts = ($cdom,$cnum);
12709: if ($filename =~ m|^(.+)/[^/]+$|) {
12710: push @parts, split(/\//,$1);
12711: }
12712: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12713: foreach my $part (@parts) {
12714: $path .= '/'.$part;
12715: if (!-e $path) {
12716: mkdir($path,0770);
1.482 albertel 12717: }
12718: }
1.828 www 12719: # now the path exists for sure
12720: # get a user agent
12721: my $ua=new LWP::UserAgent;
12722: my $transferfile=$file.'.in.transfer';
12723: # FIXME: this should flock
12724: if (-e $transferfile) { return 'ok'; }
12725: my $request;
12726: $uri=~s/^\///;
1.980 raeburn 12727: my $homeserver = &homeserver($cnum,$cdom);
12728: my $protocol = $protocol{$homeserver};
12729: $protocol = 'http' if ($protocol ne 'https');
12730: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12731: my $response=$ua->request($request,$transferfile);
12732: # did it work?
12733: if ($response->is_error()) {
12734: unlink($transferfile);
12735: &logthis("Userfile repcopy failed for $uri");
12736: return -1;
12737: }
12738: # worked, rename the transfer file
12739: rename($transferfile,$file);
1.607 raeburn 12740: return 'ok';
1.481 raeburn 12741: }
12742:
1.517 albertel 12743: sub tokenwrapper {
12744: my $uri=shift;
1.980 raeburn 12745: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12746: $uri=~s|^/||;
1.620 albertel 12747: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12748: my $token=$1;
1.552 albertel 12749: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12750: if ($udom && $uname && $file) {
12751: $file=~s|(\?\.*)*$||;
1.949 raeburn 12752: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12753: my $homeserver = &homeserver($uname,$udom);
12754: my $protocol = $protocol{$homeserver};
12755: $protocol = 'http' if ($protocol ne 'https');
12756: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12757: (($uri=~/\?/)?'&':'?').'token='.$token.
12758: '&tokenissued='.$perlvar{'lonHostID'};
12759: } else {
12760: return '/adm/notfound.html';
12761: }
12762: }
12763:
1.828 www 12764: # call with reqtype HEAD: get last modification time
12765: # call with reqtype GET: get the file contents
12766: # Do not call this with reqtype GET for large files! It loads everything into memory
12767: #
1.481 raeburn 12768: sub getuploaded {
12769: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12770: $uri=~s/^\///;
1.980 raeburn 12771: my $homeserver = &homeserver($cnum,$cdom);
12772: my $protocol = $protocol{$homeserver};
12773: $protocol = 'http' if ($protocol ne 'https');
12774: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12775: my $ua=new LWP::UserAgent;
12776: my $request=new HTTP::Request($reqtype,$uri);
12777: my $response=$ua->request($request);
12778: $$rtncode = $response->code;
1.482 albertel 12779: if (! $response->is_success()) {
12780: return 'failed';
12781: }
12782: if ($reqtype eq 'HEAD') {
1.486 www 12783: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12784: } elsif ($reqtype eq 'GET') {
12785: $$info = $response->content;
1.472 albertel 12786: }
1.482 albertel 12787: return 'ok';
1.36 albertel 12788: }
12789:
1.481 raeburn 12790: sub readfile {
12791: my $file = shift;
12792: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12793: my $fh;
12794: open($fh,"<$file");
12795: my $a='';
1.800 albertel 12796: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12797: return $a;
12798: }
12799:
1.36 albertel 12800: sub filelocation {
1.590 banghart 12801: my ($dir,$file) = @_;
12802: my $location;
12803: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12804:
12805: if ($file =~ m-^/adm/-) {
12806: $file=~s-^/adm/wrapper/-/-;
12807: $file=~s-^/adm/coursedocs/showdoc/-/-;
12808: }
1.882 albertel 12809:
1.1139 www 12810: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12811: $location = $file;
1.609 banghart 12812: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12813: my ($udom,$uname,$filename)=
1.811 albertel 12814: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12815: my $home=&homeserver($uname,$udom);
12816: my $is_me=0;
12817: my @ids=¤t_machine_ids();
12818: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12819: if ($is_me) {
1.1117 foxr 12820: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12821: } else {
12822: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12823: $udom.'/'.$uname.'/'.$filename;
12824: }
1.882 albertel 12825: } elsif ($file =~ m-^/adm/-) {
12826: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12827: } else {
12828: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12829: $file=~s:^/(res|priv)/:/:;
12830: my $space=$1;
1.590 banghart 12831: if ( !( $file =~ m:^/:) ) {
12832: $location = $dir. '/'.$file;
12833: } else {
1.1142 raeburn 12834: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12835: }
1.59 albertel 12836: }
1.590 banghart 12837: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12838: while ($location=~m{/\.\./}) {
12839: if ($location =~ m{/[^/]+/\.\./}) {
12840: $location=~ s{/[^/]+/\.\./}{/}g;
12841: } else {
12842: $location=~ s{/\.\./}{/}g;
12843: }
12844: } #remove dir/..
1.590 banghart 12845: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12846: return $location;
1.46 www 12847: }
1.36 albertel 12848:
1.46 www 12849: sub hreflocation {
12850: my ($dir,$file)=@_;
1.980 raeburn 12851: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12852: $file=filelocation($dir,$file);
1.700 albertel 12853: } elsif ($file=~m-^/adm/-) {
12854: $file=~s-^/adm/wrapper/-/-;
12855: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12856: }
12857: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12858: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12859: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12860: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12861: {/uploaded/$1/$2/}x;
1.46 www 12862: }
1.913 albertel 12863: if ($file=~ m{^/userfiles/}) {
12864: $file =~ s{^/userfiles/}{/uploaded/};
12865: }
1.462 albertel 12866: return $file;
1.465 albertel 12867: }
12868:
1.1139 www 12869:
12870:
12871:
12872:
1.465 albertel 12873: sub current_machine_domains {
1.853 albertel 12874: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12875: }
12876:
12877: sub machine_domains {
12878: my ($hostname) = @_;
1.465 albertel 12879: my @domains;
1.838 albertel 12880: my %hostname = &all_hostnames();
1.465 albertel 12881: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12882: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12883: if ($hostname eq $name) {
1.844 albertel 12884: push(@domains,&host_domain($id));
1.465 albertel 12885: }
12886: }
12887: return @domains;
12888: }
12889:
12890: sub current_machine_ids {
1.853 albertel 12891: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12892: }
12893:
12894: sub machine_ids {
12895: my ($hostname) = @_;
12896: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12897: my @ids;
1.888 albertel 12898: my %name_to_host = &all_names();
1.889 albertel 12899: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12900: return @{ $name_to_host{$hostname} };
12901: }
12902: return;
1.31 www 12903: }
12904:
1.824 raeburn 12905: sub additional_machine_domains {
12906: my @domains;
12907: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12908: while( my $line = <$fh>) {
12909: $line =~ s/\s//g;
12910: push(@domains,$line);
12911: }
12912: return @domains;
12913: }
12914:
12915: sub default_login_domain {
12916: my $domain = $perlvar{'lonDefDomain'};
12917: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12918: foreach my $posdom (¤t_machine_domains(),
12919: &additional_machine_domains()) {
12920: if (lc($posdom) eq lc($testdomain)) {
12921: $domain=$posdom;
12922: last;
12923: }
12924: }
12925: return $domain;
12926: }
12927:
1.31 www 12928: # ------------------------------------------------------------- Declutters URLs
12929:
12930: sub declutter {
12931: my $thisfn=shift;
1.569 albertel 12932: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 12933: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12934: $thisfn=~s{^/home/httpd/html}{};
12935: }
1.31 www 12936: $thisfn=~s/^\///;
1.697 albertel 12937: $thisfn=~s|^adm/wrapper/||;
12938: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12939: $thisfn=~s/^res\///;
1.1172 bisitz 12940: $thisfn=~s/^priv\///;
1.1032 raeburn 12941: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12942: $thisfn=~s/\?.+$//;
12943: }
1.268 www 12944: return $thisfn;
12945: }
12946:
12947: # ------------------------------------------------------------- Clutter up URLs
12948:
12949: sub clutter {
12950: my $thisfn='/'.&declutter(shift);
1.887 albertel 12951: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12952: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12953: $thisfn='/res'.$thisfn;
12954: }
1.1031 raeburn 12955: if ($thisfn !~m|^/adm|) {
12956: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12957: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12958: } else {
12959: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12960: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12961: if ($embstyle eq 'ssi'
12962: || ($embstyle eq 'hdn')
12963: || ($embstyle eq 'rat')
12964: || ($embstyle eq 'prv')
12965: || ($embstyle eq 'ign')) {
12966: #do nothing with these
12967: } elsif (($embstyle eq 'img')
1.695 albertel 12968: || ($embstyle eq 'emb')
12969: || ($embstyle eq 'wrp')) {
12970: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12971: } elsif ($embstyle eq 'unk'
12972: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12973: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12974: } else {
1.718 www 12975: # &logthis("Got a blank emb style");
1.695 albertel 12976: }
1.694 albertel 12977: }
1.1298 raeburn 12978: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
12979: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 12980: }
1.31 www 12981: return $thisfn;
1.12 www 12982: }
12983:
1.787 albertel 12984: sub clutter_with_no_wrapper {
12985: my $uri = &clutter(shift);
12986: if ($uri =~ m-^/adm/-) {
12987: $uri =~ s-^/adm/wrapper/-/-;
12988: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12989: }
12990: return $uri;
12991: }
12992:
1.557 albertel 12993: sub freeze_escape {
12994: my ($value)=@_;
12995: if (ref($value)) {
12996: $value=&nfreeze($value);
12997: return '__FROZEN__'.&escape($value);
12998: }
12999: return &escape($value);
13000: }
13001:
1.11 www 13002:
1.557 albertel 13003: sub thaw_unescape {
13004: my ($value)=@_;
13005: if ($value =~ /^__FROZEN__/) {
13006: substr($value,0,10,undef);
13007: $value=&unescape($value);
13008: return &thaw($value);
13009: }
13010: return &unescape($value);
13011: }
13012:
1.436 albertel 13013: sub correct_line_ends {
13014: my ($result)=@_;
13015: $$result =~s/\r\n/\n/mg;
13016: $$result =~s/\r/\n/mg;
1.415 albertel 13017: }
1.1 albertel 13018: # ================================================================ Main Program
13019:
1.184 www 13020: sub goodbye {
1.204 albertel 13021: &logthis("Starting Shut down");
1.443 albertel 13022: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13023: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13024: #converted
1.599 albertel 13025: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13026: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13027: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13028: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13029: #1.1 only
1.870 albertel 13030: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13031: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13032: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13033: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13034: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13035: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13036: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13037: &flushcourselogs();
13038: &logthis("Shutting down");
13039: }
13040:
1.852 albertel 13041: sub get_dns {
1.1210 raeburn 13042: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13043: if (!$ignore_cache) {
13044: my ($content,$cached)=
13045: &Apache::lonnet::is_cached_new('dns',$url);
13046: if ($cached) {
1.1210 raeburn 13047: &$func($content,$hashref);
1.869 albertel 13048: return;
13049: }
13050: }
13051:
13052: my %alldns;
1.852 albertel 13053: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13054: foreach my $dns (<$config>) {
13055: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 13056: my $line = $1;
13057: my ($host,$protocol) = split(/:/,$line);
13058: if ($protocol ne 'https') {
13059: $protocol = 'http';
13060: }
13061: $alldns{$host} = $protocol;
1.869 albertel 13062: }
13063: while (%alldns) {
1.1263 raeburn 13064: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 13065: my $ua=new LWP::UserAgent;
1.1134 raeburn 13066: $ua->timeout(30);
1.979 raeburn 13067: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 13068: my $response=$ua->request($request);
1.979 raeburn 13069: delete($alldns{$dns});
1.852 albertel 13070: next if ($response->is_error());
13071: my @content = split("\n",$response->content);
1.1210 raeburn 13072: unless ($nocache) {
1.1219 raeburn 13073: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 13074: }
13075: &$func(\@content,$hashref);
1.869 albertel 13076: return;
1.852 albertel 13077: }
13078: close($config);
1.871 albertel 13079: my $which = (split('/',$url))[3];
13080: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13081: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 13082: my @content = <$config>;
1.1210 raeburn 13083: &$func(\@content,$hashref);
13084: return;
13085: }
13086:
13087: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 13088: sub parse_dns_checksums_tab {
1.1210 raeburn 13089: my ($lines,$hashref) = @_;
1.1264 raeburn 13090: my $lonhost = $perlvar{'lonHostID'};
13091: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 13092: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 13093: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13094: my $webconfdir = '/etc/httpd/conf';
13095: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13096: $webconfdir = '/etc/apache2';
13097: } elsif ($distro =~ /^sles(\d+)$/) {
13098: if ($1 >= 10) {
13099: $webconfdir = '/etc/apache2';
13100: }
13101: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13102: if ($1 >= 10.0) {
13103: $webconfdir = '/etc/apache2';
13104: }
13105: }
1.1210 raeburn 13106: my ($release,$timestamp) = split(/\-/,$loncaparev);
13107: my (%chksum,%revnum);
13108: if (ref($lines) eq 'ARRAY') {
13109: chomp(@{$lines});
1.1238 raeburn 13110: my $version = shift(@{$lines});
13111: if ($version eq $release) {
1.1210 raeburn 13112: foreach my $line (@{$lines}) {
1.1238 raeburn 13113: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 13114: if ($file =~ m{^/etc/httpd/conf}) {
13115: if ($webconfdir eq '/etc/apache2') {
13116: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13117: }
13118: }
1.1238 raeburn 13119: $chksum{$file} = $shasum;
13120: $revnum{$file} = $version;
1.1210 raeburn 13121: }
13122: if (ref($hashref) eq 'HASH') {
13123: %{$hashref} = (
13124: sums => \%chksum,
13125: versions => \%revnum,
13126: );
13127: }
13128: }
13129: }
1.869 albertel 13130: return;
1.852 albertel 13131: }
1.1210 raeburn 13132:
13133: sub fetch_dns_checksums {
1.1238 raeburn 13134: my %checksums;
13135: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 13136: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 13137: my ($release,$timestamp) = split(/\-/,$loncaparev);
13138: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 13139: \%checksums);
1.1210 raeburn 13140: return \%checksums;
13141: }
13142:
1.327 albertel 13143: # ------------------------------------------------------------ Read domain file
13144: {
1.852 albertel 13145: my $loaded;
1.846 albertel 13146: my %domain;
13147:
1.852 albertel 13148: sub parse_domain_tab {
13149: my ($lines) = @_;
13150: foreach my $line (@$lines) {
13151: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 13152:
1.846 albertel 13153: chomp($line);
1.852 albertel 13154: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 13155: my %this_domain;
13156: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13157: 'lang_def', 'city', 'longi', 'lati',
13158: 'primary') {
13159: $this_domain{$field} = shift(@elements);
13160: }
13161: $domain{$name} = \%this_domain;
1.852 albertel 13162: }
13163: }
1.864 albertel 13164:
13165: sub reset_domain_info {
13166: undef($loaded);
13167: undef(%domain);
13168: }
13169:
1.852 albertel 13170: sub load_domain_tab {
1.1293 raeburn 13171: my ($ignore_cache,$nocache) = @_;
13172: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 13173: my $fh;
13174: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
13175: my @lines = <$fh>;
13176: &parse_domain_tab(\@lines);
1.448 albertel 13177: }
1.852 albertel 13178: close($fh);
13179: $loaded = 1;
1.327 albertel 13180: }
1.846 albertel 13181:
13182: sub domain {
1.852 albertel 13183: &load_domain_tab() if (!$loaded);
13184:
1.846 albertel 13185: my ($name,$what) = @_;
13186: return if ( !exists($domain{$name}) );
13187:
13188: if (!$what) {
13189: return $domain{$name}{'description'};
13190: }
13191: return $domain{$name}{$what};
13192: }
1.974 raeburn 13193:
13194: sub domain_info {
13195: &load_domain_tab() if (!$loaded);
13196: return %domain;
13197: }
13198:
1.327 albertel 13199: }
13200:
13201:
1.1 albertel 13202: # ------------------------------------------------------------- Read hosts file
13203: {
1.838 albertel 13204: my %hostname;
1.844 albertel 13205: my %hostdom;
1.845 albertel 13206: my %libserv;
1.852 albertel 13207: my $loaded;
1.888 albertel 13208: my %name_to_host;
1.1074 raeburn 13209: my %internetdom;
1.1107 raeburn 13210: my %LC_dns_serv;
1.852 albertel 13211:
13212: sub parse_hosts_tab {
13213: my ($file) = @_;
13214: foreach my $configline (@$file) {
13215: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 13216: chomp($configline);
13217: if ($configline =~ /^\^/) {
13218: if ($configline =~ /^\^([\w.\-]+)/) {
13219: $LC_dns_serv{$1} = 1;
13220: }
13221: next;
13222: }
1.1074 raeburn 13223: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 13224: $name=~s/\s//g;
13225: if ($id && $domain && $role && $name) {
13226: $hostname{$id}=$name;
1.888 albertel 13227: push(@{$name_to_host{$name}}, $id);
1.852 albertel 13228: $hostdom{$id}=$domain;
13229: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 13230: if (defined($protocol)) {
13231: if ($protocol eq 'https') {
13232: $protocol{$id} = $protocol;
13233: } else {
13234: $protocol{$id} = 'http';
13235: }
1.968 raeburn 13236: } else {
1.969 raeburn 13237: $protocol{$id} = 'http';
1.968 raeburn 13238: }
1.1074 raeburn 13239: if (defined($intdom)) {
13240: $internetdom{$id} = $intdom;
13241: }
1.852 albertel 13242: }
13243: }
13244: }
1.864 albertel 13245:
13246: sub reset_hosts_info {
1.897 albertel 13247: &purge_remembered();
1.864 albertel 13248: &reset_domain_info();
13249: &reset_hosts_ip_info();
1.892 albertel 13250: undef(%name_to_host);
1.864 albertel 13251: undef(%hostname);
13252: undef(%hostdom);
13253: undef(%libserv);
13254: undef($loaded);
13255: }
1.1 albertel 13256:
1.852 albertel 13257: sub load_hosts_tab {
1.1293 raeburn 13258: my ($ignore_cache,$nocache) = @_;
13259: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 13260: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13261: my @config = <$config>;
13262: &parse_hosts_tab(\@config);
13263: close($config);
13264: $loaded=1;
1.1 albertel 13265: }
1.852 albertel 13266:
1.838 albertel 13267: sub hostname {
1.852 albertel 13268: &load_hosts_tab() if (!$loaded);
13269:
1.838 albertel 13270: my ($lonid) = @_;
13271: return $hostname{$lonid};
13272: }
1.845 albertel 13273:
1.838 albertel 13274: sub all_hostnames {
1.852 albertel 13275: &load_hosts_tab() if (!$loaded);
13276:
1.838 albertel 13277: return %hostname;
13278: }
1.845 albertel 13279:
1.888 albertel 13280: sub all_names {
1.1293 raeburn 13281: my ($ignore_cache,$nocache) = @_;
13282: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13283:
13284: return %name_to_host;
13285: }
13286:
1.974 raeburn 13287: sub all_host_domain {
13288: &load_hosts_tab() if (!$loaded);
13289: return %hostdom;
13290: }
13291:
1.845 albertel 13292: sub is_library {
1.852 albertel 13293: &load_hosts_tab() if (!$loaded);
13294:
1.845 albertel 13295: return exists($libserv{$_[0]});
13296: }
13297:
13298: sub all_library {
1.852 albertel 13299: &load_hosts_tab() if (!$loaded);
13300:
1.845 albertel 13301: return %libserv;
13302: }
13303:
1.1062 droeschl 13304: sub unique_library {
13305: #2x reverse removes all hostnames that appear more than once
13306: my %unique = reverse &all_library();
13307: return reverse %unique;
13308: }
13309:
1.841 albertel 13310: sub get_servers {
1.852 albertel 13311: &load_hosts_tab() if (!$loaded);
13312:
1.841 albertel 13313: my ($domain,$type) = @_;
13314: my %possible_hosts = ($type eq 'library') ? %libserv
13315: : %hostname;
13316: my %result;
1.842 albertel 13317: if (ref($domain) eq 'ARRAY') {
13318: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13319: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13320: $result{$host} = $hostname;
13321: }
13322: }
13323: } else {
13324: while ( my ($host,$hostname) = each(%possible_hosts)) {
13325: if ($hostdom{$host} eq $domain) {
13326: $result{$host} = $hostname;
13327: }
1.841 albertel 13328: }
13329: }
13330: return %result;
13331: }
1.845 albertel 13332:
1.1062 droeschl 13333: sub get_unique_servers {
13334: my %unique = reverse &get_servers(@_);
13335: return reverse %unique;
13336: }
13337:
1.844 albertel 13338: sub host_domain {
1.852 albertel 13339: &load_hosts_tab() if (!$loaded);
13340:
1.844 albertel 13341: my ($lonid) = @_;
13342: return $hostdom{$lonid};
13343: }
13344:
1.841 albertel 13345: sub all_domains {
1.852 albertel 13346: &load_hosts_tab() if (!$loaded);
13347:
1.841 albertel 13348: my %seen;
13349: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13350: return @uniq;
13351: }
1.1074 raeburn 13352:
13353: sub internet_dom {
13354: &load_hosts_tab() if (!$loaded);
13355:
13356: my ($lonid) = @_;
13357: return $internetdom{$lonid};
13358: }
1.1107 raeburn 13359:
13360: sub is_LC_dns {
13361: &load_hosts_tab() if (!$loaded);
13362:
13363: my ($hostname) = @_;
13364: return exists($LC_dns_serv{$hostname});
13365: }
13366:
1.1 albertel 13367: }
13368:
1.847 albertel 13369: {
13370: my %iphost;
1.856 albertel 13371: my %name_to_ip;
13372: my %lonid_to_ip;
1.869 albertel 13373:
1.847 albertel 13374: sub get_hosts_from_ip {
13375: my ($ip) = @_;
13376: my %iphosts = &get_iphost();
13377: if (ref($iphosts{$ip})) {
13378: return @{$iphosts{$ip}};
13379: }
13380: return;
1.839 albertel 13381: }
1.864 albertel 13382:
13383: sub reset_hosts_ip_info {
13384: undef(%iphost);
13385: undef(%name_to_ip);
13386: undef(%lonid_to_ip);
13387: }
1.856 albertel 13388:
13389: sub get_host_ip {
13390: my ($lonid) = @_;
13391: if (exists($lonid_to_ip{$lonid})) {
13392: return $lonid_to_ip{$lonid};
13393: }
13394: my $name=&hostname($lonid);
13395: my $ip = gethostbyname($name);
13396: return if (!$ip || length($ip) ne 4);
13397: $ip=inet_ntoa($ip);
13398: $name_to_ip{$name} = $ip;
13399: $lonid_to_ip{$lonid} = $ip;
13400: return $ip;
13401: }
1.847 albertel 13402:
13403: sub get_iphost {
1.1293 raeburn 13404: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13405:
1.869 albertel 13406: if (!$ignore_cache) {
13407: if (%iphost) {
13408: return %iphost;
13409: }
13410: my ($ip_info,$cached)=
13411: &Apache::lonnet::is_cached_new('iphost','iphost');
13412: if ($cached) {
13413: %iphost = %{$ip_info->[0]};
13414: %name_to_ip = %{$ip_info->[1]};
13415: %lonid_to_ip = %{$ip_info->[2]};
13416: return %iphost;
13417: }
13418: }
1.894 albertel 13419:
13420: # get yesterday's info for fallback
13421: my %old_name_to_ip;
13422: my ($ip_info,$cached)=
13423: &Apache::lonnet::is_cached_new('iphost','iphost');
13424: if ($cached) {
13425: %old_name_to_ip = %{$ip_info->[1]};
13426: }
13427:
1.1293 raeburn 13428: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13429: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13430: my $ip;
13431: if (!exists($name_to_ip{$name})) {
13432: $ip = gethostbyname($name);
13433: if (!$ip || length($ip) ne 4) {
1.894 albertel 13434: if (defined($old_name_to_ip{$name})) {
13435: $ip = $old_name_to_ip{$name};
13436: &logthis("Can't find $name defaulting to old $ip");
13437: } else {
13438: &logthis("Name $name no IP found");
13439: next;
13440: }
13441: } else {
13442: $ip=inet_ntoa($ip);
1.847 albertel 13443: }
13444: $name_to_ip{$name} = $ip;
13445: } else {
13446: $ip = $name_to_ip{$name};
1.653 albertel 13447: }
1.888 albertel 13448: foreach my $id (@{ $name_to_host{$name} }) {
13449: $lonid_to_ip{$id} = $ip;
13450: }
13451: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13452: }
1.1293 raeburn 13453: unless ($nocache) {
13454: &do_cache_new('iphost','iphost',
13455: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13456: 48*60*60);
13457: }
1.869 albertel 13458:
1.847 albertel 13459: return %iphost;
1.598 albertel 13460: }
13461:
1.992 raeburn 13462: #
13463: # Given a DNS returns the loncapa host name for that DNS
13464: #
13465: sub host_from_dns {
13466: my ($dns) = @_;
13467: my @hosts;
13468: my $ip;
13469:
1.993 raeburn 13470: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13471: $ip = $name_to_ip{$dns};
13472: }
13473: if (!$ip) {
13474: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13475: if (length($ip) == 4) {
13476: $ip = &IO::Socket::inet_ntoa($ip);
13477: }
13478: }
13479: if ($ip) {
13480: @hosts = get_hosts_from_ip($ip);
13481: return $hosts[0];
13482: }
13483: return undef;
1.986 foxr 13484: }
1.992 raeburn 13485:
1.1074 raeburn 13486: sub get_internet_names {
13487: my ($lonid) = @_;
13488: return if ($lonid eq '');
13489: my ($idnref,$cached)=
13490: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13491: if ($cached) {
13492: return $idnref;
13493: }
13494: my $ip = &get_host_ip($lonid);
13495: my @hosts = &get_hosts_from_ip($ip);
13496: my %iphost = &get_iphost();
13497: my (@idns,%seen);
13498: foreach my $id (@hosts) {
13499: my $dom = &host_domain($id);
13500: my $prim_id = &domain($dom,'primary');
13501: my $prim_ip = &get_host_ip($prim_id);
13502: next if ($seen{$prim_ip});
13503: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13504: foreach my $id (@{$iphost{$prim_ip}}) {
13505: my $intdom = &internet_dom($id);
13506: unless (grep(/^\Q$intdom\E$/,@idns)) {
13507: push(@idns,$intdom);
13508: }
13509: }
13510: }
13511: $seen{$prim_ip} = 1;
13512: }
1.1219 raeburn 13513: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13514: }
13515:
1.986 foxr 13516: }
13517:
1.1079 raeburn 13518: sub all_loncaparevs {
1.1249 raeburn 13519: 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 13520: }
13521:
1.1227 raeburn 13522: # ---------------------------------------------------------- Read loncaparev table
13523: {
13524: sub load_loncaparevs {
13525: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13526: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13527: while (my $configline=<$config>) {
13528: chomp($configline);
13529: my ($hostid,$loncaparev)=split(/:/,$configline);
13530: $loncaparevs{$hostid}=$loncaparev;
13531: }
13532: close($config);
13533: }
13534: }
13535: }
13536: }
13537:
13538: # ---------------------------------------------------------- Read serverhostID table
13539: {
13540: sub load_serverhomeIDs {
13541: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13542: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13543: while (my $configline=<$config>) {
13544: chomp($configline);
13545: my ($name,$id)=split(/:/,$configline);
13546: $serverhomeIDs{$name}=$id;
13547: }
13548: close($config);
13549: }
13550: }
13551: }
13552: }
13553:
13554:
1.862 albertel 13555: BEGIN {
13556:
13557: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13558: unless ($readit) {
13559: {
13560: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13561: %perlvar = (%perlvar,%{$configvars});
13562: }
13563:
13564:
1.1 albertel 13565: # ------------------------------------------------------ Read spare server file
13566: {
1.448 albertel 13567: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13568:
13569: while (my $configline=<$config>) {
13570: chomp($configline);
1.284 matthew 13571: if ($configline) {
1.784 albertel 13572: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13573: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13574: push(@{ $spareid{$type} }, $host);
1.1 albertel 13575: }
13576: }
1.448 albertel 13577: close($config);
1.1 albertel 13578: }
1.11 www 13579: # ------------------------------------------------------------ Read permissions
13580: {
1.448 albertel 13581: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13582:
13583: while (my $configline=<$config>) {
1.448 albertel 13584: chomp($configline);
13585: if ($configline) {
13586: my ($role,$perm)=split(/ /,$configline);
13587: if ($perm ne '') { $pr{$role}=$perm; }
13588: }
1.11 www 13589: }
1.448 albertel 13590: close($config);
1.11 www 13591: }
13592:
13593: # -------------------------------------------- Read plain texts for permissions
13594: {
1.448 albertel 13595: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13596:
13597: while (my $configline=<$config>) {
1.448 albertel 13598: chomp($configline);
13599: if ($configline) {
1.742 raeburn 13600: my ($short,@plain)=split(/:/,$configline);
13601: %{$prp{$short}} = ();
13602: if (@plain > 0) {
13603: $prp{$short}{'std'} = $plain[0];
13604: for (my $i=1; $i<@plain; $i++) {
13605: $prp{$short}{'alt'.$i} = $plain[$i];
13606: }
13607: }
1.448 albertel 13608: }
1.135 www 13609: }
1.448 albertel 13610: close($config);
1.135 www 13611: }
13612:
13613: # ---------------------------------------------------------- Read package table
13614: {
1.448 albertel 13615: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13616:
13617: while (my $configline=<$config>) {
1.483 albertel 13618: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13619: chomp($configline);
13620: my ($short,$plain)=split(/:/,$configline);
13621: my ($pack,$name)=split(/\&/,$short);
13622: if ($plain ne '') {
13623: $packagetab{$pack.'&'.$name.'&name'}=$name;
13624: $packagetab{$short}=$plain;
13625: }
1.11 www 13626: }
1.448 albertel 13627: close($config);
1.329 matthew 13628: }
13629:
1.1073 raeburn 13630: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 13631:
13632: &load_loncaparevs();
1.1073 raeburn 13633:
1.1074 raeburn 13634: # ---------------------------------------------------------- Read serverhostID table
13635:
1.1227 raeburn 13636: &load_serverhomeIDs();
13637:
13638: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13639: {
13640: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13641: if (-e $file) {
13642: my $parser = HTML::LCParser->new($file);
13643: while (my $token = $parser->get_token()) {
13644: if ($token->[0] eq 'S') {
13645: my $item = $token->[1];
13646: my $name = $token->[2]{'name'};
13647: my $value = $token->[2]{'value'};
1.1285 raeburn 13648: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 13649: my $namematch = $token->[2]{'namematch'};
13650: if ($item eq 'parameter') {
13651: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13652: my $release = $parser->get_text();
13653: $release =~ s/(^\s*|\s*$ )//gx;
13654: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13655: }
13656: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 13657: my $release = $parser->get_text();
13658: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 13659: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 13660: }
13661: }
13662: }
13663: }
1.1073 raeburn 13664: }
13665:
1.1138 raeburn 13666: # ---------------------------------------------------------- Read managers table
13667: {
13668: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13669: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13670: while (my $configline=<$config>) {
13671: chomp($configline);
13672: next if ($configline =~ /^\#/);
13673: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13674: $managerstab{$configline} = 1;
13675: }
13676: }
13677: close($config);
13678: }
13679: }
13680: }
13681:
1.329 matthew 13682: # ------------- set up temporary directory
13683: {
1.1117 foxr 13684: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13685:
1.11 www 13686: }
13687:
1.794 albertel 13688: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13689: 'compress_threshold'=> 20_000,
13690: });
1.185 www 13691:
1.281 www 13692: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13693: $dumpcount=0;
1.958 www 13694: $locknum=0;
1.22 www 13695:
1.163 harris41 13696: &logtouch();
1.672 albertel 13697: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13698: $readit=1;
1.564 albertel 13699: {
13700: use integer;
13701: my $test=(2**32)+1;
1.568 albertel 13702: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13703: &logthis(" Detected 64bit platform ($_64bit)");
13704: }
1.195 www 13705: }
1.1 albertel 13706: }
1.179 www 13707:
1.1 albertel 13708: 1;
1.191 harris41 13709: __END__
13710:
1.243 albertel 13711: =pod
13712:
1.191 harris41 13713: =head1 NAME
13714:
1.243 albertel 13715: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13716:
13717: =head1 SYNOPSIS
13718:
1.243 albertel 13719: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13720:
13721: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13722:
1.243 albertel 13723: Common parameters:
13724:
13725: =over 4
13726:
13727: =item *
13728:
13729: $uname : an internal username (if $cname expecting a course Id specifically)
13730:
13731: =item *
13732:
13733: $udom : a domain (if $cdom expecting a course's domain specifically)
13734:
13735: =item *
13736:
13737: $symb : a resource instance identifier
13738:
13739: =item *
13740:
13741: $namespace : the name of a .db file that contains the data needed or
13742: being set.
13743:
13744: =back
13745:
1.394 bowersj2 13746: =head1 OVERVIEW
1.191 harris41 13747:
1.394 bowersj2 13748: lonnet provides subroutines which interact with the
13749: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13750: about classes, users, and resources.
1.243 albertel 13751:
13752: For many of these objects you can also use this to store data about
13753: them or modify them in various ways.
1.191 harris41 13754:
1.394 bowersj2 13755: =head2 Symbs
1.191 harris41 13756:
1.394 bowersj2 13757: To identify a specific instance of a resource, LON-CAPA uses symbols
13758: or "symbs"X<symb>. These identifiers are built from the URL of the
13759: map, the resource number of the resource in the map, and the URL of
13760: the resource itself. The latter is somewhat redundant, but might help
13761: if maps change.
13762:
13763: An example is
13764:
13765: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13766:
13767: The respective map entry is
13768:
13769: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13770: title="Problem 2">
13771: </resource>
13772:
13773: Symbs are used by the random number generator, as well as to store and
13774: restore data specific to a certain instance of for example a problem.
13775:
13776: =head2 Storing And Retrieving Data
13777:
13778: X<store()>X<cstore()>X<restore()>Three of the most important functions
13779: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13780: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13781: is is the non-critical message twin of cstore. These functions are for
13782: handlers to store a perl hash to a user's permanent data space in an
13783: easy manner, and to retrieve it again on another call. It is expected
13784: that a handler would use this once at the beginning to retrieve data,
13785: and then again once at the end to send only the new data back.
13786:
13787: The data is stored in the user's data directory on the user's
13788: homeserver under the ID of the course.
13789:
13790: The hash that is returned by restore will have all of the previous
13791: value for all of the elements of the hash.
13792:
13793: Example:
13794:
13795: #creating a hash
13796: my %hash;
13797: $hash{'foo'}='bar';
13798:
13799: #storing it
13800: &Apache::lonnet::cstore(\%hash);
13801:
13802: #changing a value
13803: $hash{'foo'}='notbar';
13804:
13805: #adding a new value
13806: $hash{'bar'}='foo';
13807: &Apache::lonnet::cstore(\%hash);
13808:
13809: #retrieving the hash
13810: my %history=&Apache::lonnet::restore();
13811:
13812: #print the hash
13813: foreach my $key (sort(keys(%history))) {
13814: print("\%history{$key} = $history{$key}");
13815: }
13816:
13817: Will print out:
1.191 harris41 13818:
1.394 bowersj2 13819: %history{1:foo} = bar
13820: %history{1:keys} = foo:timestamp
13821: %history{1:timestamp} = 990455579
13822: %history{2:bar} = foo
13823: %history{2:foo} = notbar
13824: %history{2:keys} = foo:bar:timestamp
13825: %history{2:timestamp} = 990455580
13826: %history{bar} = foo
13827: %history{foo} = notbar
13828: %history{timestamp} = 990455580
13829: %history{version} = 2
13830:
13831: Note that the special hash entries C<keys>, C<version> and
13832: C<timestamp> were added to the hash. C<version> will be equal to the
13833: total number of versions of the data that have been stored. The
13834: C<timestamp> attribute will be the UNIX time the hash was
13835: stored. C<keys> is available in every historical section to list which
13836: keys were added or changed at a specific historical revision of a
13837: hash.
13838:
13839: B<Warning>: do not store the hash that restore returns directly. This
13840: will cause a mess since it will restore the historical keys as if the
13841: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13842:
1.394 bowersj2 13843: Calling convention:
1.191 harris41 13844:
1.1225 raeburn 13845: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 13846: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13847:
1.394 bowersj2 13848: For more detailed information, see lonnet specific documentation.
1.191 harris41 13849:
1.394 bowersj2 13850: =head1 RETURN MESSAGES
1.191 harris41 13851:
1.394 bowersj2 13852: =over 4
1.191 harris41 13853:
1.394 bowersj2 13854: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13855:
1.394 bowersj2 13856: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13857: when the connection is brought back up
1.191 harris41 13858:
1.394 bowersj2 13859: =item * B<con_failed>: unable to contact remote host and unable to save message
13860: for later delivery
1.191 harris41 13861:
1.967 bisitz 13862: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13863:
1.394 bowersj2 13864: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13865: that was requested
1.191 harris41 13866:
1.243 albertel 13867: =back
1.191 harris41 13868:
1.243 albertel 13869: =head1 PUBLIC SUBROUTINES
1.191 harris41 13870:
1.243 albertel 13871: =head2 Session Environment Functions
1.191 harris41 13872:
1.243 albertel 13873: =over 4
1.191 harris41 13874:
1.394 bowersj2 13875: =item *
13876: X<appenv()>
1.949 raeburn 13877: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13878: the user envirnoment file, and will be restored for each access this
1.620 albertel 13879: user makes during this session, also modifies the %env for the current
1.949 raeburn 13880: process. Optional rolesarrayref - if defined contains a reference to an array
13881: of roles which are exempt from the restriction on modifying user.role entries
13882: in the user's environment.db and in %env.
1.191 harris41 13883:
13884: =item *
1.394 bowersj2 13885: X<delenv()>
1.987 raeburn 13886: B<delenv($delthis,$regexp)>: removes all items from the session
13887: environment file that begin with $delthis. If the
13888: optional second arg - $regexp - is true, $delthis is treated as a
13889: regular expression, otherwise \Q$delthis\E is used.
13890: The values are also deleted from the current processes %env.
1.191 harris41 13891:
1.795 albertel 13892: =item * get_env_multiple($name)
13893:
13894: gets $name from the %env hash, it seemlessly handles the cases where multiple
13895: values may be defined and end up as an array ref.
13896:
13897: returns an array of values
13898:
1.243 albertel 13899: =back
13900:
13901: =head2 User Information
1.191 harris41 13902:
1.243 albertel 13903: =over 4
1.191 harris41 13904:
13905: =item *
1.394 bowersj2 13906: X<queryauthenticate()>
13907: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13908: authentication scheme
13909:
13910: =item *
1.394 bowersj2 13911: X<authenticate()>
1.1073 raeburn 13912: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13913: authenticate user from domain's lib servers (first use the current
13914: one). C<$upass> should be the users password.
1.1073 raeburn 13915: $checkdefauth is optional (value is 1 if a check should be made to
13916: authenticate user using default authentication method, and allow
13917: account creation if username does not have account in the domain).
13918: $clientcancheckhost is optional (value is 1 if checking whether the
13919: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13920:
13921: =item *
1.394 bowersj2 13922: X<homeserver()>
13923: B<homeserver($uname,$udom)>: find the server which has
13924: the user's directory and files (there must be only one), this caches
13925: the answer, and also caches if there is a borken connection.
1.191 harris41 13926:
13927: =item *
1.394 bowersj2 13928: X<idget()>
1.1300 raeburn 13929: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
13930: a list of student/employee IDs or clicker IDs
13931: (student/employee IDs are a unique resource in a domain, there must be
13932: only 1 ID per username, and only 1 username per ID in a specific domain).
13933: clickerIDs are not necessarily unique, as students might share clickers.
13934: (returns hash: id=>name,id=>name)
1.191 harris41 13935:
13936: =item *
1.394 bowersj2 13937: X<idrget()>
13938: B<idrget($udom,@unames)>: find the IDs behind a list of
13939: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13940:
13941: =item *
1.394 bowersj2 13942: X<idput()>
1.1300 raeburn 13943: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
13944: names and associated student/employee IDs or clicker IDs.
13945:
13946: =item *
13947: X<iddel()>
13948: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
13949: student/employee ID or clicker ID username look-ups from domain.
13950: The homeserver ($uhome) and namespace ($namespace) are optional.
13951: If no $uhome is provided, it will be determined usig &homeserver()
13952: for each user. If no $namespace is provided, the default is ids.
13953:
13954: =item *
13955: X<updateclickers()>
13956: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
13957: clicker ID-to-username look-ups in clickers.db on library server.
13958: Permitted actions are add or del (i.e., add or delete). The
13959: clickers.db contains clickerID as keys (escaped), and each corresponding
13960: value is an escaped comma-separated list of usernames (for whom the
13961: library server is the homeserver), who registered that particular ID.
13962: If $critical is true, the update will be sent via &critical, otherwise
13963: &reply() will be used.
1.191 harris41 13964:
13965: =item *
1.394 bowersj2 13966: X<rolesinit()>
1.1169 droeschl 13967: B<rolesinit($udom,$username)>: get user privileges.
13968: returns user role, first access and timer interval hashes
1.243 albertel 13969:
13970: =item *
1.1171 droeschl 13971: X<privileged()>
13972: B<privileged($username,$domain)>: returns a true if user has a
13973: privileged and active role (i.e. su or dc), false otherwise.
13974:
13975: =item *
1.551 albertel 13976: X<getsection()>
13977: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13978: course $cname, return section name/number or '' for "not in course"
13979: and '-1' for "no section"
13980:
13981: =item *
1.394 bowersj2 13982: X<userenvironment()>
13983: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13984: passed in @what from the requested user's environment, returns a hash
13985:
1.858 raeburn 13986: =item *
13987: X<userlog_query()>
1.859 albertel 13988: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13989: activity.log file. %filters defines filters applied when parsing the
13990: log file. These can be start or end timestamps, or the type of action
13991: - log to look for Login or Logout events, check for Checkin or
13992: Checkout, role for role selection. The response is in the form
13993: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13994: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13995:
1.243 albertel 13996: =back
13997:
13998: =head2 User Roles
13999:
14000: =over 4
14001:
14002: =item *
14003:
1.1284 raeburn 14004: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14005: returns codes for allowed actions.
14006:
14007: The first argument is required, all others are optional.
14008:
14009: $priv is the privilege being checked.
14010: $uri contains additional information about what is being checked for access (e.g.,
14011: URL, course ID etc.).
14012: $symb is the unique resource instance identifier in a course; if needed,
14013: but not provided, it will be retrieved via a call to &symbread().
14014: $role is the role for which a priv is being checked (only used if priv is evb).
14015: $clientip is the user's IP address (only used when checking for access to portfolio
14016: files).
14017: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14018: prevents recursive calls to &allowed.
14019:
1.243 albertel 14020: F: full access
14021: U,I,K: authentication modes (cxx only)
14022: '': forbidden
14023: 1: user needs to choose course
14024: 2: browse allowed
1.766 albertel 14025: A: passphrase authentication needed
1.1284 raeburn 14026: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14027:
14028: =item *
14029:
1.1192 raeburn 14030: constructaccess($url,$setpriv) : check for access to construction space URL
14031:
14032: See if the owner domain and name in the URL match those in the
14033: expected environment. If so, return three element list
14034: ($ownername,$ownerdomain,$ownerhome).
14035:
14036: Otherwise return the null string.
14037:
14038: If second argument 'setpriv' is true, it assigns the privileges,
14039: and returns the same three element list, unless the owner has
14040: blocked "ad hoc" Domain Coordinator access to the Author Space,
14041: in which case the null string is returned.
14042:
14043: =item *
14044:
1.1326 raeburn 14045: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14046: define a custom role rolename set privileges in format of lonTabs/roles.tab
14047: for system, domain, and course level. $uname and $udom are optional (current
14048: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14049:
14050: =item *
14051:
1.988 raeburn 14052: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14053: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 14054: $type is Course (default) or Community.
1.988 raeburn 14055: If $forcedefault evaluates to true, text returned will be default
14056: text for $type. Otherwise, if this is a course, the text returned
14057: will be a custom name for the role (if defined in the course's
14058: environment). If no custom name is defined the default is returned.
14059:
1.832 raeburn 14060: =item *
14061:
1.1219 raeburn 14062: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 14063: All arguments are optional. Returns a hash of a roles, either for
14064: co-author/assistant author roles for a user's Construction Space
1.906 albertel 14065: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 14066: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14067: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14068: For each key, value is set to colon-separated start and end times for
14069: the role. If no username and domain are specified, will default to
1.934 raeburn 14070: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 14071: of role statuses (active, future or previous), roles
14072: (e.g., cc,in, st etc.) and domains of the roles which can be used
14073: to restrict the list of roles reported. If no array ref is
14074: provided for types, will default to return only active roles.
1.834 albertel 14075:
1.1195 raeburn 14076: =item *
14077:
14078: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 14079: user: $uname:$udom has a role in the course: $cdom_$cnum.
14080:
14081: Additional optional arguments are: $type (if role checking is to be restricted
14082: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 14083: available roles) or future (roles available in the future), and
14084: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 14085: have active Domain Coordinator role in course's domain or in additional
14086: domains (specified in 'Domains to check for privileged users' in course
14087: environment -- set via: Course Settings -> Classlists and staff listing).
14088:
14089: =item *
14090:
14091: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14092: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14093: $possdomains and $possroles are optional array refs -- to domains to check and
14094: roles to check. If $possdomains is not specified, a dump will be done of the
14095: users' roles.db to check for a dc or su role in any domain. This can be
14096: time consuming if &privileged is called repeatedly (e.g., when displaying a
14097: classlist), so in such cases, supplying a $possdomains array is preferred, as
14098: this then allows &privileged_by_domain() to be used, which caches the identity
14099: of privileged users, eliminating the need for repeated calls to &dump().
14100:
14101: =item *
14102:
14103: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14104: where the outer hash keys are domains specified in the $possdomains array ref,
14105: next inner hash keys are privileged roles specified in the $roles array ref,
14106: and the innermost hash contains key = value pairs for username:domain = end:start
14107: for active or future "privileged" users with that role in that domain. To avoid
14108: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14109: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 14110:
1.243 albertel 14111: =back
14112:
14113: =head2 User Modification
14114:
14115: =over 4
14116:
14117: =item *
14118:
1.957 raeburn 14119: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 14120: user for the level given by URL. Optional start and end dates (leave empty
14121: string or zero for "no date")
1.191 harris41 14122:
14123: =item *
14124:
1.243 albertel 14125: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14126: change a users, password, possible return values are: ok,
14127: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14128: refused
1.191 harris41 14129:
14130: =item *
14131:
1.243 albertel 14132: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 14133:
14134: =item *
14135:
1.1058 raeburn 14136: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14137: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14138:
14139: will update user information (firstname,middlename,lastname,generation,
14140: permanentemail), and if forceid is true, student/employee ID also.
14141: A user's institutional affiliation(s) can also be updated.
14142: User information fields will not be overwritten with empty entries
14143: unless the field is included in the $candelete array reference.
14144: This array is included when a single user is modified via "Manage Users",
14145: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 14146:
14147: =item *
14148:
1.286 matthew 14149: modifystudent
14150:
1.957 raeburn 14151: modify a student's enrollment and identification information.
1.1235 raeburn 14152: The course id is resolved based on the current user's environment.
14153: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 14154: associated with a course.
14155:
1.297 matthew 14156: This call is essentially a wrapper for lonnet::modifyuser and
14157: lonnet::modify_student_enrollment
1.286 matthew 14158:
14159: Inputs:
14160:
14161: =over 4
14162:
1.957 raeburn 14163: =item B<$udom> Student's loncapa domain
1.286 matthew 14164:
1.957 raeburn 14165: =item B<$uname> Student's loncapa login name
1.286 matthew 14166:
1.964 bisitz 14167: =item B<$uid> Student/Employee ID
1.286 matthew 14168:
1.957 raeburn 14169: =item B<$umode> Student's authentication mode
1.286 matthew 14170:
1.957 raeburn 14171: =item B<$upass> Student's password
1.286 matthew 14172:
1.957 raeburn 14173: =item B<$first> Student's first name
1.286 matthew 14174:
1.957 raeburn 14175: =item B<$middle> Student's middle name
1.286 matthew 14176:
1.957 raeburn 14177: =item B<$last> Student's last name
1.286 matthew 14178:
1.957 raeburn 14179: =item B<$gene> Student's generation
1.286 matthew 14180:
1.957 raeburn 14181: =item B<$usec> Student's section in course
1.286 matthew 14182:
14183: =item B<$end> Unix time of the roles expiration
14184:
14185: =item B<$start> Unix time of the roles start date
14186:
14187: =item B<$forceid> If defined, allow $uid to be changed
14188:
14189: =item B<$desiredhome> server to use as home server for student
14190:
1.957 raeburn 14191: =item B<$email> Student's permanent e-mail address
14192:
14193: =item B<$type> Type of enrollment (auto or manual)
14194:
1.963 raeburn 14195: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14196:
14197: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 14198:
1.963 raeburn 14199: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 14200:
1.963 raeburn 14201: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 14202:
1.1216 raeburn 14203: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14204:
14205: =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 14206:
1.286 matthew 14207: =back
1.297 matthew 14208:
14209: =item *
14210:
14211: modify_student_enrollment
14212:
1.1235 raeburn 14213: Change a student's enrollment status in a class. The environment variable
1.297 matthew 14214: 'role.request.course' must be defined for this function to proceed.
14215:
14216: Inputs:
14217:
14218: =over 4
14219:
1.1235 raeburn 14220: =item $udom, student's domain
1.297 matthew 14221:
1.1235 raeburn 14222: =item $uname, student's name
1.297 matthew 14223:
1.1235 raeburn 14224: =item $uid, student's user id
1.297 matthew 14225:
1.1235 raeburn 14226: =item $first, student's first name
1.297 matthew 14227:
14228: =item $middle
14229:
14230: =item $last
14231:
14232: =item $gene
14233:
14234: =item $usec
14235:
14236: =item $end
14237:
14238: =item $start
14239:
1.957 raeburn 14240: =item $type
14241:
14242: =item $locktype
14243:
14244: =item $cid
14245:
14246: =item $selfenroll
14247:
14248: =item $context
14249:
1.1216 raeburn 14250: =item $credits, number of credits student will earn from this class
14251:
1.1314 raeburn 14252: =item $instsec, institutional course section code for student
14253:
1.297 matthew 14254: =back
14255:
1.191 harris41 14256:
14257: =item *
14258:
1.243 albertel 14259: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14260: custom role; give a custom role to a user for the level given by URL. Specify
14261: name and domain of role author, and role name
1.191 harris41 14262:
14263: =item *
14264:
1.243 albertel 14265: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 14266:
14267: =item *
14268:
1.243 albertel 14269: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14270:
14271: =back
14272:
14273: =head2 Course Infomation
14274:
14275: =over 4
1.191 harris41 14276:
14277: =item *
14278:
1.1118 foxr 14279: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 14280: specified course id, including all environment settings for the
14281: course, the description of the course will be in the hash under the
14282: key 'description'
1.191 harris41 14283:
1.1118 foxr 14284: $options is an optional parameter that if supplied is a hash reference that controls
14285: what how this function works. It has the following key/values:
14286:
14287: =over 4
14288:
14289: =item freshen_cache
14290:
14291: If defined, and the environment cache for the course is valid, it is
14292: returned in the returned hash.
14293:
14294: =item one_time
14295:
14296: If defined, the last cache time is set to _now_
14297:
14298: =item user
14299:
14300: If defined, the supplied username is used instead of the current user.
14301:
14302:
14303: =back
14304:
1.191 harris41 14305: =item *
14306:
1.624 albertel 14307: resdata($name,$domain,$type,@which) : request for current parameter
14308: setting for a specific $type, where $type is either 'course' or 'user',
14309: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 14310: answers for 10 minutes.
1.243 albertel 14311:
1.877 foxr 14312: =item *
14313:
14314: get_courseresdata($courseid, $domain) : dump the entire course resource
14315: data base, returning a hash that is keyed by the resource name and has
14316: values that are the resource value. I believe that the timestamps and
14317: versions are also returned.
14318:
1.1236 raeburn 14319: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14320: supplemental content area. This routine caches the number of files for
14321: 10 minutes.
14322:
1.243 albertel 14323: =back
14324:
14325: =head2 Course Modification
14326:
14327: =over 4
1.191 harris41 14328:
14329: =item *
14330:
1.243 albertel 14331: writecoursepref($courseid,%prefs) : write preferences (environment
14332: database) for a course
1.191 harris41 14333:
14334: =item *
14335:
1.1011 raeburn 14336: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14337:
14338: =item *
14339:
1.1038 raeburn 14340: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14341:
1.1167 droeschl 14342: =item *
14343:
14344: is_course($courseid), is_course($cdom, $cnum)
14345:
14346: Accepts either a combined $courseid (in the form of domain_courseid) or the
14347: two component version $cdom, $cnum. It checks if the specified course exists.
14348:
14349: Returns:
14350: undef if the course doesn't exist, otherwise
14351: in scalar context the combined courseid.
14352: in list context the two components of the course identifier, domain and
14353: courseid.
14354:
1.243 albertel 14355: =back
14356:
14357: =head2 Resource Subroutines
14358:
14359: =over 4
1.191 harris41 14360:
14361: =item *
14362:
1.243 albertel 14363: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14364:
14365: =item *
14366:
1.243 albertel 14367: repcopy($filename) : subscribes to the requested file, and attempts to
14368: replicate from the owning library server, Might return
1.607 raeburn 14369: 'unavailable', 'not_found', 'forbidden', 'ok', or
14370: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14371: resource. Expects the local filesystem pathname
14372: (/home/httpd/html/res/....)
14373:
14374: =back
14375:
14376: =head2 Resource Information
14377:
14378: =over 4
1.191 harris41 14379:
14380: =item *
14381:
1.1228 raeburn 14382: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14383: and returns the value of a variety of different possible values,
14384: $varname should be a request string, and the other parameters can be
14385: used to specify who and what one is asking about. Ordinarily, $cid
14386: does not need to be specified, as it is retrived from
14387: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14388: within lonuserstate::loadmap() when initializing a course, before
14389: $env{'request.course.id'} has been set, so it needs to be provided
14390: in that one case.
1.243 albertel 14391:
14392: Possible values for $varname are environment.lastname (or other item
14393: from the envirnment hash), user.name (or someother aspect about the
14394: user), resource.0.maxtries (or some other part and parameter of a
14395: resource)
1.204 albertel 14396:
14397: =item *
14398:
1.243 albertel 14399: directcondval($number) : get current value of a condition; reads from a state
14400: string
1.204 albertel 14401:
14402: =item *
14403:
1.243 albertel 14404: condval($condidx) : value of condition index based on state
1.204 albertel 14405:
14406: =item *
14407:
1.243 albertel 14408: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14409: resource's metadata, $what should be either a specific key, or either
14410: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14411: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14412:
14413: this function automatically caches all requests
1.191 harris41 14414:
14415: =item *
14416:
1.243 albertel 14417: metadata_query($query,$custom,$customshow) : make a metadata query against the
14418: network of library servers; returns file handle of where SQL and regex results
14419: will be stored for query
1.191 harris41 14420:
14421: =item *
14422:
1.1282 raeburn 14423: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14424: return symbolic list entry (all arguments optional).
14425:
14426: Args: filename is the filename (including path) for the file for which a symb
14427: is required; donotrecurse, if true will prevent calls to allowed() being made
14428: to check access status if more than one resource was found in the bighash
14429: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14430: a randompick); ignorecachednull, if true will prevent a symb of '' being
14431: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14432: cause possible symbs to be checked to determine if they are subject to content
14433: blocking, if so they will not be included as possible symbs; possibles is a
14434: ref to a hash, which, as a side effect, will be populated with all possible
14435: symbs (content blocking not tested).
14436:
1.243 albertel 14437: returns the data handle
1.191 harris41 14438:
14439: =item *
14440:
1.1190 raeburn 14441: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14442: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14443: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 14444: on failure, user must be in a course, as it assumes the existence of
14445: the course initial hash, and uses $env('request.course.id'}. The third
14446: arg is an optional reference to a scalar. If this arg is passed in the
14447: call to symbverify, it will be set to 1 if the symb has been set to be
14448: encrypted; otherwise it will be null.
1.191 harris41 14449:
14450: =item *
14451:
1.243 albertel 14452: symbclean($symb) : removes versions numbers from a symb, returns the
14453: cleaned symb
1.191 harris41 14454:
14455: =item *
14456:
1.243 albertel 14457: is_on_map($uri) : checks if the $uri is somewhere on the current
14458: course map, user must be in a course for it to work.
1.191 harris41 14459:
14460: =item *
14461:
1.243 albertel 14462: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14463:
14464: =item *
14465:
1.243 albertel 14466: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14467: a random seed, all arguments are optional, if they aren't sent it uses the
14468: environment to derive them. Note: if symb isn't sent and it can't get one
14469: from &symbread it will use the current time as its return value
1.191 harris41 14470:
14471: =item *
14472:
1.243 albertel 14473: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14474: unfakeable, receipt
1.191 harris41 14475:
14476: =item *
14477:
1.620 albertel 14478: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14479:
14480: =item *
14481:
1.243 albertel 14482: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14483:
14484: =item *
14485:
1.243 albertel 14486: 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 14487:
14488: =item *
14489:
1.243 albertel 14490: 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 14491:
14492: =item *
14493:
1.243 albertel 14494: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14495:
14496: =item *
14497:
1.243 albertel 14498: devalidate($symb) : devalidate temporary spreadsheet calculations,
14499: forcing spreadsheet to reevaluate the resource scores next time.
14500:
1.1195 raeburn 14501: =item *
14502:
1.1196 raeburn 14503: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14504: when viewing in course context.
1.1195 raeburn 14505:
1.1196 raeburn 14506: input: six args -- filename (decluttered), course number, course domain,
14507: url, symb (if registered) and group (if this is a
14508: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 14509:
1.1196 raeburn 14510: output: array of five scalars --
1.1195 raeburn 14511: $cfile -- url for file editing if editable on current server
14512: $home -- homeserver of resource (i.e., for author if published,
14513: or course if uploaded.).
14514: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 14515: $forceedit -- 1 if icon/link should be to go to edit mode
14516: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 14517:
14518: =item *
14519:
14520: is_course_upload($file,$cnum,$cdom)
14521:
14522: Used in course context to determine if current file was uploaded to
14523: the course (i.e., would be found in /userfiles/docs on the course's
14524: homeserver.
14525:
14526: input: 3 args -- filename (decluttered), course number and course domain.
14527: output: boolean -- 1 if file was uploaded.
14528:
1.243 albertel 14529: =back
14530:
14531: =head2 Storing/Retreiving Data
14532:
14533: =over 4
1.191 harris41 14534:
14535: =item *
14536:
1.1269 raeburn 14537: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14538: permanently for this url; hashref needs to be given and should be a \%hashname;
14539: the remaining args aren't required and if they aren't passed or are '' they will
14540: be derived from the env (with the exception of $laststore, which is an
14541: optional arg used when a user's submission is stored in grading).
14542: $laststore is $version=$timestamp, where $version is the most recent version
14543: number retrieved for the corresponding $symb in the $namespace db file, and
14544: $timestamp is the timestamp for that transaction (UNIX time).
14545: $laststore is currently only passed when cstore() is called by
14546: structuretags::finalize_storage().
1.191 harris41 14547:
14548: =item *
14549:
1.1269 raeburn 14550: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14551: but uses critical subroutine
1.191 harris41 14552:
14553: =item *
14554:
1.243 albertel 14555: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14556: all args are optional
1.191 harris41 14557:
14558: =item *
14559:
1.717 albertel 14560: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14561: dumps the complete (or key matching regexp) namespace into a hash
14562: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14563: normally &store()ed into
14564:
14565: $range should be either an integer '100' (give me the first 100
14566: matching records)
14567: or be two integers sperated by a - with no spaces
14568: '30-50' (give me the 30th through the 50th matching
14569: records)
14570:
14571:
14572: =item *
14573:
1.1269 raeburn 14574: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14575: replaces a &store() version of data with a replacement set of data
14576: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 14577: reference. If $tolog is true, the transaction is logged in the courselog
14578: with an action=PUTSTORE.
1.717 albertel 14579:
14580: =item *
14581:
1.243 albertel 14582: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14583: works very similar to store/cstore, but all data is stored in a
14584: temporary location and can be reset using tmpreset, $storehash should
14585: be a hash reference, returns nothing on success
1.191 harris41 14586:
14587: =item *
14588:
1.243 albertel 14589: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14590: similar to restore, but all data is stored in a temporary location and
14591: can be reset using tmpreset. Returns a hash of values on success,
14592: error string otherwise.
1.191 harris41 14593:
14594: =item *
14595:
1.243 albertel 14596: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14597: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14598:
14599: =item *
14600:
1.243 albertel 14601: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14602: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14603:
14604: =item *
14605:
1.243 albertel 14606: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14607: namesp ($udom and $uname are optional)
1.191 harris41 14608:
14609: =item *
14610:
1.702 albertel 14611: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14612: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14613: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14614:
1.702 albertel 14615: $range should be either an integer '100' (give me the first 100
14616: matching records)
14617: or be two integers sperated by a - with no spaces
14618: '30-50' (give me the 30th through the 50th matching
14619: records)
1.449 matthew 14620: =item *
14621:
14622: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14623: $store can be a scalar, an array reference, or if the amount to be
14624: incremented is > 1, a hash reference.
14625:
14626: ($udom and $uname are optional)
1.191 harris41 14627:
14628: =item *
14629:
1.243 albertel 14630: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14631: ($udom and $uname are optional)
1.191 harris41 14632:
14633: =item *
14634:
1.243 albertel 14635: cput($namespace,$storehash,$udom,$uname) : critical put
14636: ($udom and $uname are optional)
1.191 harris41 14637:
14638: =item *
14639:
1.748 albertel 14640: newput($namespace,$storehash,$udom,$uname) :
14641:
14642: Attempts to store the items in the $storehash, but only if they don't
14643: currently exist, if this succeeds you can be certain that you have
14644: successfully created a new key value pair in the $namespace db.
14645:
14646:
14647: Args:
14648: $namespace: name of database to store values to
14649: $storehash: hashref to store to the db
14650: $udom: (optional) domain of user containing the db
14651: $uname: (optional) name of user caontaining the db
14652:
14653: Returns:
14654: 'ok' -> succeeded in storing all keys of $storehash
14655: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14656: least <key> already existed in the db (other
14657: requested keys may also already exist)
1.967 bisitz 14658: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14659: 'con_lost' -> unable to contact request server
14660: 'refused' -> action was not allowed by remote machine
14661:
14662:
14663: =item *
14664:
1.243 albertel 14665: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14666: reference filled in from namesp (encrypts the return communication)
14667: ($udom and $uname are optional)
1.191 harris41 14668:
14669: =item *
14670:
1.243 albertel 14671: log($udom,$name,$home,$message) : write to permanent log for user; use
14672: critical subroutine
14673:
1.806 raeburn 14674: =item *
14675:
1.860 raeburn 14676: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14677: array reference filled in from namespace found in domain level on either
14678: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14679:
14680: =item *
14681:
1.860 raeburn 14682: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14683: domain level either on specified domain server ($uhome) or primary domain
14684: server ($udom and $uhome are optional)
1.806 raeburn 14685:
1.943 raeburn 14686: =item *
14687:
1.1240 raeburn 14688: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14689: for: authentication, language, quotas, timezone, date locale, and portal URL in
14690: the target domain.
14691:
14692: May also include additional key => value pairs for the following groups:
14693:
14694: =over
14695:
14696: =item
14697: disk quotas (MB allocated by default to portfolios and authoring spaces).
14698:
14699: =over
14700:
14701: =item defaultquota, authorquota
14702:
14703: =back
14704:
14705: =item
14706: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14707: portfolio for users).
14708:
14709: =over
14710:
14711: =item
14712: aboutme, blog, webdav, portfolio
14713:
14714: =back
14715:
14716: =item
14717: requestcourses: ability to request courses, and how requests are processed.
14718:
14719: =over
14720:
14721: =item
1.1305 raeburn 14722: official, unofficial, community, textbook, placement
1.1240 raeburn 14723:
14724: =back
14725:
14726: =item
14727: inststatus: types of institutional affiliation, and order in which they are displayed.
14728:
14729: =over
14730:
14731: =item
1.1256 raeburn 14732: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 14733:
14734: =back
14735:
14736: =item
14737: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14738: for course's uploaded content.
14739:
14740: =over
14741:
14742: =item
1.1246 raeburn 14743: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 14744: communityquota, textbookquota, placementquota
1.1240 raeburn 14745:
14746: =back
14747:
14748: =item
14749: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14750: on your servers.
14751:
14752: =over
14753:
14754: =item
14755: remotesessions, hostedsessions
14756:
14757: =back
14758:
14759: =back
14760:
14761: In cases where a domain coordinator has never used the "Set Domain Configuration"
14762: utility to create a configuration.db file on a domain's primary library server
14763: only the following domain defaults: auth_def, auth_arg_def, lang_def
14764: -- corresponding values are authentication type (internal, krb4, krb5,
14765: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14766: will be available. Values are retrieved from cache (if current), unless the
14767: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14768: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14769:
14770: Typical usage:
1.943 raeburn 14771:
1.1240 raeburn 14772: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14773:
1.243 albertel 14774: =back
14775:
14776: =head2 Network Status Functions
14777:
14778: =over 4
1.191 harris41 14779:
14780: =item *
14781:
1.1137 raeburn 14782: dirlist() : return directory list based on URI (first arg).
14783:
14784: Inputs: 1 required, 5 optional.
14785:
14786: =over
14787:
14788: =item
14789: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14790:
14791: =item
14792: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14793:
14794: =item
14795: $username - username of user/course to be listed. Extracted from $uri if absent.
14796:
14797: =item
14798: $getpropath - boolean: 1 if prepend path using &propath().
14799:
14800: =item
14801: $getuserdir - boolean: 1 if prepend path for "userfiles".
14802:
14803: =item
14804: $alternateRoot - path to prepend in place of path from $uri.
14805:
14806: =back
14807:
14808: Returns: Array of up to two items.
14809:
14810: =over
14811:
14812: a reference to an array of files/subdirectories
14813:
14814: =over
14815:
14816: Each element in the array of files/subdirectories is a & separated list of
14817: item name and the result of running stat on the item. If dirlist was requested
14818: for a file instead of a directory, the item name will be ''. For a directory
14819: listing, if the item is a metadata file, the element will end &N&M
14820: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14821: default copyright set (1).
14822:
14823: =back
14824:
14825: a scalar containing error condition (if encountered).
14826:
14827: =over
14828:
14829: =item
14830: no_host (no homeserver identified for $username:$domain).
14831:
14832: =item
14833: no_such_host (server contacted for listing not identified as valid host).
14834:
14835: =item
14836: con_lost (connection to remote server failed).
14837:
14838: =item
14839: refused (invalid $username:$domain received on lond side).
14840:
14841: =item
14842: no_such_dir (directory at specified path on lond side does not exist).
14843:
14844: =item
14845: empty (directory at specified path on lond side is empty).
14846:
14847: =over
14848:
14849: This is currently not encountered because the &ls3, &ls2,
14850: &ls (_handler) routines on the lond side do not filter out
14851: . and .. from a directory listing.
14852:
14853: =back
14854:
14855: =back
14856:
14857: =back
1.191 harris41 14858:
14859: =item *
14860:
1.243 albertel 14861: spareserver() : find server with least workload from spare.tab
14862:
1.986 foxr 14863:
14864: =item *
14865:
14866: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14867: if there is no corresponding loncapa host.
14868:
1.243 albertel 14869: =back
14870:
1.986 foxr 14871:
1.243 albertel 14872: =head2 Apache Request
14873:
14874: =over 4
1.191 harris41 14875:
14876: =item *
14877:
1.243 albertel 14878: ssi($url,%hash) : server side include, does a complete request cycle on url to
14879: localhost, posts hash
14880:
14881: =back
14882:
14883: =head2 Data to String to Data
14884:
14885: =over 4
1.191 harris41 14886:
14887: =item *
14888:
1.243 albertel 14889: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14890: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14891:
14892: =item *
14893:
1.243 albertel 14894: hashref2str($hashref) : convert a hashref into a string complete with
14895: escaping and '=' and '&' separators, supports elements that are
14896: arrayrefs and hashrefs
1.191 harris41 14897:
14898: =item *
14899:
1.243 albertel 14900: arrayref2str($arrayref) : convert an arrayref into a string complete
14901: with escaping and '&' separators, supports elements that are arrayrefs
14902: and hashrefs
1.191 harris41 14903:
14904: =item *
14905:
1.243 albertel 14906: str2hash($string) : convert string to hash using unescaping and
14907: splitting on '=' and '&', supports elements that are arrayrefs and
14908: hashrefs
1.191 harris41 14909:
14910: =item *
14911:
1.243 albertel 14912: str2array($string) : convert string to hash using unescaping and
14913: splitting on '&', supports elements that are arrayrefs and hashrefs
14914:
14915: =back
14916:
14917: =head2 Logging Routines
14918:
14919:
14920: These routines allow one to make log messages in the lonnet.log and
14921: lonnet.perm logfiles.
1.191 harris41 14922:
1.1119 foxr 14923: =over 4
14924:
1.191 harris41 14925: =item *
14926:
1.243 albertel 14927: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14928:
14929: =item *
14930:
1.243 albertel 14931: logthis() : append message to the normal lonnet.log file, it gets
14932: preiodically rolled over and deleted.
1.191 harris41 14933:
14934: =item *
14935:
1.243 albertel 14936: logperm() : append a permanent message to lonnet.perm.log, this log
14937: file never gets deleted by any automated portion of the system, only
14938: messages of critical importance should go in here.
14939:
1.1119 foxr 14940:
1.243 albertel 14941: =back
14942:
14943: =head2 General File Helper Routines
14944:
14945: =over 4
1.191 harris41 14946:
14947: =item *
14948:
1.481 raeburn 14949: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14950: (a) files in /uploaded
14951: (i) If a local copy of the file exists -
14952: compares modification date of local copy with last-modified date for
14953: definitive version stored on home server for course. If local copy is
14954: stale, requests a new version from the home server and stores it.
14955: If the original has been removed from the home server, then local copy
14956: is unlinked.
14957: (ii) If local copy does not exist -
14958: requests the file from the home server and stores it.
14959:
14960: If $caller is 'uploadrep':
14961: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14962: for request for files originally uploaded via DOCS.
14963: - returns 'ok' if fresh local copy now available, -1 otherwise.
14964:
14965: Otherwise:
14966: This indicates a call from the content generation phase of the request.
14967: - returns the entire contents of the file or -1.
14968:
14969: (b) files in /res
14970: - returns the entire contents of a file or -1;
14971: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14972:
1.712 albertel 14973:
14974: =item *
14975:
14976: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14977: reference
14978:
14979: returns either a stat() list of data about the file or an empty list
14980: if the file doesn't exist or couldn't find out about it (connection
14981: problems or user unknown)
14982:
1.191 harris41 14983: =item *
14984:
1.243 albertel 14985: filelocation($dir,$file) : returns file system location of a file
14986: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14987: directory that relative $file lookups are to looked in ($dir of /a/dir
14988: and a file of ../bob will become /a/bob)
1.191 harris41 14989:
14990: =item *
14991:
14992: hreflocation($dir,$file) : returns file system location or a URL; same as
14993: filelocation except for hrefs
14994:
14995: =item *
14996:
1.1261 raeburn 14997: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14998: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14999:
1.243 albertel 15000: =back
15001:
1.608 albertel 15002: =head2 Usererfile file routines (/uploaded*)
15003:
15004: =over 4
15005:
15006: =item *
15007:
15008: userfileupload(): main rotine for putting a file in a user or course's
15009: filespace, arguments are,
15010:
1.620 albertel 15011: formname - required - this is the name of the element in $env where the
1.608 albertel 15012: filename, and the contents of the file to create/modifed exist
1.620 albertel 15013: the filename is in $env{'form.'.$formname.'.filename'} and the
15014: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 15015: context - if coursedoc, store the file in the course of the active role
15016: of the current user;
15017: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15018: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 15019: subdir - required - subdirectory to put the file in under ../userfiles/
15020: if undefined, it will be placed in "unknown"
15021:
15022: (This routine calls clean_filename() to remove any dangerous
15023: characters from the filename, and then calls finuserfileupload() to
15024: complete the transaction)
15025:
15026: returns either the url of the uploaded file (/uploaded/....) if successful
15027: and /adm/notfound.html if unsuccessful
15028:
15029: =item *
15030:
15031: clean_filename(): routine for cleaing a filename up for storage in
15032: userfile space, argument is:
15033:
15034: filename - proposed filename
15035:
15036: returns: the new clean filename
15037:
15038: =item *
15039:
1.1090 raeburn 15040: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 15041: userspace, probably shouldn't be called directly
15042:
15043: docuname: username or courseid of destination for the file
15044: docudom: domain of user/course of destination for the file
15045: formname: same as for userfileupload()
1.1090 raeburn 15046: fname: filename (including subdirectories) for the file
15047: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15048: allfiles: reference to hash used to store objects found by parser
15049: codebase: reference to hash used for codebases of java objects found by parser
15050: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15051: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15052: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15053: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15054: context: if 'overwrite', will move the uploaded file from its temporary location to
15055: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 15056: mimetype: reference to scalar to accommodate mime type determined
15057: from File::MMagic if $parser = parse.
1.608 albertel 15058:
15059: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 15060: and /adm/notfound.html if unsuccessful (or an error message if context
15061: was 'overwrite').
15062:
1.608 albertel 15063:
15064: =item *
15065:
15066: renameuserfile(): renames an existing userfile to a new name
15067:
15068: Args:
15069: docuname: username or courseid of destination for the file
15070: docudom: domain of user/course of destination for the file
15071: old: current file name (including any subdirs under userfiles)
15072: new: desired file name (including any subdirs under userfiles)
15073:
15074: =item *
15075:
15076: mkdiruserfile(): creates a directory is a userfiles dir
15077:
15078: Args:
15079: docuname: username or courseid of destination for the file
15080: docudom: domain of user/course of destination for the file
15081: dir: dir to create (including any subdirs under userfiles)
15082:
15083: =item *
15084:
15085: removeuserfile(): removes a file that exists in userfiles
15086:
15087: Args:
15088: docuname: username or courseid of destination for the file
15089: docudom: domain of user/course of destination for the file
15090: fname: filname to delete (including any subdirs under userfiles)
15091:
15092: =item *
15093:
15094: removeuploadedurl(): convience function for removeuserfile()
15095:
15096: Args:
15097: url: a full /uploaded/... url to delete
15098:
1.747 albertel 15099: =item *
15100:
15101: get_portfile_permissions():
15102: Args:
15103: domain: domain of user or course contain the portfolio files
15104: user: name of user or num of course contain the portfolio files
15105: Returns:
15106: hashref of a dump of the proper file_permissions.db
15107:
15108:
15109: =item *
15110:
15111: get_access_controls():
15112:
15113: Args:
15114: current_permissions: the hash ref returned from get_portfile_permissions()
15115: group: (optional) the group you want the files associated with
15116: file: (optional) the file you want access info on
15117:
15118: Returns:
1.749 raeburn 15119: a hash (keys are file names) of hashes containing
15120: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15121: values are XML containing access control settings (see below)
1.747 albertel 15122:
15123: Internal notes:
15124:
1.749 raeburn 15125: access controls are stored in file_permissions.db as key=value pairs.
15126: key -> path to file/file_name\0uniqueID:scope_end_start
15127: where scope -> public,guest,course,group,domains or users.
15128: end -> UNIX time for end of access (0 -> no end date)
15129: start -> UNIX time for start of access
15130:
15131: value -> XML description of access control
15132: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15133: <start></start>
15134: <end></end>
15135:
15136: <password></password> for scope type = guest
15137:
15138: <domain></domain> for scope type = course or group
15139: <number></number>
15140: <roles id="">
15141: <role></role>
15142: <access></access>
15143: <section></section>
15144: <group></group>
15145: </roles>
15146:
15147: <dom></dom> for scope type = domains
15148:
15149: <users> for scope type = users
15150: <user>
15151: <uname></uname>
15152: <udom></udom>
15153: </user>
15154: </users>
15155: </scope>
15156:
15157: Access data is also aggregated for each file in an additional key=value pair:
15158: key -> path to file/file_name\0accesscontrol
15159: value -> reference to hash
15160: hash contains key = value pairs
15161: where key = uniqueID:scope_end_start
15162: value = UNIX time record was last updated
15163:
15164: Used to improve speed of look-ups of access controls for each file.
15165:
15166: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15167:
1.1198 raeburn 15168: =item *
15169:
1.749 raeburn 15170: modify_access_controls():
15171:
15172: Modifies access controls for a portfolio file
15173: Args
15174: 1. file name
15175: 2. reference to hash of required changes,
15176: 3. domain
15177: 4. username
15178: where domain,username are the domain of the portfolio owner
15179: (either a user or a course)
15180:
15181: Returns:
15182: 1. result of additions or updates ('ok' or 'error', with error message).
15183: 2. result of deletions ('ok' or 'error', with error message).
15184: 3. reference to hash of any new or updated access controls.
15185: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15186: key = integer (inbound ID)
1.1198 raeburn 15187: value = uniqueID
15188:
15189: =item *
15190:
15191: get_timebased_id():
15192:
15193: Attempts to get a unique timestamp-based suffix for use with items added to a
15194: course via the Course Editor (e.g., folders, composite pages,
15195: group bulletin boards).
15196:
15197: Args: (first three required; six others optional)
15198:
15199: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15200: docssequence, or name of group
15201:
15202: 2. keyid (alphanumeric): name of temporary locking key in hash,
15203: e.g., num, boardids
15204:
15205: 3. namespace: name of gdbm file used to store suffixes already assigned;
15206: file will be named nohist_namespace.db
15207:
15208: 4. cdom: domain of course; default is current course domain from %env
15209:
15210: 5. cnum: course number; default is current course number from %env
15211:
15212: 6. idtype: set to concat if an additional digit is to be appended to the
15213: unix timestamp to form the suffix, if the plain timestamp is already
15214: in use. Default is to not do this, but simply increment the unix
15215: timestamp by 1 until a unique key is obtained.
15216:
15217: 7. who: holder of locking key; defaults to user:domain for user.
15218:
15219: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15220: retrying); default is 3.
15221:
15222: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15223:
15224: Returns:
15225:
15226: 1. suffix obtained (numeric)
15227:
15228: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15229:
15230: 3. error: contains (localized) error message if an error occurred.
15231:
1.747 albertel 15232:
1.608 albertel 15233: =back
15234:
1.243 albertel 15235: =head2 HTTP Helper Routines
15236:
15237: =over 4
15238:
1.191 harris41 15239: =item *
15240:
15241: escape() : unpack non-word characters into CGI-compatible hex codes
15242:
15243: =item *
15244:
15245: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15246:
1.243 albertel 15247: =back
15248:
15249: =head1 PRIVATE SUBROUTINES
15250:
15251: =head2 Underlying communication routines (Shouldn't call)
15252:
15253: =over 4
15254:
15255: =item *
15256:
15257: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15258:
15259: =item *
15260:
15261: reply() : uses subreply to send a message to remote machine, logs all failures
15262:
15263: =item *
15264:
15265: critical() : passes a critical message to another server; if cannot
15266: get through then place message in connection buffer directory and
15267: returns con_delayed, if incapable of saving message, returns
15268: con_failed
15269:
15270: =item *
15271:
15272: reconlonc() : tries to reconnect lonc client processes.
15273:
15274: =back
15275:
15276: =head2 Resource Access Logging
15277:
15278: =over 4
15279:
15280: =item *
15281:
15282: flushcourselogs() : flush (save) buffer logs and access logs
15283:
15284: =item *
15285:
15286: courselog($what) : save message for course in hash
15287:
15288: =item *
15289:
15290: courseacclog($what) : save message for course using &courselog(). Perform
15291: special processing for specific resource types (problems, exams, quizzes, etc).
15292:
1.191 harris41 15293: =item *
15294:
15295: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15296: as a PerlChildExitHandler
1.243 albertel 15297:
15298: =back
15299:
15300: =head2 Other
15301:
15302: =over 4
15303:
15304: =item *
15305:
15306: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15307:
15308: =back
15309:
15310: =cut
1.877 foxr 15311:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>