Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1408
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1408 ! raeburn 4: # $Id: lonnet.pm,v 1.1407 2019/04/24 01:44:46 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.486 www 74: use HTTP::Date;
1.977 amueller 75: use Image::Magick;
1.1389 raeburn 76: use CGI::Cookie;
1.1182 foxr 77:
1.1173 foxr 78: use Encode;
79:
1.1405 raeburn 80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138 raeburn 81: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
82: %managerstab);
1.871 albertel 83:
84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
85: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
86: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 87: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 88:
1.1 albertel 89: use IO::Socket;
1.31 www 90: use GDBM_File;
1.208 albertel 91: use HTML::LCParser;
1.88 www 92: use Fcntl qw(:flock);
1.870 albertel 93: use Storable qw(thaw nfreeze);
1.1289 damieng 94: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 95: use Cache::Memcached;
1.676 albertel 96: use Digest::MD5;
1.790 albertel 97: use Math::Random;
1.1024 raeburn 98: use File::MMagic;
1.807 albertel 99: use LONCAPA qw(:DEFAULT :match);
1.740 www 100: use LONCAPA::Configuration;
1.1160 www 101: use LONCAPA::lonmetadata;
1.1167 droeschl 102: use LONCAPA::Lond;
1.1345 raeburn 103: use LONCAPA::LWPReq;
1.1406 raeburn 104: use LONCAPA::transliterate;
1.1117 foxr 105:
1.1090 raeburn 106: use File::Copy;
1.676 albertel 107:
1.195 www 108: my $readit;
1.1288 damieng 109: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 110:
1.619 albertel 111: require Exporter;
112:
113: our @ISA = qw (Exporter);
114: our @EXPORT = qw(%env);
115:
1.449 matthew 116:
1.1187 raeburn 117: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 118: {
119: my $logid;
1.1187 raeburn 120: sub write_log {
1.1188 raeburn 121: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 122: if ($context eq 'course') {
123: if (($cnum eq '') || ($cdom eq '')) {
124: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
125: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
126: }
1.957 raeburn 127: }
1.1184 raeburn 128: $logid ++;
1.957 raeburn 129: my $now = time();
130: my $id=$now.'00000'.$$.'00000'.$logid;
1.1184 raeburn 131: my $logentry = {
132: $id => {
133: 'exe_uname' => $env{'user.name'},
134: 'exe_udom' => $env{'user.domain'},
135: 'exe_time' => $now,
136: 'exe_ip' => $ENV{'REMOTE_ADDR'},
137: 'delflag' => $delflag,
138: 'logentry' => $storehash,
139: 'uname' => $uname,
140: 'udom' => $udom,
141: }
142: };
143: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 144: }
145: }
1.1 albertel 146:
1.163 harris41 147: sub logtouch {
148: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 149: unless (-e "$execdir/logs/lonnet.log") {
1.1359 raeburn 150: open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 151: close $fh;
152: }
153: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
154: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
155: }
156:
1.1 albertel 157: sub logthis {
158: my $message=shift;
159: my $execdir=$perlvar{'lonDaemons'};
160: my $now=time;
161: my $local=localtime($now);
1.1359 raeburn 162: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 163: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
164: print $fh $logstring;
1.448 albertel 165: close($fh);
166: }
1.1 albertel 167: return 1;
168: }
169:
170: sub logperm {
171: my $message=shift;
172: my $execdir=$perlvar{'lonDaemons'};
173: my $now=time;
174: my $local=localtime($now);
1.1359 raeburn 175: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 176: print $fh "$now:$message:$local\n";
177: close($fh);
178: }
1.1 albertel 179: return 1;
180: }
181:
1.850 albertel 182: sub create_connection {
1.853 albertel 183: my ($hostname,$lonid) = @_;
1.851 albertel 184: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 185: Type => SOCK_STREAM,
186: Timeout => 10);
187: return 0 if (!$client);
1.1399 raeburn 188: print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
1.850 albertel 189: my $result = <$client>;
190: chomp($result);
191: return 1 if ($result eq 'done');
192: return 0;
193: }
194:
1.983 raeburn 195: sub get_server_timezone {
196: my ($cnum,$cdom) = @_;
197: my $home=&homeserver($cnum,$cdom);
198: if ($home ne 'no_host') {
199: my $cachetime = 24*3600;
200: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
201: if (defined($cached)) {
202: return $timezone;
203: } else {
204: my $timezone = &reply('servertimezone',$home);
205: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
206: }
207: }
208: }
1.850 albertel 209:
1.1106 raeburn 210: sub get_server_distarch {
211: my ($lonhost,$ignore_cache) = @_;
212: if (defined($lonhost)) {
213: if (!defined(&hostname($lonhost))) {
214: return;
215: }
216: my $cachetime = 12*3600;
217: if (!$ignore_cache) {
218: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
219: if (defined($cached)) {
220: return $distarch;
221: }
222: }
223: my $rep = &reply('serverdistarch',$lonhost);
224: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
225: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
226: $rep eq '') {
227: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
228: }
229: }
230: return;
231: }
232:
1.1315 raeburn 233: sub get_servercerts_info {
1.1383 raeburn 234: my ($lonhost,$hostname,$context) = @_;
235: return if ($lonhost eq '');
236: if ($hostname eq '') {
237: $hostname = &hostname($lonhost);
238: }
239: return if ($hostname eq '');
1.1315 raeburn 240: my ($rep,$uselocal);
1.1388 raeburn 241: if ($context eq 'install') {
1.1387 raeburn 242: $uselocal = 1;
243: } elsif (grep { $_ eq $lonhost } ¤t_machine_ids()) {
1.1315 raeburn 244: $uselocal = 1;
245: }
1.1387 raeburn 246: if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315 raeburn 247: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323 raeburn 248: if ($distro eq '') {
249: $uselocal = 0;
250: } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315 raeburn 251: if ($1 < 6) {
252: $uselocal = 0;
253: }
1.1346 raeburn 254: } elsif ($distro =~ /^(?:sles)(\d+)$/) {
255: if ($1 < 12) {
256: $uselocal = 0;
257: }
1.1315 raeburn 258: }
259: }
260: if ($uselocal) {
1.1383 raeburn 261: $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315 raeburn 262: } else {
263: $rep=&reply('servercerts',$lonhost);
264: }
265: my ($result,%returnhash);
266: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
267: ($rep eq 'unknown_cmd')) {
268: $result = $rep;
269: } else {
270: $result = 'ok';
271: my @pairs=split(/\&/,$rep);
272: foreach my $item (@pairs) {
273: my ($key,$value)=split(/=/,$item,2);
274: my $what = &unescape($key);
275: $returnhash{$what}=&thaw_unescape($value);
276: }
277: }
278: return ($result,\%returnhash);
279: }
280:
1.993 raeburn 281: sub get_server_loncaparev {
1.1073 raeburn 282: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 283: if (defined($lonhost)) {
284: if (!defined(&hostname($lonhost))) {
285: undef($lonhost);
286: }
287: }
288: if (!defined($lonhost)) {
289: if (defined(&domain($dom,'primary'))) {
290: $lonhost=&domain($dom,'primary');
291: if ($lonhost eq 'no_host') {
292: undef($lonhost);
293: }
294: }
295: }
296: if (defined($lonhost)) {
1.1073 raeburn 297: my $cachetime = 12*3600;
298: if (!$ignore_cache) {
299: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
300: if (defined($cached)) {
301: return $loncaparev;
302: }
303: }
304: my ($answer,$loncaparev);
305: my @ids=¤t_machine_ids();
306: if (grep(/^\Q$lonhost\E$/,@ids)) {
307: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 308: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 309: $loncaparev = $1;
310: }
311: } else {
312: $answer = &reply('serverloncaparev',$lonhost);
313: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
314: if ($caller eq 'loncron') {
1.1397 raeburn 315: my $hostname = &hostname($lonhost);
1.1073 raeburn 316: my $protocol = $protocol{$lonhost};
317: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 318: my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073 raeburn 319: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 320: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073 raeburn 321: unless ($response->is_error()) {
322: my $content = $response->content;
1.1081 raeburn 323: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 324: $loncaparev = $1;
325: }
326: }
327: } else {
328: $loncaparev = $loncaparevs{$lonhost};
329: }
1.1081 raeburn 330: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 331: $loncaparev = $1;
332: }
1.993 raeburn 333: }
1.1073 raeburn 334: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 335: }
336: }
337:
1.1074 raeburn 338: sub get_server_homeID {
339: my ($hostname,$ignore_cache,$caller) = @_;
340: unless ($ignore_cache) {
341: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
342: if (defined($cached)) {
343: return $serverhomeID;
344: }
345: }
346: my $cachetime = 12*3600;
347: my $serverhomeID;
348: if ($caller eq 'loncron') {
349: my @machine_ids = &machine_ids($hostname);
350: foreach my $id (@machine_ids) {
351: my $response = &reply('serverhomeID',$id);
352: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
353: $serverhomeID = $response;
354: last;
355: }
356: }
357: if ($serverhomeID eq '') {
358: $serverhomeID = $machine_ids[-1];
359: }
360: } else {
361: $serverhomeID = $serverhomeIDs{$hostname};
362: }
363: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
364: }
365:
1.1121 raeburn 366: sub get_remote_globals {
367: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 368: my ($result,%returnhash,%whatneeded);
369: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 370: foreach my $what (sort(keys(%{$whathash}))) {
371: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 372: my ($response,$cached);
1.1121 raeburn 373: unless ($ignore_cache) {
1.1125 raeburn 374: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 375: }
376: if (defined($cached)) {
1.1125 raeburn 377: $returnhash{$what} = $response;
1.1121 raeburn 378: } else {
1.1125 raeburn 379: $whatneeded{$what} = 1;
1.1121 raeburn 380: }
381: }
1.1125 raeburn 382: if (keys(%whatneeded) == 0) {
383: $result = 'ok';
384: } else {
1.1121 raeburn 385: my $requested = &freeze_escape(\%whatneeded);
386: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 387: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
388: ($rep eq 'unknown_cmd')) {
389: $result = $rep;
390: } else {
391: $result = 'ok';
1.1121 raeburn 392: my @pairs=split(/\&/,$rep);
1.1125 raeburn 393: foreach my $item (@pairs) {
394: my ($key,$value)=split(/=/,$item,2);
395: my $what = &unescape($key);
396: my $hashid = $lonhost.'-'.$what;
397: $returnhash{$what}=&thaw_unescape($value);
398: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 399: }
400: }
401: }
402: }
1.1125 raeburn 403: return ($result,\%returnhash);
1.1121 raeburn 404: }
405:
1.1124 raeburn 406: sub remote_devalidate_cache {
1.1241 raeburn 407: my ($lonhost,$cachekeys) = @_;
408: my $items;
409: return unless (ref($cachekeys) eq 'ARRAY');
410: my $cachestr = join('&',@{$cachekeys});
411: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 412: return $response;
413: }
414:
1.1 albertel 415: # -------------------------------------------------- Non-critical communication
416: sub subreply {
417: my ($cmd,$server)=@_;
1.838 albertel 418: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 419: #
420: # With loncnew process trimming, there's a timing hole between lonc server
421: # process exit and the master server picking up the listen on the AF_UNIX
422: # socket. In that time interval, a lock file will exist:
423:
424: my $lockfile=$peerfile.".lock";
425: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1289 damieng 426: sleep(0.1);
1.549 foxr 427: }
428: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 429: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 430: #
1.550 foxr 431: # We'll give the connection a few tries before abandoning it. If
432: # connection is not possible, we'll con_lost back to the client.
433: #
434: my $client;
435: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
436: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
437: Type => SOCK_STREAM,
438: Timeout => 10);
1.869 albertel 439: if ($client) {
1.550 foxr 440: last; # Connected!
1.850 albertel 441: } else {
1.853 albertel 442: &create_connection(&hostname($server),$server);
1.550 foxr 443: }
1.1289 damieng 444: sleep(0.1); # Try again later if failed connection.
1.550 foxr 445: }
446: my $answer;
447: if ($client) {
1.704 albertel 448: print $client "sethost:$server:$cmd\n";
1.550 foxr 449: $answer=<$client>;
450: if (!$answer) { $answer="con_lost"; }
451: chomp($answer);
452: } else {
453: $answer = 'con_lost'; # Failed connection.
454: }
1.1 albertel 455: return $answer;
456: }
457:
458: sub reply {
459: my ($cmd,$server)=@_;
1.838 albertel 460: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 461: my $answer=subreply($cmd,$server);
1.65 www 462: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396 raeburn 463: my $logged = $cmd;
464: if ($cmd =~ /^encrypt:([^:]+):/) {
465: my $subcmd = $1;
466: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
467: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
468: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
469: (undef,undef,my @rest) = split(/:/,$cmd);
470: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
471: splice(@rest,2,1,'Hidden');
472: } elsif ($subcmd eq 'passwd') {
473: splice(@rest,2,2,('Hidden','Hidden'));
474: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
475: ($subcmd eq 'autoexportgrades')) {
476: splice(@rest,3,1,'Hidden');
477: }
478: $logged = join(':',('encrypt:'.$subcmd,@rest));
479: }
480: }
481: &logthis("<font color=\"blue\">WARNING:".
482: " $logged to $server returned $answer</font>");
1.12 www 483: }
1.1 albertel 484: return $answer;
485: }
486:
487: # ----------------------------------------------------------- Send USR1 to lonc
488:
489: sub reconlonc {
1.891 albertel 490: my ($lonid) = @_;
491: if ($lonid) {
1.1295 raeburn 492: my $hostname = &hostname($lonid);
1.891 albertel 493: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
494: if ($hostname && -e $peerfile) {
495: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
496: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
497: Type => SOCK_STREAM,
498: Timeout => 10);
499: if ($client) {
500: print $client ("reset_retries\n");
501: my $answer=<$client>;
502: #reset just this one.
503: }
504: }
505: return;
506: }
507:
1.836 www 508: &logthis("Trying to reconnect lonc");
1.1 albertel 509: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359 raeburn 510: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 511: my $loncpid=<$fh>;
512: chomp($loncpid);
513: if (kill 0 => $loncpid) {
514: &logthis("lonc at pid $loncpid responding, sending USR1");
515: kill USR1 => $loncpid;
516: sleep 1;
1.1295 raeburn 517: } else {
1.12 www 518: &logthis(
1.672 albertel 519: "<font color=\"blue\">WARNING:".
1.12 www 520: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 521: }
522: } else {
1.836 www 523: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 524: }
525: }
526:
527: # ------------------------------------------------------ Critical communication
1.12 www 528:
1.1 albertel 529: sub critical {
530: my ($cmd,$server)=@_;
1.838 albertel 531: unless (&hostname($server)) {
1.672 albertel 532: &logthis("<font color=\"blue\">WARNING:".
1.89 www 533: " Critical message to unknown server ($server)</font>");
534: return 'no_such_host';
535: }
1.1 albertel 536: my $answer=reply($cmd,$server);
537: if ($answer eq 'con_lost') {
1.1295 raeburn 538: &reconlonc($server);
1.589 albertel 539: my $answer=reply($cmd,$server);
1.1 albertel 540: if ($answer eq 'con_lost') {
541: my $now=time;
542: my $middlename=$cmd;
1.5 www 543: $middlename=substr($middlename,0,16);
1.1 albertel 544: $middlename=~s/\W//g;
545: my $dfilename=
1.305 www 546: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
547: $dumpcount++;
1.1 albertel 548: {
1.448 albertel 549: my $dfh;
1.1359 raeburn 550: if (open($dfh,">",$dfilename)) {
1.448 albertel 551: print $dfh "$cmd\n";
552: close($dfh);
553: }
1.1 albertel 554: }
1.1288 damieng 555: sleep 1;
1.1 albertel 556: my $wcmd='';
557: {
1.448 albertel 558: my $dfh;
1.1359 raeburn 559: if (open($dfh,"<",$dfilename)) {
1.448 albertel 560: $wcmd=<$dfh>;
561: close($dfh);
562: }
1.1 albertel 563: }
564: chomp($wcmd);
1.7 www 565: if ($wcmd eq $cmd) {
1.672 albertel 566: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 567: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 568: &logperm("D:$server:$cmd");
569: return 'con_delayed';
570: } else {
1.672 albertel 571: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 572: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 573: &logperm("F:$server:$cmd");
574: return 'con_failed';
575: }
576: }
577: }
578: return $answer;
1.405 albertel 579: }
580:
1.755 albertel 581: # ------------------------------------------- check if return value is an error
582:
583: sub error {
584: my ($result) = @_;
1.756 albertel 585: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 586: if ($2 == 2) { return undef; }
587: return $1;
588: }
589: return undef;
590: }
591:
1.783 albertel 592: sub convert_and_load_session_env {
593: my ($lonidsdir,$handle)=@_;
594: my @profile;
595: {
1.917 albertel 596: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
597: if (!$opened) {
1.915 albertel 598: return 0;
599: }
1.783 albertel 600: flock($idf,LOCK_SH);
601: @profile=<$idf>;
602: close($idf);
603: }
604: my %temp_env;
605: foreach my $line (@profile) {
1.786 albertel 606: if ($line !~ m/=/) {
607: return 0;
608: }
1.783 albertel 609: chomp($line);
610: my ($envname,$envvalue)=split(/=/,$line,2);
611: $temp_env{&unescape($envname)} = &unescape($envvalue);
612: }
613: unlink("$lonidsdir/$handle.id");
614: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
615: 0640)) {
616: %disk_env = %temp_env;
617: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
618: untie(%disk_env);
619: }
1.786 albertel 620: return 1;
1.783 albertel 621: }
622:
1.374 www 623: # ------------------------------------------- Transfer profile into environment
1.780 albertel 624: my $env_loaded;
625: sub transfer_profile_to_env {
1.788 albertel 626: my ($lonidsdir,$handle,$force_transfer) = @_;
627: if (!$force_transfer && $env_loaded) { return; }
1.374 www 628:
1.720 albertel 629: if (!defined($lonidsdir)) {
630: $lonidsdir = $perlvar{'lonIDsDir'};
631: }
632: if (!defined($handle)) {
633: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
634: }
635:
1.786 albertel 636: my $convert;
637: {
1.917 albertel 638: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
639: if (!$opened) {
1.915 albertel 640: return;
641: }
1.786 albertel 642: flock($idf,LOCK_SH);
643: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
644: &GDBM_READER(),0640)) {
645: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
646: untie(%disk_env);
647: } else {
648: $convert = 1;
649: }
650: }
651: if ($convert) {
652: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
653: &logthis("Failed to load session, or convert session.");
654: }
1.374 www 655: }
1.783 albertel 656:
1.786 albertel 657: my %remove;
1.783 albertel 658: while ( my $envname = each(%env) ) {
1.433 matthew 659: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
660: if ($time < time-300) {
1.783 albertel 661: $remove{$key}++;
1.433 matthew 662: }
663: }
664: }
1.783 albertel 665:
1.619 albertel 666: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 667: $env_loaded=1;
1.783 albertel 668: foreach my $expired_key (keys(%remove)) {
1.433 matthew 669: &delenv($expired_key);
1.374 www 670: }
1.1 albertel 671: }
672:
1.916 albertel 673: # ---------------------------------------------------- Check for valid session
674: sub check_for_valid_session {
1.1355 raeburn 675: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 676: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378 raeburn 677: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
678: if ($name eq 'lonDAV') {
679: $lonidsdir=$r->dir_config('lonDAVsessDir');
680: } else {
681: $lonidsdir=$r->dir_config('lonIDsDir');
682: if ($name eq '') {
683: $name = 'lonID';
684: }
685: }
686: if ($name eq 'lonID') {
687: $secure = 'lonSID';
1.1337 raeburn 688: $linkname = 'lonLinkID';
689: $pubname = 'lonPubID';
1.1378 raeburn 690: if (exists($cookies{$secure})) {
691: $lonid=$cookies{$secure};
692: } elsif (exists($cookies{$name})) {
693: $lonid=$cookies{$name};
1.1400 raeburn 694: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337 raeburn 695: $lonid=$cookies{$linkname};
1.1378 raeburn 696: } elsif (exists($cookies{$pubname})) {
697: $lonid=$cookies{$pubname};
1.1337 raeburn 698: }
1.1378 raeburn 699: } else {
700: $lonid=$cookies{$name};
1.1337 raeburn 701: }
1.916 albertel 702: return undef if (!$lonid);
703:
704: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378 raeburn 705: if (-l "$lonidsdir/$handle.id") {
706: my $link = readlink("$lonidsdir/$handle.id");
707: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
708: $handle = $1;
709: }
1.1155 raeburn 710: }
1.1355 raeburn 711: if (!-e "$lonidsdir/$handle.id") {
712: if ((ref($domref)) && ($name eq 'lonID') &&
713: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
714: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
715: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
716: $$domref = $possudom;
717: }
718: }
719: return undef;
720: }
1.916 albertel 721:
1.917 albertel 722: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
723: return undef if (!$opened);
1.916 albertel 724:
725: flock($idf,LOCK_SH);
726: my %disk_env;
727: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
728: &GDBM_READER(),0640)) {
729: return undef;
730: }
731:
732: if (!defined($disk_env{'user.name'})
733: || !defined($disk_env{'user.domain'})) {
1.1394 raeburn 734: untie(%disk_env);
1.916 albertel 735: return undef;
736: }
1.1245 raeburn 737:
738: if (ref($userhashref) eq 'HASH') {
739: $userhashref->{'name'} = $disk_env{'user.name'};
740: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1361 raeburn 741: $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375 raeburn 742: if ($userhashref->{'lti'}) {
743: $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
744: $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
745: }
1.1212 raeburn 746: }
1.1394 raeburn 747: untie(%disk_env);
1.1245 raeburn 748:
1.916 albertel 749: return $handle;
750: }
751:
1.830 albertel 752: sub timed_flock {
753: my ($file,$lock_type) = @_;
754: my $failed=0;
755: eval {
756: local $SIG{__DIE__}='DEFAULT';
757: local $SIG{ALRM}=sub {
758: $failed=1;
759: die("failed lock");
760: };
761: alarm(13);
762: flock($file,$lock_type);
763: alarm(0);
764: };
765: if ($failed) {
766: return undef;
767: } else {
768: return 1;
769: }
770: }
771:
1.1392 raeburn 772: sub get_sessionfile_vars {
773: my ($handle,$lonidsdir,$storearr) = @_;
774: my %returnhash;
775: unless (ref($storearr) eq 'ARRAY') {
776: return %returnhash;
777: }
778: if (-l "$lonidsdir/$handle.id") {
779: my $link = readlink("$lonidsdir/$handle.id");
780: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
781: $handle = $1;
782: }
783: }
784: if ((-e "$lonidsdir/$handle.id") &&
785: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
786: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
787: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
788: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
789: flock($idf,LOCK_SH);
790: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
791: &GDBM_READER(),0640)) {
792: foreach my $item (@{$storearr}) {
793: $returnhash{$item} = $disk_env{$item};
794: }
795: untie(%disk_env);
796: }
797: }
798: }
799: }
800: return %returnhash;
801: }
802:
1.5 www 803: # ---------------------------------------------------------- Append Environment
804:
805: sub appenv {
1.949 raeburn 806: my ($newenv,$roles) = @_;
807: if (ref($newenv) eq 'HASH') {
808: foreach my $key (keys(%{$newenv})) {
809: my $refused = 0;
810: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
811: $refused = 1;
812: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 813: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 814: if (grep(/^\Q$role\E$/,@{$roles})) {
815: $refused = 0;
816: }
817: }
818: }
819: if ($refused) {
820: &logthis("<font color=\"blue\">WARNING: ".
821: "Attempt to modify environment ".$key." to ".$newenv->{$key}
822: .'</font>');
823: delete($newenv->{$key});
824: } else {
825: $env{$key}=$newenv->{$key};
826: }
827: }
1.1376 raeburn 828: my $lonids = $perlvar{'lonIDsDir'};
829: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
830: my $opened = open(my $env_file,'+<',$env{'user.environment'});
831: if ($opened
832: && &timed_flock($env_file,LOCK_EX)
833: &&
834: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
835: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
836: while (my ($key,$value) = each(%{$newenv})) {
837: $disk_env{$key} = $value;
838: }
839: untie(%disk_env);
840: }
1.35 www 841: }
1.191 harris41 842: }
1.56 www 843: return 'ok';
844: }
845: # ----------------------------------------------------- Delete from Environment
846:
847: sub delenv {
1.1104 raeburn 848: my ($delthis,$regexp,$roles) = @_;
849: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
850: my $refused = 1;
851: if (ref($roles) eq 'ARRAY') {
852: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
853: if (grep(/^\Q$role\E$/,@{$roles})) {
854: $refused = 0;
855: }
856: }
857: if ($refused) {
858: &logthis("<font color=\"blue\">WARNING: ".
859: "Attempt to delete from environment ".$delthis);
860: return 'error';
861: }
1.56 www 862: }
1.917 albertel 863: my $opened = open(my $env_file,'+<',$env{'user.environment'});
864: if ($opened
1.915 albertel 865: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 866: &&
867: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
868: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 869: foreach my $key (keys(%disk_env)) {
1.987 raeburn 870: if ($regexp) {
871: if ($key=~/^$delthis/) {
872: delete($env{$key});
873: delete($disk_env{$key});
874: }
875: } else {
876: if ($key=~/^\Q$delthis\E/) {
877: delete($env{$key});
878: delete($disk_env{$key});
879: }
880: }
1.448 albertel 881: }
1.783 albertel 882: untie(%disk_env);
1.5 www 883: }
884: return 'ok';
1.369 albertel 885: }
886:
1.790 albertel 887: sub get_env_multiple {
888: my ($name) = @_;
889: my @values;
890: if (defined($env{$name})) {
891: # exists is it an array
892: if (ref($env{$name})) {
893: @values=@{ $env{$name} };
894: } else {
895: $values[0]=$env{$name};
896: }
897: }
898: return(@values);
899: }
900:
1.958 www 901: # ------------------------------------------------------------------- Locking
902:
903: sub set_lock {
904: my ($text)=@_;
905: $locknum++;
906: my $id=$$.'-'.$locknum;
907: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
908: 'session.lock.'.$id => $text});
909: return $id;
910: }
911:
912: sub get_locks {
913: my $num=0;
914: my %texts=();
915: foreach my $lock (split(/\,/,$env{'session.locks'})) {
916: if ($lock=~/\w/) {
917: $num++;
918: $texts{$lock}=$env{'session.lock.'.$lock};
919: }
920: }
921: return ($num,%texts);
922: }
923:
924: sub remove_lock {
925: my ($id)=@_;
926: my $newlocks='';
927: foreach my $lock (split(/\,/,$env{'session.locks'})) {
928: if (($lock=~/\w/) && ($lock ne $id)) {
929: $newlocks.=','.$lock;
930: }
931: }
932: &appenv({'session.locks' => $newlocks});
933: &delenv('session.lock.'.$id);
934: }
935:
936: sub remove_all_locks {
937: my $activelocks=$env{'session.locks'};
938: foreach my $lock (split(/\,/,$env{'session.locks'})) {
939: if ($lock=~/\w/) {
940: &remove_lock($lock);
941: }
942: }
943: }
944:
945:
1.369 albertel 946: # ------------------------------------------ Find out current server userload
947: sub userload {
948: my $numusers=0;
949: {
950: opendir(LONIDS,$perlvar{'lonIDsDir'});
951: my $filename;
952: my $curtime=time;
953: while ($filename=readdir(LONIDS)) {
1.925 albertel 954: next if ($filename eq '.' || $filename eq '..');
955: next if ($filename =~ /publicuser_\d+\.id/);
1.1390 raeburn 956: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 957: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 958: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 959: }
960: closedir(LONIDS);
961: }
962: my $userloadpercent=0;
963: my $maxuserload=$perlvar{'lonUserLoadLim'};
964: if ($maxuserload) {
1.371 albertel 965: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 966: }
1.372 albertel 967: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 968: return $userloadpercent;
1.283 www 969: }
970:
1.1 albertel 971: # ------------------------------ Find server with least workload from spare.tab
1.11 www 972:
1.1 albertel 973: sub spareserver {
1.1083 raeburn 974: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 975: my $spare_server;
1.370 albertel 976: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 977: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
978: : $userloadpercent;
1.1083 raeburn 979: my ($uint_dom,$remotesessions);
980: if (($udom ne '') && (&domain($udom) ne '')) {
981: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
982: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
983: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
984: $remotesessions = $udomdefaults{'remotesessions'};
985: }
1.1123 raeburn 986: my $spareshash = &this_host_spares($udom);
987: if (ref($spareshash) eq 'HASH') {
988: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
989: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 990: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
991: $try_server));
1.1123 raeburn 992: ($spare_server, $lowest_load) =
993: &compare_server_load($try_server, $spare_server, $lowest_load);
994: }
1.1083 raeburn 995: }
1.784 albertel 996:
1.1123 raeburn 997: my $found_server = ($spare_server ne '' && $lowest_load < 100);
998:
999: if (!$found_server) {
1000: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1001: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 1002: next unless (&spare_can_host($udom,$uint_dom,
1003: $remotesessions,$try_server));
1.1123 raeburn 1004: ($spare_server, $lowest_load) =
1005: &compare_server_load($try_server, $spare_server, $lowest_load);
1006: }
1007: }
1008: }
1.784 albertel 1009: }
1010:
1011: if (!$want_server_name) {
1.1001 raeburn 1012: if (defined($spare_server)) {
1013: my $hostname = &hostname($spare_server);
1.1083 raeburn 1014: if (defined($hostname)) {
1.1397 raeburn 1015: my $protocol = 'http';
1016: if ($protocol{$spare_server} eq 'https') {
1017: $protocol = $protocol{$spare_server};
1018: }
1.1001 raeburn 1019: $spare_server = $protocol.'://'.$hostname;
1020: }
1021: }
1.784 albertel 1022: }
1023: return $spare_server;
1024: }
1025:
1026: sub compare_server_load {
1.1253 raeburn 1027: my ($try_server, $spare_server, $lowest_load, $required) = @_;
1028:
1029: if ($required) {
1030: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
1031: my $remoterev = &get_server_loncaparev(undef,$try_server);
1032: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
1033: if (($major eq '' && $minor eq '') ||
1034: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
1035: return ($spare_server,$lowest_load);
1036: }
1037: }
1.784 albertel 1038:
1039: my $loadans = &reply('load', $try_server);
1040: my $userloadans = &reply('userload',$try_server);
1041:
1042: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 1043: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 1044: }
1045:
1046: my $load;
1047: if ($loadans =~ /\d/) {
1048: if ($userloadans =~ /\d/) {
1049: #both are numbers, pick the bigger one
1050: $load = ($loadans > $userloadans) ? $loadans
1051: : $userloadans;
1.411 albertel 1052: } else {
1.784 albertel 1053: $load = $loadans;
1.411 albertel 1054: }
1.784 albertel 1055: } else {
1056: $load = $userloadans;
1057: }
1058:
1059: if (($load =~ /\d/) && ($load < $lowest_load)) {
1060: $spare_server = $try_server;
1061: $lowest_load = $load;
1.370 albertel 1062: }
1.784 albertel 1063: return ($spare_server,$lowest_load);
1.202 matthew 1064: }
1.914 albertel 1065:
1066: # --------------------------- ask offload servers if user already has a session
1067: sub find_existing_session {
1068: my ($udom,$uname) = @_;
1.1123 raeburn 1069: my $spareshash = &this_host_spares($udom);
1070: if (ref($spareshash) eq 'HASH') {
1071: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1072: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1073: return $try_server if (&has_user_session($try_server, $udom, $uname));
1074: }
1075: }
1076: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1077: foreach my $try_server (@{ $spareshash->{'default'} }) {
1078: return $try_server if (&has_user_session($try_server, $udom, $uname));
1079: }
1080: }
1.914 albertel 1081: }
1082: return;
1083: }
1084:
1.1389 raeburn 1085: # check if user's browser sent load balancer cookie and server still has session
1086: # and is not overloaded.
1087: sub check_for_balancer_cookie {
1088: my ($r,$update_mtime) = @_;
1089: my ($otherserver,$cookie);
1090: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1091: if (exists($cookies{'balanceID'})) {
1092: my $balid = $cookies{'balanceID'};
1093: $cookie=&LONCAPA::clean_handle($balid->value);
1094: my $balancedir=$r->dir_config('lonBalanceDir');
1095: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1096: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1097: my ($possudom,$possuname) = ($1,$2);
1098: my $has_session = 0;
1099: if ((&domain($possudom) ne '') &&
1100: (&homeserver($possuname,$possudom) ne 'no_host')) {
1101: my $try_server;
1102: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1103: if ($opened) {
1104: flock($idf,LOCK_SH);
1105: while (my $line = <$idf>) {
1106: chomp($line);
1107: if (&hostname($line) ne '') {
1108: $try_server = $line;
1109: last;
1110: }
1111: }
1112: close($idf);
1113: if (($try_server) &&
1114: (&has_user_session($try_server,$possudom,$possuname))) {
1115: my $lowest_load = 30000;
1116: ($otherserver,$lowest_load) =
1117: &compare_server_load($try_server,undef,$lowest_load);
1118: if ($otherserver ne '' && $lowest_load < 100) {
1119: $has_session = 1;
1120: } else {
1121: undef($otherserver);
1122: }
1123: }
1124: }
1125: }
1126: if ($has_session) {
1127: if ($update_mtime) {
1128: my $atime = my $mtime = time;
1129: utime($atime,$mtime,"$balancedir/$cookie.id");
1130: }
1131: } else {
1132: unlink("$balancedir/$cookie.id");
1133: }
1134: }
1135: }
1136: }
1137: return ($otherserver,$cookie);
1138: }
1139:
1140: sub delbalcookie {
1141: my ($cookie,$balancer) =@_;
1142: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1143: my ($udom,$uname) = ($1,$2);
1144: my $uprimary_id = &domain($udom,'primary');
1145: my $uintdom = &internet_dom($uprimary_id);
1146: my $intdom = &internet_dom($balancer);
1147: my $serverhomedom = &host_domain($balancer);
1148: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1149: return &reply("delbalcookie:$cookie",$balancer);
1150: }
1151: }
1152: }
1153:
1.914 albertel 1154: # -------------------------------- ask if server already has a session for user
1155: sub has_user_session {
1156: my ($lonid,$udom,$uname) = @_;
1157: my $result = &reply(join(':','userhassession',
1158: map {&escape($_)} ($udom,$uname)),$lonid);
1159: return 1 if ($result eq 'ok');
1160:
1161: return 0;
1162: }
1163:
1.1076 raeburn 1164: # --------- determine least loaded server in a user's domain which allows login
1165:
1166: sub choose_server {
1.1259 raeburn 1167: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1168: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1169: my %servers = &get_servers($udom);
1.1076 raeburn 1170: my $lowest_load = 30000;
1.1259 raeburn 1171: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1172: if ($skiploadbal) {
1173: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1174: unless (defined($cached)) {
1175: my $cachetime = 60*60*24;
1176: my %domconfig =
1177: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1178: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1179: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1180: $cachetime);
1181: }
1182: }
1183: }
1.1076 raeburn 1184: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1185: if ($skiploadbal) {
1186: if (ref($balancers) eq 'HASH') {
1187: next if (exists($balancers->{$lonhost}));
1188: }
1.1389 raeburn 1189: }
1.1115 raeburn 1190: my $loginvia;
1191: if ($checkloginvia) {
1192: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1193: if ($loginvia) {
1194: my ($server,$path) = split(/:/,$loginvia);
1195: ($login_host, $lowest_load) =
1.1253 raeburn 1196: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1197: if ($login_host eq $server) {
1198: $portal_path = $path;
1.1151 raeburn 1199: $isredirect = 1;
1.1116 raeburn 1200: }
1201: } else {
1202: ($login_host, $lowest_load) =
1.1253 raeburn 1203: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1204: if ($login_host eq $lonhost) {
1205: $portal_path = '';
1.1151 raeburn 1206: $isredirect = '';
1.1116 raeburn 1207: }
1208: }
1209: } else {
1.1076 raeburn 1210: ($login_host, $lowest_load) =
1.1253 raeburn 1211: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1212: }
1213: }
1214: if ($login_host ne '') {
1.1116 raeburn 1215: $hostname = &hostname($login_host);
1.1076 raeburn 1216: }
1.1331 raeburn 1217: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1218: }
1219:
1.202 matthew 1220: # --------------------------------------------- Try to change a user's password
1221:
1222: sub changepass {
1.799 raeburn 1223: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1224: $currentpass = &escape($currentpass);
1225: $newpass = &escape($newpass);
1.1030 raeburn 1226: my $lonhost = $perlvar{'lonHostID'};
1227: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1228: $server);
1229: if (! $answer) {
1230: &logthis("No reply on password change request to $server ".
1231: "by $uname in domain $udom.");
1232: } elsif ($answer =~ "^ok") {
1233: &logthis("$uname in $udom successfully changed their password ".
1234: "on $server.");
1235: } elsif ($answer =~ "^pwchange_failure") {
1236: &logthis("$uname in $udom was unable to change their password ".
1237: "on $server. The action was blocked by either lcpasswd ".
1238: "or pwchange");
1239: } elsif ($answer =~ "^non_authorized") {
1240: &logthis("$uname in $udom did not get their password correct when ".
1241: "attempting to change it on $server.");
1242: } elsif ($answer =~ "^auth_mode_error") {
1243: &logthis("$uname in $udom attempted to change their password despite ".
1244: "not being locally or internally authenticated on $server.");
1245: } elsif ($answer =~ "^unknown_user") {
1246: &logthis("$uname in $udom attempted to change their password ".
1247: "on $server but were unable to because $server is not ".
1248: "their home server.");
1249: } elsif ($answer =~ "^refused") {
1250: &logthis("$server refused to change $uname in $udom password because ".
1251: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1252: } elsif ($answer =~ "invalid_client") {
1253: &logthis("$server refused to change $uname in $udom password because ".
1254: "it was a reset by e-mail originating from an invalid server.");
1.1408 ! raeburn 1255: } elsif ($answer =~ "^prioruse") {
! 1256: &logthis("$server refused to change $uname in $udom password because ".
! 1257: "the password had been used before");
1.202 matthew 1258: }
1259: return $answer;
1.1 albertel 1260: }
1261:
1.169 harris41 1262: # ----------------------- Try to determine user's current authentication scheme
1263:
1264: sub queryauthenticate {
1265: my ($uname,$udom)=@_;
1.456 albertel 1266: my $uhome=&homeserver($uname,$udom);
1267: if (!$uhome) {
1268: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1269: return 'no_host';
1270: }
1271: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1272: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1273: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1274: }
1.456 albertel 1275: return $answer;
1.169 harris41 1276: }
1277:
1.1 albertel 1278: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1279:
1.1 albertel 1280: sub authenticate {
1.1073 raeburn 1281: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1282: $upass=&escape($upass);
1283: $uname= &LONCAPA::clean_username($uname);
1.836 www 1284: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1285: my $newhome;
1.836 www 1286: if ((!$uhome) || ($uhome eq 'no_host')) {
1287: # Maybe the machine was offline and only re-appeared again recently?
1288: &reconlonc();
1289: # One more
1.952 raeburn 1290: $uhome=&homeserver($uname,$udom,1);
1291: if (($uhome eq 'no_host') && $checkdefauth) {
1292: if (defined(&domain($udom,'primary'))) {
1293: $newhome=&domain($udom,'primary');
1294: }
1295: if ($newhome ne '') {
1296: $uhome = $newhome;
1297: }
1298: }
1.836 www 1299: if ((!$uhome) || ($uhome eq 'no_host')) {
1300: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1301: return 'no_host';
1302: }
1.1 albertel 1303: }
1.1073 raeburn 1304: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1305: if ($answer eq 'authorized') {
1.952 raeburn 1306: if ($newhome) {
1307: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1308: return 'no_account_on_host';
1309: } else {
1310: &logthis("User $uname at $udom authorized by $uhome");
1311: return $uhome;
1312: }
1.471 albertel 1313: }
1314: if ($answer eq 'non_authorized') {
1315: &logthis("User $uname at $udom rejected by $uhome");
1316: return 'no_host';
1.9 www 1317: }
1.471 albertel 1318: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1319: return 'no_host';
1320: }
1321:
1.1073 raeburn 1322: sub can_host_session {
1.1074 raeburn 1323: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1324: my $canhost = 1;
1.1074 raeburn 1325: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1326: if (ref($remotesessions) eq 'HASH') {
1327: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1328: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1329: $canhost = 0;
1330: } else {
1331: $canhost = 1;
1332: }
1333: }
1334: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1335: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1336: $canhost = 1;
1337: } else {
1338: $canhost = 0;
1339: }
1340: }
1341: if ($canhost) {
1342: if ($remotesessions->{'version'} ne '') {
1343: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1344: if ($reqmajor ne '' && $reqminor ne '') {
1345: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1346: my $major = $1;
1347: my $minor = $2;
1348: if (($major < $reqmajor ) ||
1349: (($major == $reqmajor) && ($minor < $reqminor))) {
1350: $canhost = 0;
1351: }
1352: } else {
1353: $canhost = 0;
1354: }
1355: }
1356: }
1357: }
1358: }
1359: if ($canhost) {
1360: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1361: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1362: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1363: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1364: if (($uint_dom ne '') &&
1365: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1366: $canhost = 0;
1367: } else {
1368: $canhost = 1;
1369: }
1370: }
1371: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1372: if (($uint_dom ne '') &&
1373: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1374: $canhost = 1;
1375: } else {
1376: $canhost = 0;
1377: }
1378: }
1379: }
1380: }
1381: return $canhost;
1382: }
1383:
1.1083 raeburn 1384: sub spare_can_host {
1385: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1386: my $canhost=1;
1.1279 raeburn 1387: my $try_server_hostname = &hostname($try_server);
1388: my $serverhomeID = &get_server_homeID($try_server_hostname);
1389: my $serverhomedom = &host_domain($serverhomeID);
1390: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1391: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1392: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1393: $canhost = 0;
1394: }
1395: }
1396: if (($canhost) && ($uint_dom)) {
1397: my @intdoms;
1398: my $internet_names = &get_internet_names($try_server);
1399: if (ref($internet_names) eq 'ARRAY') {
1400: @intdoms = @{$internet_names};
1401: }
1402: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1403: my $remoterev = &get_server_loncaparev(undef,$try_server);
1404: $canhost = &can_host_session($udom,$try_server,$remoterev,
1405: $remotesessions,
1406: $defdomdefaults{'hostedsessions'});
1407: }
1.1083 raeburn 1408: }
1409: return $canhost;
1410: }
1411:
1.1123 raeburn 1412: sub this_host_spares {
1413: my ($dom) = @_;
1.1126 raeburn 1414: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1415: my @hosts = ¤t_machine_ids();
1416: foreach my $lonhost (@hosts) {
1417: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1418: $dom_in_use = $dom;
1419: $lonhost_in_use = $lonhost;
1.1123 raeburn 1420: last;
1421: }
1422: }
1.1126 raeburn 1423: if ($dom_in_use ne '') {
1424: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1425: }
1426: if (ref($result) ne 'HASH') {
1427: $lonhost_in_use = $perlvar{'lonHostID'};
1428: $dom_in_use = &host_domain($lonhost_in_use);
1429: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1430: if (ref($result) ne 'HASH') {
1431: $result = \%spareid;
1432: }
1433: }
1434: return $result;
1435: }
1436:
1437: sub spares_for_offload {
1438: my ($dom_in_use,$lonhost_in_use) = @_;
1439: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1440: if (defined($cached)) {
1441: return $result;
1442: } else {
1.1126 raeburn 1443: my $cachetime = 60*60*24;
1444: my %domconfig =
1445: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1446: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1447: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1448: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1449: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1450: }
1451: }
1452: }
1453: }
1.1126 raeburn 1454: return;
1.1123 raeburn 1455: }
1456:
1.1129 raeburn 1457: sub get_lonbalancer_config {
1458: my ($servers) = @_;
1459: my ($currbalancer,$currtargets);
1460: if (ref($servers) eq 'HASH') {
1461: foreach my $server (keys(%{$servers})) {
1462: my %what = (
1463: spareid => 1,
1464: perlvar => 1,
1465: );
1466: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1467: if ($result eq 'ok') {
1468: if (ref($returnhash) eq 'HASH') {
1469: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1470: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1471: $currbalancer = $server;
1472: $currtargets = {};
1473: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1474: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1475: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1476: }
1477: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1478: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1479: }
1480: }
1481: last;
1482: }
1483: }
1484: }
1485: }
1486: }
1487: }
1488: return ($currbalancer,$currtargets);
1489: }
1490:
1491: sub check_loadbalancing {
1.1331 raeburn 1492: my ($uname,$udom,$caller) = @_;
1.1191 raeburn 1493: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391 raeburn 1494: $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129 raeburn 1495: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1496: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1497: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1498: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1499: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1500: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1501: my $domneedscache;
1.1129 raeburn 1502: my $cachetime = 60*60*24;
1503:
1504: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1505: $dom_in_use = $udom;
1506: $homeintdom = 1;
1507: } else {
1508: $dom_in_use = $serverhomedom;
1509: }
1510: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1511: unless (defined($cached)) {
1512: my %domconfig =
1513: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1514: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1515: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1516: } else {
1517: $domneedscache = $dom_in_use;
1.1129 raeburn 1518: }
1519: }
1520: if (ref($result) eq 'HASH') {
1.1391 raeburn 1521: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1522: &check_balancer_result($result,@hosts);
1.1129 raeburn 1523: if ($is_balancer) {
1524: if (ref($currrules) eq 'HASH') {
1525: if ($homeintdom) {
1526: if ($uname ne '') {
1527: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1528: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1529: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1530: $rule_in_effect = $currrules->{'_LC_author'};
1531: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1532: $rule_in_effect = $currrules->{'_LC_adv'}
1533: }
1534: }
1535: if ($rule_in_effect eq '') {
1536: my %userenv = &userenvironment($udom,$uname,'inststatus');
1537: if ($userenv{'inststatus'} ne '') {
1538: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1539: my ($othertitle,$usertypes,$types) =
1540: &Apache::loncommon::sorted_inst_types($udom);
1541: if (ref($types) eq 'ARRAY') {
1542: foreach my $type (@{$types}) {
1543: if (grep(/^\Q$type\E$/,@statuses)) {
1544: if (exists($currrules->{$type})) {
1545: $rule_in_effect = $currrules->{$type};
1546: }
1547: }
1548: }
1549: }
1550: } else {
1551: if (exists($currrules->{'default'})) {
1552: $rule_in_effect = $currrules->{'default'};
1553: }
1554: }
1555: }
1556: } else {
1557: if (exists($currrules->{'default'})) {
1558: $rule_in_effect = $currrules->{'default'};
1559: }
1560: }
1561: } else {
1562: if ($currrules->{'_LC_external'} ne '') {
1563: $rule_in_effect = $currrules->{'_LC_external'};
1564: }
1565: }
1566: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1567: $uname,$udom);
1568: }
1569: }
1570: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1571: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1572: unless (defined($cached)) {
1573: my %domconfig =
1574: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1575: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1576: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1577: } else {
1578: $domneedscache = $serverhomedom;
1.1129 raeburn 1579: }
1580: }
1581: if (ref($result) eq 'HASH') {
1.1391 raeburn 1582: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1583: &check_balancer_result($result,@hosts);
1584: if ($is_balancer) {
1.1129 raeburn 1585: if (ref($currrules) eq 'HASH') {
1586: if ($currrules->{'_LC_internetdom'} ne '') {
1587: $rule_in_effect = $currrules->{'_LC_internetdom'};
1588: }
1589: }
1590: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1591: $uname,$udom);
1592: }
1593: } else {
1594: if ($perlvar{'lonBalancer'} eq 'yes') {
1595: $is_balancer = 1;
1596: $offloadto = &this_host_spares($dom_in_use);
1597: }
1.1307 raeburn 1598: unless (defined($cached)) {
1599: $domneedscache = $serverhomedom;
1600: }
1.1129 raeburn 1601: }
1602: } else {
1603: if ($perlvar{'lonBalancer'} eq 'yes') {
1604: $is_balancer = 1;
1605: $offloadto = &this_host_spares($dom_in_use);
1606: }
1.1307 raeburn 1607: unless (defined($cached)) {
1608: $domneedscache = $serverhomedom;
1609: }
1610: }
1611: if ($domneedscache) {
1612: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1613: }
1.1176 raeburn 1614: if ($is_balancer) {
1615: my $lowest_load = 30000;
1616: if (ref($offloadto) eq 'HASH') {
1617: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1618: foreach my $try_server (@{$offloadto->{'primary'}}) {
1619: ($otherserver,$lowest_load) =
1620: &compare_server_load($try_server,$otherserver,$lowest_load);
1621: }
1.1129 raeburn 1622: }
1.1176 raeburn 1623: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1624:
1.1176 raeburn 1625: if (!$found_server) {
1626: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1627: foreach my $try_server (@{$offloadto->{'default'}}) {
1628: ($otherserver,$lowest_load) =
1629: &compare_server_load($try_server,$otherserver,$lowest_load);
1630: }
1631: }
1632: }
1633: } elsif (ref($offloadto) eq 'ARRAY') {
1634: if (@{$offloadto} == 1) {
1635: $otherserver = $offloadto->[0];
1636: } elsif (@{$offloadto} > 1) {
1637: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1638: ($otherserver,$lowest_load) =
1639: &compare_server_load($try_server,$otherserver,$lowest_load);
1640: }
1641: }
1642: }
1.1331 raeburn 1643: unless ($caller eq 'login') {
1644: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1645: $is_balancer = 0;
1646: if ($uname ne '' && $udom ne '') {
1647: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389 raeburn 1648: &appenv({'user.loadbalexempt' => $lonhost,
1.1331 raeburn 1649: 'user.loadbalcheck.time' => time});
1650: }
1.1176 raeburn 1651: }
1.1129 raeburn 1652: }
1653: }
1.1389 raeburn 1654: unless ($homeintdom) {
1655: undef($setcookie);
1656: }
1.1129 raeburn 1657: }
1.1391 raeburn 1658: return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129 raeburn 1659: }
1660:
1.1191 raeburn 1661: sub check_balancer_result {
1662: my ($result,@hosts) = @_;
1.1391 raeburn 1663: my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1664: if (ref($result) eq 'HASH') {
1665: if ($result->{'lonhost'} ne '') {
1666: my $currbalancer = $result->{'lonhost'};
1667: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1668: $is_balancer = 1;
1669: $currtargets = $result->{'targets'};
1670: $currrules = $result->{'rules'};
1671: }
1.1391 raeburn 1672: $dom_balancers = $currbalancer;
1.1191 raeburn 1673: } else {
1.1391 raeburn 1674: if (keys(%{$result})) {
1675: foreach my $key (keys(%{$result})) {
1676: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1677: (ref($result->{$key}) eq 'HASH')) {
1678: $is_balancer = 1;
1679: $currrules = $result->{$key}{'rules'};
1680: $currtargets = $result->{$key}{'targets'};
1681: $setcookie = $result->{$key}{'cookie'};
1682: last;
1683: }
1.1191 raeburn 1684: }
1.1391 raeburn 1685: $dom_balancers = join(',',sort(keys(%{$result})));
1.1191 raeburn 1686: }
1687: }
1688: }
1.1391 raeburn 1689: return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1690: }
1691:
1.1129 raeburn 1692: sub get_loadbalancer_targets {
1693: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1694: my $offloadto;
1.1175 raeburn 1695: if ($rule_in_effect eq 'none') {
1696: return [$perlvar{'lonHostID'}];
1697: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1698: $offloadto = $currtargets;
1699: } else {
1700: if ($rule_in_effect eq 'homeserver') {
1701: my $homeserver = &homeserver($uname,$udom);
1702: if ($homeserver ne 'no_host') {
1703: $offloadto = [$homeserver];
1704: }
1705: } elsif ($rule_in_effect eq 'externalbalancer') {
1706: my %domconfig =
1707: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1708: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1709: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1710: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1711: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1712: }
1713: }
1714: } else {
1.1178 raeburn 1715: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1716: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1717: if (&hostname($remotebalancer) ne '') {
1718: $offloadto = [$remotebalancer];
1719: }
1720: }
1721: } elsif (&hostname($rule_in_effect) ne '') {
1722: $offloadto = [$rule_in_effect];
1723: }
1724: }
1725: return $offloadto;
1726: }
1727:
1.1127 raeburn 1728: sub internet_dom_servers {
1729: my ($dom) = @_;
1730: my (%uniqservers,%servers);
1731: my $primaryserver = &hostname(&domain($dom,'primary'));
1732: my @machinedoms = &machine_domains($primaryserver);
1733: foreach my $mdom (@machinedoms) {
1734: my %currservers = %servers;
1735: my %server = &get_servers($mdom);
1736: %servers = (%currservers,%server);
1737: }
1738: my %by_hostname;
1739: foreach my $id (keys(%servers)) {
1740: push(@{$by_hostname{$servers{$id}}},$id);
1741: }
1742: foreach my $hostname (sort(keys(%by_hostname))) {
1743: if (@{$by_hostname{$hostname}} > 1) {
1744: my $match = 0;
1745: foreach my $id (@{$by_hostname{$hostname}}) {
1746: if (&host_domain($id) eq $dom) {
1747: $uniqservers{$id} = $hostname;
1748: $match = 1;
1749: }
1750: }
1751: unless ($match) {
1752: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1753: }
1754: } else {
1755: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1756: }
1757: }
1758: return %uniqservers;
1759: }
1760:
1.1347 raeburn 1761: sub trusted_domains {
1762: my ($cmdtype,$calldom) = @_;
1.1349 raeburn 1763: my ($trusted,$untrusted);
1.1347 raeburn 1764: if (&domain($calldom) eq '') {
1.1349 raeburn 1765: return ($trusted,$untrusted);
1.1347 raeburn 1766: }
1.1395 raeburn 1767: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349 raeburn 1768: return ($trusted,$untrusted);
1.1347 raeburn 1769: }
1770: my $callprimary = &domain($calldom,'primary');
1771: my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
1772: if ($intcalldom eq '') {
1.1349 raeburn 1773: return ($trusted,$untrusted);
1.1347 raeburn 1774: }
1775:
1776: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
1777: unless (defined($cached)) {
1778: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
1779: &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1780: $trustconfig = $domconfig{'trust'};
1781: }
1782: if (ref($trustconfig)) {
1783: my (%possexc,%possinc,@allexc,@allinc);
1784: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1785: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1786: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1787: }
1788: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395 raeburn 1789: $possinc{$intcalldom} = 1;
1.1347 raeburn 1790: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1791: }
1792: }
1793: if (keys(%possexc)) {
1794: if (keys(%possinc)) {
1795: foreach my $key (sort(keys(%possexc))) {
1796: next if ($key eq $intcalldom);
1797: unless ($possinc{$key}) {
1798: push(@allexc,$key);
1799: }
1800: }
1801: } else {
1802: @allexc = sort(keys(%possexc));
1803: }
1804: }
1805: if (keys(%possinc)) {
1806: $possinc{$intcalldom} = 1;
1807: @allinc = sort(keys(%possinc));
1808: }
1809: if ((@allexc > 0) || (@allinc > 0)) {
1810: my %doms_by_intdom;
1811: my %allintdoms = &all_host_intdom();
1812: my %alldoms = &all_host_domain();
1813: foreach my $key (%allintdoms) {
1814: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1815: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1816: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1817: }
1818: } else {
1819: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1820: }
1821: }
1822: foreach my $exc (@allexc) {
1823: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395 raeburn 1824: push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347 raeburn 1825: }
1826: }
1827: foreach my $inc (@allinc) {
1828: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395 raeburn 1829: push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347 raeburn 1830: }
1831: }
1832: }
1833: }
1.1349 raeburn 1834: return ($trusted,$untrusted);
1.1347 raeburn 1835: }
1836:
1837: sub will_trust {
1838: my ($cmdtype,$domain,$possdom) = @_;
1839: return 1 if ($domain eq $possdom);
1840: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1841: my $willtrust;
1842: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1843: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1844: $willtrust = 1;
1845: }
1846: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1847: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1848: $willtrust = 1;
1849: }
1850: } else {
1851: $willtrust = 1;
1852: }
1853: return $willtrust;
1854: }
1855:
1.1 albertel 1856: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1857:
1.599 albertel 1858: my %homecache;
1.1 albertel 1859: sub homeserver {
1.230 stredwic 1860: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1861: my $index="$uname:$udom";
1.426 albertel 1862:
1.599 albertel 1863: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1864:
1865: my %servers = &get_servers($udom,'library');
1866: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1867: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1868: exists($badServerCache{$tryserver}));
1.841 albertel 1869:
1870: my $answer=reply("home:$udom:$uname",$tryserver);
1871: if ($answer eq 'found') {
1872: delete($badServerCache{$tryserver});
1873: return $homecache{$index}=$tryserver;
1874: } elsif ($answer eq 'no_host') {
1875: $badServerCache{$tryserver}=1;
1876: }
1.1 albertel 1877: }
1878: return 'no_host';
1.70 www 1879: }
1880:
1.1300 raeburn 1881: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1882:
1883: sub idget {
1.1300 raeburn 1884: my ($udom,$idsref,$namespace)=@_;
1.70 www 1885: my %returnhash=();
1.1300 raeburn 1886: my @ids=();
1887: if (ref($idsref) eq 'ARRAY') {
1888: @ids = @{$idsref};
1889: } else {
1890: return %returnhash;
1891: }
1892: if ($namespace eq '') {
1893: $namespace = 'ids';
1894: }
1.70 www 1895:
1.841 albertel 1896: my %servers = &get_servers($udom,'library');
1897: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1898: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1899: if ($namespace eq 'ids') {
1900: $idlist=~tr/A-Z/a-z/;
1901: }
1902: my $reply;
1903: if ($namespace eq 'ids') {
1904: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1905: } else {
1906: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1907: }
1.841 albertel 1908: my @answer=();
1909: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1910: @answer=split(/\&/,$reply);
1911: } ;
1912: my $i;
1913: for ($i=0;$i<=$#ids;$i++) {
1914: if ($answer[$i]) {
1.1299 raeburn 1915: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1916: }
1.841 albertel 1917: }
1.1300 raeburn 1918: }
1.70 www 1919: return %returnhash;
1920: }
1921:
1922: # ------------------------------------- Find the IDs behind a list of usernames
1923:
1924: sub idrget {
1925: my ($udom,@unames)=@_;
1926: my %returnhash=();
1.800 albertel 1927: foreach my $uname (@unames) {
1928: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1929: }
1.70 www 1930: return %returnhash;
1931: }
1932:
1.1300 raeburn 1933: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 1934:
1935: sub idput {
1.1300 raeburn 1936: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 1937: my %servers=();
1.1300 raeburn 1938: my %ids=();
1939: my %byid = ();
1940: if (ref($idsref) eq 'HASH') {
1941: %ids=%{$idsref};
1942: }
1943: if ($namespace eq '') {
1944: $namespace = 'ids';
1945: }
1.800 albertel 1946: foreach my $uname (keys(%ids)) {
1947: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 1948: if ($uhom eq '') {
1949: $uhom=&homeserver($uname,$udom);
1950: }
1.70 www 1951: if ($uhom ne 'no_host') {
1.800 albertel 1952: my $esc_unam=&escape($uname);
1.1300 raeburn 1953: if ($namespace eq 'ids') {
1954: my $id=&escape($ids{$uname});
1955: $id=~tr/A-Z/a-z/;
1956: my $esc_unam=&escape($uname);
1957: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 1958: } else {
1.1300 raeburn 1959: my @currids = split(/,/,$ids{$uname});
1960: foreach my $id (@currids) {
1961: $byid{$uhom}{$id} .= $uname.',';
1962: }
1963: }
1964: }
1965: }
1966: if ($namespace eq 'clickers') {
1967: foreach my $server (keys(%byid)) {
1968: if (ref($byid{$server}) eq 'HASH') {
1969: foreach my $id (keys(%{$byid{$server}})) {
1970: $byid{$server} =~ s/,$//;
1971: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
1972: }
1.70 www 1973: }
1974: }
1.191 harris41 1975: }
1.800 albertel 1976: foreach my $server (keys(%servers)) {
1.1300 raeburn 1977: $servers{$server} =~ s/\&$//;
1978: if ($namespace eq 'ids') {
1979: &critical('idput:'.$udom.':'.$servers{$server},$server);
1980: } else {
1981: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
1982: }
1.191 harris41 1983: }
1.344 www 1984: }
1985:
1.1300 raeburn 1986: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 1987:
1988: sub iddel {
1.1300 raeburn 1989: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 1990: my %result=();
1.1300 raeburn 1991: my %ids=();
1992: my %byid = ();
1993: if (ref($idshashref) eq 'HASH') {
1994: %ids=%{$idshashref};
1995: } else {
1.1231 raeburn 1996: return %result;
1997: }
1.1300 raeburn 1998: if ($namespace eq '') {
1999: $namespace = 'ids';
2000: }
1.1231 raeburn 2001: my %servers=();
1.1300 raeburn 2002: while (my ($id,$unamestr) = each(%ids)) {
2003: if ($namespace eq 'ids') {
2004: my $uhom = $uhome;
2005: if ($uhom eq '') {
2006: $uhom=&homeserver($unamestr,$udom);
2007: }
2008: if ($uhom ne 'no_host') {
2009: $servers{$uhom}.='&'.&escape($id);
2010: }
2011: } else {
2012: my @curritems = split(/,/,$ids{$id});
2013: foreach my $uname (@curritems) {
2014: my $uhom = $uhome;
2015: if ($uhom eq '') {
2016: $uhom=&homeserver($uname,$udom);
2017: }
2018: if ($uhom ne 'no_host') {
2019: $byid{$uhom}{$id} .= $uname.',';
2020: }
2021: }
1.1231 raeburn 2022: }
1.1300 raeburn 2023: }
2024: if ($namespace eq 'clickers') {
2025: foreach my $server (keys(%byid)) {
2026: if (ref($byid{$server}) eq 'HASH') {
2027: foreach my $id (keys(%{$byid{$server}})) {
2028: $byid{$server}{$id} =~ s/,$//;
2029: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
2030: }
1.1231 raeburn 2031: }
2032: }
2033: }
2034: foreach my $server (keys(%servers)) {
1.1300 raeburn 2035: $servers{$server} =~ s/\&$//;
2036: if ($namespace eq 'ids') {
2037: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
2038: } elsif ($namespace eq 'clickers') {
2039: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
2040: }
1.1231 raeburn 2041: }
2042: return %result;
2043: }
2044:
1.1300 raeburn 2045: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
2046:
2047: sub updateclickers {
2048: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
2049: my %clickers;
2050: if (ref($idshashref) eq 'HASH') {
2051: %clickers=%{$idshashref};
2052: } else {
2053: return;
2054: }
2055: my $items='';
2056: foreach my $item (keys(%clickers)) {
2057: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
2058: }
2059: $items=~s/\&$//;
2060: my $request = "updateclickers:$udom:$action:$items";
2061: if ($critical) {
2062: return &critical($request,$uhome);
2063: } else {
2064: return &reply($request,$uhome);
2065: }
2066: }
2067:
1.1023 raeburn 2068: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 2069: sub dump_dom {
1.1165 droeschl 2070: my ($namespace, $udom, $regexp) = @_;
2071:
2072: $udom ||= $env{'user.domain'};
2073:
2074: return () unless $udom;
2075:
2076: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 2077: }
2078:
1.1023 raeburn 2079: # ------------------------------------------ get items from domain db files
1.806 raeburn 2080:
2081: sub get_dom {
1.860 raeburn 2082: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 2083: return if ($udom eq 'public');
1.806 raeburn 2084: my $items='';
2085: foreach my $item (@$storearr) {
2086: $items.=&escape($item).'&';
2087: }
2088: $items=~s/\&$//;
1.860 raeburn 2089: if (!$udom) {
2090: $udom=$env{'user.domain'};
1.1267 raeburn 2091: return if ($udom eq 'public');
1.860 raeburn 2092: if (defined(&domain($udom,'primary'))) {
2093: $uhome=&domain($udom,'primary');
2094: } else {
1.874 albertel 2095: undef($uhome);
1.860 raeburn 2096: }
2097: } else {
2098: if (!$uhome) {
2099: if (defined(&domain($udom,'primary'))) {
2100: $uhome=&domain($udom,'primary');
2101: }
2102: }
2103: }
2104: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344 raeburn 2105: my $rep;
2106: if ($namespace =~ /^enc/) {
2107: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
2108: } else {
2109: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
2110: }
1.866 raeburn 2111: my %returnhash;
1.875 albertel 2112: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 2113: return %returnhash;
2114: }
1.806 raeburn 2115: my @pairs=split(/\&/,$rep);
2116: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2117: return @pairs;
2118: }
2119: my $i=0;
2120: foreach my $item (@$storearr) {
2121: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2122: $i++;
2123: }
2124: return %returnhash;
2125: } else {
1.880 banghart 2126: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 2127: }
2128: }
2129:
2130: # -------------------------------------------- put items in domain db files
2131:
2132: sub put_dom {
1.860 raeburn 2133: my ($namespace,$storehash,$udom,$uhome)=@_;
2134: if (!$udom) {
2135: $udom=$env{'user.domain'};
2136: if (defined(&domain($udom,'primary'))) {
2137: $uhome=&domain($udom,'primary');
2138: } else {
1.874 albertel 2139: undef($uhome);
1.860 raeburn 2140: }
2141: } else {
2142: if (!$uhome) {
2143: if (defined(&domain($udom,'primary'))) {
2144: $uhome=&domain($udom,'primary');
2145: }
2146: }
2147: }
2148: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 2149: my $items='';
2150: foreach my $item (keys(%$storehash)) {
2151: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2152: }
2153: $items=~s/\&$//;
1.1344 raeburn 2154: if ($namespace =~ /^enc/) {
2155: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2156: } else {
2157: return &reply("putdom:$udom:$namespace:$items",$uhome);
2158: }
1.806 raeburn 2159: } else {
1.860 raeburn 2160: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 2161: }
2162: }
2163:
1.1023 raeburn 2164: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 2165: sub newput_dom {
1.1023 raeburn 2166: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 2167: my $result;
2168: if (!$udom) {
2169: $udom=$env{'user.domain'};
2170: }
1.1023 raeburn 2171: if ($udom) {
2172: my $uname = &get_domainconfiguser($udom);
2173: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 2174: }
2175: return $result;
2176: }
2177:
1.1023 raeburn 2178: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 2179: sub del_dom {
1.1023 raeburn 2180: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 2181: if (ref($storearr) eq 'ARRAY') {
2182: if (!$udom) {
2183: $udom=$env{'user.domain'};
2184: }
1.1023 raeburn 2185: if ($udom) {
2186: my $uname = &get_domainconfiguser($udom);
2187: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 2188: }
2189: }
2190: }
2191:
1.1023 raeburn 2192: # ----------------------------------construct domainconfig user for a domain
2193: sub get_domainconfiguser {
2194: my ($udom) = @_;
2195: return $udom.'-domainconfig';
2196: }
2197:
1.837 raeburn 2198: sub retrieve_inst_usertypes {
2199: my ($udom) = @_;
2200: my (%returnhash,@order);
1.989 raeburn 2201: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2202: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2203: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 2204: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2205: } else {
2206: if (defined(&domain($udom,'primary'))) {
2207: my $uhome=&domain($udom,'primary');
2208: my $rep=&reply("inst_usertypes:$udom",$uhome);
2209: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 2210: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2211: return (\%returnhash,\@order);
2212: }
2213: my ($hashitems,$orderitems) = split(/:/,$rep);
2214: my @pairs=split(/\&/,$hashitems);
2215: foreach my $item (@pairs) {
2216: my ($key,$value)=split(/=/,$item,2);
2217: $key = &unescape($key);
2218: next if ($key =~ /^error: 2 /);
2219: $returnhash{$key}=&thaw_unescape($value);
2220: }
2221: my @esc_order = split(/\&/,$orderitems);
2222: foreach my $item (@esc_order) {
2223: push(@order,&unescape($item));
2224: }
2225: } else {
1.1256 raeburn 2226: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2227: }
1.1256 raeburn 2228: return (\%returnhash,\@order);
1.837 raeburn 2229: }
2230: }
2231:
1.868 raeburn 2232: sub is_domainimage {
2233: my ($url) = @_;
1.1306 raeburn 2234: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 2235: if (&domain($1) ne '') {
2236: return '1';
2237: }
2238: }
2239: return;
2240: }
2241:
1.899 raeburn 2242: sub inst_directory_query {
2243: my ($srch) = @_;
2244: my $udom = $srch->{'srchdomain'};
2245: my %results;
2246: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2247: my $outcome;
1.899 raeburn 2248: if ($homeserver ne '') {
1.1357 raeburn 2249: unless ($homeserver eq $perlvar{'lonHostID'}) {
2250: if ($srch->{'srchby'} eq 'email') {
2251: my $lcrev = &get_server_loncaparev(undef,$homeserver);
2252: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2253: if (($major eq '' && $minor eq '') || ($major < 2) ||
2254: (($major == 2) && ($minor < 12))) {
2255: return;
2256: }
2257: }
2258: }
1.904 albertel 2259: my $queryid=&reply("querysend:instdirsearch:".
2260: &escape($srch->{'srchby'}).':'.
2261: &escape($srch->{'srchterm'}).':'.
2262: &escape($srch->{'srchtype'}),$homeserver);
2263: my $host=&hostname($homeserver);
2264: if ($queryid !~/^\Q$host\E\_/) {
1.1343 raeburn 2265: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2266: return;
2267: }
2268: my $response = &get_query_reply($queryid);
2269: my $maxtries = 5;
2270: my $tries = 1;
2271: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2272: $response = &get_query_reply($queryid);
2273: $tries ++;
2274: }
2275:
2276: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2277: if ($response eq 'unavailable') {
2278: $outcome = $response;
2279: } else {
2280: $outcome = 'ok';
2281: my @matches = split(/\n/,$response);
2282: foreach my $match (@matches) {
2283: my ($key,$value) = split(/=/,$match);
2284: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2285: }
1.899 raeburn 2286: }
2287: }
2288: }
1.909 raeburn 2289: return ($outcome,%results);
1.899 raeburn 2290: }
2291:
2292: sub usersearch {
2293: my ($srch) = @_;
2294: my $dom = $srch->{'srchdomain'};
2295: my %results;
2296: my %libserv = &all_library();
2297: my $query = 'usersearch';
2298: foreach my $tryserver (keys(%libserv)) {
2299: if (&host_domain($tryserver) eq $dom) {
1.1357 raeburn 2300: unless ($tryserver eq $perlvar{'lonHostID'}) {
2301: if ($srch->{'srchby'} eq 'email') {
2302: my $lcrev = &get_server_loncaparev(undef,$tryserver);
2303: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2304: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2305: (($major == 2) && ($minor < 12)));
2306: }
2307: }
1.899 raeburn 2308: my $host=&hostname($tryserver);
2309: my $queryid=
1.911 raeburn 2310: &reply("querysend:".&escape($query).':'.
2311: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2312: &escape($srch->{'srchtype'}).':'.
2313: &escape($srch->{'srchterm'}),$tryserver);
2314: if ($queryid !~/^\Q$host\E\_/) {
2315: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2316: next;
1.899 raeburn 2317: }
2318: my $reply = &get_query_reply($queryid);
2319: my $maxtries = 1;
2320: my $tries = 1;
2321: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2322: $reply = &get_query_reply($queryid);
2323: $tries ++;
2324: }
2325: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2326: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2327: } else {
1.911 raeburn 2328: my @matches;
2329: if ($reply =~ /\n/) {
2330: @matches = split(/\n/,$reply);
2331: } else {
2332: @matches = split(/\&/,$reply);
2333: }
1.899 raeburn 2334: foreach my $match (@matches) {
2335: my ($uname,$udom,%userhash);
1.911 raeburn 2336: foreach my $entry (split(/:/,$match)) {
2337: my ($key,$value) =
2338: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2339: $userhash{$key} = $value;
2340: if ($key eq 'username') {
2341: $uname = $value;
2342: } elsif ($key eq 'domain') {
2343: $udom = $value;
1.911 raeburn 2344: }
1.899 raeburn 2345: }
2346: $results{$uname.':'.$udom} = \%userhash;
2347: }
2348: }
2349: }
2350: }
2351: return %results;
2352: }
2353:
1.912 raeburn 2354: sub get_instuser {
2355: my ($udom,$uname,$id) = @_;
2356: my $homeserver = &domain($udom,'primary');
2357: my ($outcome,%results);
2358: if ($homeserver ne '') {
2359: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2360: &escape($id).':'.&escape($udom),$homeserver);
2361: my $host=&hostname($homeserver);
2362: if ($queryid !~/^\Q$host\E\_/) {
2363: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2364: return;
2365: }
2366: my $response = &get_query_reply($queryid);
2367: my $maxtries = 5;
2368: my $tries = 1;
2369: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2370: $response = &get_query_reply($queryid);
2371: $tries ++;
2372: }
2373: if (!&error($response) && $response ne 'refused') {
2374: if ($response eq 'unavailable') {
2375: $outcome = $response;
2376: } else {
2377: $outcome = 'ok';
2378: my @matches = split(/\n/,$response);
2379: foreach my $match (@matches) {
2380: my ($key,$value) = split(/=/,$match);
2381: $results{&unescape($key)} = &thaw_unescape($value);
2382: }
2383: }
2384: }
2385: }
2386: my %userinfo;
2387: if (ref($results{$uname}) eq 'HASH') {
2388: %userinfo = %{$results{$uname}};
2389: }
2390: return ($outcome,%userinfo);
2391: }
2392:
1.1290 raeburn 2393: sub get_multiple_instusers {
2394: my ($udom,$users,$caller) = @_;
2395: my ($outcome,$results);
2396: if (ref($users) eq 'HASH') {
2397: my $count = keys(%{$users});
2398: my $requested = &freeze_escape($users);
2399: my $homeserver = &domain($udom,'primary');
2400: if ($homeserver ne '') {
2401: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2402: my $host=&hostname($homeserver);
2403: if ($queryid !~/^\Q$host\E\_/) {
2404: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2405: ' for host: '.$homeserver.'in domain '.$udom);
2406: return ($outcome,$results);
2407: }
2408: my $response = &get_query_reply($queryid);
2409: my $maxtries = 5;
2410: if ($count > 100) {
2411: $maxtries = 1+int($count/20);
2412: }
2413: my $tries = 1;
2414: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2415: $response = &get_query_reply($queryid);
2416: $tries ++;
2417: }
2418: if ($response eq '') {
2419: $results = {};
2420: foreach my $key (keys(%{$users})) {
2421: my ($uname,$id);
2422: if ($caller eq 'id') {
2423: $id = $key;
2424: } else {
2425: $uname = $key;
2426: }
2427: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2428: $outcome = $resp;
1.1290 raeburn 2429: if ($resp eq 'ok') {
2430: %{$results} = (%{$results}, %info);
2431: } else {
2432: last;
2433: }
2434: }
2435: } elsif(!&error($response) && ($response ne 'refused')) {
2436: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2437: $outcome = $response;
2438: } else {
1.1291 raeburn 2439: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2440: if ($outcome eq 'ok') {
2441: $results = &thaw_unescape($userdata);
2442: }
2443: }
2444: }
2445: }
2446: }
2447: return ($outcome,$results);
2448: }
2449:
1.912 raeburn 2450: sub inst_rulecheck {
1.923 raeburn 2451: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2452: my %returnhash;
2453: if ($udom ne '') {
2454: if (ref($rules) eq 'ARRAY') {
2455: @{$rules} = map {&escape($_);} (@{$rules});
2456: my $rulestr = join(':',@{$rules});
2457: my $homeserver=&domain($udom,'primary');
2458: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2459: my $response;
2460: if ($item eq 'username') {
2461: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2462: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2463: $homeserver));
1.923 raeburn 2464: } elsif ($item eq 'id') {
2465: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2466: ':'.&escape($id).':'.$rulestr,
2467: $homeserver));
1.945 raeburn 2468: } elsif ($item eq 'selfcreate') {
2469: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2470: &escape($udom).':'.&escape($uname).
2471: ':'.$rulestr,$homeserver));
1.923 raeburn 2472: }
1.912 raeburn 2473: if ($response ne 'refused') {
2474: my @pairs=split(/\&/,$response);
2475: foreach my $item (@pairs) {
2476: my ($key,$value)=split(/=/,$item,2);
2477: $key = &unescape($key);
2478: next if ($key =~ /^error: 2 /);
2479: $returnhash{$key}=&thaw_unescape($value);
2480: }
2481: }
2482: }
2483: }
2484: }
2485: return %returnhash;
2486: }
2487:
2488: sub inst_userrules {
1.923 raeburn 2489: my ($udom,$check) = @_;
1.912 raeburn 2490: my (%ruleshash,@ruleorder);
2491: if ($udom ne '') {
2492: my $homeserver=&domain($udom,'primary');
2493: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2494: my $response;
2495: if ($check eq 'id') {
2496: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2497: $homeserver);
1.943 raeburn 2498: } elsif ($check eq 'email') {
2499: $response=&reply('instemailrules:'.&escape($udom),
2500: $homeserver);
1.923 raeburn 2501: } else {
2502: $response=&reply('instuserrules:'.&escape($udom),
2503: $homeserver);
2504: }
1.912 raeburn 2505: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2506: ($response ne 'unknown_cmd') &&
1.912 raeburn 2507: ($response ne 'no_such_host')) {
2508: my ($hashitems,$orderitems) = split(/:/,$response);
2509: my @pairs=split(/\&/,$hashitems);
2510: foreach my $item (@pairs) {
2511: my ($key,$value)=split(/=/,$item,2);
2512: $key = &unescape($key);
2513: next if ($key =~ /^error: 2 /);
2514: $ruleshash{$key}=&thaw_unescape($value);
2515: }
2516: my @esc_order = split(/\&/,$orderitems);
2517: foreach my $item (@esc_order) {
2518: push(@ruleorder,&unescape($item));
2519: }
2520: }
2521: }
2522: }
2523: return (\%ruleshash,\@ruleorder);
2524: }
2525:
1.976 raeburn 2526: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2527:
2528: sub get_domain_defaults {
1.1240 raeburn 2529: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2530: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2531: my $cachetime = 60*60*24;
1.1240 raeburn 2532: unless ($ignore_cache) {
2533: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2534: if (defined($cached)) {
2535: if (ref($result) eq 'HASH') {
2536: return %{$result};
2537: }
1.943 raeburn 2538: }
2539: }
2540: my %domdefaults;
2541: my %domconfig =
1.989 raeburn 2542: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2543: 'requestcourses','inststatus',
1.1183 raeburn 2544: 'coursedefaults','usersessions',
1.1258 raeburn 2545: 'requestauthor','selfenrollment',
1.1320 raeburn 2546: 'coursecategories','ssl','autoenroll',
1.1332 raeburn 2547: 'trust','helpsettings'],$domain);
1.1305 raeburn 2548: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2549: if (ref($domconfig{'defaults'}) eq 'HASH') {
2550: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2551: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2552: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2553: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2554: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2555: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340 raeburn 2556: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2557: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2558: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2559: } else {
2560: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2561: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2562: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2563: }
1.976 raeburn 2564: if (ref($domconfig{'quotas'}) eq 'HASH') {
2565: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2566: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2567: } else {
2568: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2569: }
1.1177 raeburn 2570: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2571: foreach my $item (@usertools) {
2572: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2573: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2574: }
2575: }
1.1229 raeburn 2576: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2577: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2578: }
1.976 raeburn 2579: }
1.985 raeburn 2580: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2581: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2582: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2583: }
2584: }
1.1183 raeburn 2585: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2586: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2587: }
1.989 raeburn 2588: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2589: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2590: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2591: }
2592: }
1.1047 raeburn 2593: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2594: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2595: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2596: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2597: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2598: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2599: }
1.1254 raeburn 2600: foreach my $type (@coursetypes) {
2601: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2602: unless ($type eq 'community') {
2603: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2604: }
2605: }
2606: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2607: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2608: }
1.1277 raeburn 2609: if ($domdefaults{'postsubmit'} eq 'on') {
2610: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2611: $domdefaults{$type.'postsubtimeout'} =
2612: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2613: }
2614: }
1.1230 raeburn 2615: }
1.1286 raeburn 2616: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2617: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2618: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2619: if (@clonecodes) {
2620: $domdefaults{'canclone'} = join('+',@clonecodes);
2621: }
2622: }
2623: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2624: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2625: }
1.1356 raeburn 2626: if ($domconfig{'coursedefaults'}{'texengine'}) {
2627: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2628: }
1.1047 raeburn 2629: }
1.1073 raeburn 2630: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2631: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2632: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2633: }
2634: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2635: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2636: }
1.1279 raeburn 2637: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2638: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2639: }
1.1073 raeburn 2640: }
1.1254 raeburn 2641: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2642: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2643: my @settings = ('types','registered','enroll_dates','access_dates','section',
2644: 'approval','limit');
2645: foreach my $type (@coursetypes) {
2646: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2647: my @mgrdc = ();
2648: foreach my $item (@settings) {
2649: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2650: push(@mgrdc,$item);
2651: }
2652: }
2653: if (@mgrdc) {
2654: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2655: }
2656: }
2657: }
2658: }
2659: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2660: foreach my $type (@coursetypes) {
2661: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2662: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2663: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2664: }
2665: }
2666: }
2667: }
2668: }
1.1258 raeburn 2669: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2670: $domdefaults{'catauth'} = 'std';
2671: $domdefaults{'catunauth'} = 'std';
2672: if ($domconfig{'coursecategories'}{'auth'}) {
2673: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2674: }
2675: if ($domconfig{'coursecategories'}{'unauth'}) {
2676: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2677: }
2678: }
1.1315 raeburn 2679: if (ref($domconfig{'ssl'}) eq 'HASH') {
2680: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2681: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2682: }
1.1338 raeburn 2683: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2684: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2685: }
2686: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2687: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315 raeburn 2688: }
2689: }
1.1320 raeburn 2690: if (ref($domconfig{'trust'}) eq 'HASH') {
2691: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2692: foreach my $prefix (@prefixes) {
2693: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2694: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2695: }
2696: }
2697: }
1.1314 raeburn 2698: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2699: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2700: }
1.1332 raeburn 2701: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2702: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2703: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2704: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2705: }
2706: }
1.1219 raeburn 2707: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2708: return %domdefaults;
2709: }
2710:
1.1311 raeburn 2711: sub course_portal_url {
2712: my ($cnum,$cdom) = @_;
2713: my $chome = &homeserver($cnum,$cdom);
2714: my $hostname = &hostname($chome);
2715: my $protocol = $protocol{$chome};
2716: $protocol = 'http' if ($protocol ne 'https');
2717: my %domdefaults = &get_domain_defaults($cdom);
2718: my $firsturl;
2719: if ($domdefaults{'portal_def'}) {
2720: $firsturl = $domdefaults{'portal_def'};
2721: } else {
2722: $firsturl = $protocol.'://'.$hostname;
2723: }
2724: return $firsturl;
2725: }
2726:
1.1407 raeburn 2727: # --------------------------------------------- Get domain config for passwords
2728:
2729: sub get_passwdconf {
2730: my ($dom) = @_;
2731: my (%passwdconf,$gotconf,$lookup);
2732: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2733: if (defined($cached)) {
2734: if (ref($result) eq 'HASH') {
2735: %passwdconf = %{$result};
2736: $gotconf = 1;
2737: }
2738: }
2739: unless ($gotconf) {
2740: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2741: if (ref($domconfig{'passwords'}) eq 'HASH') {
2742: %passwdconf = %{$domconfig{'passwords'}};
2743: }
2744: my $cachetime = 24*60*60;
2745: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2746: }
2747: return %passwdconf;
2748: }
2749:
1.344 www 2750: # --------------------------------------------------- Assign a key to a student
2751:
2752: sub assign_access_key {
1.364 www 2753: #
2754: # a valid key looks like uname:udom#comments
2755: # comments are being appended
2756: #
1.498 www 2757: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2758: $kdom=
1.620 albertel 2759: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2760: $knum=
1.620 albertel 2761: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2762: $cdom=
1.620 albertel 2763: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2764: $cnum=
1.620 albertel 2765: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2766: $udom=$env{'user.name'} unless (defined($udom));
2767: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2768: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2769: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2770: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2771: # assigned to this person
2772: # - this should not happen,
1.345 www 2773: # unless something went wrong
2774: # the first time around
2775: # ready to assign
1.364 www 2776: $logentry=$1.'; '.$logentry;
1.496 www 2777: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2778: $kdom,$knum) eq 'ok') {
1.345 www 2779: # key now belongs to user
1.346 www 2780: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2781: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2782: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2783: return 'ok';
2784: } else {
2785: return
2786: 'error: Count not permanently assign key, will need to be re-entered later.';
2787: }
2788: } else {
2789: return 'error: Could not assign key, try again later.';
2790: }
1.364 www 2791: } elsif (!$existing{$ckey}) {
1.345 www 2792: # the key does not exist
2793: return 'error: The key does not exist';
2794: } else {
2795: # the key is somebody else's
2796: return 'error: The key is already in use';
2797: }
1.344 www 2798: }
2799:
1.364 www 2800: # ------------------------------------------ put an additional comment on a key
2801:
2802: sub comment_access_key {
2803: #
2804: # a valid key looks like uname:udom#comments
2805: # comments are being appended
2806: #
2807: my ($ckey,$cdom,$cnum,$logentry)=@_;
2808: $cdom=
1.620 albertel 2809: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2810: $cnum=
1.620 albertel 2811: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2812: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2813: if ($existing{$ckey}) {
2814: $existing{$ckey}.='; '.$logentry;
2815: # ready to assign
1.367 www 2816: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2817: $cdom,$cnum) eq 'ok') {
2818: return 'ok';
2819: } else {
2820: return 'error: Count not store comment.';
2821: }
2822: } else {
2823: # the key does not exist
2824: return 'error: The key does not exist';
2825: }
2826: }
2827:
1.344 www 2828: # ------------------------------------------------------ Generate a set of keys
2829:
2830: sub generate_access_keys {
1.364 www 2831: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2832: $cdom=
1.620 albertel 2833: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2834: $cnum=
1.620 albertel 2835: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2836: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2837: unless (($cdom) && ($cnum)) { return 0; }
2838: if ($number>10000) { return 0; }
2839: sleep(2); # make sure don't get same seed twice
2840: srand(time()^($$+($$<<15))); # from "Programming Perl"
2841: my $total=0;
2842: for (my $i=1;$i<=$number;$i++) {
2843: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2844: sprintf("%lx",int(100000*rand)).'-'.
2845: sprintf("%lx",int(100000*rand));
2846: $newkey=~s/1/g/g; # folks mix up 1 and l
2847: $newkey=~s/0/h/g; # and also 0 and O
2848: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2849: if ($existing{$newkey}) {
2850: $i--;
2851: } else {
1.364 www 2852: if (&put('accesskeys',
2853: { $newkey => '# generated '.localtime().
1.620 albertel 2854: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2855: '; '.$logentry },
2856: $cdom,$cnum) eq 'ok') {
1.344 www 2857: $total++;
2858: }
2859: }
2860: }
1.620 albertel 2861: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2862: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2863: return $total;
2864: }
2865:
2866: # ------------------------------------------------------- Validate an accesskey
2867:
2868: sub validate_access_key {
2869: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2870: $cdom=
1.620 albertel 2871: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2872: $cnum=
1.620 albertel 2873: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2874: $udom=$env{'user.domain'} unless (defined($udom));
2875: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2876: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2877: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2878: }
2879:
2880: # ------------------------------------- Find the section of student in a course
1.652 albertel 2881: sub devalidate_getsection_cache {
2882: my ($udom,$unam,$courseid)=@_;
2883: my $hashid="$udom:$unam:$courseid";
2884: &devalidate_cache_new('getsection',$hashid);
2885: }
1.298 matthew 2886:
1.815 albertel 2887: sub courseid_to_courseurl {
2888: my ($courseid) = @_;
2889: #already url style courseid
2890: return $courseid if ($courseid =~ m{^/});
2891:
2892: if (exists($env{'course.'.$courseid.'.num'})) {
2893: my $cnum = $env{'course.'.$courseid.'.num'};
2894: my $cdom = $env{'course.'.$courseid.'.domain'};
2895: return "/$cdom/$cnum";
2896: }
2897:
2898: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2899: if (exists($courseinfo{'num'})) {
2900: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2901: }
2902:
2903: return undef;
2904: }
2905:
1.298 matthew 2906: sub getsection {
2907: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2908: my $cachetime=1800;
1.551 albertel 2909:
2910: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2911: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2912: if (defined($cached)) { return $result; }
2913:
1.298 matthew 2914: my %Pending;
2915: my %Expired;
2916: #
2917: # Each role can either have not started yet (pending), be active,
2918: # or have expired.
2919: #
2920: # If there is an active role, we are done.
2921: #
2922: # If there is more than one role which has not started yet,
2923: # choose the one which will start sooner
2924: # If there is one role which has not started yet, return it.
2925: #
2926: # If there is more than one expired role, choose the one which ended last.
2927: # If there is a role which has expired, return it.
2928: #
1.815 albertel 2929: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2930: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2931: foreach my $key (keys(%roleshash)) {
1.479 albertel 2932: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2933: my $section=$1;
2934: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2935: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2936: my $now=time;
1.548 albertel 2937: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2938: $Expired{$end}=$section;
2939: next;
2940: }
1.548 albertel 2941: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2942: $Pending{$start}=$section;
2943: next;
2944: }
1.599 albertel 2945: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2946: }
2947: #
2948: # Presumedly there will be few matching roles from the above
2949: # loop and the sorting time will be negligible.
2950: if (scalar(keys(%Pending))) {
2951: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2952: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2953: }
2954: if (scalar(keys(%Expired))) {
2955: my @sorted = sort {$a <=> $b} keys(%Expired);
2956: my $time = pop(@sorted);
1.599 albertel 2957: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2958: }
1.599 albertel 2959: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2960: }
1.70 www 2961:
1.599 albertel 2962: sub save_cache {
2963: &purge_remembered();
1.722 albertel 2964: #&Apache::loncommon::validate_page();
1.620 albertel 2965: undef(%env);
1.780 albertel 2966: undef($env_loaded);
1.599 albertel 2967: }
1.452 albertel 2968:
1.599 albertel 2969: my $to_remember=-1;
2970: my %remembered;
2971: my %accessed;
2972: my $kicks=0;
2973: my $hits=0;
1.849 albertel 2974: sub make_key {
2975: my ($name,$id) = @_;
1.872 albertel 2976: if (length($id) > 65
2977: && length(&escape($id)) > 200) {
2978: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2979: }
1.849 albertel 2980: return &escape($name.':'.$id);
2981: }
2982:
1.599 albertel 2983: sub devalidate_cache_new {
2984: my ($name,$id,$debug) = @_;
2985: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 2986: my $remembered_id=$name.':'.$id;
1.849 albertel 2987: $id=&make_key($name,$id);
1.599 albertel 2988: $memcache->delete($id);
1.1319 damieng 2989: delete($remembered{$remembered_id});
2990: delete($accessed{$remembered_id});
1.599 albertel 2991: }
2992:
2993: sub is_cached_new {
2994: my ($name,$id,$debug) = @_;
1.1319 damieng 2995: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
2996: if (exists($remembered{$remembered_id})) {
2997: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2998: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2999: $hits++;
1.1319 damieng 3000: return ($remembered{$remembered_id},1);
1.599 albertel 3001: }
1.1319 damieng 3002: $id=&make_key($name,$id);
1.599 albertel 3003: my $value = $memcache->get($id);
3004: if (!(defined($value))) {
3005: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 3006: return (undef,undef);
1.416 albertel 3007: }
1.599 albertel 3008: if ($value eq '__undef__') {
3009: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3010: $value=undef;
3011: }
1.1319 damieng 3012: &make_room($remembered_id,$value,$debug);
1.599 albertel 3013: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3014: return ($value,1);
3015: }
3016:
3017: sub do_cache_new {
3018: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 3019: my $remembered_id=$name.':'.$id;
1.849 albertel 3020: $id=&make_key($name,$id);
1.599 albertel 3021: my $setvalue=$value;
3022: if (!defined($setvalue)) {
3023: $setvalue='__undef__';
3024: }
1.623 albertel 3025: if (!defined($time) ) {
3026: $time=600;
3027: }
1.599 albertel 3028: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 3029: my $result = $memcache->set($id,$setvalue,$time);
3030: if (! $result) {
1.872 albertel 3031: &logthis("caching of id -> $id failed");
1.910 albertel 3032: $memcache->disconnect_all();
1.872 albertel 3033: }
1.600 albertel 3034: # need to make a copy of $value
1.1319 damieng 3035: &make_room($remembered_id,$value,$debug);
1.599 albertel 3036: return $value;
3037: }
3038:
3039: sub make_room {
1.1319 damieng 3040: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 3041:
1.1319 damieng 3042: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 3043: : $value;
1.599 albertel 3044: if ($to_remember<0) { return; }
1.1319 damieng 3045: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3046: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3047: my $to_kick;
3048: my $max_time=0;
3049: foreach my $other (keys(%accessed)) {
3050: if (&tv_interval($accessed{$other}) > $max_time) {
3051: $to_kick=$other;
3052: $max_time=&tv_interval($accessed{$other});
3053: }
3054: }
3055: delete($remembered{$to_kick});
3056: delete($accessed{$to_kick});
3057: $kicks++;
3058: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 3059: return;
3060: }
3061:
1.599 albertel 3062: sub purge_remembered {
1.604 albertel 3063: #&logthis("Tossing ".scalar(keys(%remembered)));
3064: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 3065: undef(%remembered);
3066: undef(%accessed);
1.428 albertel 3067: }
1.70 www 3068: # ------------------------------------- Read an entry from a user's environment
3069:
3070: sub userenvironment {
3071: my ($udom,$unam,@what)=@_;
1.976 raeburn 3072: my $items;
3073: foreach my $item (@what) {
3074: $items.=&escape($item).'&';
3075: }
3076: $items=~s/\&$//;
1.70 www 3077: my %returnhash=();
1.1009 raeburn 3078: my $uhome = &homeserver($unam,$udom);
3079: unless ($uhome eq 'no_host') {
3080: my @answer=split(/\&/,
3081: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 3082: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3083: return %returnhash;
3084: }
1.1009 raeburn 3085: my $i;
3086: for ($i=0;$i<=$#what;$i++) {
3087: $returnhash{$what[$i]}=&unescape($answer[$i]);
3088: }
1.70 www 3089: }
3090: return %returnhash;
1.1 albertel 3091: }
3092:
1.617 albertel 3093: # ---------------------------------------------------------- Get a studentphoto
3094: sub studentphoto {
3095: my ($udom,$unam,$ext) = @_;
3096: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 3097: if (defined($env{'request.course.id'})) {
1.708 raeburn 3098: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 3099: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3100: return(&retrievestudentphoto($udom,$unam,$ext));
3101: } else {
3102: my ($result,$perm_reqd)=
1.707 albertel 3103: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 3104: if ($result eq 'ok') {
3105: if (!($perm_reqd eq 'yes')) {
3106: return(&retrievestudentphoto($udom,$unam,$ext));
3107: }
3108: }
3109: }
3110: }
3111: } else {
3112: my ($result,$perm_reqd) =
1.707 albertel 3113: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 3114: if ($result eq 'ok') {
3115: if (!($perm_reqd eq 'yes')) {
3116: return(&retrievestudentphoto($udom,$unam,$ext));
3117: }
3118: }
3119: }
3120: return '/adm/lonKaputt/lonlogo_broken.gif';
3121: }
3122:
3123: sub retrievestudentphoto {
3124: my ($udom,$unam,$ext,$type) = @_;
3125: my $home=&Apache::lonnet::homeserver($unam,$udom);
3126: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
3127: if ($ret eq 'ok') {
3128: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3129: if ($type eq 'thumbnail') {
3130: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3131: }
3132: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
3133: return $tokenurl;
3134: } else {
3135: if ($type eq 'thumbnail') {
3136: return '/adm/lonKaputt/genericstudent_tn.gif';
3137: } else {
3138: return '/adm/lonKaputt/lonlogo_broken.gif';
3139: }
1.617 albertel 3140: }
3141: }
3142:
1.263 www 3143: # -------------------------------------------------------------------- New chat
3144:
3145: sub chatsend {
1.724 raeburn 3146: my ($newentry,$anon,$group)=@_;
1.620 albertel 3147: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3148: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3149: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 3150: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 3151: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 3152: &escape($newentry)).':'.$group,$chome);
1.292 www 3153: }
3154:
3155: # ------------------------------------------ Find current version of a resource
3156:
3157: sub getversion {
3158: my $fname=&clutter(shift);
1.1189 raeburn 3159: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3160: return ¤tversion(&filelocation('',$fname));
3161: }
3162:
3163: sub currentversion {
3164: my $fname=shift;
3165: my $author=$fname;
3166: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3167: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3168: my $home=&homeserver($uname,$udom);
1.292 www 3169: if ($home eq 'no_host') {
3170: return -1;
3171: }
1.1112 www 3172: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3173: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3174: return -1;
3175: }
1.1112 www 3176: return $answer;
1.263 www 3177: }
3178:
1.1111 www 3179: #
3180: # Return special version number of resource if set by override, empty otherwise
3181: #
3182: sub usedversion {
3183: my $fname=shift;
3184: unless ($fname) { $fname=$env{'request.uri'}; }
3185: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3186: if ($urlversion) { return $urlversion; }
3187: return '';
3188: }
3189:
1.1 albertel 3190: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3191:
1.1 albertel 3192: sub subscribe {
3193: my $fname=shift;
1.761 raeburn 3194: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3195: $fname=~s/[\n\r]//g;
1.1 albertel 3196: my $author=$fname;
3197: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3198: my ($udom,$uname)=split(/\//,$author);
3199: my $home=homeserver($uname,$udom);
1.335 albertel 3200: if ($home eq 'no_host') {
3201: return 'not_found';
1.1 albertel 3202: }
3203: my $answer=reply("sub:$fname",$home);
1.64 www 3204: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3205: $answer.=' by '.$home;
3206: }
1.1 albertel 3207: return $answer;
3208: }
3209:
1.8 www 3210: # -------------------------------------------------------------- Replicate file
3211:
3212: sub repcopy {
3213: my $filename=shift;
1.23 www 3214: $filename=~s/\/+/\//g;
1.1142 raeburn 3215: my $londocroot = $perlvar{'lonDocRoot'};
3216: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3217: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3218: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3219: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3220: return &repcopy_userfile($filename);
3221: }
1.532 albertel 3222: $filename=~s/[\n\r]//g;
1.8 www 3223: my $transname="$filename.in.transfer";
1.828 www 3224: # FIXME: this should flock
1.607 raeburn 3225: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3226: my $remoteurl=subscribe($filename);
1.64 www 3227: if ($remoteurl =~ /^con_lost by/) {
3228: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3229: return 'unavailable';
1.8 www 3230: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3231: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3232: return 'not_found';
1.64 www 3233: } elsif ($remoteurl =~ /^rejected by/) {
3234: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3235: return 'forbidden';
1.20 www 3236: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3237: return 'ok';
1.8 www 3238: } else {
1.290 www 3239: my $author=$filename;
3240: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3241: my ($udom,$uname)=split(/\//,$author);
3242: my $home=homeserver($uname,$udom);
3243: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3244: my @parts=split(/\//,$filename);
3245: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3246: if ($path ne "$londocroot/res") {
1.8 www 3247: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3248: return 'bad_request';
1.8 www 3249: }
3250: my $count;
3251: for ($count=5;$count<$#parts;$count++) {
3252: $path.="/$parts[$count]";
3253: if ((-e $path)!=1) {
3254: mkdir($path,0777);
3255: }
3256: }
3257: my $request=new HTTP::Request('GET',"$remoteurl");
1.1345 raeburn 3258: my $response;
3259: if ($remoteurl =~ m{/raw/}) {
3260: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3261: } else {
3262: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3263: }
1.8 www 3264: if ($response->is_error()) {
3265: unlink($transname);
3266: my $message=$response->status_line;
1.672 albertel 3267: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3268: ." LWP get: $message: $filename</font>");
1.607 raeburn 3269: return 'unavailable';
1.8 www 3270: } else {
1.16 www 3271: if ($remoteurl!~/\.meta$/) {
3272: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345 raeburn 3273: my $mresponse;
3274: if ($remoteurl =~ m{/raw/}) {
3275: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3276: } else {
3277: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3278: }
1.16 www 3279: if ($mresponse->is_error()) {
3280: unlink($filename.'.meta');
3281: &logthis(
1.672 albertel 3282: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3283: }
3284: }
1.8 www 3285: rename($transname,$filename);
1.607 raeburn 3286: return 'ok';
1.8 www 3287: }
1.290 www 3288: }
1.8 www 3289: }
1.330 www 3290: }
3291:
3292: # ------------------------------------------------ Get server side include body
3293: sub ssi_body {
1.381 albertel 3294: my ($filelink,%form)=@_;
1.606 matthew 3295: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3296: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3297: }
1.953 www 3298: my $output='';
3299: my $response;
1.980 raeburn 3300: if ($filelink=~/^https?\:/) {
1.954 raeburn 3301: ($output,$response)=&externalssi($filelink);
1.953 www 3302: } else {
1.1004 droeschl 3303: $filelink .= $filelink=~/\?/ ? '&' : '?';
3304: $filelink .= 'inhibitmenu=yes';
1.953 www 3305: ($output,$response)=&ssi($filelink,%form);
3306: }
1.778 albertel 3307: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3308: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3309: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3310: if (wantarray) {
3311: return ($output, $response);
3312: } else {
3313: return $output;
3314: }
1.8 www 3315: }
3316:
1.15 www 3317: # --------------------------------------------------------- Server Side Include
3318:
1.782 albertel 3319: sub absolute_url {
3320: my ($host_name) = @_;
3321: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3322: if ($host_name eq '') {
3323: $host_name = $ENV{'SERVER_NAME'};
3324: }
3325: return $protocol.$host_name;
3326: }
3327:
1.942 foxr 3328: #
3329: # Server side include.
3330: # Parameters:
3331: # fn Possibly encrypted resource name/id.
3332: # form Hash that describes how the rendering should be done
3333: # and other things.
1.944 foxr 3334: # Returns:
1.950 raeburn 3335: # Scalar context: The content of the response.
3336: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3337: #
1.15 www 3338: sub ssi {
3339:
1.944 foxr 3340: my ($fn,%form)=@_;
1.23 www 3341: my $request;
1.711 albertel 3342:
3343: $form{'no_update_last_known'}=1;
1.895 albertel 3344: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3345: if (%form) {
1.782 albertel 3346: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 3347: $request->content(join('&',map {
3348: my $name = escape($_);
3349: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3350: ? join("&$name=", map {escape($_) } @{$form{$_}})
3351: : &escape($form{$_}) );
3352: } keys(%form)));
1.23 www 3353: } else {
1.782 albertel 3354: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3355: }
3356:
1.15 www 3357: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345 raeburn 3358: my $lonhost = $perlvar{'lonHostID'};
1.1385 raeburn 3359: my $islocal;
3360: if (($env{'request.course.id'}) &&
3361: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3362: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3363: ($form{'grade_symb'} ne '') &&
3364: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3365: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
3366: $islocal = 1;
3367: }
1.1384 raeburn 3368: my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385 raeburn 3369: '','','',$islocal);
1.1182 foxr 3370:
1.944 foxr 3371: if (wantarray) {
1.1345 raeburn 3372: return ($response->content, $response);
1.944 foxr 3373: } else {
1.1345 raeburn 3374: return $response->content;
1.942 foxr 3375: }
1.324 www 3376: }
3377:
3378: sub externalssi {
3379: my ($url)=@_;
3380: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 3381: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954 raeburn 3382: if (wantarray) {
3383: return ($response->content, $response);
3384: } else {
3385: return $response->content;
3386: }
1.15 www 3387: }
1.254 www 3388:
1.1354 raeburn 3389:
3390: # If the local copy of a replicated resource is outdated, trigger a
3391: # connection from the homeserver to flush the delayed queue. If no update
3392: # happens, remove local copies of outdated resource (and corresponding
3393: # metadata file).
3394:
1.1352 raeburn 3395: sub remove_stale_resfile {
3396: my ($url) = @_;
1.1354 raeburn 3397: my $removed;
1.1352 raeburn 3398: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3399: my $audom = $1;
3400: my $auname = $2;
1.1353 raeburn 3401: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352 raeburn 3402: my $homeserver = &homeserver($auname,$audom);
3403: unless (($homeserver eq 'no_host') ||
3404: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3405: my $fname = &filelocation('',$url);
3406: if (-e $fname) {
3407: my $hostname = &hostname($homeserver);
3408: if ($hostname) {
1.1397 raeburn 3409: my $protocol = $protocol{$homeserver};
3410: $protocol = 'http' if ($protocol ne 'https');
1.1352 raeburn 3411: my $uri = &declutter($url);
3412: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3413: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3414: if ($response->is_success()) {
3415: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3416: my $locmodtime = (stat($fname))[9];
3417: if ($locmodtime < $remmodtime) {
1.1354 raeburn 3418: my $stale;
3419: my $answer = &reply('pong',$homeserver);
3420: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3421: sleep(0.2);
3422: $locmodtime = (stat($fname))[9];
3423: if ($locmodtime < $remmodtime) {
3424: my $posstransfer = $fname.'.in.transfer';
3425: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3426: $removed = 1;
3427: } else {
3428: $stale = 1;
3429: }
3430: } else {
3431: $removed = 1;
3432: }
3433: } else {
3434: $stale = 1;
3435: }
3436: if ($stale) {
3437: unlink($fname);
3438: if ($uri!~/\.meta$/) {
3439: unlink($fname.'.meta');
3440: }
3441: &reply("unsub:$fname",$homeserver);
3442: $removed = 1;
1.1352 raeburn 3443: }
3444: }
3445: }
3446: }
3447: }
3448: }
3449: }
3450: }
1.1354 raeburn 3451: return $removed;
1.1352 raeburn 3452: }
3453:
1.492 albertel 3454: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3455:
3456: sub allowuploaded {
3457: my ($srcurl,$url)=@_;
3458: $url=&clutter(&declutter($url));
3459: my $dir=$url;
3460: $dir=~s/\/[^\/]+$//;
3461: my %httpref=();
3462: my $httpurl=&hreflocation('',$url);
3463: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3464: &Apache::lonnet::appenv(\%httpref);
1.254 www 3465: }
1.477 raeburn 3466:
1.1193 raeburn 3467: #
3468: # Determine if the current user should be able to edit a particular resource,
3469: # when viewing in course context.
3470: # (a) When viewing resource used to determine if "Edit" item is included in
3471: # Functions.
3472: # (b) When displaying folder contents in course editor, used to determine if
3473: # "Edit" link will be displayed alongside resource.
3474: #
1.1196 raeburn 3475: # input: six args -- filename (decluttered), course number, course domain,
3476: # url, symb (if registered) and group (if this is a group
3477: # item -- e.g., bulletin board, group page etc.).
3478: # output: array of five scalars --
1.1193 raeburn 3479: # $cfile -- url for file editing if editable on current server
3480: # $home -- homeserver of resource (i.e., for author if published,
3481: # or course if uploaded.).
3482: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3483: # $forceedit -- 1 if icon/link should be to go to edit mode
3484: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3485: #
3486:
3487: sub can_edit_resource {
1.1194 raeburn 3488: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3489: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3490: #
3491: # For aboutme pages user can only edit his/her own.
3492: #
1.1199 raeburn 3493: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3494: my ($sdom,$sname) = ($1,$2);
3495: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3496: $home = $env{'user.home'};
3497: $cfile = $resurl;
3498: if ($env{'form.forceedit'}) {
3499: $forceview = 1;
3500: } else {
3501: $forceedit = 1;
3502: }
3503: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3504: } else {
3505: return;
3506: }
3507: }
3508:
3509: if ($env{'request.course.id'}) {
3510: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3511: if ($group ne '') {
3512: # if this is a group homepage or group bulletin board, check group privs
3513: my $allowed = 0;
1.1197 raeburn 3514: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3515: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3516: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3517: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3518: $allowed = 1;
3519: }
1.1197 raeburn 3520: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3521: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3522: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3523: $allowed = 1;
3524: }
3525: }
3526: if ($allowed) {
3527: $home=&homeserver($cnum,$cdom);
3528: if ($env{'form.forceedit'}) {
3529: $forceview = 1;
3530: } else {
3531: $forceedit = 1;
3532: }
3533: $cfile = $resurl;
3534: } else {
3535: return;
3536: }
3537: } else {
1.1208 raeburn 3538: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3539: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3540: return;
3541: }
3542: } elsif (!$crsedit) {
1.1194 raeburn 3543: #
3544: # No edit allowed where CC has switched to student role.
3545: #
3546: return;
3547: }
3548: }
3549: }
3550:
1.1193 raeburn 3551: if ($file ne '') {
3552: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3553: if (&is_course_upload($file,$cnum,$cdom)) {
3554: $uploaded = 1;
3555: $incourse = 1;
1.1193 raeburn 3556: if ($file =~/\.(htm|html|css|js|txt)$/) {
3557: $cfile = &hreflocation('',$file);
1.1201 raeburn 3558: if ($env{'form.forceedit'}) {
3559: $forceview = 1;
3560: } else {
3561: $forceedit = 1;
3562: }
1.1194 raeburn 3563: }
3564: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3565: $incourse = 1;
3566: if ($env{'form.forceedit'}) {
3567: $forceview = 1;
3568: } else {
3569: $forceedit = 1;
3570: }
3571: $cfile = $resurl;
3572: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3573: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3574: $incourse = 1;
3575: if ($env{'form.forceedit'}) {
3576: $forceview = 1;
3577: } else {
3578: $forceedit = 1;
3579: }
3580: $cfile = $resurl;
1.1199 raeburn 3581: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3582: $incourse = 1;
3583: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3584: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3585: $incourse = 1;
1.1199 raeburn 3586: if ($env{'form.forceedit'}) {
3587: $forceview = 1;
3588: } else {
3589: $forceedit = 1;
3590: }
3591: $cfile = $resurl;
1.1343 raeburn 3592: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3593: $incourse = 1;
3594: if ($env{'form.forceedit'}) {
3595: $forceview = 1;
3596: } else {
3597: $forceedit = 1;
3598: }
3599: $cfile = $resurl;
1.1208 raeburn 3600: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3601: $incourse = 1;
3602: if ($env{'form.forceedit'}) {
3603: $forceview = 1;
3604: } else {
3605: $forceedit = 1;
3606: }
3607: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3608: }
3609: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3610: my $template = '/res/lib/templates/simpleproblem.problem';
3611: if (&is_on_map($template)) {
3612: $incourse = 1;
3613: $forceview = 1;
3614: $cfile = $template;
1.1193 raeburn 3615: }
1.1199 raeburn 3616: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3617: $incourse = 1;
3618: if ($env{'form.forceedit'}) {
3619: $forceview = 1;
3620: } else {
3621: $forceedit = 1;
3622: }
3623: $cfile = $resurl;
1.1343 raeburn 3624: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298 raeburn 3625: $incourse = 1;
3626: if ($env{'form.forceedit'}) {
3627: $forceview = 1;
3628: } else {
3629: $forceedit = 1;
3630: }
3631: $cfile = $resurl;
1.1199 raeburn 3632: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3633: $incourse = 1;
3634: $forceview = 1;
3635: if ($symb) {
3636: my ($map,$id,$res)=&decode_symb($symb);
3637: $env{'request.symb'} = $symb;
3638: $cfile = &clutter($res);
3639: } else {
3640: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3641: my $escfile = &unescape($cfile);
1.1343 raeburn 3642: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3643: $cfile = '/adm/wrapper'.$escfile;
3644: } else {
3645: $escfile =~ s{^http://}{};
3646: $cfile = &escape("/adm/wrapper/ext/$escfile");
3647: }
1.1199 raeburn 3648: }
1.1234 raeburn 3649: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3650: if ($env{'form.forceedit'}) {
3651: $forceview = 1;
3652: } else {
3653: $forceedit = 1;
3654: }
3655: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3656: }
3657: }
1.1194 raeburn 3658: if ($uploaded || $incourse) {
3659: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3660: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3661: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3662: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3663: # Check that the user has permission to edit this resource
3664: my $setpriv = 1;
3665: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3666: if (defined($cfudom)) {
3667: $home=&homeserver($cfuname,$cfudom);
3668: $cfile=$file;
3669: }
3670: }
1.1194 raeburn 3671: if (($cfile ne '') && (!$incourse || $uploaded) &&
3672: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3673: my @ids=¤t_machine_ids();
3674: unless (grep(/^\Q$home\E$/,@ids)) {
3675: $switchserver=1;
3676: }
3677: }
3678: }
1.1194 raeburn 3679: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3680: }
3681:
3682: sub is_course_upload {
3683: my ($file,$cnum,$cdom) = @_;
3684: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3685: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3686: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3687: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3688: return 1;
3689: }
3690: return;
3691: }
3692:
1.1194 raeburn 3693: sub in_course {
1.1195 raeburn 3694: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3695: if ($hideprivileged) {
3696: my $skipuser;
1.1219 raeburn 3697: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3698: my @possdoms = ($cdom);
3699: if ($coursehash{'checkforpriv'}) {
3700: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3701: }
3702: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3703: $skipuser = 1;
3704: if ($coursehash{'nothideprivileged'}) {
3705: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3706: my $user;
3707: if ($item =~ /:/) {
3708: $user = $item;
3709: } else {
3710: $user = join(':',split(/[\@]/,$item));
3711: }
3712: if ($user eq $uname.':'.$udom) {
3713: undef($skipuser);
3714: last;
3715: }
3716: }
3717: }
3718: if ($skipuser) {
3719: return 0;
3720: }
3721: }
3722: }
1.1194 raeburn 3723: $type ||= 'any';
3724: if (!defined($cdom) || !defined($cnum)) {
3725: my $cid = $env{'request.course.id'};
3726: $cdom = $env{'course.'.$cid.'.domain'};
3727: $cnum = $env{'course.'.$cid.'.num'};
3728: }
3729: my $typesref;
1.1195 raeburn 3730: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3731: $typesref = ['active','previous','future'];
3732: } elsif ($type eq 'previous' || $type eq 'future') {
3733: $typesref = [$type];
3734: }
3735: my %roles = &get_my_roles($uname,$udom,'userroles',
3736: $typesref,undef,[$cdom]);
3737: my ($tmp) = keys(%roles);
3738: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3739: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3740: if (@course_roles > 0) {
3741: return 1;
3742: }
3743: return 0;
3744: }
3745:
1.478 albertel 3746: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3747: # input: action, courseID, current domain, intended
1.637 raeburn 3748: # path to file, source of file, instruction to parse file for objects,
3749: # ref to hash for embedded objects,
3750: # ref to hash for codebase of java objects.
1.1095 raeburn 3751: # reference to scalar to accommodate mime type determined
3752: # from File::MMagic if $parser = parse.
1.637 raeburn 3753: #
1.485 raeburn 3754: # output: url to file (if action was uploaddoc),
3755: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3756: #
1.478 albertel 3757: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3758: # course.
1.477 raeburn 3759: #
1.478 albertel 3760: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3761: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3762: # course's home server.
1.477 raeburn 3763: #
1.478 albertel 3764: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3765: # be copied from $source (current location) to
3766: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3767: # and will then be copied to
3768: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3769: # course's home server.
1.485 raeburn 3770: #
1.481 raeburn 3771: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3772: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3773: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3774: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3775: # in course's home server.
1.637 raeburn 3776: #
1.477 raeburn 3777:
3778: sub process_coursefile {
1.1095 raeburn 3779: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3780: $mimetype)=@_;
1.477 raeburn 3781: my $fetchresult;
1.638 albertel 3782: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3783: if ($action eq 'propagate') {
1.638 albertel 3784: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3785: $home);
1.481 raeburn 3786: } else {
1.477 raeburn 3787: my $fpath = '';
3788: my $fname = $file;
1.478 albertel 3789: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3790: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3791: my $filepath = &build_filepath($fpath);
1.481 raeburn 3792: if ($action eq 'copy') {
3793: if ($source eq '') {
3794: $fetchresult = 'no source file';
3795: return $fetchresult;
3796: } else {
3797: my $destination = $filepath.'/'.$fname;
3798: rename($source,$destination);
3799: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3800: $home);
1.481 raeburn 3801: }
3802: } elsif ($action eq 'uploaddoc') {
1.1359 raeburn 3803: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3804: print $fh $env{'form.'.$source};
1.481 raeburn 3805: close($fh);
1.637 raeburn 3806: if ($parser eq 'parse') {
1.1024 raeburn 3807: my $mm = new File::MMagic;
1.1095 raeburn 3808: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3809: if ($type eq 'text/html') {
1.1024 raeburn 3810: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3811: unless ($parse_result eq 'ok') {
3812: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3813: }
1.637 raeburn 3814: }
1.1095 raeburn 3815: if (ref($mimetype)) {
3816: $$mimetype = $type;
3817: }
1.637 raeburn 3818: }
1.477 raeburn 3819: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3820: $home);
1.481 raeburn 3821: if ($fetchresult eq 'ok') {
3822: return '/uploaded/'.$fpath.'/'.$fname;
3823: } else {
3824: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3825: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3826: return '/adm/notfound.html';
3827: }
1.477 raeburn 3828: }
3829: }
1.485 raeburn 3830: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3831: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3832: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3833: }
3834: return $fetchresult;
3835: }
3836:
1.637 raeburn 3837: sub build_filepath {
3838: my ($fpath) = @_;
3839: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3840: unless ($fpath eq '') {
3841: my @parts=split('/',$fpath);
3842: foreach my $part (@parts) {
3843: $filepath.= '/'.$part;
3844: if ((-e $filepath)!=1) {
3845: mkdir($filepath,0777);
3846: }
3847: }
3848: }
3849: return $filepath;
3850: }
3851:
3852: sub store_edited_file {
1.638 albertel 3853: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3854: my $file = $primary_url;
3855: $file =~ s#^/uploaded/$docudom/$docuname/##;
3856: my $fpath = '';
3857: my $fname = $file;
3858: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3859: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3860: my $filepath = &build_filepath($fpath);
1.1359 raeburn 3861: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3862: print $fh $content;
3863: close($fh);
1.638 albertel 3864: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3865: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3866: $home);
1.637 raeburn 3867: if ($$fetchresult eq 'ok') {
3868: return '/uploaded/'.$fpath.'/'.$fname;
3869: } else {
1.638 albertel 3870: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3871: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3872: return '/adm/notfound.html';
3873: }
3874: }
3875:
1.531 albertel 3876: sub clean_filename {
1.831 albertel 3877: my ($fname,$args)=@_;
1.315 www 3878: # Replace Windows backslashes by forward slashes
1.257 www 3879: $fname=~s/\\/\//g;
1.831 albertel 3880: if (!$args->{'keep_path'}) {
3881: # Get rid of everything but the actual filename
3882: $fname=~s/^.*\/([^\/]+)$/$1/;
3883: }
1.315 www 3884: # Replace spaces by underscores
3885: $fname=~s/\s+/\_/g;
1.1406 raeburn 3886: # Transliterate non-ascii text to ascii
3887: my $lang = &Apache::lonlocal::current_language();
3888: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 3889: # Replace all other weird characters by nothing
1.831 albertel 3890: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3891: # Replace all .\d. sequences with _\d. so they no longer look like version
3892: # numbers
3893: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3894: return $fname;
3895: }
1.1406 raeburn 3896:
1.1051 raeburn 3897: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3898: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3899: # image with the same aspect ratio as the original, but with dimensions which do
3900: # not exceed $resizewidth and $resizeheight.
3901:
1.984 neumanie 3902: sub resizeImage {
1.1051 raeburn 3903: my ($img_path,$resizewidth,$resizeheight) = @_;
3904: my $ima = Image::Magick->new;
3905: my $resized;
3906: if (-e $img_path) {
3907: $ima->Read($img_path);
3908: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3909: my $width = $ima->Get('width');
3910: my $height = $ima->Get('height');
3911: if ($width > $resizewidth) {
3912: my $factor = $width/$resizewidth;
3913: my $newheight = $height/$factor;
3914: $ima->Scale(width=>$resizewidth,height=>$newheight);
3915: $resized = 1;
3916: }
3917: }
3918: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3919: my $width = $ima->Get('width');
3920: my $height = $ima->Get('height');
3921: if ($height > $resizeheight) {
3922: my $factor = $height/$resizeheight;
3923: my $newwidth = $width/$factor;
3924: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3925: $resized = 1;
3926: }
3927: }
3928: if ($resized) {
3929: $ima->Write($img_path);
3930: }
3931: }
3932: return;
1.977 amueller 3933: }
3934:
1.608 albertel 3935: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3936: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3937: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3938: # $context - possible values: coursedoc, existingfile, overwrite,
1.1401 raeburn 3939: # canceloverwrite, scantron or ''.
1.1090 raeburn 3940: # if 'coursedoc': upload to the current course
3941: # if 'existingfile': write file to tmp/overwrites directory
3942: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3943: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3944: # $subdir - directory in userfile to store the file into
1.1401 raeburn 3945: # $parser - instruction to parse file for objects ($parser = parse) or
3946: # if context is 'scantron', $parser is hashref of csv column mapping
3947: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
3948: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 3949: # $allfiles - reference to hash for embedded objects
3950: # $codebase - reference to hash for codebase of java objects
3951: # $desuname - username for permanent storage of uploaded file
3952: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3953: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3954: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3955: # $resizewidth - width (pixels) to which to resize uploaded image
3956: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3957: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3958: # from File::MMagic.
1.858 raeburn 3959: #
1.686 albertel 3960: # output: url of file in userspace, or error: <message>
3961: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3962:
1.531 albertel 3963: sub userfileupload {
1.1090 raeburn 3964: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3965: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3966: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3967: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3968: $fname=&clean_filename($fname);
1.1090 raeburn 3969: # See if there is anything left
1.257 www 3970: unless ($fname) { return 'error: no uploaded file'; }
1.1406 raeburn 3971: # If filename now begins with a . prepend unix timestamp _ milliseconds
3972: if ($fname =~ /^\./) {
3973: my ($s,$usec) = &gettimeofday();
3974: while (length($usec) < 6) {
3975: $usec = '0'.$usec;
3976: }
3977: $fname = $s.'_'.substr($usec,0,3).$fname;
3978: }
1.1090 raeburn 3979: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3980: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3981: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3982: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3983: my $now = time;
1.1090 raeburn 3984: my $filepath;
1.1095 raeburn 3985: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3986: $filepath = 'tmp/helprequests/'.$now;
3987: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3988: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3989: '_'.$env{'user.domain'}.'/pending';
3990: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3991: my ($docuname,$docudom);
1.1350 raeburn 3992: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3993: $docudom = $destudom;
3994: } else {
3995: $docudom = $env{'user.domain'};
3996: }
1.1350 raeburn 3997: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3998: $docuname = $destuname;
3999: } else {
4000: $docuname = $env{'user.name'};
4001: }
4002: if (exists($env{'form.group'})) {
4003: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4004: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4005: }
4006: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4007: if ($context eq 'canceloverwrite') {
4008: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4009: if (-e $tempfile) {
4010: my @info = stat($tempfile);
4011: if ($info[9] eq $env{'form.timestamp'}) {
4012: unlink($tempfile);
4013: }
4014: }
4015: return;
1.523 raeburn 4016: }
4017: }
1.1090 raeburn 4018: # Create the directory if not present
1.741 raeburn 4019: my @parts=split(/\//,$filepath);
4020: my $fullpath = $perlvar{'lonDaemons'};
4021: for (my $i=0;$i<@parts;$i++) {
4022: $fullpath .= '/'.$parts[$i];
4023: if ((-e $fullpath)!=1) {
4024: mkdir($fullpath,0777);
4025: }
4026: }
1.1359 raeburn 4027: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 4028: print $fh $env{'form.'.$formname};
4029: close($fh);
1.1090 raeburn 4030: if ($context eq 'existingfile') {
4031: my @info = stat($fullpath.'/'.$fname);
4032: return ($fullpath.'/'.$fname,$info[9]);
4033: } else {
4034: return $fullpath.'/'.$fname;
4035: }
1.523 raeburn 4036: }
1.995 raeburn 4037: if ($subdir eq 'scantron') {
4038: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 4039: } else {
1.995 raeburn 4040: $fname="$subdir/$fname";
4041: }
1.1090 raeburn 4042: if ($context eq 'coursedoc') {
1.638 albertel 4043: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4044: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 4045: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 4046: return &finishuserfileupload($docuname,$docudom,
4047: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 4048: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 4049: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 4050: } else {
1.1218 raeburn 4051: if ($env{'form.folder'}) {
4052: $fname=$env{'form.folder'}.'/'.$fname;
4053: }
1.638 albertel 4054: return &process_coursefile('uploaddoc',$docuname,$docudom,
4055: $fname,$formname,$parser,
1.1095 raeburn 4056: $allfiles,$codebase,$mimetype);
1.481 raeburn 4057: }
1.719 banghart 4058: } elsif (defined($destuname)) {
4059: my $docuname=$destuname;
4060: my $docudom=$destudom;
1.860 raeburn 4061: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4062: $parser,$allfiles,$codebase,
1.1051 raeburn 4063: $thumbwidth,$thumbheight,
1.1095 raeburn 4064: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4065: } else {
1.638 albertel 4066: my $docuname=$env{'user.name'};
4067: my $docudom=$env{'user.domain'};
1.1220 raeburn 4068: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 4069: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4070: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4071: }
1.860 raeburn 4072: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4073: $parser,$allfiles,$codebase,
1.1051 raeburn 4074: $thumbwidth,$thumbheight,
1.1095 raeburn 4075: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4076: }
1.271 www 4077: }
4078:
4079: sub finishuserfileupload {
1.860 raeburn 4080: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4081: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4082: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4083: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4084:
1.860 raeburn 4085: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4086: $file=$fname;
4087: if ($fname=~m|/|) {
4088: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4089: $path.=$fnamepath.'/';
4090: }
1.259 www 4091: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4092: my $count;
4093: for ($count=4;$count<=$#parts;$count++) {
4094: $filepath.="/$parts[$count]";
4095: if ((-e $filepath)!=1) {
4096: mkdir($filepath,0777);
4097: }
4098: }
1.984 neumanie 4099:
1.258 www 4100: # Save the file
4101: {
1.1359 raeburn 4102: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4103: &logthis('Failed to create '.$filepath.'/'.$file);
4104: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4105: return '/adm/notfound.html';
4106: }
1.1090 raeburn 4107: if ($context eq 'overwrite') {
1.1117 foxr 4108: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4109: my $target = $filepath.'/'.$file;
4110: if (-e $source) {
4111: my @info = stat($source);
4112: if ($info[9] eq $env{'form.timestamp'}) {
4113: unless (&File::Copy::move($source,$target)) {
4114: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4115: return "Moving from $source failed";
4116: }
4117: } else {
4118: return "Temporary file: $source had unexpected date/time for last modification";
4119: }
4120: } else {
4121: return "Temporary file: $source missing";
4122: }
4123: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4124: &logthis('Failed to write to '.$filepath.'/'.$file);
4125: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4126: return '/adm/notfound.html';
4127: }
1.570 albertel 4128: close(FH);
1.1051 raeburn 4129: if ($resizewidth && $resizeheight) {
4130: my $mm = new File::MMagic;
4131: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4132: if ($mime_type =~ m{^image/}) {
4133: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4134: }
1.977 amueller 4135: }
1.258 www 4136: }
1.1152 raeburn 4137: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4138: if (ref($mimetype)) {
4139: if ($$mimetype eq '') {
4140: my $mm = new File::MMagic;
4141: my $type = $mm->checktype_filename($filepath.'/'.$file);
4142: $$mimetype = $type;
4143: }
4144: }
4145: }
1.1401 raeburn 4146: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4147: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4148: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4149: $allfiles,$codebase);
4150: unless ($parse_result eq 'ok') {
4151: &logthis('Failed to parse '.$filepath.$file.
4152: ' for embedded media: '.$parse_result);
4153: }
1.637 raeburn 4154: }
1.1401 raeburn 4155: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4156: my $format = $env{'form.scantron_format'};
4157: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4158: }
1.860 raeburn 4159: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4160: my $input = $filepath.'/'.$file;
4161: my $output = $filepath.'/'.'tn-'.$file;
4162: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359 raeburn 4163: my @args = ('convert','-sample',$thumbsize,$input,$output);
4164: system({$args[0]} @args);
1.860 raeburn 4165: if (-e $filepath.'/'.'tn-'.$file) {
4166: $fetchthumb = 1;
4167: }
4168: }
1.858 raeburn 4169:
1.259 www 4170: # Notify homeserver to grep it
4171: #
1.984 neumanie 4172: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4173: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4174: if ($fetchresult eq 'ok') {
1.860 raeburn 4175: if ($fetchthumb) {
4176: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4177: if ($thumbresult ne 'ok') {
4178: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4179: $docuhome.': '.$thumbresult);
4180: }
4181: }
1.259 www 4182: #
1.258 www 4183: # Return the URL to it
1.494 albertel 4184: return '/uploaded/'.$path.$file;
1.263 www 4185: } else {
1.494 albertel 4186: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4187: ': '.$fetchresult);
1.263 www 4188: return '/adm/notfound.html';
1.858 raeburn 4189: }
1.493 albertel 4190: }
4191:
1.637 raeburn 4192: sub extract_embedded_items {
1.961 raeburn 4193: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4194: my @state = ();
1.1164 raeburn 4195: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4196: my %javafiles = (
4197: codebase => '',
4198: code => '',
4199: archive => ''
4200: );
4201: my %mediafiles = (
4202: src => '',
4203: movie => '',
4204: );
1.648 raeburn 4205: my $p;
4206: if ($content) {
4207: $p = HTML::LCParser->new($content);
4208: } else {
1.961 raeburn 4209: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4210: }
1.641 albertel 4211: while (my $t=$p->get_token()) {
1.640 albertel 4212: if ($t->[0] eq 'S') {
4213: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4214: push(@state, $tagname);
1.648 raeburn 4215: if (lc($tagname) eq 'allow') {
4216: &add_filetype($allfiles,$attr->{'src'},'src');
4217: }
1.640 albertel 4218: if (lc($tagname) eq 'img') {
4219: &add_filetype($allfiles,$attr->{'src'},'src');
4220: }
1.886 albertel 4221: if (lc($tagname) eq 'a') {
1.1222 raeburn 4222: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 4223: &add_filetype($allfiles,$attr->{'href'},'href');
4224: }
1.886 albertel 4225: }
1.645 raeburn 4226: if (lc($tagname) eq 'script') {
1.1164 raeburn 4227: my $src;
1.645 raeburn 4228: if ($attr->{'archive'} =~ /\.jar$/i) {
4229: &add_filetype($allfiles,$attr->{'archive'},'archive');
4230: } else {
1.1164 raeburn 4231: if ($attr->{'src'} ne '') {
4232: $src = $attr->{'src'};
4233: &add_filetype($allfiles,$src,'src');
4234: }
4235: }
4236: my $text = $p->get_trimmed_text();
4237: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4238: my @swfargs = split(/,/,$1);
4239: foreach my $item (@swfargs) {
4240: $item =~ s/["']//g;
4241: $item =~ s/^\s+//;
4242: $item =~ s/\s+$//;
4243: }
4244: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4245: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4246: push(@{$related{$swfargs[0]}},$swfargs[2]);
4247: } else {
4248: $related{$swfargs[0]} = [$swfargs[2]];
4249: }
4250: }
1.645 raeburn 4251: }
4252: }
4253: if (lc($tagname) eq 'link') {
4254: if (lc($attr->{'rel'}) eq 'stylesheet') {
4255: &add_filetype($allfiles,$attr->{'href'},'href');
4256: }
4257: }
1.640 albertel 4258: if (lc($tagname) eq 'object' ||
4259: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4260: foreach my $item (keys(%javafiles)) {
4261: $javafiles{$item} = '';
4262: }
1.1164 raeburn 4263: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4264: $lastids{lc($tagname)} = $attr->{'id'};
4265: }
1.640 albertel 4266: }
4267: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4268: my $name = lc($attr->{'name'});
4269: foreach my $item (keys(%javafiles)) {
4270: if ($name eq $item) {
4271: $javafiles{$item} = $attr->{'value'};
4272: last;
4273: }
4274: }
1.1164 raeburn 4275: my $pathfrom;
1.640 albertel 4276: foreach my $item (keys(%mediafiles)) {
4277: if ($name eq $item) {
1.1164 raeburn 4278: $pathfrom = $attr->{'value'};
4279: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4280: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4281: last;
4282: }
4283: }
1.1164 raeburn 4284: if ($name eq 'flashvars') {
4285: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4286: }
4287: if ($pathfrom ne '') {
4288: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4289: $pathfrom);
4290: }
1.640 albertel 4291: }
4292: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4293: foreach my $item (keys(%javafiles)) {
4294: if ($attr->{$item}) {
4295: $javafiles{$item} = $attr->{$item};
4296: last;
4297: }
4298: }
4299: foreach my $item (keys(%mediafiles)) {
4300: if ($attr->{$item}) {
4301: &add_filetype($allfiles,$attr->{$item},$item);
4302: last;
4303: }
4304: }
1.1164 raeburn 4305: if (lc($tagname) eq 'embed') {
4306: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4307: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4308: $attr->{'src'});
4309: }
4310: }
1.640 albertel 4311: }
1.1243 raeburn 4312: if (lc($tagname) eq 'iframe') {
4313: my $src = $attr->{'src'} ;
4314: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4315: &add_filetype($allfiles,$src,'src');
4316: } elsif ($src =~ m{^/}) {
4317: if ($env{'request.course.id'}) {
4318: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4319: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4320: my $url = &hreflocation('',$fullpath);
4321: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4322: my $relpath = $1;
4323: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4324: &add_filetype($allfiles,$1,'src');
4325: }
4326: }
4327: }
4328: }
4329: }
1.1164 raeburn 4330: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 4331: pop(@state);
1.1164 raeburn 4332: }
1.640 albertel 4333: } elsif ($t->[0] eq 'E') {
4334: my ($tagname) = ($t->[1]);
4335: if ($javafiles{'codebase'} ne '') {
4336: $javafiles{'codebase'} .= '/';
4337: }
4338: if (lc($tagname) eq 'applet' ||
4339: lc($tagname) eq 'object' ||
4340: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4341: ) {
4342: foreach my $item (keys(%javafiles)) {
4343: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4344: my $file=$javafiles{'codebase'}.$javafiles{$item};
4345: &add_filetype($allfiles,$file,$item);
4346: }
4347: }
4348: }
4349: pop @state;
4350: }
4351: }
1.1164 raeburn 4352: foreach my $id (sort(keys(%flashvars))) {
4353: if ($shockwave{$id} ne '') {
4354: my @pairs = split(/\&/,$flashvars{$id});
4355: foreach my $pair (@pairs) {
4356: my ($key,$value) = split(/\=/,$pair);
4357: if ($key eq 'thumb') {
4358: &add_filetype($allfiles,$value,$key);
4359: } elsif ($key eq 'content') {
4360: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4361: my ($ext) = ($value =~ /\.([^.]+)$/);
4362: if ($ext ne '') {
4363: &add_filetype($allfiles,$path.$value,$ext);
4364: }
4365: }
4366: }
4367: }
4368: }
1.637 raeburn 4369: return 'ok';
4370: }
4371:
1.639 albertel 4372: sub add_filetype {
4373: my ($allfiles,$file,$type)=@_;
4374: if (exists($allfiles->{$file})) {
4375: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4376: push(@{$allfiles->{$file}}, &escape($type));
4377: }
4378: } else {
4379: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4380: }
4381: }
4382:
1.1164 raeburn 4383: sub embedded_dependency {
4384: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4385: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4386: if (($identifier ne '') &&
4387: (ref($related->{$identifier}) eq 'ARRAY') &&
4388: ($pathfrom ne '')) {
4389: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4390: foreach my $dep (@{$related->{$identifier}}) {
4391: &add_filetype($allfiles,$path.$dep,'object');
4392: }
4393: }
4394: }
4395: return;
4396: }
4397:
1.1401 raeburn 4398: sub bubblesheet_converter {
4399: my ($cdom,$fullpath,$config,$format) = @_;
4400: if ((&domain($cdom) ne '') &&
1.1403 raeburn 4401: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401 raeburn 4402: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404 raeburn 4403: my (%csvcols,%csvoptions);
4404: if (ref($config->{'fields'}) eq 'HASH') {
4405: %csvcols = %{$config->{'fields'}};
4406: }
4407: if (ref($config->{'options'}) eq 'HASH') {
4408: %csvoptions = %{$config->{'options'}};
4409: }
1.1401 raeburn 4410: my %csvbynum = reverse(%csvcols);
4411: my %scantronconf = &get_scantron_config($format,$cdom);
4412: if (keys(%scantronconf)) {
4413: my %bynum = (
4414: $scantronconf{CODEstart} => 'CODEstart',
4415: $scantronconf{IDstart} => 'IDstart',
4416: $scantronconf{PaperID} => 'PaperID',
4417: $scantronconf{FirstName} => 'FirstName',
4418: $scantronconf{LastName} => 'LastName',
4419: $scantronconf{Qstart} => 'Qstart',
4420: );
4421: my @ordered;
4422: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403 raeburn 4423: push(@ordered,$bynum{$item});
1.1401 raeburn 4424: }
4425: my %mapstart = (
4426: CODEstart => 'CODE',
4427: IDstart => 'ID',
4428: PaperID => 'PaperID',
4429: FirstName => 'FirstName',
4430: LastName => 'LastName',
4431: Qstart => 'FirstQuestion',
4432: );
4433: my %maplength = (
4434: CODEstart => 'CODElength',
4435: IDstart => 'IDlength',
4436: PaperID => 'PaperIDlength',
4437: FirstName => 'FirstNamelength',
4438: LastName => 'LastNamelength',
4439: );
4440: if (open(my $fh,'<',$fullpath)) {
4441: my $output;
1.1403 raeburn 4442: my %lettdig = &letter_to_digits();
4443: my %diglett = reverse(%lettdig);
4444: my $numletts = scalar(keys(%lettdig));
1.1404 raeburn 4445: my $num = 0;
1.1401 raeburn 4446: while (my $line=<$fh>) {
1.1404 raeburn 4447: $num ++;
4448: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401 raeburn 4449: $line =~ s{[\r\n]+$}{};
4450: my %found;
4451: my @values = split(/,/,$line);
4452: my ($qstart,$record);
4453: for (my $i=0; $i<@values; $i++) {
1.1403 raeburn 4454: if ((($qstart ne '') && ($i > $qstart)) ||
4455: ($csvbynum{$i} eq 'FirstQuestion')) {
4456: if ($values[$i] eq '') {
4457: $values[$i] = $scantronconf{'Qoff'};
4458: } elsif ($scantronconf{'Qon'} eq 'number') {
4459: if ($values[$i] =~ /^[A-Ja-j]$/) {
4460: $values[$i] = $lettdig{uc($values[$i])};
4461: }
4462: } elsif ($scantronconf{'Qon'} eq 'letter') {
4463: if ($values[$i] =~ /^[0-9]$/) {
4464: $values[$i] = $diglett{$values[$i]};
4465: }
4466: } else {
4467: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4468: my $digit;
4469: if ($values[$i] =~ /^[A-Ja-j]$/) {
4470: $digit = $lettdig{uc($values[$i])}-1;
4471: if ($values[$i] eq 'J') {
4472: $digit += $numletts;
4473: }
4474: } elsif ($values[$i] =~ /^[0-9]$/) {
4475: $digit = $values[$i]-1;
4476: if ($values[$i] eq '0') {
4477: $digit += $numletts;
4478: }
4479: }
4480: my $qval='';
4481: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4482: if ($j == $digit) {
4483: $qval .= $scantronconf{'Qon'};
4484: } else {
4485: $qval .= $scantronconf{'Qoff'};
4486: }
4487: }
4488: $values[$i] = $qval;
4489: }
4490: }
4491: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4492: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4493: }
4494: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4495: if ($numblank > 0) {
4496: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4497: }
1.1401 raeburn 4498: if ($csvbynum{$i} eq 'FirstQuestion') {
4499: $qstart = $i;
1.1403 raeburn 4500: $found{$csvbynum{$i}} = $values[$i];
1.1401 raeburn 4501: } else {
1.1403 raeburn 4502: $found{'FirstQuestion'} .= $values[$i];
4503: }
4504: } elsif (exists($csvbynum{$i})) {
1.1404 raeburn 4505: if ($csvoptions{'rem'}) {
4506: $values[$i] =~ s/^\s+//;
4507: }
4508: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403 raeburn 4509: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4510: $values[$i] = '0'.$values[$i];
1.1401 raeburn 4511: }
4512: }
4513: $found{$csvbynum{$i}} = $values[$i];
4514: }
4515: }
4516: foreach my $item (@ordered) {
4517: my $currlength = 1+length($record);
4518: my $numspaces = $scantronconf{$item} - $currlength;
4519: if ($numspaces > 0) {
4520: $record .= (' ' x $numspaces);
4521: }
4522: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4523: unless ($item eq 'Qstart') {
4524: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4525: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4526: }
4527: }
4528: $record .= $found{$mapstart{$item}};
4529: }
4530: }
4531: $output .= "$record\n";
4532: }
4533: close($fh);
4534: if ($output) {
4535: if (open(my $fh,'>',$fullpath)) {
4536: print $fh $output;
4537: close($fh);
4538: }
4539: }
4540: }
4541: }
4542: return;
4543: }
4544: }
4545:
1.1403 raeburn 4546: sub letter_to_digits {
4547: my %lettdig = (
4548: A => 1,
4549: B => 2,
4550: C => 3,
4551: D => 4,
4552: E => 5,
4553: F => 6,
4554: G => 7,
4555: H => 8,
4556: I => 9,
4557: J => 0,
4558: );
4559: return %lettdig;
4560: }
4561:
1.1401 raeburn 4562: sub get_scantron_config {
4563: my ($which,$cdom) = @_;
4564: my @lines = &get_scantronformat_file($cdom);
4565: my %config;
4566: #FIXME probably should move to XML it has already gotten a bit much now
4567: foreach my $line (@lines) {
4568: my ($name,$descrip)=split(/:/,$line);
4569: if ($name ne $which ) { next; }
4570: chomp($line);
4571: my @config=split(/:/,$line);
4572: $config{'name'}=$config[0];
4573: $config{'description'}=$config[1];
4574: $config{'CODElocation'}=$config[2];
4575: $config{'CODEstart'}=$config[3];
4576: $config{'CODElength'}=$config[4];
4577: $config{'IDstart'}=$config[5];
4578: $config{'IDlength'}=$config[6];
4579: $config{'Qstart'}=$config[7];
4580: $config{'Qlength'}=$config[8];
4581: $config{'Qoff'}=$config[9];
4582: $config{'Qon'}=$config[10];
4583: $config{'PaperID'}=$config[11];
4584: $config{'PaperIDlength'}=$config[12];
4585: $config{'FirstName'}=$config[13];
4586: $config{'FirstNamelength'}=$config[14];
4587: $config{'LastName'}=$config[15];
4588: $config{'LastNamelength'}=$config[16];
4589: $config{'BubblesPerRow'}=$config[17];
4590: last;
4591: }
4592: return %config;
4593: }
4594:
4595: sub get_scantronformat_file {
4596: my ($cdom) = @_;
4597: if ($cdom eq '') {
4598: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4599: }
4600: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4601: my $gottab = 0;
4602: my @lines;
4603: if (ref($domconfig{'scantron'}) eq 'HASH') {
4604: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4605: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4606: if ($formatfile ne '-1') {
4607: @lines = split("\n",$formatfile,-1);
4608: $gottab = 1;
4609: }
4610: }
4611: }
4612: if (!$gottab) {
4613: my $confname = $cdom.'-domainconfig';
4614: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4615: my $formatfile = &getfile($default);
4616: if ($formatfile ne '-1') {
4617: @lines = split("\n",$formatfile,-1);
4618: $gottab = 1;
4619: }
4620: }
4621: if (!$gottab) {
4622: my @domains = ¤t_machine_domains();
4623: if (grep(/^\Q$cdom\E$/,@domains)) {
4624: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4625: @lines = <$fh>;
4626: close($fh);
1.1403 raeburn 4627: }
1.1401 raeburn 4628: } else {
4629: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4630: @lines = <$fh>;
4631: close($fh);
4632: }
4633: }
4634: }
4635: return @lines;
4636: }
4637:
1.493 albertel 4638: sub removeuploadedurl {
1.984 neumanie 4639: my ($url)=@_;
4640: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4641: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4642: }
4643:
4644: sub removeuserfile {
4645: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4646: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4647: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4648: if ($result eq 'ok') {
1.798 raeburn 4649: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4650: my $metafile = $fname.'.meta';
4651: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4652: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4653: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4654: my $sqlresult =
1.823 albertel 4655: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4656: 'portfolio_metadata',$group,
4657: 'delete');
1.798 raeburn 4658: }
4659: }
4660: return $result;
1.257 www 4661: }
1.15 www 4662:
1.530 albertel 4663: sub mkdiruserfile {
4664: my ($docuname,$docudom,$dir)=@_;
4665: my $home=&homeserver($docuname,$docudom);
4666: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4667: }
4668:
1.531 albertel 4669: sub renameuserfile {
4670: my ($docuname,$docudom,$old,$new)=@_;
4671: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4672: my $result = &reply("renameuserfile:$docudom:$docuname:".
4673: &escape("$old").':'.&escape("$new"),$home);
4674: if ($result eq 'ok') {
4675: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4676: my $oldmeta = $old.'.meta';
4677: my $newmeta = $new.'.meta';
4678: my $metaresult =
4679: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4680: my $url = "/uploaded/$docudom/$docuname/$old";
4681: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4682: my $sqlresult =
1.823 albertel 4683: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4684: 'portfolio_metadata',$group,
4685: 'delete');
1.798 raeburn 4686: }
4687: }
4688: return $result;
1.531 albertel 4689: }
4690:
1.14 www 4691: # ------------------------------------------------------------------------- Log
4692:
4693: sub log {
4694: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4695: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4696: }
4697:
4698: # ------------------------------------------------------------------ Course Log
1.352 www 4699: #
4700: # This routine flushes several buffers of non-mission-critical nature
4701: #
1.157 www 4702:
4703: sub flushcourselogs {
1.352 www 4704: &logthis('Flushing log buffers');
4705: #
4706: # course logs
4707: # This is a log of all transactions in a course, which can be used
4708: # for data mining purposes
4709: #
4710: # It also collects the courseid database, which lists last transaction
4711: # times and course titles for all courseids
4712: #
4713: my %courseidbuffer=();
1.921 raeburn 4714: foreach my $crsid (keys(%courselogs)) {
1.352 www 4715: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4716: &escape($courselogs{$crsid}),
4717: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4718: delete $courselogs{$crsid};
4719: } else {
4720: &logthis('Failed to flush log buffer for '.$crsid);
4721: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4722: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4723: " exceeded maximum size, deleting.</font>");
4724: delete $courselogs{$crsid};
4725: }
1.352 www 4726: }
1.920 raeburn 4727: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4728: 'description' => $coursedescrbuf{$crsid},
4729: 'inst_code' => $courseinstcodebuf{$crsid},
4730: 'type' => $coursetypebuf{$crsid},
4731: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4732: };
1.191 harris41 4733: }
1.352 www 4734: #
4735: # Write course id database (reverse lookup) to homeserver of courses
4736: # Is used in pickcourse
4737: #
1.840 albertel 4738: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4739: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4740: $courseidbuffer{$crs_home},
4741: $crs_home,'timeonly');
1.352 www 4742: }
4743: #
4744: # File accesses
4745: # Writes to the dynamic metadata of resources to get hit counts, etc.
4746: #
1.449 matthew 4747: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4748: if ($entry =~ /___count$/) {
4749: my ($dom,$name);
1.807 albertel 4750: ($dom,$name,undef)=
1.811 albertel 4751: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4752: if (! defined($dom) || $dom eq '' ||
4753: ! defined($name) || $name eq '') {
1.620 albertel 4754: my $cid = $env{'request.course.id'};
4755: $dom = $env{'request.'.$cid.'.domain'};
4756: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4757: }
1.450 matthew 4758: my $value = $accesshash{$entry};
4759: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4760: my %temphash=($url => $value);
1.449 matthew 4761: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4762: if ($result eq 'ok') {
4763: delete $accesshash{$entry};
4764: }
4765: } else {
1.811 albertel 4766: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4767: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4768: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4769: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4770: delete $accesshash{$entry};
4771: }
1.185 www 4772: }
1.191 harris41 4773: }
1.352 www 4774: #
4775: # Roles
4776: # Reverse lookup of user roles for course faculty/staff and co-authorship
4777: #
1.800 albertel 4778: foreach my $entry (keys(%userrolehash)) {
1.351 www 4779: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4780: split(/\:/,$entry);
4781: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4782: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4783: $rudom,$runame) eq 'ok') {
4784: delete $userrolehash{$entry};
4785: }
4786: }
1.662 raeburn 4787: #
1.1334 raeburn 4788: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4789: #
4790: my %domrolebuffer = ();
1.1000 raeburn 4791: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4792: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4793: if ($domrolebuffer{$rudom}) {
4794: $domrolebuffer{$rudom}.='&'.&escape($entry).
4795: '='.&escape($domainrolehash{$entry});
4796: } else {
4797: $domrolebuffer{$rudom}.=&escape($entry).
4798: '='.&escape($domainrolehash{$entry});
4799: }
4800: delete $domainrolehash{$entry};
4801: }
4802: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 4803: my %servers;
4804: if (defined(&domain($dom,'primary'))) {
4805: my $primary=&domain($dom,'primary');
4806: my $hostname=&hostname($primary);
4807: $servers{$primary} = $hostname;
4808: } else {
4809: %servers = &get_servers($dom,'library');
4810: }
1.841 albertel 4811: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 4812: if (&reply('domroleput:'.$dom.':'.
4813: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4814: last;
4815: } else {
1.841 albertel 4816: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4817: }
1.662 raeburn 4818: }
4819: }
1.186 www 4820: $dumpcount++;
1.157 www 4821: }
4822:
4823: sub courselog {
4824: my $what=shift;
1.158 www 4825: $what=time.':'.$what;
1.620 albertel 4826: unless ($env{'request.course.id'}) { return ''; }
4827: $coursedombuf{$env{'request.course.id'}}=
4828: $env{'course.'.$env{'request.course.id'}.'.domain'};
4829: $coursenumbuf{$env{'request.course.id'}}=
4830: $env{'course.'.$env{'request.course.id'}.'.num'};
4831: $coursehombuf{$env{'request.course.id'}}=
4832: $env{'course.'.$env{'request.course.id'}.'.home'};
4833: $coursedescrbuf{$env{'request.course.id'}}=
4834: $env{'course.'.$env{'request.course.id'}.'.description'};
4835: $courseinstcodebuf{$env{'request.course.id'}}=
4836: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4837: $courseownerbuf{$env{'request.course.id'}}=
4838: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4839: $coursetypebuf{$env{'request.course.id'}}=
4840: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4841: if (defined $courselogs{$env{'request.course.id'}}) {
4842: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4843: } else {
1.620 albertel 4844: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4845: }
1.620 albertel 4846: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4847: &flushcourselogs();
4848: }
1.158 www 4849: }
4850:
4851: sub courseacclog {
4852: my $fnsymb=shift;
1.620 albertel 4853: unless ($env{'request.course.id'}) { return ''; }
4854: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4855: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4856: $what.=':POST';
1.583 matthew 4857: # FIXME: Probably ought to escape things....
1.800 albertel 4858: foreach my $key (keys(%env)) {
4859: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4860: my $formitem = $1;
4861: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4862: $what.=':'.$formitem.'='.$env{$key};
4863: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4864: $what.=':'.$formitem.'='.$env{$key};
4865: }
1.158 www 4866: }
1.191 harris41 4867: }
1.583 matthew 4868: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4869: # FIXME: We should not be depending on a form parameter that someone
4870: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4871: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4872: $what.= ':POST';
4873: # FIXME: Probably ought to escape things....
4874: foreach my $element ('courseexp','crsfulltext','crsrelated',
4875: 'crsdiscuss') {
1.620 albertel 4876: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4877: }
4878: }
1.158 www 4879: }
4880: &courselog($what);
1.149 www 4881: }
4882:
1.185 www 4883: sub countacc {
4884: my $url=&declutter(shift);
1.458 matthew 4885: return if (! defined($url) || $url eq '');
1.620 albertel 4886: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4887: #
4888: # Mark that this url was used in this course
4889: #
1.620 albertel 4890: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4891: #
4892: # Increase the access count for this resource in this child process
4893: #
1.281 www 4894: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4895: $accesshash{$key}++;
1.185 www 4896: }
1.349 www 4897:
1.361 www 4898: sub linklog {
4899: my ($from,$to)=@_;
4900: $from=&declutter($from);
4901: $to=&declutter($to);
4902: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4903: $accesshash{$to.'___'.$from.'___goto'}=1;
4904: }
1.1160 www 4905:
4906: sub statslog {
4907: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4908: if ($users<2) { return; }
4909: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4910: 'course' => $env{'request.course.id'},
4911: 'sections' => '"all"',
4912: 'num_students' => $users,
4913: 'part' => $part,
4914: 'symb' => $symb,
4915: 'mean_tries' => $av_attempts,
4916: 'deg_of_diff' => $degdiff});
4917: foreach my $key (keys(%dynstore)) {
4918: $accesshash{$key}=$dynstore{$key};
4919: }
4920: }
1.361 www 4921:
1.349 www 4922: sub userrolelog {
4923: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4924: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4925: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4926: $userrolehash
4927: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4928: =$tend.':'.$tstart;
1.662 raeburn 4929: }
1.1169 droeschl 4930: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4931: $userrolehash
4932: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4933: =$tend.':'.$tstart;
4934: }
1.1334 raeburn 4935: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4936: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4937: $domainrolehash
4938: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4939: = $tend.':'.$tstart;
4940: }
1.351 www 4941: }
4942:
1.957 raeburn 4943: sub courserolelog {
4944: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 4945: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4946: my $cdom = $1;
4947: my $cnum = $2;
4948: my $sec = $3;
4949: my $namespace = 'rolelog';
4950: my %storehash = (
4951: role => $trole,
4952: start => $tstart,
4953: end => $tend,
4954: selfenroll => $selfenroll,
4955: context => $context,
4956: );
4957: if ($trole eq 'gr') {
4958: $namespace = 'groupslog';
4959: $storehash{'group'} = $sec;
4960: } else {
4961: $storehash{'section'} = $sec;
4962: }
1.1188 raeburn 4963: &write_log('course',$namespace,\%storehash,$delflag,$username,
4964: $domain,$cnum,$cdom);
1.1184 raeburn 4965: if (($trole ne 'st') || ($sec ne '')) {
4966: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4967: }
4968: }
4969: return;
4970: }
4971:
1.1184 raeburn 4972: sub domainrolelog {
4973: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4974: if ($area =~ m{^/($match_domain)/$}) {
4975: my $cdom = $1;
4976: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4977: my $namespace = 'rolelog';
4978: my %storehash = (
4979: role => $trole,
4980: start => $tstart,
4981: end => $tend,
4982: context => $context,
4983: );
1.1188 raeburn 4984: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4985: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4986: }
4987: return;
4988:
4989: }
4990:
4991: sub coauthorrolelog {
4992: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4993: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4994: my $audom = $1;
4995: my $auname = $2;
4996: my $namespace = 'rolelog';
4997: my %storehash = (
4998: role => $trole,
4999: start => $tstart,
5000: end => $tend,
5001: context => $context,
5002: );
1.1188 raeburn 5003: &write_log('author',$namespace,\%storehash,$delflag,$username,
5004: $domain,$auname,$audom);
1.1184 raeburn 5005: }
5006: return;
5007: }
5008:
1.351 www 5009: sub get_course_adv_roles {
1.948 raeburn 5010: my ($cid,$codes) = @_;
1.620 albertel 5011: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 5012: my %coursehash=&coursedescription($cid);
1.988 raeburn 5013: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 5014: my %nothide=();
1.800 albertel 5015: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 5016: if ($user !~ /:/) {
5017: $nothide{join(':',split(/[\@]/,$user))}=1;
5018: } else {
5019: $nothide{$user}=1;
5020: }
1.470 www 5021: }
1.1219 raeburn 5022: my @possdoms = ($coursehash{'domain'});
5023: if ($coursehash{'checkforpriv'}) {
5024: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5025: }
1.351 www 5026: my %returnhash=();
5027: my %dumphash=
5028: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5029: my $now=time;
1.997 raeburn 5030: my %privileged;
1.1000 raeburn 5031: foreach my $entry (keys(%dumphash)) {
1.800 albertel 5032: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 5033: if (($tstart) && ($tstart<0)) { next; }
5034: if (($tend) && ($tend<$now)) { next; }
5035: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 5036: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 5037: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 5038: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 5039: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 5040: if ($role eq 'cr') { next; }
1.948 raeburn 5041: if ($codes) {
5042: if ($section) { $role .= ':'.$section; }
5043: if ($returnhash{$role}) {
5044: $returnhash{$role}.=','.$username.':'.$domain;
5045: } else {
5046: $returnhash{$role}=$username.':'.$domain;
5047: }
1.351 www 5048: } else {
1.988 raeburn 5049: my $key=&plaintext($role,$crstype);
1.973 bisitz 5050: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 5051: if ($returnhash{$key}) {
5052: $returnhash{$key}.=','.$username.':'.$domain;
5053: } else {
5054: $returnhash{$key}=$username.':'.$domain;
5055: }
1.351 www 5056: }
1.948 raeburn 5057: }
1.400 www 5058: return %returnhash;
5059: }
5060:
5061: sub get_my_roles {
1.937 raeburn 5062: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5063: unless (defined($uname)) { $uname=$env{'user.name'}; }
5064: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5065: my (%dumphash,%nothide);
1.1086 raeburn 5066: if ($context eq 'userroles') {
1.1166 raeburn 5067: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5068: } else {
1.1219 raeburn 5069: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5070: if ($hidepriv) {
5071: my %coursehash=&coursedescription($udom.'_'.$uname);
5072: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5073: if ($user !~ /:/) {
5074: $nothide{join(':',split(/[\@]/,$user))} = 1;
5075: } else {
5076: $nothide{$user} = 1;
5077: }
5078: }
5079: }
1.858 raeburn 5080: }
1.400 www 5081: my %returnhash=();
5082: my $now=time;
1.999 raeburn 5083: my %privileged;
1.800 albertel 5084: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5085: my ($role,$tend,$tstart);
5086: if ($context eq 'userroles') {
1.1149 raeburn 5087: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5088: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5089: } else {
5090: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5091: }
1.400 www 5092: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5093: my $status = 'active';
1.939 raeburn 5094: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5095: $status = 'previous';
5096: }
5097: if (($tstart) && ($now<$tstart)) {
5098: $status = 'future';
5099: }
5100: if (ref($types) eq 'ARRAY') {
5101: if (!grep(/^\Q$status\E$/,@{$types})) {
5102: next;
5103: }
5104: } else {
5105: if ($status ne 'active') {
5106: next;
5107: }
5108: }
1.867 raeburn 5109: my ($rolecode,$username,$domain,$section,$area);
5110: if ($context eq 'userroles') {
1.1186 raeburn 5111: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5112: (undef,$domain,$username,$section) = split(/\//,$area);
5113: } else {
5114: ($role,$username,$domain,$section) = split(/\:/,$entry);
5115: }
1.832 raeburn 5116: if (ref($roledoms) eq 'ARRAY') {
5117: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5118: next;
5119: }
5120: }
5121: if (ref($roles) eq 'ARRAY') {
5122: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5123: if ($role =~ /^cr\//) {
5124: if (!grep(/^cr$/,@{$roles})) {
5125: next;
5126: }
1.1104 raeburn 5127: } elsif ($role =~ /^gr\//) {
5128: if (!grep(/^gr$/,@{$roles})) {
5129: next;
5130: }
1.922 raeburn 5131: } else {
5132: next;
5133: }
1.832 raeburn 5134: }
1.867 raeburn 5135: }
1.937 raeburn 5136: if ($hidepriv) {
1.1219 raeburn 5137: my @privroles = ('dc','su');
1.999 raeburn 5138: if ($context eq 'userroles') {
1.1219 raeburn 5139: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5140: } else {
1.1219 raeburn 5141: my $possdoms = [$domain];
5142: if (ref($roledoms) eq 'ARRAY') {
5143: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5144: }
1.1219 raeburn 5145: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5146: if (!$nothide{$username.':'.$domain}) {
5147: next;
5148: }
5149: }
1.937 raeburn 5150: }
5151: }
1.933 raeburn 5152: if ($withsec) {
5153: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5154: $tstart.':'.$tend;
5155: } else {
5156: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5157: }
1.832 raeburn 5158: }
1.373 www 5159: return %returnhash;
1.399 www 5160: }
5161:
1.1333 raeburn 5162: sub get_all_adhocroles {
5163: my ($dom) = @_;
5164: my @roles_by_num = ();
5165: my %domdefaults = &get_domain_defaults($dom);
5166: my (%description,%access_in_dom,%access_info);
5167: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5168: my $count = 0;
5169: my %domcurrent = %{$domdefaults{'adhocroles'}};
5170: my %ordered;
5171: foreach my $role (sort(keys(%domcurrent))) {
5172: my ($order,$desc,$access_in_dom);
5173: if (ref($domcurrent{$role}) eq 'HASH') {
5174: $order = $domcurrent{$role}{'order'};
5175: $desc = $domcurrent{$role}{'desc'};
5176: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5177: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5178: }
5179: if ($order eq '') {
5180: $order = $count;
5181: }
5182: $ordered{$order} = $role;
5183: if ($desc ne '') {
5184: $description{$role} = $desc;
5185: } else {
5186: $description{$role}= $role;
5187: }
5188: $count++;
5189: }
5190: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5191: push(@roles_by_num,$ordered{$item});
5192: }
5193: }
5194: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5195: }
5196:
1.1332 raeburn 5197: sub get_my_adhocroles {
1.1333 raeburn 5198: my ($cid,$checkreg) = @_;
5199: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5200: if ($env{'request.course.id'} eq $cid) {
5201: $cdom = $env{'course.'.$cid.'.domain'};
5202: $cnum = $env{'course.'.$cid.'.num'};
5203: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5204: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5205: $cdom = $1;
5206: $cnum = $2;
5207: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5208: $cdom,$cnum);
5209: }
5210: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5211: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5212: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5213: if ($rosterhash{$user} ne '') {
5214: my $type = (split(/:/,$rosterhash{$user}))[5];
5215: return ([],{}) if ($type eq 'auto');
5216: }
5217: }
5218: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 5219: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 5220: my $then=$env{'user.login.time'};
5221: my $update=$env{'user.update.time'};
1.1335 raeburn 5222: if (!$update) {
5223: $update = $then;
5224: }
5225: my @liveroles;
1.1334 raeburn 5226: foreach my $role ('dh','da') {
5227: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 5228: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 5229: my $limit = $update;
5230: if ($env{'request.role'} eq "$role./$cdom/") {
5231: $limit = $then;
5232: }
1.1335 raeburn 5233: my $activerole = 1;
5234: if ($tstart && $tstart>$limit) { $activerole = 0; }
5235: if ($tend && $tend <$limit) { $activerole = 0; }
5236: if ($activerole) {
5237: push(@liveroles,$role);
5238: }
1.1334 raeburn 5239: }
1.1332 raeburn 5240: }
1.1335 raeburn 5241: if (@liveroles) {
1.1332 raeburn 5242: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 5243: my ($accessref,$accessinfo,%access_in_dom);
5244: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5245: if (ref($roles_by_num) eq 'ARRAY') {
5246: if (@{$roles_by_num}) {
1.1332 raeburn 5247: my %settings;
5248: if ($env{'request.course.id'} eq $cid) {
5249: foreach my $envkey (keys(%env)) {
5250: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5251: $settings{$1} = $env{$envkey};
5252: }
5253: }
5254: } else {
5255: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5256: }
5257: my %setincrs;
5258: if ($settings{'internal.adhocaccess'}) {
5259: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5260: }
5261: my @statuses;
5262: if ($env{'environment.inststatus'}) {
5263: @statuses = split(/,/,$env{'environment.inststatus'});
5264: }
5265: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 5266: if (ref($accessref) eq 'HASH') {
5267: %access_in_dom = %{$accessref};
5268: }
5269: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 5270: my ($curraccess,@okstatus,@personnel);
5271: if ($setincrs{$role}) {
5272: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5273: if ($curraccess eq 'status') {
5274: @okstatus = split(/\&/,$rest);
5275: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5276: @personnel = split(/\&/,$rest);
5277: }
5278: } else {
5279: $curraccess = $access_in_dom{$role};
1.1333 raeburn 5280: if (ref($accessinfo) eq 'HASH') {
5281: if ($curraccess eq 'status') {
5282: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5283: @okstatus = @{$accessinfo->{$role}};
5284: }
5285: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5286: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5287: @personnel = @{$accessinfo->{$role}};
5288: }
1.1332 raeburn 5289: }
5290: }
5291: }
5292: if ($curraccess eq 'none') {
5293: next;
5294: } elsif ($curraccess eq 'all') {
5295: push(@possroles,$role);
1.1336 raeburn 5296: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 5297: if (grep(/^dh$/,@liveroles)) {
5298: push(@possroles,$role);
5299: } else {
5300: next;
5301: }
1.1336 raeburn 5302: } elsif ($curraccess eq 'da') {
1.1335 raeburn 5303: if (grep(/^da$/,@liveroles)) {
5304: push(@possroles,$role);
5305: } else {
5306: next;
5307: }
1.1332 raeburn 5308: } elsif ($curraccess eq 'status') {
5309: if (@okstatus) {
5310: if (!@statuses) {
5311: if (grep(/^default$/,@okstatus)) {
5312: push(@possroles,$role);
5313: }
5314: } else {
5315: foreach my $status (@okstatus) {
5316: if (grep(/^\Q$status\E$/,@statuses)) {
5317: push(@possroles,$role);
5318: last;
5319: }
5320: }
5321: }
5322: }
5323: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5324: if (grep(/^\Q$user\E$/,@personnel)) {
5325: if ($curraccess eq 'exc') {
5326: push(@possroles,$role);
5327: }
5328: } elsif ($curraccess eq 'inc') {
5329: push(@possroles,$role);
5330: }
5331: }
5332: }
5333: }
5334: }
5335: }
5336: }
5337: }
5338: }
1.1333 raeburn 5339: unless (ref($description) eq 'HASH') {
5340: if (ref($roles_by_num) eq 'ARRAY') {
5341: my %desc;
5342: map { $desc{$_} = $_; } (@{$roles_by_num});
5343: $description = \%desc;
5344: } else {
5345: $description = {};
5346: }
5347: }
5348: return (\@possroles,$description);
1.1332 raeburn 5349: }
5350:
1.399 www 5351: # ----------------------------------------------------- Frontpage Announcements
5352: #
5353: #
5354:
5355: sub postannounce {
5356: my ($server,$text)=@_;
1.844 albertel 5357: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5358: unless ($text=~/\w/) { $text=''; }
5359: return &reply('setannounce:'.&escape($text),$server);
5360: }
5361:
5362: sub getannounce {
1.448 albertel 5363:
1.1359 raeburn 5364: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5365: my $announcement='';
1.800 albertel 5366: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5367: close($fh);
1.399 www 5368: if ($announcement=~/\w/) {
5369: return
5370: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5371: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5372: } else {
5373: return '';
5374: }
5375: } else {
5376: return '';
5377: }
1.351 www 5378: }
1.353 www 5379:
5380: # ---------------------------------------------------------- Course ID routines
5381: # Deal with domain's nohist_courseid.db files
5382: #
5383:
5384: sub courseidput {
1.921 raeburn 5385: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5386: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5387: my $outcome;
5388: if ($caller eq 'timeonly') {
5389: my $cids = '';
5390: foreach my $item (keys(%$storehash)) {
5391: $cids.=&escape($item).'&';
5392: }
5393: $cids=~s/\&$//;
5394: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5395: $coursehome);
5396: } else {
5397: my $items = '';
5398: foreach my $item (keys(%$storehash)) {
5399: $items.= &escape($item).'='.
5400: &freeze_escape($$storehash{$item}).'&';
5401: }
5402: $items=~s/\&$//;
5403: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5404: $coursehome);
1.918 raeburn 5405: }
5406: if ($outcome eq 'unknown_cmd') {
5407: my $what;
5408: foreach my $cid (keys(%$storehash)) {
5409: $what .= &escape($cid).'=';
1.921 raeburn 5410: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5411: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5412: }
5413: $what =~ s/\:$/&/;
5414: }
5415: $what =~ s/\&$//;
5416: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5417: } else {
5418: return $outcome;
5419: }
1.353 www 5420: }
5421:
5422: sub courseiddump {
1.921 raeburn 5423: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5424: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5425: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 5426: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 5427: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5428: my $as_hash = 1;
5429: my %returnhash;
5430: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5431: my %libserv = &all_library();
5432: foreach my $tryserver (keys(%libserv)) {
5433: if ( ( $hostidflag == 1
5434: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5435: || (!defined($hostidflag)) ) {
5436:
1.918 raeburn 5437: if (($domfilter eq '') ||
5438: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 5439: my $rep;
5440: if (grep { $_ eq $tryserver } current_machine_ids()) {
5441: $rep = LONCAPA::Lond::dump_course_id_handler(
5442: join(":", (&host_domain($tryserver), $sincefilter,
5443: &escape($descfilter), &escape($instcodefilter),
5444: &escape($ownerfilter), &escape($coursefilter),
5445: &escape($typefilter), &escape($regexp_ok),
5446: $as_hash, &escape($selfenrollonly),
5447: &escape($catfilter), $showhidden, $caller,
5448: &escape($cloner), &escape($cc_clone), $cloneonly,
5449: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 5450: &escape($creationcontext),$domcloner,$hasuniquecode,
5451: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 5452: } else {
5453: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5454: $sincefilter.':'.&escape($descfilter).':'.
5455: &escape($instcodefilter).':'.&escape($ownerfilter).
5456: ':'.&escape($coursefilter).':'.&escape($typefilter).
5457: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5458: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5459: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5460: &escape($cc_clone).':'.$cloneonly.':'.
5461: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 5462: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5463: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 5464: }
5465:
1.918 raeburn 5466: my @pairs=split(/\&/,$rep);
5467: foreach my $item (@pairs) {
5468: my ($key,$value)=split(/\=/,$item,2);
5469: $key = &unescape($key);
5470: next if ($key =~ /^error: 2 /);
5471: my $result = &thaw_unescape($value);
5472: if (ref($result) eq 'HASH') {
5473: $returnhash{$key}=$result;
5474: } else {
1.921 raeburn 5475: my @responses = split(/:/,$value);
5476: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5477: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5478: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5479: }
1.1008 raeburn 5480: }
1.353 www 5481: }
5482: }
5483: }
5484: }
5485: return %returnhash;
5486: }
5487:
1.1055 raeburn 5488: sub courselastaccess {
5489: my ($cdom,$cnum,$hostidref) = @_;
5490: my %returnhash;
5491: if ($cdom && $cnum) {
5492: my $chome = &homeserver($cnum,$cdom);
5493: if ($chome ne 'no_host') {
5494: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5495: &extract_lastaccess(\%returnhash,$rep);
5496: }
5497: } else {
5498: if (!$cdom) { $cdom=''; }
5499: my %libserv = &all_library();
5500: foreach my $tryserver (keys(%libserv)) {
5501: if (ref($hostidref) eq 'ARRAY') {
5502: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5503: }
5504: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5505: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5506: &extract_lastaccess(\%returnhash,$rep);
5507: }
5508: }
5509: }
5510: return %returnhash;
5511: }
5512:
5513: sub extract_lastaccess {
5514: my ($returnhash,$rep) = @_;
5515: if (ref($returnhash) eq 'HASH') {
5516: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5517: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5518: $rep eq '') {
5519: my @pairs=split(/\&/,$rep);
5520: foreach my $item (@pairs) {
5521: my ($key,$value)=split(/\=/,$item,2);
5522: $key = &unescape($key);
5523: next if ($key =~ /^error: 2 /);
5524: $returnhash->{$key} = &thaw_unescape($value);
5525: }
5526: }
5527: }
5528: return;
5529: }
5530:
1.658 raeburn 5531: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5532:
5533: sub dcmailput {
1.685 raeburn 5534: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5535: my $status = &Apache::lonnet::critical(
1.740 www 5536: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5537: &escape($message),$server);
1.662 raeburn 5538: return $status;
5539: }
5540:
1.658 raeburn 5541: sub dcmaildump {
5542: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5543: my %returnhash=();
1.846 albertel 5544:
5545: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5546: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5547: &escape($enddate).':';
5548: my @esc_senders=map { &escape($_)} @$senders;
5549: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5550: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5551: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5552: if (($key) && ($value)) {
5553: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5554: }
5555: }
5556: }
5557: return %returnhash;
5558: }
1.662 raeburn 5559: # ---------------------------------------------------------- Domain roles
5560:
5561: sub get_domain_roles {
5562: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5563: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5564: $startdate = '.';
5565: }
1.1018 raeburn 5566: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5567: $enddate = '.';
5568: }
1.922 raeburn 5569: my $rolelist;
5570: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 5571: $rolelist = join('&',@{$roles});
1.922 raeburn 5572: }
1.662 raeburn 5573: my %personnel = ();
1.841 albertel 5574:
5575: my %servers = &get_servers($dom,'library');
5576: foreach my $tryserver (keys(%servers)) {
5577: %{$personnel{$tryserver}}=();
5578: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5579: &escape($startdate).':'.
5580: &escape($enddate).':'.
5581: &escape($rolelist), $tryserver))) {
5582: my ($key,$value) = split(/\=/,$line,2);
5583: if (($key) && ($value)) {
5584: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5585: }
5586: }
1.662 raeburn 5587: }
5588: return %personnel;
5589: }
1.658 raeburn 5590:
1.1332 raeburn 5591: sub get_active_domroles {
5592: my ($dom,$roles) = @_;
5593: return () unless (ref($roles) eq 'ARRAY');
5594: my $now = time;
5595: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5596: my %domroles;
5597: foreach my $server (keys(%dompersonnel)) {
5598: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5599: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5600: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5601: }
5602: }
5603: return %domroles;
5604: }
5605:
1.1057 www 5606: # ----------------------------------------------------------- Interval timing
1.149 www 5607:
1.1153 www 5608: {
5609: # Caches needed for speedup of navmaps
5610: # We don't want to cache this for very long at all (5 seconds at most)
5611: #
5612: # The user for whom we cache
5613: my $cachedkey='';
5614: # The cached times for this user
5615: my %cachedtimes=();
5616: # When this was last done
1.1282 raeburn 5617: my $cachedtime='';
1.1153 www 5618:
5619: sub load_all_first_access {
1.1308 raeburn 5620: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5621: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 5622: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5623: (!$ignorecache)) {
1.1154 raeburn 5624: return;
5625: }
5626: $cachedtime=time;
5627: $cachedkey=$uname.':'.$udom;
5628: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5629: }
5630:
1.504 albertel 5631: sub get_first_access {
1.1308 raeburn 5632: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5633: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5634: if ($argsymb) { $symb=$argsymb; }
5635: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5636: if ($argmap) { $map = $argmap; }
1.926 albertel 5637: if ($type eq 'course') {
5638: $res='course';
5639: } elsif ($type eq 'map') {
1.588 albertel 5640: $res=&symbread($map);
5641: } else {
5642: $res=$symb;
5643: }
1.1308 raeburn 5644: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 5645: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5646: }
5647:
5648: sub set_first_access {
1.1162 raeburn 5649: my ($type,$interval)=@_;
1.790 albertel 5650: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5651: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5652: if ($type eq 'course') {
5653: $res='course';
5654: } elsif ($type eq 'map') {
1.588 albertel 5655: $res=&symbread($map);
5656: } else {
5657: $res=$symb;
5658: }
1.1153 www 5659: $cachedkey='';
1.1162 raeburn 5660: my $firstaccess=&get_first_access($type,$symb,$map);
1.1386 raeburn 5661: if ($firstaccess) {
5662: &logthis("First access time already set ($firstaccess) when attempting ".
1.1393 raeburn 5663: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5664: "in $courseid");
1.1386 raeburn 5665: return 'already_set';
5666: } else {
1.1162 raeburn 5667: my $start = time;
5668: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5669: $udom,$uname);
5670: if ($putres eq 'ok') {
5671: &put('timerinterval',{"$courseid\0$res"=>$interval},
5672: $udom,$uname);
5673: &appenv(
5674: {
5675: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5676: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5677: }
5678: );
1.1365 raeburn 5679: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5680: $cachedtimes{"$courseid\0$res"} = $start;
5681: }
1.1386 raeburn 5682: } elsif ($putres ne 'refused') {
5683: &logthis("Result: $putres when attempting to set first access time ".
5684: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5685: }
5686: return $putres;
1.505 albertel 5687: }
5688: return 'already_set';
1.504 albertel 5689: }
1.1153 www 5690: }
1.1282 raeburn 5691:
1.110 www 5692: # --------------------------------------------- Set Expire Date for Spreadsheet
5693:
5694: sub expirespread {
5695: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5696: my $cid=$env{'request.course.id'};
1.110 www 5697: if ($cid) {
5698: my $now=time;
5699: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5700: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5701: $env{'course.'.$cid.'.num'}.
1.110 www 5702: ':nohist_expirationdates:'.
5703: &escape($key).'='.$now,
1.620 albertel 5704: $env{'course.'.$cid.'.home'})
1.110 www 5705: }
5706: return 'ok';
1.14 www 5707: }
5708:
1.109 www 5709: # ----------------------------------------------------- Devalidate Spreadsheets
5710:
5711: sub devalidate {
1.325 www 5712: my ($symb,$uname,$udom)=@_;
1.620 albertel 5713: my $cid=$env{'request.course.id'};
1.109 www 5714: if ($cid) {
1.391 matthew 5715: # delete the stored spreadsheets for
5716: # - the student level sheet of this user in course's homespace
5717: # - the assessment level sheet for this resource
5718: # for this user in user's homespace
1.553 albertel 5719: # - current conditional state info
1.325 www 5720: my $key=$uname.':'.$udom.':';
1.109 www 5721: my $status=
1.299 matthew 5722: &del('nohist_calculatedsheets',
1.391 matthew 5723: [$key.'studentcalc:'],
1.620 albertel 5724: $env{'course.'.$cid.'.domain'},
5725: $env{'course.'.$cid.'.num'})
1.133 albertel 5726: .' '.
5727: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5728: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5729: unless ($status eq 'ok ok') {
5730: &logthis('Could not devalidate spreadsheet '.
1.325 www 5731: $uname.' at '.$udom.' for '.
1.109 www 5732: $symb.': '.$status);
1.133 albertel 5733: }
1.553 albertel 5734: &delenv('user.state.'.$cid);
1.109 www 5735: }
5736: }
5737:
1.265 albertel 5738: sub get_scalar {
5739: my ($string,$end) = @_;
5740: my $value;
5741: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5742: $value = $1;
5743: } elsif ($$string =~ s/^([^&]*?)&//) {
5744: $value = $1;
5745: }
5746: return &unescape($value);
5747: }
5748:
5749: sub array2str {
5750: my (@array) = @_;
5751: my $result=&arrayref2str(\@array);
5752: $result=~s/^__ARRAY_REF__//;
5753: $result=~s/__END_ARRAY_REF__$//;
5754: return $result;
5755: }
5756:
1.204 albertel 5757: sub arrayref2str {
5758: my ($arrayref) = @_;
1.265 albertel 5759: my $result='__ARRAY_REF__';
1.204 albertel 5760: foreach my $elem (@$arrayref) {
1.265 albertel 5761: if(ref($elem) eq 'ARRAY') {
5762: $result.=&arrayref2str($elem).'&';
5763: } elsif(ref($elem) eq 'HASH') {
5764: $result.=&hashref2str($elem).'&';
5765: } elsif(ref($elem)) {
5766: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5767: } else {
5768: $result.=&escape($elem).'&';
5769: }
5770: }
5771: $result=~s/\&$//;
1.265 albertel 5772: $result .= '__END_ARRAY_REF__';
1.204 albertel 5773: return $result;
5774: }
5775:
1.168 albertel 5776: sub hash2str {
1.204 albertel 5777: my (%hash) = @_;
5778: my $result=&hashref2str(\%hash);
1.265 albertel 5779: $result=~s/^__HASH_REF__//;
5780: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5781: return $result;
5782: }
5783:
5784: sub hashref2str {
5785: my ($hashref)=@_;
1.265 albertel 5786: my $result='__HASH_REF__';
1.800 albertel 5787: foreach my $key (sort(keys(%$hashref))) {
5788: if (ref($key) eq 'ARRAY') {
5789: $result.=&arrayref2str($key).'=';
5790: } elsif (ref($key) eq 'HASH') {
5791: $result.=&hashref2str($key).'=';
5792: } elsif (ref($key)) {
1.265 albertel 5793: $result.='=';
1.800 albertel 5794: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5795: } else {
1.1132 raeburn 5796: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5797: }
5798:
1.800 albertel 5799: if(ref($hashref->{$key}) eq 'ARRAY') {
5800: $result.=&arrayref2str($hashref->{$key}).'&';
5801: } elsif(ref($hashref->{$key}) eq 'HASH') {
5802: $result.=&hashref2str($hashref->{$key}).'&';
5803: } elsif(ref($hashref->{$key})) {
1.265 albertel 5804: $result.='&';
1.800 albertel 5805: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5806: } else {
1.800 albertel 5807: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5808: }
5809: }
1.168 albertel 5810: $result=~s/\&$//;
1.265 albertel 5811: $result .= '__END_HASH_REF__';
1.168 albertel 5812: return $result;
5813: }
5814:
5815: sub str2hash {
1.265 albertel 5816: my ($string)=@_;
5817: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5818: return %$hash;
5819: }
5820:
5821: sub str2hashref {
1.168 albertel 5822: my ($string) = @_;
1.265 albertel 5823:
5824: my %hash;
5825:
5826: if($string !~ /^__HASH_REF__/) {
5827: if (! ($string eq '' || !defined($string))) {
5828: $hash{'error'}='Not hash reference';
5829: }
5830: return (\%hash, $string);
5831: }
5832:
5833: $string =~ s/^__HASH_REF__//;
5834:
5835: while($string !~ /^__END_HASH_REF__/) {
5836: #key
5837: my $key='';
5838: if($string =~ /^__HASH_REF__/) {
5839: ($key, $string)=&str2hashref($string);
5840: if(defined($key->{'error'})) {
5841: $hash{'error'}='Bad data';
5842: return (\%hash, $string);
5843: }
5844: } elsif($string =~ /^__ARRAY_REF__/) {
5845: ($key, $string)=&str2arrayref($string);
5846: if($key->[0] eq 'Array reference error') {
5847: $hash{'error'}='Bad data';
5848: return (\%hash, $string);
5849: }
5850: } else {
5851: $string =~ s/^(.*?)=//;
1.267 albertel 5852: $key=&unescape($1);
1.265 albertel 5853: }
5854: $string =~ s/^=//;
5855:
5856: #value
5857: my $value='';
5858: if($string =~ /^__HASH_REF__/) {
5859: ($value, $string)=&str2hashref($string);
5860: if(defined($value->{'error'})) {
5861: $hash{'error'}='Bad data';
5862: return (\%hash, $string);
5863: }
5864: } elsif($string =~ /^__ARRAY_REF__/) {
5865: ($value, $string)=&str2arrayref($string);
5866: if($value->[0] eq 'Array reference error') {
5867: $hash{'error'}='Bad data';
5868: return (\%hash, $string);
5869: }
5870: } else {
5871: $value=&get_scalar(\$string,'__END_HASH_REF__');
5872: }
5873: $string =~ s/^&//;
5874:
5875: $hash{$key}=$value;
1.204 albertel 5876: }
1.265 albertel 5877:
5878: $string =~ s/^__END_HASH_REF__//;
5879:
5880: return (\%hash, $string);
1.204 albertel 5881: }
5882:
5883: sub str2array {
1.265 albertel 5884: my ($string)=@_;
5885: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5886: return @$array;
5887: }
5888:
5889: sub str2arrayref {
1.204 albertel 5890: my ($string) = @_;
1.265 albertel 5891: my @array;
5892:
5893: if($string !~ /^__ARRAY_REF__/) {
5894: if (! ($string eq '' || !defined($string))) {
5895: $array[0]='Array reference error';
5896: }
5897: return (\@array, $string);
5898: }
5899:
5900: $string =~ s/^__ARRAY_REF__//;
5901:
5902: while($string !~ /^__END_ARRAY_REF__/) {
5903: my $value='';
5904: if($string =~ /^__HASH_REF__/) {
5905: ($value, $string)=&str2hashref($string);
5906: if(defined($value->{'error'})) {
5907: $array[0] ='Array reference error';
5908: return (\@array, $string);
5909: }
5910: } elsif($string =~ /^__ARRAY_REF__/) {
5911: ($value, $string)=&str2arrayref($string);
5912: if($value->[0] eq 'Array reference error') {
5913: $array[0] ='Array reference error';
5914: return (\@array, $string);
5915: }
5916: } else {
5917: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5918: }
5919: $string =~ s/^&//;
5920:
5921: push(@array, $value);
1.191 harris41 5922: }
1.265 albertel 5923:
5924: $string =~ s/^__END_ARRAY_REF__//;
5925:
5926: return (\@array, $string);
1.168 albertel 5927: }
5928:
1.167 albertel 5929: # -------------------------------------------------------------------Temp Store
5930:
1.168 albertel 5931: sub tmpreset {
5932: my ($symb,$namespace,$domain,$stuname) = @_;
5933: if (!$symb) {
5934: $symb=&symbread();
1.620 albertel 5935: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5936: }
5937: $symb=escape($symb);
5938:
1.620 albertel 5939: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5940: $namespace=~s/\//\_/g;
5941: $namespace=~s/\W//g;
5942:
1.620 albertel 5943: if (!$domain) { $domain=$env{'user.domain'}; }
5944: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5945: if ($domain eq 'public' && $stuname eq 'public') {
5946: $stuname=$ENV{'REMOTE_ADDR'};
5947: }
1.1117 foxr 5948: my $path=LONCAPA::tempdir();
1.168 albertel 5949: my %hash;
5950: if (tie(%hash,'GDBM_File',
5951: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5952: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5953: foreach my $key (keys(%hash)) {
1.180 albertel 5954: if ($key=~ /:$symb/) {
1.168 albertel 5955: delete($hash{$key});
5956: }
5957: }
5958: }
5959: }
5960:
1.167 albertel 5961: sub tmpstore {
1.168 albertel 5962: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5963:
5964: if (!$symb) {
5965: $symb=&symbread();
1.620 albertel 5966: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5967: }
5968: $symb=escape($symb);
5969:
5970: if (!$namespace) {
5971: # I don't think we would ever want to store this for a course.
5972: # it seems this will only be used if we don't have a course.
1.620 albertel 5973: #$namespace=$env{'request.course.id'};
1.168 albertel 5974: #if (!$namespace) {
1.620 albertel 5975: $namespace=$env{'request.state'};
1.168 albertel 5976: #}
5977: }
5978: $namespace=~s/\//\_/g;
5979: $namespace=~s/\W//g;
1.620 albertel 5980: if (!$domain) { $domain=$env{'user.domain'}; }
5981: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5982: if ($domain eq 'public' && $stuname eq 'public') {
5983: $stuname=$ENV{'REMOTE_ADDR'};
5984: }
1.168 albertel 5985: my $now=time;
5986: my %hash;
1.1117 foxr 5987: my $path=LONCAPA::tempdir();
1.168 albertel 5988: if (tie(%hash,'GDBM_File',
5989: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5990: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5991: $hash{"version:$symb"}++;
5992: my $version=$hash{"version:$symb"};
5993: my $allkeys='';
5994: foreach my $key (keys(%$storehash)) {
5995: $allkeys.=$key.':';
1.591 albertel 5996: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5997: }
5998: $hash{"$version:$symb:timestamp"}=$now;
5999: $allkeys.='timestamp';
6000: $hash{"$version:keys:$symb"}=$allkeys;
6001: if (untie(%hash)) {
6002: return 'ok';
6003: } else {
6004: return "error:$!";
6005: }
6006: } else {
6007: return "error:$!";
6008: }
6009: }
1.167 albertel 6010:
1.168 albertel 6011: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6012:
1.168 albertel 6013: sub tmprestore {
6014: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6015:
1.168 albertel 6016: if (!$symb) {
6017: $symb=&symbread();
1.620 albertel 6018: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6019: }
6020: $symb=escape($symb);
6021:
1.620 albertel 6022: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6023:
1.620 albertel 6024: if (!$domain) { $domain=$env{'user.domain'}; }
6025: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6026: if ($domain eq 'public' && $stuname eq 'public') {
6027: $stuname=$ENV{'REMOTE_ADDR'};
6028: }
1.168 albertel 6029: my %returnhash;
6030: $namespace=~s/\//\_/g;
6031: $namespace=~s/\W//g;
6032: my %hash;
1.1117 foxr 6033: my $path=LONCAPA::tempdir();
1.168 albertel 6034: if (tie(%hash,'GDBM_File',
6035: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6036: &GDBM_READER(),0640)) {
1.168 albertel 6037: my $version=$hash{"version:$symb"};
6038: $returnhash{'version'}=$version;
6039: my $scope;
6040: for ($scope=1;$scope<=$version;$scope++) {
6041: my $vkeys=$hash{"$scope:keys:$symb"};
6042: my @keys=split(/:/,$vkeys);
6043: my $key;
6044: $returnhash{"$scope:keys"}=$vkeys;
6045: foreach $key (@keys) {
1.591 albertel 6046: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6047: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6048: }
6049: }
1.168 albertel 6050: if (!(untie(%hash))) {
6051: return "error:$!";
6052: }
6053: } else {
6054: return "error:$!";
6055: }
6056: return %returnhash;
1.167 albertel 6057: }
6058:
1.9 www 6059: # ----------------------------------------------------------------------- Store
6060:
6061: sub store {
1.1269 raeburn 6062: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6063: my $home='';
6064:
1.168 albertel 6065: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6066:
1.213 www 6067: $symb=&symbclean($symb);
1.122 albertel 6068: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6069:
1.620 albertel 6070: if (!$domain) { $domain=$env{'user.domain'}; }
6071: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6072:
6073: &devalidate($symb,$stuname,$domain);
1.109 www 6074:
6075: $symb=escape($symb);
1.187 www 6076: if (!$namespace) {
1.620 albertel 6077: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6078: return '';
6079: }
6080: }
1.620 albertel 6081: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6082:
6083: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
6084: $$storehash{'host'}=$perlvar{'lonHostID'};
6085:
1.12 www 6086: my $namevalue='';
1.800 albertel 6087: foreach my $key (keys(%$storehash)) {
6088: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6089: }
1.12 www 6090: $namevalue=~s/\&$//;
1.187 www 6091: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 6092: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6093: }
6094:
1.47 www 6095: # -------------------------------------------------------------- Critical Store
6096:
6097: sub cstore {
1.1269 raeburn 6098: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6099: my $home='';
6100:
1.168 albertel 6101: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6102:
1.213 www 6103: $symb=&symbclean($symb);
1.122 albertel 6104: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6105:
1.620 albertel 6106: if (!$domain) { $domain=$env{'user.domain'}; }
6107: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6108:
6109: &devalidate($symb,$stuname,$domain);
1.109 www 6110:
6111: $symb=escape($symb);
1.187 www 6112: if (!$namespace) {
1.620 albertel 6113: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6114: return '';
6115: }
6116: }
1.620 albertel 6117: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6118:
6119: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
6120: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6121:
1.47 www 6122: my $namevalue='';
1.800 albertel 6123: foreach my $key (keys(%$storehash)) {
6124: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6125: }
1.47 www 6126: $namevalue=~s/\&$//;
1.187 www 6127: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6128: return critical
1.1269 raeburn 6129: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6130: }
6131:
1.9 www 6132: # --------------------------------------------------------------------- Restore
6133:
6134: sub restore {
1.124 www 6135: my ($symb,$namespace,$domain,$stuname) = @_;
6136: my $home='';
6137:
1.168 albertel 6138: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6139:
1.122 albertel 6140: if (!$symb) {
1.1224 raeburn 6141: return if ($namespace eq 'courserequests');
6142: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6143: } else {
1.1224 raeburn 6144: unless ($namespace eq 'courserequests') {
6145: $symb=&escape(&symbclean($symb));
6146: }
1.122 albertel 6147: }
1.188 www 6148: if (!$namespace) {
1.620 albertel 6149: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6150: return '';
6151: }
6152: }
1.620 albertel 6153: if (!$domain) { $domain=$env{'user.domain'}; }
6154: if (!$stuname) { $stuname=$env{'user.name'}; }
6155: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6156: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6157:
1.12 www 6158: my %returnhash=();
1.800 albertel 6159: foreach my $line (split(/\&/,$answer)) {
6160: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6161: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6162: }
1.75 www 6163: my $version;
6164: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6165: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6166: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6167: }
1.75 www 6168: }
1.13 www 6169: return %returnhash;
1.34 www 6170: }
6171:
6172: # ---------------------------------------------------------- Course Description
1.1118 foxr 6173: #
6174: #
1.34 www 6175:
6176: sub coursedescription {
1.731 albertel 6177: my ($courseid,$args)=@_;
1.34 www 6178: $courseid=~s/^\///;
1.49 www 6179: $courseid=~s/\_/\//g;
1.34 www 6180: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6181: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6182: my $normalid=$cdomain.'_'.$cnum;
6183: # need to always cache even if we get errors otherwise we keep
6184: # trying and trying and trying to get the course description.
6185: my %envhash=();
6186: my %returnhash=();
1.731 albertel 6187:
6188: my $expiretime=600;
6189: if ($env{'request.course.id'} eq $normalid) {
6190: $expiretime=120;
6191: }
6192:
6193: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6194: if (!$args->{'freshen_cache'}
6195: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6196: foreach my $key (keys(%env)) {
6197: next if ($key !~ /^\Q$prefix\E(.*)/);
6198: my ($setting) = $1;
6199: $returnhash{$setting} = $env{$key};
6200: }
6201: return %returnhash;
6202: }
6203:
1.1118 foxr 6204: # get the data again
6205:
1.731 albertel 6206: if (!$args->{'one_time'}) {
6207: $envhash{'course.'.$normalid.'.last_cache'}=time;
6208: }
1.811 albertel 6209:
1.34 www 6210: if ($chome ne 'no_host') {
1.302 albertel 6211: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6212: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6213: my $username = $env{'user.name'}; # Defult username
6214: if(defined $args->{'user'}) {
6215: $username = $args->{'user'};
6216: }
1.129 albertel 6217: $returnhash{'home'}= $chome;
6218: $returnhash{'domain'} = $cdomain;
6219: $returnhash{'num'} = $cnum;
1.741 raeburn 6220: if (!defined($returnhash{'type'})) {
6221: $returnhash{'type'} = 'Course';
6222: }
1.130 albertel 6223: while (my ($name,$value) = each %returnhash) {
1.53 www 6224: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6225: }
1.270 www 6226: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6227: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6228: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6229: $envhash{'course.'.$normalid.'.home'}=$chome;
6230: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6231: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6232: }
6233: }
1.731 albertel 6234: if (!$args->{'one_time'}) {
1.949 raeburn 6235: &appenv(\%envhash);
1.731 albertel 6236: }
1.302 albertel 6237: return %returnhash;
1.461 www 6238: }
6239:
1.1080 raeburn 6240: sub update_released_required {
6241: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6242: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6243: $cid = $env{'request.course.id'};
6244: $cdom = $env{'course.'.$cid.'.domain'};
6245: $cnum = $env{'course.'.$cid.'.num'};
6246: $chome = $env{'course.'.$cid.'.home'};
6247: }
6248: if ($needsrelease) {
6249: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6250: my $needsupdate;
6251: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6252: $needsupdate = 1;
6253: } else {
6254: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6255: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6256: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6257: $needsupdate = 1;
6258: }
6259: }
6260: if ($needsupdate) {
6261: my %needshash = (
6262: 'internal.releaserequired' => $needsrelease,
6263: );
6264: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6265: if ($putresult eq 'ok') {
6266: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6267: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6268: if (ref($crsinfo{$cid}) eq 'HASH') {
6269: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6270: &courseidput($cdom,\%crsinfo,$chome,'notime');
6271: }
6272: }
6273: }
6274: }
6275: return;
6276: }
6277:
1.461 www 6278: # -------------------------------------------------See if a user is privileged
6279:
6280: sub privileged {
1.1219 raeburn 6281: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6282: my $now = time;
1.1219 raeburn 6283: my $roles;
6284: if (ref($possroles) eq 'ARRAY') {
6285: $roles = $possroles;
6286: } else {
6287: $roles = ['dc','su'];
6288: }
6289: if (ref($possdomains) eq 'ARRAY') {
6290: my %privileged = &privileged_by_domain($possdomains,$roles);
6291: foreach my $dom (@{$possdomains}) {
6292: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6293: (ref($privileged{$dom}) eq 'HASH')) {
6294: foreach my $role (@{$roles}) {
6295: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6296: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6297: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6298: return 1 unless (($end && $end < $now) ||
6299: ($start && $start > $now));
6300: }
6301: }
6302: }
6303: }
6304: }
6305: } else {
6306: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6307: my $now = time;
1.1170 droeschl 6308:
1.1275 musolffc 6309: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6310: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 6311: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 6312: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 6313: or ($tstart && $tstart > $now);
1.1170 droeschl 6314: }
1.1219 raeburn 6315: }
6316: }
6317: return 0;
6318: }
1.1170 droeschl 6319:
1.1219 raeburn 6320: sub privileged_by_domain {
6321: my ($domains,$roles) = @_;
6322: my %privileged = ();
6323: my $cachetime = 60*60*24;
6324: my $now = time;
6325: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6326: return %privileged;
6327: }
6328: foreach my $dom (@{$domains}) {
6329: next if (ref($privileged{$dom}) eq 'HASH');
6330: my $needroles;
6331: foreach my $role (@{$roles}) {
6332: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6333: if (defined($cached)) {
6334: if (ref($result) eq 'HASH') {
6335: $privileged{$dom}{$role} = $result;
6336: }
6337: } else {
6338: $needroles = 1;
6339: }
6340: }
6341: if ($needroles) {
6342: my %dompersonnel = &get_domain_roles($dom,$roles);
6343: $privileged{$dom} = {};
6344: foreach my $server (keys(%dompersonnel)) {
6345: if (ref($dompersonnel{$server}) eq 'HASH') {
6346: foreach my $item (keys(%{$dompersonnel{$server}})) {
6347: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6348: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6349: next if ($end && $end < $now);
6350: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6351: $dompersonnel{$server}{$item};
6352: }
6353: }
6354: }
6355: if (ref($privileged{$dom}) eq 'HASH') {
6356: foreach my $role (@{$roles}) {
6357: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6358: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6359: } else {
6360: my %hash = ();
6361: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6362: }
6363: }
6364: }
6365: }
6366: }
6367: return %privileged;
1.9 www 6368: }
1.1 albertel 6369:
1.103 harris41 6370: # -------------------------------------------------------- Get user privileges
1.11 www 6371:
6372: sub rolesinit {
1.1169 droeschl 6373: my ($domain, $username) = @_;
6374: my %userroles = ('user.login.time' => time);
6375: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6376:
6377: # firstaccess and timerinterval are related to timed maps/resources.
6378: # also, blocking can be triggered by an activating timer
6379: # it's saved in the user's %env.
6380: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6381: my %timerinterval = &dump('timerinterval', $domain, $username);
6382: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6383: %timerintchk, %timerintenv);
6384:
1.1162 raeburn 6385: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6386: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6387: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6388: }
1.1169 droeschl 6389:
1.1162 raeburn 6390: foreach my $key (keys(%timerinterval)) {
6391: my ($cid,$rest) = split(/\0/,$key);
6392: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6393: }
1.1169 droeschl 6394:
1.11 www 6395: my %allroles=();
1.1162 raeburn 6396: my %allgroups=();
1.11 www 6397:
1.1274 raeburn 6398: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6399: my $role = $rolesdump{$area};
6400: $area =~ s/\_\w\w$//;
6401:
6402: my ($trole, $tend, $tstart, $group_privs);
6403:
6404: if ($role =~ /^cr/) {
6405: # Custom role, defined by a user
6406: # e.g., user.role.cr/msu/smith/mynewrole
6407: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6408: $trole = $1;
6409: ($tend, $tstart) = split('_', $2);
6410: } else {
6411: $trole = $role;
6412: }
6413: } elsif ($role =~ m|^gr/|) {
6414: # Role of member in a group, defined within a course/community
6415: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6416: ($trole, $tend, $tstart) = split(/_/, $role);
6417: next if $tstart eq '-1';
6418: ($trole, $group_privs) = split(/\//, $trole);
6419: $group_privs = &unescape($group_privs);
6420: } else {
6421: # Just a normal role, defined in roles.tab
6422: ($trole, $tend, $tstart) = split(/_/,$role);
6423: }
6424:
6425: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6426: $username);
6427: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6428:
6429: # role expired or not available yet?
6430: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6431: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6432:
6433: next if $area eq '' or $trole eq '';
6434:
6435: my $spec = "$trole.$area";
6436: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6437:
6438: if ($trole =~ /^cr\//) {
6439: # Custom role, defined by a user
6440: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6441: } elsif ($trole eq 'gr') {
6442: # Role of a member in a group, defined within a course/community
6443: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6444: next;
6445: } else {
6446: # Normal role, defined in roles.tab
6447: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6448: }
6449:
6450: my $cid = $tdomain.'_'.$trest;
6451: unless ($firstaccchk{$cid}) {
6452: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6453: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6454: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6455: $coursetimerstarts{$cid}{$item};
6456: }
6457: }
6458: $firstaccchk{$cid} = 1;
6459: }
6460: unless ($timerintchk{$cid}) {
6461: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6462: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6463: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6464: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6465: }
1.12 www 6466: }
1.1169 droeschl 6467: $timerintchk{$cid} = 1;
1.191 harris41 6468: }
1.11 www 6469: }
1.1169 droeschl 6470:
1.1341 raeburn 6471: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6472: \%allroles, \%allgroups);
1.1169 droeschl 6473: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 6474: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6475:
1.1162 raeburn 6476: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6477: }
6478:
1.567 raeburn 6479: sub set_arearole {
1.1215 raeburn 6480: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6481: unless ($nolog) {
1.567 raeburn 6482: # log the associated role with the area
1.1215 raeburn 6483: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6484: }
1.743 albertel 6485: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6486: }
6487:
6488: sub custom_roleprivs {
6489: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6490: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 6491: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6492: if (&hostname($homsvr) ne '') {
1.567 raeburn 6493: my ($rdummy,$roledef)=
6494: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6495: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6496: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6497: if (defined($syspriv)) {
1.1043 raeburn 6498: if ($trest =~ /^$match_community$/) {
6499: $syspriv =~ s/bre\&S//;
6500: }
1.567 raeburn 6501: $$allroles{'cm./'}.=':'.$syspriv;
6502: $$allroles{$spec.'./'}.=':'.$syspriv;
6503: }
6504: if ($tdomain ne '') {
6505: if (defined($dompriv)) {
6506: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6507: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6508: }
6509: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 6510: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6511: my $rolename = $1;
6512: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6513: }
1.567 raeburn 6514: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6515: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6516: }
6517: }
6518: }
6519: }
6520: }
6521:
1.1332 raeburn 6522: sub course_adhocrole_privs {
6523: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6524: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6525: if ($overrides{"internal.adhocpriv.$rolename"}) {
6526: my (%currprivs,%storeprivs);
6527: foreach my $item (split(/:/,$coursepriv)) {
6528: my ($priv,$restrict) = split(/\&/,$item);
6529: $currprivs{$priv} = $restrict;
6530: }
6531: my (%possadd,%possremove,%full);
6532: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6533: my ($priv,$restrict)=split(/\&/,$item);
6534: $full{$priv} = $restrict;
6535: }
6536: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6537: next if ($item eq '');
6538: my ($rule,$rest) = split(/=/,$item);
6539: next unless (($rule eq 'off') || ($rule eq 'on'));
6540: foreach my $priv (split(/:/,$rest)) {
6541: if ($priv ne '') {
6542: if ($rule eq 'off') {
6543: $possremove{$priv} = 1;
6544: } else {
6545: $possadd{$priv} = 1;
6546: }
6547: }
6548: }
6549: }
6550: foreach my $priv (sort(keys(%full))) {
6551: if (exists($currprivs{$priv})) {
6552: unless (exists($possremove{$priv})) {
6553: $storeprivs{$priv} = $currprivs{$priv};
6554: }
6555: } elsif (exists($possadd{$priv})) {
6556: $storeprivs{$priv} = $full{$priv};
6557: }
6558: }
6559: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6560: }
6561: return $coursepriv;
6562: }
6563:
1.678 raeburn 6564: sub group_roleprivs {
6565: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6566: my $access = 1;
6567: my $now = time;
6568: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6569: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6570: if ($access) {
1.811 albertel 6571: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6572: $$allgroups{$course}{$group} .=':'.$group_privs;
6573: }
6574: }
1.567 raeburn 6575:
6576: sub standard_roleprivs {
6577: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6578: if (defined($pr{$trole.':s'})) {
6579: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6580: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6581: }
6582: if ($tdomain ne '') {
6583: if (defined($pr{$trole.':d'})) {
6584: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6585: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6586: }
6587: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6588: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6589: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6590: }
6591: }
6592: }
6593:
6594: sub set_userprivs {
1.1064 raeburn 6595: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6596: my $author=0;
6597: my $adv=0;
1.1341 raeburn 6598: my $rar=0;
1.678 raeburn 6599: my %grouproles = ();
6600: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6601: my @groupkeys;
1.1000 raeburn 6602: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6603: push(@groupkeys,$role);
6604: }
6605: if (ref($groups_roles) eq 'HASH') {
6606: foreach my $key (keys(%{$groups_roles})) {
6607: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6608: push(@groupkeys,$key);
6609: }
6610: }
6611: }
6612: if (@groupkeys > 0) {
6613: foreach my $role (@groupkeys) {
6614: my ($trole,$area,$sec,$extendedarea);
6615: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6616: $trole = $1;
6617: $area = $2;
6618: $sec = $3;
6619: $extendedarea = $area.$sec;
6620: if (exists($$allgroups{$area})) {
6621: foreach my $group (keys(%{$$allgroups{$area}})) {
6622: my $spec = $trole.'.'.$extendedarea;
6623: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6624: $$allgroups{$area}{$group};
1.1064 raeburn 6625: }
1.678 raeburn 6626: }
6627: }
6628: }
6629: }
6630: }
1.800 albertel 6631: foreach my $group (keys(%grouproles)) {
6632: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6633: }
1.800 albertel 6634: foreach my $role (keys(%{$allroles})) {
6635: my %thesepriv;
1.941 raeburn 6636: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6637: foreach my $item (split(/:/,$$allroles{$role})) {
6638: if ($item ne '') {
6639: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6640: if ($restrictions eq '') {
6641: $thesepriv{$privilege}='F';
6642: } elsif ($thesepriv{$privilege} ne 'F') {
6643: $thesepriv{$privilege}.=$restrictions;
6644: }
6645: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 6646: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6647: }
6648: }
6649: my $thesestr='';
1.1104 raeburn 6650: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6651: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6652: }
6653: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6654: }
1.1341 raeburn 6655: return ($author,$adv,$rar);
1.567 raeburn 6656: }
6657:
1.994 raeburn 6658: sub role_status {
1.1104 raeburn 6659: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6660: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 6661: my ($one,$two) = split(m{\./},$rolekey,2);
6662: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6663: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 6664: $$where = '/'.$two;
1.994 raeburn 6665: $$trolecode=$$role.'.'.$$where;
6666: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6667: $$tstatus='is';
1.1104 raeburn 6668: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6669: $$tstatus='future';
1.1034 raeburn 6670: if ($$tstart<$now) {
6671: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6672: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6673: my (%allroles,%allgroups,$group_privs,
6674: %groups_roles,@rolecodes);
1.1002 raeburn 6675: my %userroles = (
6676: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6677: );
1.1064 raeburn 6678: @rolecodes = ('cm');
1.1002 raeburn 6679: my $spec=$$role.'.'.$$where;
6680: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6681: if ($$role =~ /^cr\//) {
6682: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6683: push(@rolecodes,'cr');
1.1002 raeburn 6684: } elsif ($$role eq 'gr') {
1.1064 raeburn 6685: push(@rolecodes,$$role);
1.1002 raeburn 6686: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6687: $env{'user.name'});
1.1064 raeburn 6688: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6689: (undef,my $group_privs) = split(/\//,$trole);
6690: $group_privs = &unescape($group_privs);
6691: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6692: 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 6693: &get_groups_roles($tdomain,$trest,
6694: \%course_roles,\@rolecodes,
6695: \%groups_roles);
1.1002 raeburn 6696: } else {
1.1064 raeburn 6697: push(@rolecodes,$$role);
1.1002 raeburn 6698: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6699: }
1.1341 raeburn 6700: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6701: \%groups_roles);
1.1064 raeburn 6702: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 6703: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6704: }
6705: }
1.1034 raeburn 6706: $$tstatus = 'is';
1.1002 raeburn 6707: }
1.994 raeburn 6708: }
6709: if ($$tend) {
1.1104 raeburn 6710: if ($$tend<$update) {
1.994 raeburn 6711: $$tstatus='expired';
6712: } elsif ($$tend<$now) {
6713: $$tstatus='will_not';
6714: }
6715: }
6716: }
6717: }
6718: }
6719:
1.1104 raeburn 6720: sub get_groups_roles {
6721: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6722: return unless((ref($cdom_courseroles) eq 'HASH') &&
6723: (ref($rolecodes) eq 'ARRAY') &&
6724: (ref($groups_roles) eq 'HASH'));
6725: if (keys(%{$cdom_courseroles}) > 0) {
6726: my ($cnum) = ($rest =~ /^($match_courseid)/);
6727: if ($cdom ne '' && $cnum ne '') {
6728: foreach my $key (keys(%{$cdom_courseroles})) {
6729: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6730: my $crsrole = $1;
6731: my $crssec = $2;
6732: if ($crsrole =~ /^cr/) {
6733: unless (grep(/^cr$/,@{$rolecodes})) {
6734: push(@{$rolecodes},'cr');
6735: }
6736: } else {
6737: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6738: push(@{$rolecodes},$crsrole);
6739: }
6740: }
6741: my $rolekey = "$crsrole./$cdom/$cnum";
6742: if ($crssec ne '') {
6743: $rolekey .= "/$crssec";
6744: }
6745: $rolekey .= './';
6746: $groups_roles->{$rolekey} = $rolecodes;
6747: }
6748: }
6749: }
6750: }
6751: return;
6752: }
6753:
6754: sub delete_env_groupprivs {
6755: my ($where,$courseroles,$possroles) = @_;
6756: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6757: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6758: unless (ref($courseroles->{$udom}) eq 'HASH') {
6759: %{$courseroles->{$udom}} =
6760: &get_my_roles('','','userroles',['active'],
6761: $possroles,[$udom],1);
6762: }
6763: if (ref($courseroles->{$udom}) eq 'HASH') {
6764: foreach my $item (keys(%{$courseroles->{$udom}})) {
6765: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6766: my $area = '/'.$cdom.'/'.$cnum;
6767: my $privkey = "user.priv.$crsrole.$area";
6768: if ($crssec ne '') {
6769: $privkey .= '/'.$crssec;
6770: }
6771: $privkey .= ".$area/$group";
6772: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6773: }
6774: }
6775: return;
6776: }
6777:
1.994 raeburn 6778: sub check_adhoc_privs {
1.1329 raeburn 6779: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6780: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 6781: if ($sec) {
6782: $cckey .= '/'.$sec;
6783: }
1.1185 raeburn 6784: my $setprivs;
1.994 raeburn 6785: if ($env{$cckey}) {
6786: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6787: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6788: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 6789: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6790: $setprivs = 1;
1.994 raeburn 6791: }
6792: } else {
1.1330 raeburn 6793: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6794: $setprivs = 1;
1.994 raeburn 6795: }
1.1185 raeburn 6796: return $setprivs;
1.994 raeburn 6797: }
6798:
6799: sub set_adhoc_privileges {
1.1326 raeburn 6800: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 6801: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6802: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 6803: if ($sec ne '') {
6804: $area .= '/'.$sec;
6805: }
1.994 raeburn 6806: my $spec = $role.'.'.$area;
6807: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 6808: $env{'user.name'},1);
1.1326 raeburn 6809: my %rolehash = ();
1.1332 raeburn 6810: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6811: my $rolename = $1;
1.1326 raeburn 6812: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 6813: my %domdef = &get_domain_defaults($dcdom);
6814: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6815: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6816: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6817: }
6818: }
1.1326 raeburn 6819: } else {
6820: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6821: }
1.1341 raeburn 6822: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6823: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 6824: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402 raeburn 6825: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
6826: ($caller eq 'tiny')) {
1.1088 raeburn 6827: &appenv( {'request.role' => $spec,
6828: 'request.role.domain' => $dcdom,
1.1332 raeburn 6829: 'request.course.sec' => $sec,
1.1088 raeburn 6830: }
6831: );
6832: my $tadv=0;
6833: if (&allowed('adv') eq 'F') { $tadv=1; }
6834: &appenv({'request.role.adv' => $tadv});
6835: }
1.994 raeburn 6836: }
6837:
1.12 www 6838: # --------------------------------------------------------------- get interface
6839:
6840: sub get {
1.131 albertel 6841: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6842: my $items='';
1.800 albertel 6843: foreach my $item (@$storearr) {
6844: $items.=&escape($item).'&';
1.191 harris41 6845: }
1.12 www 6846: $items=~s/\&$//;
1.620 albertel 6847: if (!$udomain) { $udomain=$env{'user.domain'}; }
6848: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6849: my $uhome=&homeserver($uname,$udomain);
6850:
1.133 albertel 6851: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6852: my @pairs=split(/\&/,$rep);
1.273 albertel 6853: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6854: return @pairs;
6855: }
1.15 www 6856: my %returnhash=();
1.42 www 6857: my $i=0;
1.800 albertel 6858: foreach my $item (@$storearr) {
6859: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6860: $i++;
1.191 harris41 6861: }
1.15 www 6862: return %returnhash;
1.27 www 6863: }
6864:
6865: # --------------------------------------------------------------- del interface
6866:
6867: sub del {
1.133 albertel 6868: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6869: my $items='';
1.800 albertel 6870: foreach my $item (@$storearr) {
6871: $items.=&escape($item).'&';
1.191 harris41 6872: }
1.984 neumanie 6873:
1.27 www 6874: $items=~s/\&$//;
1.620 albertel 6875: if (!$udomain) { $udomain=$env{'user.domain'}; }
6876: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6877: my $uhome=&homeserver($uname,$udomain);
6878: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6879: }
6880:
6881: # -------------------------------------------------------------- dump interface
6882:
1.1180 droeschl 6883: sub unserialize {
6884: my ($rep, $escapedkeys) = @_;
6885:
6886: return {} if $rep =~ /^error/;
6887:
6888: my %returnhash=();
1.1252 raeburn 6889: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 6890: my ($key, $value) = split(/=/, $item, 2);
6891: $key = unescape($key) unless $escapedkeys;
6892: next if $key =~ /^error: 2 /;
1.1252 raeburn 6893: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 6894: }
6895: #return %returnhash;
6896: return \%returnhash;
6897: }
6898:
6899: # see Lond::dump_with_regexp
6900: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6901: sub dump {
1.1180 droeschl 6902: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6903: if (!$udomain) { $udomain=$env{'user.domain'}; }
6904: if (!$uname) { $uname=$env{'user.name'}; }
6905: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6906:
1.1266 raeburn 6907: if ($regexp) {
6908: $regexp=&escape($regexp);
6909: } else {
6910: $regexp='.';
6911: }
1.1180 droeschl 6912: if (grep { $_ eq $uhome } current_machine_ids()) {
6913: # user is hosted on this machine
1.1266 raeburn 6914: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 6915: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 6916: return %{unserialize($reply, $escapedkeys)};
6917: }
1.1166 raeburn 6918: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6919: my @pairs=split(/\&/,$rep);
6920: my %returnhash=();
1.1098 foxr 6921: if (!($rep =~ /^error/ )) {
6922: foreach my $item (@pairs) {
6923: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 6924: $key = unescape($key) unless $escapedkeys;
6925: #$key = &unescape($key);
1.1098 foxr 6926: next if ($key =~ /^error: 2 /);
6927: $returnhash{$key}=&thaw_unescape($value);
6928: }
1.755 albertel 6929: }
6930: return %returnhash;
1.407 www 6931: }
6932:
1.1098 foxr 6933:
1.717 albertel 6934: # --------------------------------------------------------- dumpstore interface
6935:
6936: sub dumpstore {
6937: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 6938: # same as dump but keys must be escaped. They may contain colon separated
6939: # lists of values that may themself contain colons (e.g. symbs).
6940: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6941: }
6942:
1.407 www 6943: # -------------------------------------------------------------- keys interface
6944:
6945: sub getkeys {
6946: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6947: if (!$udomain) { $udomain=$env{'user.domain'}; }
6948: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6949: my $uhome=&homeserver($uname,$udomain);
6950: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6951: my @keyarray=();
1.800 albertel 6952: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6953: next if ($key =~ /^error: 2 /);
1.800 albertel 6954: push(@keyarray,&unescape($key));
1.407 www 6955: }
6956: return @keyarray;
1.318 matthew 6957: }
6958:
1.319 matthew 6959: # --------------------------------------------------------------- currentdump
6960: sub currentdump {
1.328 matthew 6961: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6962: $courseid = $env{'request.course.id'} if (! defined($courseid));
6963: $sdom = $env{'user.domain'} if (! defined($sdom));
6964: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6965: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 6966: my $rep;
6967:
6968: if (grep { $_ eq $uhome } current_machine_ids()) {
6969: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6970: $courseid)));
6971: } else {
6972: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6973: }
6974:
1.318 matthew 6975: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6976: #
1.318 matthew 6977: my %returnhash=();
1.319 matthew 6978: #
1.1343 raeburn 6979: if ($rep eq 'unknown_cmd') {
1.319 matthew 6980: # an old lond will not know currentdump
6981: # Do a dump and make it look like a currentdump
1.822 albertel 6982: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6983: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6984: my %hash = @tmp;
6985: @tmp=();
1.424 matthew 6986: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6987: } else {
6988: my @pairs=split(/\&/,$rep);
1.800 albertel 6989: foreach my $pair (@pairs) {
6990: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6991: my ($symb,$param) = split(/:/,$key);
6992: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6993: &thaw_unescape($value);
1.319 matthew 6994: }
1.191 harris41 6995: }
1.12 www 6996: return %returnhash;
1.424 matthew 6997: }
6998:
6999: sub convert_dump_to_currentdump{
7000: my %hash = %{shift()};
7001: my %returnhash;
7002: # Code ripped from lond, essentially. The only difference
7003: # here is the unescaping done by lonnet::dump(). Conceivably
7004: # we might run in to problems with parameter names =~ /^v\./
7005: while (my ($key,$value) = each(%hash)) {
7006: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7007: $symb = &unescape($symb);
7008: $param = &unescape($param);
1.424 matthew 7009: next if ($v eq 'version' || $symb eq 'keys');
7010: next if (exists($returnhash{$symb}) &&
7011: exists($returnhash{$symb}->{$param}) &&
7012: $returnhash{$symb}->{'v.'.$param} > $v);
7013: $returnhash{$symb}->{$param}=$value;
7014: $returnhash{$symb}->{'v.'.$param}=$v;
7015: }
7016: #
7017: # Remove all of the keys in the hashes which keep track of
7018: # the version of the parameter.
7019: while (my ($symb,$param_hash) = each(%returnhash)) {
7020: # use a foreach because we are going to delete from the hash.
7021: foreach my $key (keys(%$param_hash)) {
7022: delete($param_hash->{$key}) if ($key =~ /^v\./);
7023: }
7024: }
7025: return \%returnhash;
1.12 www 7026: }
7027:
1.627 albertel 7028: # ------------------------------------------------------ critical inc interface
7029:
7030: sub cinc {
7031: return &inc(@_,'critical');
7032: }
7033:
1.449 matthew 7034: # --------------------------------------------------------------- inc interface
7035:
7036: sub inc {
1.627 albertel 7037: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7038: if (!$udomain) { $udomain=$env{'user.domain'}; }
7039: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7040: my $uhome=&homeserver($uname,$udomain);
7041: my $items='';
7042: if (! ref($store)) {
7043: # got a single value, so use that instead
7044: $items = &escape($store).'=&';
7045: } elsif (ref($store) eq 'SCALAR') {
7046: $items = &escape($$store).'=&';
7047: } elsif (ref($store) eq 'ARRAY') {
7048: $items = join('=&',map {&escape($_);} @{$store});
7049: } elsif (ref($store) eq 'HASH') {
7050: while (my($key,$value) = each(%{$store})) {
7051: $items.= &escape($key).'='.&escape($value).'&';
7052: }
7053: }
7054: $items=~s/\&$//;
1.627 albertel 7055: if ($critical) {
7056: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7057: } else {
7058: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7059: }
1.449 matthew 7060: }
7061:
1.12 www 7062: # --------------------------------------------------------------- put interface
7063:
7064: sub put {
1.134 albertel 7065: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7066: if (!$udomain) { $udomain=$env{'user.domain'}; }
7067: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7068: my $uhome=&homeserver($uname,$udomain);
1.12 www 7069: my $items='';
1.800 albertel 7070: foreach my $item (keys(%$storehash)) {
7071: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7072: }
1.12 www 7073: $items=~s/\&$//;
1.134 albertel 7074: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 7075: }
7076:
1.631 albertel 7077: # ------------------------------------------------------------ newput interface
7078:
7079: sub newput {
7080: my ($namespace,$storehash,$udomain,$uname)=@_;
7081: if (!$udomain) { $udomain=$env{'user.domain'}; }
7082: if (!$uname) { $uname=$env{'user.name'}; }
7083: my $uhome=&homeserver($uname,$udomain);
7084: my $items='';
7085: foreach my $key (keys(%$storehash)) {
7086: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7087: }
7088: $items=~s/\&$//;
7089: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7090: }
7091:
7092: # --------------------------------------------------------- putstore interface
7093:
1.524 raeburn 7094: sub putstore {
1.1269 raeburn 7095: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7096: if (!$udomain) { $udomain=$env{'user.domain'}; }
7097: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7098: my $uhome=&homeserver($uname,$udomain);
7099: my $items='';
1.715 albertel 7100: foreach my $key (keys(%$storehash)) {
7101: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7102: }
1.715 albertel 7103: $items=~s/\&$//;
1.716 albertel 7104: my $esc_symb=&escape($symb);
7105: my $esc_v=&escape($version);
1.715 albertel 7106: my $reply =
1.716 albertel 7107: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7108: $uhome);
1.1269 raeburn 7109: if (($tolog) && ($reply eq 'ok')) {
7110: my $namevalue='';
7111: foreach my $key (keys(%{$storehash})) {
7112: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7113: }
7114: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
7115: '&host='.&escape($perlvar{'lonHostID'}).
7116: '&version='.$esc_v.
7117: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7118: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7119: }
1.715 albertel 7120: if ($reply eq 'unknown_cmd') {
1.716 albertel 7121: # gfall back to way things use to be done
1.715 albertel 7122: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7123: $uname);
1.524 raeburn 7124: }
1.715 albertel 7125: return $reply;
7126: }
7127:
7128: sub old_putstore {
1.716 albertel 7129: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7130: if (!$udomain) { $udomain=$env{'user.domain'}; }
7131: if (!$uname) { $uname=$env{'user.name'}; }
7132: my $uhome=&homeserver($uname,$udomain);
7133: my %newstorehash;
1.800 albertel 7134: foreach my $item (keys(%$storehash)) {
7135: my $key = $version.':'.&escape($symb).':'.$item;
7136: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7137: }
7138: my $items='';
7139: my %allitems = ();
1.800 albertel 7140: foreach my $item (keys(%newstorehash)) {
7141: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7142: my $key = $1.':keys:'.$2;
7143: $allitems{$key} .= $3.':';
7144: }
1.800 albertel 7145: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7146: }
1.800 albertel 7147: foreach my $item (keys(%allitems)) {
7148: $allitems{$item} =~ s/\:$//;
7149: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7150: }
7151: $items=~s/\&$//;
7152: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7153: }
7154:
1.47 www 7155: # ------------------------------------------------------ critical put interface
7156:
7157: sub cput {
1.134 albertel 7158: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7159: if (!$udomain) { $udomain=$env{'user.domain'}; }
7160: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7161: my $uhome=&homeserver($uname,$udomain);
1.47 www 7162: my $items='';
1.800 albertel 7163: foreach my $item (keys(%$storehash)) {
7164: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7165: }
1.47 www 7166: $items=~s/\&$//;
1.134 albertel 7167: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7168: }
7169:
7170: # -------------------------------------------------------------- eget interface
7171:
7172: sub eget {
1.133 albertel 7173: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7174: my $items='';
1.800 albertel 7175: foreach my $item (@$storearr) {
7176: $items.=&escape($item).'&';
1.191 harris41 7177: }
1.12 www 7178: $items=~s/\&$//;
1.620 albertel 7179: if (!$udomain) { $udomain=$env{'user.domain'}; }
7180: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7181: my $uhome=&homeserver($uname,$udomain);
7182: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7183: my @pairs=split(/\&/,$rep);
7184: my %returnhash=();
1.42 www 7185: my $i=0;
1.800 albertel 7186: foreach my $item (@$storearr) {
7187: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7188: $i++;
1.191 harris41 7189: }
1.12 www 7190: return %returnhash;
7191: }
7192:
1.667 albertel 7193: # ------------------------------------------------------------ tmpput interface
7194: sub tmpput {
1.802 raeburn 7195: my ($storehash,$server,$context)=@_;
1.667 albertel 7196: my $items='';
1.800 albertel 7197: foreach my $item (keys(%$storehash)) {
7198: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7199: }
7200: $items=~s/\&$//;
1.802 raeburn 7201: if (defined($context)) {
7202: $items .= ':'.&escape($context);
7203: }
1.667 albertel 7204: return &reply("tmpput:$items",$server);
7205: }
7206:
7207: # ------------------------------------------------------------ tmpget interface
7208: sub tmpget {
1.688 albertel 7209: my ($token,$server)=@_;
7210: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7211: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7212: my %returnhash;
1.1328 raeburn 7213: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7214: return %returnhash;
7215: }
1.667 albertel 7216: foreach my $item (split(/\&/,$rep)) {
7217: my ($key,$value)=split(/=/,$item);
7218: $returnhash{&unescape($key)}=&thaw_unescape($value);
7219: }
7220: return %returnhash;
7221: }
7222:
1.1113 raeburn 7223: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7224: sub tmpdel {
7225: my ($token,$server)=@_;
7226: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7227: return &reply("tmpdel:$token",$server);
7228: }
7229:
1.1198 raeburn 7230: # ------------------------------------------------------------ get_timebased_id
7231:
7232: sub get_timebased_id {
7233: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7234: $maxtries) = @_;
7235: my ($newid,$error,$dellock);
7236: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7237: return ('','ok','invalid call to get suffix');
7238: }
7239:
7240: # set defaults for any optional args for which values were not supplied
7241: if ($who eq '') {
7242: $who = $env{'user.name'}.':'.$env{'user.domain'};
7243: }
7244: if (!$locktries) {
7245: $locktries = 3;
7246: }
7247: if (!$maxtries) {
7248: $maxtries = 10;
7249: }
7250:
7251: if (($cdom eq '') || ($cnum eq '')) {
7252: if ($env{'request.course.id'}) {
7253: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7254: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7255: }
7256: if (($cdom eq '') || ($cnum eq '')) {
7257: return ('','ok','call to get suffix not in course context');
7258: }
7259: }
7260:
7261: # construct locking item
7262: my $lockhash = {
7263: $prefix."\0".'locked_'.$keyid => $who,
7264: };
7265: my $tries = 0;
7266:
7267: # attempt to get lock on nohist_$namespace file
7268: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7269: while (($gotlock ne 'ok') && $tries <$locktries) {
7270: $tries ++;
7271: sleep 1;
7272: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7273: }
7274:
7275: # attempt to get unique identifier, based on current timestamp
7276: if ($gotlock eq 'ok') {
7277: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7278: my $id = time;
7279: $newid = $id;
1.1268 raeburn 7280: if ($idtype eq 'addcode') {
7281: $newid .= &sixnum_code();
7282: }
1.1198 raeburn 7283: my $idtries = 0;
7284: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7285: if ($idtype eq 'concat') {
7286: $newid = $id.$idtries;
1.1268 raeburn 7287: } elsif ($idtype eq 'addcode') {
7288: $newid = $newid.&sixnum_code();
1.1198 raeburn 7289: } else {
7290: $newid ++;
7291: }
7292: $idtries ++;
7293: }
7294: if (!exists($inuse{$prefix."\0".$newid})) {
7295: my %new_item = (
7296: $prefix."\0".$newid => $who,
7297: );
7298: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7299: $cdom,$cnum);
7300: if ($putresult ne 'ok') {
7301: undef($newid);
7302: $error = 'error saving new item: '.$putresult;
7303: }
7304: } else {
1.1268 raeburn 7305: undef($newid);
1.1198 raeburn 7306: $error = ('error: no unique suffix available for the new item ');
7307: }
7308: # remove lock
7309: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7310: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7311: } else {
7312: $error = "error: could not obtain lockfile\n";
7313: $dellock = 'ok';
1.1276 raeburn 7314: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7315: $dellock = 'nolock';
7316: }
1.1198 raeburn 7317: }
7318: return ($newid,$dellock,$error);
7319: }
7320:
1.1268 raeburn 7321: sub sixnum_code {
7322: my $code;
7323: for (0..6) {
7324: $code .= int( rand(9) );
7325: }
7326: return $code;
7327: }
7328:
1.765 albertel 7329: # -------------------------------------------------- portfolio access checking
7330:
7331: sub portfolio_access {
1.1270 raeburn 7332: my ($requrl,$clientip) = @_;
1.765 albertel 7333: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 7334: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7335: if ($result) {
7336: my %setters;
7337: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7338: my ($startblock,$endblock) =
7339: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
7340: if ($startblock && $endblock) {
7341: return 'B';
7342: }
7343: } else {
7344: my ($startblock,$endblock) =
7345: &Apache::loncommon::blockcheck(\%setters,'port');
7346: if ($startblock && $endblock) {
7347: return 'B';
7348: }
7349: }
7350: }
1.765 albertel 7351: if ($result eq 'ok') {
1.766 albertel 7352: return 'F';
1.765 albertel 7353: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7354: return 'A';
1.765 albertel 7355: }
1.766 albertel 7356: return '';
1.765 albertel 7357: }
7358:
7359: sub get_portfolio_access {
1.1270 raeburn 7360: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7361:
7362: if (!ref($access_hash)) {
7363: my $current_perms = &get_portfile_permissions($udom,$unum);
7364: my %access_controls = &get_access_controls($current_perms,$group,
7365: $file_name);
7366: $access_hash = $access_controls{$file_name};
7367: }
7368:
1.1270 raeburn 7369: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7370: my $now = time;
7371: if (ref($access_hash) eq 'HASH') {
7372: foreach my $key (keys(%{$access_hash})) {
7373: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7374: if ($start > $now) {
7375: next;
7376: }
7377: if ($end && $end<$now) {
7378: next;
7379: }
7380: if ($scope eq 'public') {
7381: $public = $key;
7382: last;
7383: } elsif ($scope eq 'guest') {
7384: $guest = $key;
7385: } elsif ($scope eq 'domains') {
7386: push(@domains,$key);
7387: } elsif ($scope eq 'users') {
7388: push(@users,$key);
7389: } elsif ($scope eq 'course') {
7390: push(@courses,$key);
7391: } elsif ($scope eq 'group') {
7392: push(@groups,$key);
1.1270 raeburn 7393: } elsif ($scope eq 'ip') {
7394: push(@ips,$key);
1.765 albertel 7395: }
7396: }
7397: if ($public) {
7398: return 'ok';
1.1270 raeburn 7399: } elsif (@ips > 0) {
7400: my $allowed;
7401: foreach my $ipkey (@ips) {
7402: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7403: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7404: $allowed = 1;
7405: last;
7406: }
7407: }
7408: }
7409: if ($allowed) {
7410: return 'ok';
7411: }
1.765 albertel 7412: }
7413: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7414: if ($guest) {
7415: return $guest;
7416: }
7417: } else {
7418: if (@domains > 0) {
7419: foreach my $domkey (@domains) {
7420: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7421: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7422: return 'ok';
7423: }
7424: }
7425: }
7426: }
7427: if (@users > 0) {
7428: foreach my $userkey (@users) {
1.865 raeburn 7429: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7430: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7431: if (ref($item) eq 'HASH') {
7432: if (($item->{'uname'} eq $env{'user.name'}) &&
7433: ($item->{'udom'} eq $env{'user.domain'})) {
7434: return 'ok';
7435: }
7436: }
7437: }
7438: }
1.765 albertel 7439: }
7440: }
7441: my %roleshash;
7442: my @courses_and_groups = @courses;
7443: push(@courses_and_groups,@groups);
7444: if (@courses_and_groups > 0) {
7445: my (%allgroups,%allroles);
7446: my ($start,$end,$role,$sec,$group);
7447: foreach my $envkey (%env) {
1.1060 raeburn 7448: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7449: my $cid = $2.'_'.$3;
7450: if ($1 eq 'gr') {
7451: $group = $4;
7452: $allgroups{$cid}{$group} = $env{$envkey};
7453: } else {
7454: if ($4 eq '') {
7455: $sec = 'none';
7456: } else {
7457: $sec = $4;
7458: }
7459: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7460: }
1.811 albertel 7461: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7462: my $cid = $2.'_'.$3;
7463: if ($4 eq '') {
7464: $sec = 'none';
7465: } else {
7466: $sec = $4;
7467: }
7468: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7469: }
7470: }
7471: if (keys(%allroles) == 0) {
7472: return;
7473: }
7474: foreach my $key (@courses_and_groups) {
7475: my %content = %{$$access_hash{$key}};
7476: my $cnum = $content{'number'};
7477: my $cdom = $content{'domain'};
7478: my $cid = $cdom.'_'.$cnum;
7479: if (!exists($allroles{$cid})) {
7480: next;
7481: }
7482: foreach my $role_id (keys(%{$content{'roles'}})) {
7483: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7484: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7485: my @status = @{$content{'roles'}{$role_id}{'access'}};
7486: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7487: foreach my $role (keys(%{$allroles{$cid}})) {
7488: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7489: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7490: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7491: if (grep/^all$/,@sections) {
7492: return 'ok';
7493: } else {
7494: if (grep/^$sec$/,@sections) {
7495: return 'ok';
7496: }
7497: }
7498: }
7499: }
7500: if (keys(%{$allgroups{$cid}}) == 0) {
7501: if (grep/^none$/,@groups) {
7502: return 'ok';
7503: }
7504: } else {
7505: if (grep/^all$/,@groups) {
7506: return 'ok';
7507: }
7508: foreach my $group (keys(%{$allgroups{$cid}})) {
7509: if (grep/^$group$/,@groups) {
7510: return 'ok';
7511: }
7512: }
7513: }
7514: }
7515: }
7516: }
7517: }
7518: }
7519: if ($guest) {
7520: return $guest;
7521: }
7522: }
7523: }
7524: return;
7525: }
7526:
7527: sub course_group_datechecker {
7528: my ($dates,$now,$status) = @_;
7529: my ($start,$end) = split(/\./,$dates);
7530: if (!$start && !$end) {
7531: return 'ok';
7532: }
7533: if (grep/^active$/,@{$status}) {
7534: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7535: return 'ok';
7536: }
7537: }
7538: if (grep/^previous$/,@{$status}) {
7539: if ($end > $now ) {
7540: return 'ok';
7541: }
7542: }
7543: if (grep/^future$/,@{$status}) {
7544: if ($start > $now) {
7545: return 'ok';
7546: }
7547: }
7548: return;
7549: }
7550:
7551: sub parse_portfolio_url {
7552: my ($url) = @_;
7553:
7554: my ($type,$udom,$unum,$group,$file_name);
7555:
1.823 albertel 7556: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7557: $type = 1;
7558: $udom = $1;
7559: $unum = $2;
7560: $file_name = $3;
1.823 albertel 7561: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7562: $type = 2;
7563: $udom = $1;
7564: $unum = $2;
7565: $group = $3;
7566: $file_name = $3.'/'.$4;
7567: }
7568: if (wantarray) {
7569: return ($type,$udom,$unum,$file_name,$group);
7570: }
7571: return $type;
7572: }
7573:
7574: sub is_portfolio_url {
7575: my ($url) = @_;
7576: return scalar(&parse_portfolio_url($url));
7577: }
7578:
1.798 raeburn 7579: sub is_portfolio_file {
7580: my ($file) = @_;
1.820 raeburn 7581: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7582: return 1;
7583: }
7584: return;
7585: }
7586:
1.976 raeburn 7587: sub usertools_access {
1.1084 raeburn 7588: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7589: my ($access,%tools);
7590: if ($context eq '') {
7591: $context = 'tools';
7592: }
7593: if ($context eq 'requestcourses') {
7594: %tools = (
7595: official => 1,
7596: unofficial => 1,
1.1006 raeburn 7597: community => 1,
1.1246 raeburn 7598: textbook => 1,
1.1305 raeburn 7599: placement => 1,
1.1368 raeburn 7600: lti => 1,
1.985 raeburn 7601: );
1.1183 raeburn 7602: } elsif ($context eq 'requestauthor') {
7603: %tools = (
7604: requestauthor => 1,
7605: );
1.985 raeburn 7606: } else {
7607: %tools = (
7608: aboutme => 1,
7609: blog => 1,
1.1177 raeburn 7610: webdav => 1,
1.985 raeburn 7611: portfolio => 1,
7612: );
7613: }
1.976 raeburn 7614: return if (!defined($tools{$tool}));
7615:
1.1242 raeburn 7616: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7617: $udom = $env{'user.domain'};
7618: $uname = $env{'user.name'};
7619: }
7620:
1.978 raeburn 7621: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7622: if ($action ne 'reload') {
1.985 raeburn 7623: if ($context eq 'requestcourses') {
7624: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 7625: } elsif ($context eq 'requestauthor') {
7626: return $env{'environment.canrequest.author'};
1.985 raeburn 7627: } else {
7628: return $env{'environment.availabletools.'.$tool};
7629: }
7630: }
1.976 raeburn 7631: }
7632:
1.1183 raeburn 7633: my ($toolstatus,$inststatus,$envkey);
7634: if ($context eq 'requestauthor') {
7635: $envkey = $context;
7636: } else {
7637: $envkey = $context.'.'.$tool;
7638: }
1.976 raeburn 7639:
1.985 raeburn 7640: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7641: ($action ne 'reload')) {
1.1183 raeburn 7642: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7643: $inststatus = $env{'environment.inststatus'};
7644: } else {
1.1084 raeburn 7645: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 7646: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7647: $inststatus = $userenvref->{'inststatus'};
7648: } else {
1.1183 raeburn 7649: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7650: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7651: $inststatus = $userenv{'inststatus'};
7652: }
1.976 raeburn 7653: }
7654:
7655: if ($toolstatus ne '') {
7656: if ($toolstatus) {
7657: $access = 1;
7658: } else {
7659: $access = 0;
7660: }
7661: return $access;
7662: }
7663:
1.1084 raeburn 7664: my ($is_adv,%domdef);
7665: if (ref($is_advref) eq 'HASH') {
7666: $is_adv = $is_advref->{'is_adv'};
7667: } else {
7668: $is_adv = &is_advanced_user($udom,$uname);
7669: }
7670: if (ref($domdefref) eq 'HASH') {
7671: %domdef = %{$domdefref};
7672: } else {
7673: %domdef = &get_domain_defaults($udom);
7674: }
1.976 raeburn 7675: if (ref($domdef{$tool}) eq 'HASH') {
7676: if ($is_adv) {
7677: if ($domdef{$tool}{'_LC_adv'} ne '') {
7678: if ($domdef{$tool}{'_LC_adv'}) {
7679: $access = 1;
7680: } else {
7681: $access = 0;
7682: }
7683: return $access;
7684: }
7685: }
7686: if ($inststatus ne '') {
7687: my ($hasaccess,$hasnoaccess);
7688: foreach my $affiliation (split(/:/,$inststatus)) {
7689: if ($domdef{$tool}{$affiliation} ne '') {
7690: if ($domdef{$tool}{$affiliation}) {
7691: $hasaccess = 1;
7692: } else {
7693: $hasnoaccess = 1;
7694: }
7695: }
7696: }
7697: if ($hasaccess || $hasnoaccess) {
7698: if ($hasaccess) {
7699: $access = 1;
7700: } elsif ($hasnoaccess) {
7701: $access = 0;
7702: }
7703: return $access;
7704: }
7705: } else {
7706: if ($domdef{$tool}{'default'} ne '') {
7707: if ($domdef{$tool}{'default'}) {
7708: $access = 1;
7709: } elsif ($domdef{$tool}{'default'} == 0) {
7710: $access = 0;
7711: }
7712: return $access;
7713: }
7714: }
7715: } else {
1.1177 raeburn 7716: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7717: $access = 1;
7718: } else {
7719: $access = 0;
7720: }
1.976 raeburn 7721: return $access;
7722: }
7723: }
7724:
1.1050 raeburn 7725: sub is_course_owner {
7726: my ($cdom,$cnum,$udom,$uname) = @_;
7727: if (($udom eq '') || ($uname eq '')) {
7728: $udom = $env{'user.domain'};
7729: $uname = $env{'user.name'};
7730: }
7731: unless (($udom eq '') || ($uname eq '')) {
7732: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7733: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7734: return 1;
7735: } else {
7736: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7737: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7738: return 1;
7739: }
7740: }
7741: }
7742: }
7743: return;
7744: }
7745:
1.976 raeburn 7746: sub is_advanced_user {
7747: my ($udom,$uname) = @_;
1.1085 raeburn 7748: if ($udom ne '' && $uname ne '') {
7749: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7750: if (wantarray) {
7751: return ($env{'user.adv'},$env{'user.author'});
7752: } else {
7753: return $env{'user.adv'};
7754: }
1.1085 raeburn 7755: }
7756: }
1.976 raeburn 7757: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7758: my %allroles;
1.1128 raeburn 7759: my ($is_adv,$is_author);
1.976 raeburn 7760: foreach my $role (keys(%roleshash)) {
7761: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7762: my $area = '/'.$tdomain.'/'.$trest;
7763: if ($sec ne '') {
7764: $area .= '/'.$sec;
7765: }
7766: if (($area ne '') && ($trole ne '')) {
7767: my $spec=$trole.'.'.$area;
7768: if ($trole =~ /^cr\//) {
7769: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7770: } elsif ($trole ne 'gr') {
7771: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7772: }
1.1128 raeburn 7773: if ($trole eq 'au') {
7774: $is_author = 1;
7775: }
1.976 raeburn 7776: }
7777: }
7778: foreach my $role (keys(%allroles)) {
7779: last if ($is_adv);
7780: foreach my $item (split(/:/,$allroles{$role})) {
7781: if ($item ne '') {
7782: my ($privilege,$restrictions)=split(/&/,$item);
7783: if ($privilege eq 'adv') {
7784: $is_adv = 1;
7785: last;
7786: }
7787: }
7788: }
7789: }
1.1128 raeburn 7790: if (wantarray) {
7791: return ($is_adv,$is_author);
7792: }
1.976 raeburn 7793: return $is_adv;
7794: }
1.798 raeburn 7795:
1.1035 raeburn 7796: sub check_can_request {
1.1368 raeburn 7797: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035 raeburn 7798: my $canreq = 0;
1.1368 raeburn 7799: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7800: $uname = $env{'user.name'};
7801: $udom = $env{'user.domain'};
7802: }
1.1035 raeburn 7803: my ($types,$typename) = &Apache::loncommon::course_types();
7804: my @options = ('approval','validate','autolimit');
7805: my $optregex = join('|',@options);
7806: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7807: foreach my $type (@{$types}) {
1.1368 raeburn 7808: if (&usertools_access($uname,$udom,$type,undef,
7809: 'requestcourses')) {
1.1035 raeburn 7810: $canreq ++;
1.1036 raeburn 7811: if (ref($request_domains) eq 'HASH') {
1.1368 raeburn 7812: push(@{$request_domains->{$type}},$udom);
1.1036 raeburn 7813: }
1.1368 raeburn 7814: if ($dom eq $udom) {
1.1035 raeburn 7815: $can_request->{$type} = 1;
7816: }
7817: }
1.1368 raeburn 7818: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
7819: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035 raeburn 7820: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7821: if (@curr > 0) {
1.1036 raeburn 7822: foreach my $item (@curr) {
7823: if (ref($request_domains) eq 'HASH') {
7824: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7825: if ($otherdom ne '') {
7826: if (ref($request_domains->{$type}) eq 'ARRAY') {
7827: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7828: push(@{$request_domains->{$type}},$otherdom);
7829: }
7830: } else {
7831: push(@{$request_domains->{$type}},$otherdom);
7832: }
7833: }
7834: }
7835: }
1.1368 raeburn 7836: unless ($dom eq $env{'user.domain'}) {
1.1036 raeburn 7837: $canreq ++;
1.1035 raeburn 7838: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7839: $can_request->{$type} = 1;
7840: }
7841: }
7842: }
7843: }
7844: }
7845: }
7846: return $canreq;
7847: }
7848:
1.341 www 7849: # ---------------------------------------------- Custom access rule evaluation
7850:
7851: sub customaccess {
7852: my ($priv,$uri)=@_;
1.807 albertel 7853: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7854: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7855: $udom = &LONCAPA::clean_domain($udom);
7856: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7857: my $access=0;
1.800 albertel 7858: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7859: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7860: if ($type eq 'user') {
7861: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7862: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7863: if ($tdom) {
7864: if ($tdom ne $env{'user.domain'}) { next; }
7865: }
1.896 albertel 7866: if ($tuname) {
7867: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7868: }
7869: $access=($effect eq 'allow');
7870: last;
7871: }
7872: } else {
7873: if ($role) {
7874: if ($role ne $urole) { next; }
7875: }
7876: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7877: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7878: if ($tdom) {
7879: if ($tdom ne $udom) { next; }
7880: }
7881: if ($tcrs) {
7882: if ($tcrs ne $ucrs) { next; }
7883: }
7884: if ($tsec) {
7885: if ($tsec ne $usec) { next; }
7886: }
7887: $access=($effect eq 'allow');
7888: last;
7889: }
7890: if ($realm eq '' && $role eq '') {
7891: $access=($effect eq 'allow');
7892: }
1.402 bowersj2 7893: }
1.341 www 7894: }
7895: return $access;
7896: }
7897:
1.103 harris41 7898: # ------------------------------------------------- Check for a user privilege
1.12 www 7899:
7900: sub allowed {
1.1281 raeburn 7901: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7902: my $ver_orguri=$uri;
1.439 www 7903: $uri=&deversion($uri);
1.152 www 7904: my $orguri=$uri;
1.52 www 7905: $uri=&declutter($uri);
1.809 raeburn 7906:
1.810 raeburn 7907: if ($priv eq 'evb') {
7908: # Evade communication block restrictions for specified role in a course
7909: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7910: return $1;
7911: } else {
7912: return;
7913: }
7914: }
7915:
1.620 albertel 7916: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7917: # Free bre access to adm and meta resources
1.1343 raeburn 7918: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$}))
1.769 albertel 7919: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7920: && ($priv eq 'bre')) {
1.14 www 7921: return 'F';
1.159 www 7922: }
7923:
1.545 banghart 7924: # Free bre access to user's own portfolio contents
1.714 raeburn 7925: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7926: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7927: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7928: my %setters;
7929: my ($startblock,$endblock) =
7930: &Apache::loncommon::blockcheck(\%setters,'port');
7931: if ($startblock && $endblock) {
7932: return 'B';
7933: } else {
7934: return 'F';
7935: }
1.545 banghart 7936: }
7937:
1.762 raeburn 7938: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7939: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7940: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7941: if (exists($env{'request.course.id'})) {
7942: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7943: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7944: if (($domain eq $cdom) && ($name eq $cnum)) {
7945: my $courseprivid=$env{'request.course.id'};
7946: $courseprivid=~s/\_/\//;
7947: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7948: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7949: return $1;
1.762 raeburn 7950: } else {
7951: if ($env{'request.course.sec'}) {
7952: $courseprivid.='/'.$env{'request.course.sec'};
7953: }
7954: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7955: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7956: return $2;
7957: }
1.714 raeburn 7958: }
7959: }
7960: }
7961: }
7962:
1.159 www 7963: # Free bre to public access
7964:
7965: if ($priv eq 'bre') {
1.1362 raeburn 7966: my $copyright;
7967: unless ($uri =~ /ext\.tool/) {
7968: $copyright=&metadata($uri,'copyright');
7969: }
1.620 albertel 7970: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7971: return 'F';
7972: }
1.238 www 7973: if ($copyright eq 'priv') {
7974: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7975: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7976: return '';
7977: }
7978: }
7979: if ($copyright eq 'domain') {
7980: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7981: unless (($env{'user.domain'} eq $1) ||
7982: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7983: return '';
7984: }
1.262 matthew 7985: }
1.620 albertel 7986: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7987: # Library role, so allow browsing of resources in this domain.
7988: return 'F';
1.238 www 7989: }
1.341 www 7990: if ($copyright eq 'custom') {
7991: unless (&customaccess($priv,$uri)) { return ''; }
7992: }
1.14 www 7993: }
1.264 matthew 7994: # Domain coordinator is trying to create a course
1.620 albertel 7995: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7996: # uri is the requested domain in this case.
7997: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7998: # a role of dc for the domain in question.
1.620 albertel 7999: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8000: }
1.29 www 8001:
1.52 www 8002: my $thisallowed='';
8003: my $statecond=0;
8004: my $courseprivid='';
8005:
1.1039 raeburn 8006: my $ownaccess;
1.1043 raeburn 8007: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8008: if (($priv eq 'bro') && ($env{'user.author'})) {
8009: if ($uri eq '') {
8010: $ownaccess = 1;
8011: } else {
8012: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8013: my $udom = $env{'user.domain'};
8014: my $uname = $env{'user.name'};
8015: if ($uri =~ m{^\Q$udom\E/?$}) {
8016: $ownaccess = 1;
1.1040 raeburn 8017: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8018: unless ($uri =~ m{\.\./}) {
8019: $ownaccess = 1;
8020: }
8021: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8022: my $now = time;
8023: if ($uri =~ m{^([^/]+)/?$}) {
8024: my $adom = $1;
8025: foreach my $key (keys(%env)) {
1.1042 raeburn 8026: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 8027: my ($start,$end) = split('.',$env{$key});
8028: if (($now >= $start) && (!$end || $end < $now)) {
8029: $ownaccess = 1;
8030: last;
8031: }
8032: }
8033: }
8034: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8035: my $adom = $1;
8036: my $aname = $2;
1.1042 raeburn 8037: foreach my $role ('ca','aa') {
8038: if ($env{"user.role.$role./$adom/$aname"}) {
8039: my ($start,$end) =
8040: split('.',$env{"user.role.$role./$adom/$aname"});
8041: if (($now >= $start) && (!$end || $end < $now)) {
8042: $ownaccess = 1;
8043: last;
8044: }
1.1039 raeburn 8045: }
8046: }
8047: }
8048: }
8049: }
8050: }
8051: }
8052:
1.52 www 8053: # Course
8054:
1.620 albertel 8055: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8056: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8057: $thisallowed.=$1;
8058: }
1.52 www 8059: }
1.29 www 8060:
1.52 www 8061: # Domain
8062:
1.620 albertel 8063: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8064: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8065: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8066: $thisallowed.=$1;
8067: }
1.12 www 8068: }
1.52 www 8069:
1.1141 raeburn 8070: # User who is not author or co-author might still be able to edit
8071: # resource of an author in the domain (e.g., if Domain Coordinator).
8072: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8073: (&allowed('mdc',$env{'request.course.id'}))) {
8074: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8075: $thisallowed.=$1;
8076: }
8077: }
8078:
1.52 www 8079: # Course: uri itself is a course
1.66 www 8080: my $courseuri=$uri;
8081: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8082: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8083:
1.620 albertel 8084: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8085: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8086: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8087: $thisallowed.=$1;
8088: }
1.12 www 8089: }
1.29 www 8090:
1.665 albertel 8091: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8092: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8093: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8094: $thisallowed='';
1.671 raeburn 8095: my ($match)=&is_on_map($uri);
8096: if ($match) {
8097: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8098: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 8099: my $value = $1;
1.1402 raeburn 8100: my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8101: if ($deeplinkblock) {
8102: $thisallowed='D';
8103: } elsif ($noblockcheck) {
1.1281 raeburn 8104: $thisallowed.=$value;
1.1162 raeburn 8105: } else {
1.1281 raeburn 8106: my @blockers = &has_comm_blocking($priv,$symb,$uri);
8107: if (@blockers > 0) {
8108: $thisallowed = 'B';
8109: } else {
8110: $thisallowed.=$value;
8111: }
1.1162 raeburn 8112: }
1.671 raeburn 8113: }
8114: } else {
1.705 albertel 8115: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8116: if ($refuri) {
8117: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8118: $thisallowed='F';
1.671 raeburn 8119: } else {
8120: $refuri=&declutter($refuri);
8121: my ($match) = &is_on_map($refuri);
8122: if ($match) {
1.1402 raeburn 8123: my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8124: if ($deeplinkblock) {
8125: $thisallowed='D';
8126: } elsif ($noblockcheck) {
1.1281 raeburn 8127: $thisallowed='F';
1.1162 raeburn 8128: } else {
1.1281 raeburn 8129: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
8130: if (@blockers > 0) {
8131: $thisallowed = 'B';
8132: } else {
8133: $thisallowed='F';
8134: }
1.1162 raeburn 8135: }
1.671 raeburn 8136: }
1.669 raeburn 8137: }
1.671 raeburn 8138: }
8139: }
1.314 www 8140: }
1.492 albertel 8141:
1.766 albertel 8142: if ($priv eq 'bre'
8143: && $thisallowed ne 'F'
8144: && $thisallowed ne '2'
8145: && &is_portfolio_url($uri)) {
1.1270 raeburn 8146: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8147: }
1.1250 raeburn 8148:
1.52 www 8149: # Full access at system, domain or course-wide level? Exit.
1.29 www 8150: if ($thisallowed=~/F/) {
8151: return 'F';
8152: }
8153:
1.52 www 8154: # If this is generating or modifying users, exit with special codes
1.29 www 8155:
1.643 www 8156: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8157: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8158: my ($audom,$auname)=split('/',$uri);
1.643 www 8159: # no author name given, so this just checks on the general right to make a co-author in this domain
8160: unless ($auname) { return $thisallowed; }
8161: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8162: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8163: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8164: ($audom ne $env{'request.role.domain'}))) { return ''; }
8165: }
1.52 www 8166: return $thisallowed;
8167: }
8168: #
1.103 harris41 8169: # Gathered so far: system, domain and course wide privileges
1.52 www 8170: #
8171: # Course: See if uri or referer is an individual resource that is part of
8172: # the course
8173:
1.620 albertel 8174: if ($env{'request.course.id'}) {
1.232 www 8175:
1.620 albertel 8176: $courseprivid=$env{'request.course.id'};
8177: if ($env{'request.course.sec'}) {
8178: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8179: }
8180: $courseprivid=~s/\_/\//;
8181: my $checkreferer=1;
1.232 www 8182: my ($match,$cond)=&is_on_map($uri);
8183: if ($match) {
8184: $statecond=$cond;
1.620 albertel 8185: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8186: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8187: my $value = $1;
8188: if ($priv eq 'bre') {
1.1281 raeburn 8189: if ($noblockcheck) {
8190: $thisallowed.=$value;
1.1162 raeburn 8191: } else {
1.1281 raeburn 8192: my @blockers = &has_comm_blocking($priv,$symb,$uri);
8193: if (@blockers > 0) {
8194: $thisallowed = 'B';
8195: } else {
8196: $thisallowed.=$value;
8197: }
1.1162 raeburn 8198: }
8199: } else {
8200: $thisallowed.=$value;
8201: }
1.52 www 8202: $checkreferer=0;
8203: }
1.29 www 8204: }
1.83 www 8205:
1.148 www 8206: if ($checkreferer) {
1.620 albertel 8207: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8208: unless ($refuri) {
1.800 albertel 8209: foreach my $key (keys(%env)) {
8210: if ($key=~/^httpref\..*\*/) {
8211: my $pattern=$key;
1.156 www 8212: $pattern=~s/^httpref\.\/res\///;
1.148 www 8213: $pattern=~s/\*/\[\^\/\]\+/g;
8214: $pattern=~s/\//\\\//g;
1.152 www 8215: if ($orguri=~/$pattern/) {
1.800 albertel 8216: $refuri=$env{$key};
1.148 www 8217: }
8218: }
1.191 harris41 8219: }
1.148 www 8220: }
1.232 www 8221:
1.148 www 8222: if ($refuri) {
1.152 www 8223: $refuri=&declutter($refuri);
1.232 www 8224: my ($match,$cond)=&is_on_map($refuri);
8225: if ($match) {
8226: my $refstatecond=$cond;
1.620 albertel 8227: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8228: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8229: my $value = $1;
8230: if ($priv eq 'bre') {
1.1402 raeburn 8231: my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8232: if ($deeplinkblock) {
8233: $thisallowed = 'D';
8234: } elsif ($noblockcheck) {
1.1281 raeburn 8235: $thisallowed.=$value;
1.1162 raeburn 8236: } else {
1.1281 raeburn 8237: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
8238: if (@blockers > 0) {
8239: $thisallowed = 'B';
8240: } else {
8241: $thisallowed.=$value;
8242: }
1.1162 raeburn 8243: }
8244: } else {
8245: $thisallowed.=$value;
8246: }
1.53 www 8247: $uri=$refuri;
8248: $statecond=$refstatecond;
1.52 www 8249: }
8250: }
1.148 www 8251: }
1.29 www 8252: }
1.52 www 8253: }
1.29 www 8254:
1.52 www 8255: #
1.103 harris41 8256: # Gathered now: all privileges that could apply, and condition number
1.52 www 8257: #
8258: #
8259: # Full or no access?
8260: #
1.29 www 8261:
1.52 www 8262: if ($thisallowed=~/F/) {
8263: return 'F';
8264: }
1.29 www 8265:
1.52 www 8266: unless ($thisallowed) {
8267: return '';
8268: }
1.29 www 8269:
1.52 www 8270: # Restrictions exist, deal with them
8271: #
8272: # C:according to course preferences
8273: # R:according to resource settings
8274: # L:unless locked
8275: # X:according to user session state
8276: #
8277:
8278: # Possibly locked functionality, check all courses
1.54 www 8279: # Locks might take effect only after 10 minutes cache expiration for other
8280: # courses, and 2 minutes for current course
1.52 www 8281:
8282: my $envkey;
8283: if ($thisallowed=~/L/) {
1.1000 raeburn 8284: foreach $envkey (keys(%env)) {
1.54 www 8285: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8286: my $courseid=$2;
8287: my $roleid=$1.'.'.$2;
1.92 www 8288: $courseid=~s/^\///;
1.54 www 8289: my $expiretime=600;
1.620 albertel 8290: if ($env{'request.role'} eq $roleid) {
1.54 www 8291: $expiretime=120;
8292: }
8293: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8294: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8295: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8296: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8297: }
1.620 albertel 8298: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8299: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8300: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8301: &log($env{'user.domain'},$env{'user.name'},
8302: $env{'user.home'},
1.57 www 8303: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8304: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8305: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8306: return '';
8307: }
8308: }
1.620 albertel 8309: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8310: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8311: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
8312: &log($env{'user.domain'},$env{'user.name'},
8313: $env{'user.home'},
1.57 www 8314: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8315: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8316: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8317: return '';
8318: }
8319: }
8320: }
1.29 www 8321: }
1.52 www 8322: }
8323:
8324: #
8325: # Rest of the restrictions depend on selected course
8326: #
8327:
1.620 albertel 8328: unless ($env{'request.course.id'}) {
1.766 albertel 8329: if ($thisallowed eq 'A') {
8330: return 'A';
1.814 raeburn 8331: } elsif ($thisallowed eq 'B') {
8332: return 'B';
1.766 albertel 8333: } else {
8334: return '1';
8335: }
1.52 www 8336: }
1.29 www 8337:
1.52 www 8338: #
8339: # Now user is definitely in a course
8340: #
1.53 www 8341:
8342:
8343: # Course preferences
8344:
8345: if ($thisallowed=~/C/) {
1.620 albertel 8346: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8347: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8348: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8349: =~/\Q$rolecode\E/) {
1.1304 raeburn 8350: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8351: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8352: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8353: $env{'request.course.id'});
8354: }
1.237 www 8355: return '';
8356: }
8357:
1.620 albertel 8358: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8359: =~/\Q$unamedom\E/) {
1.1304 raeburn 8360: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8361: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8362: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8363: $env{'request.course.id'});
8364: }
1.54 www 8365: return '';
8366: }
1.53 www 8367: }
8368:
8369: # Resource preferences
8370:
8371: if ($thisallowed=~/R/) {
1.620 albertel 8372: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8373: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8374: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8375: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8376: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8377: }
8378: return '';
1.54 www 8379: }
1.53 www 8380: }
1.30 www 8381:
1.246 www 8382: # Restricted by state or randomout?
1.30 www 8383:
1.52 www 8384: if ($thisallowed=~/X/) {
1.620 albertel 8385: if ($env{'acc.randomout'}) {
1.579 albertel 8386: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8387: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8388: return '';
8389: }
1.247 www 8390: }
8391: if (&condval($statecond)) {
1.52 www 8392: return '2';
8393: } else {
8394: return '';
8395: }
8396: }
1.30 www 8397:
1.766 albertel 8398: if ($thisallowed eq 'A') {
8399: return 'A';
1.814 raeburn 8400: } elsif ($thisallowed eq 'B') {
8401: return 'B';
1.1402 raeburn 8402: } elsif ($thisallowed eq 'D') {
8403: return 'D';
1.766 albertel 8404: }
1.52 www 8405: return 'F';
1.232 www 8406: }
1.1162 raeburn 8407:
1.1192 raeburn 8408: # ------------------------------------------- Check construction space access
8409:
8410: sub constructaccess {
8411: my ($url,$setpriv)=@_;
8412:
8413: # We do not allow editing of previous versions of files
8414: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8415:
8416: # Get username and domain from URL
8417: my ($ownername,$ownerdomain,$ownerhome);
8418:
8419: ($ownerdomain,$ownername) =
1.1325 raeburn 8420: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 8421:
8422: # The URL does not really point to any authorspace, forget it
8423: unless (($ownername) && ($ownerdomain)) { return ''; }
8424:
8425: # Now we need to see if the user has access to the authorspace of
8426: # $ownername at $ownerdomain
8427:
8428: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8429: # Real author for this?
8430: $ownerhome = $env{'user.home'};
8431: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8432: return ($ownername,$ownerdomain,$ownerhome);
8433: }
8434: } else {
8435: # Co-author for this?
8436: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8437: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8438: $ownerhome = &homeserver($ownername,$ownerdomain);
8439: return ($ownername,$ownerdomain,$ownerhome);
8440: }
1.1312 raeburn 8441: if ($env{'request.course.id'}) {
8442: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
8443: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
8444: if (&allowed('mdc',$env{'request.course.id'})) {
8445: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
8446: return ($ownername,$ownerdomain,$ownerhome);
8447: }
8448: }
8449: }
1.1192 raeburn 8450: }
8451:
8452: # We don't have any access right now. If we are not possibly going to do anything about this,
8453: # we might as well leave
8454: unless ($setpriv) { return ''; }
8455:
8456: # Backdoor access?
8457: my $allowed=&allowed('eco',$ownerdomain);
8458: # Nope
8459: unless ($allowed) { return ''; }
8460: # Looks like we may have access, but could be locked by the owner of the construction space
8461: if ($allowed eq 'U') {
8462: my %blocked=&get('environment',['domcoord.author'],
8463: $ownerdomain,$ownername);
8464: # Is blocked by owner
8465: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8466: }
8467: if (($allowed eq 'F') || ($allowed eq 'U')) {
8468: # Grant temporary access
8469: my $then=$env{'user.login.time'};
1.1209 raeburn 8470: my $update=$env{'user.update.time'};
1.1192 raeburn 8471: if (!$update) { $update = $then; }
8472: my $refresh=$env{'user.refresh.time'};
8473: if (!$refresh) { $refresh = $update; }
8474: my $now = time;
8475: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8476: $now,'ca','constructaccess');
8477: $ownerhome = &homeserver($ownername,$ownerdomain);
8478: return($ownername,$ownerdomain,$ownerhome);
8479: }
8480: # No business here
8481: return '';
8482: }
8483:
1.1282 raeburn 8484: # ----------------------------------------------------------- Content Blocking
8485:
8486: {
8487: # Caches for faster Course Contents display where content blocking
8488: # is in operation (i.e., interval param set) for timed quiz.
8489: #
8490: # User for whom data are being temporarily cached.
8491: my $cacheduser='';
8492: # Cached blockers for this user (a hash of blocking items).
8493: my %cachedblockers=();
8494: # When the data were last cached.
8495: my $cachedlast='';
8496:
8497: sub load_all_blockers {
8498: my ($uname,$udom,$blocks)=@_;
8499: if (($uname ne '') && ($udom ne '')) {
8500: if (($cacheduser eq $uname.':'.$udom) &&
8501: (abs($cachedlast-time)<5)) {
8502: return;
8503: }
8504: }
8505: $cachedlast=time;
8506: $cacheduser=$uname.':'.$udom;
8507: %cachedblockers = &get_commblock_resources($blocks);
8508: }
8509:
1.1162 raeburn 8510: sub get_comm_blocks {
8511: my ($cdom,$cnum) = @_;
8512: if ($cdom eq '' || $cnum eq '') {
8513: return unless ($env{'request.course.id'});
8514: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8515: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8516: }
8517: my %commblocks;
8518: my $hashid=$cdom.'_'.$cnum;
8519: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8520: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8521: %commblocks = %{$blocksref};
8522: } else {
8523: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8524: my $cachetime = 600;
8525: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8526: }
8527: return %commblocks;
8528: }
8529:
1.1282 raeburn 8530: sub get_commblock_resources {
8531: my ($blocks) = @_;
8532: my %blockers = ();
8533: return %blockers unless ($env{'request.course.id'});
8534: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 8535: my %commblocks;
8536: if (ref($blocks) eq 'HASH') {
8537: %commblocks = %{$blocks};
8538: } else {
8539: %commblocks = &get_comm_blocks();
8540: }
1.1282 raeburn 8541: return %blockers unless (keys(%commblocks) > 0);
8542: my $navmap = Apache::lonnavmaps::navmap->new();
8543: return %blockers unless (ref($navmap));
1.1162 raeburn 8544: my $now = time;
8545: foreach my $block (keys(%commblocks)) {
8546: if ($block =~ /^(\d+)____(\d+)$/) {
8547: my ($start,$end) = ($1,$2);
8548: if ($start <= $now && $end >= $now) {
8549: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8550: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8551: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 8552: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8553: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8554: }
8555: }
8556: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 8557: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8558: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8559: }
8560: }
8561: }
8562: }
8563: }
8564: } elsif ($block =~ /^firstaccess____(.+)$/) {
8565: my $item = $1;
1.1163 raeburn 8566: my @to_test;
1.1162 raeburn 8567: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8568: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 8569: my @interval;
8570: my $type = 'map';
8571: if ($item eq 'course') {
8572: $type = 'course';
8573: @interval=&EXT("resource.0.interval");
8574: } else {
8575: if ($item =~ /___\d+___/) {
8576: $type = 'resource';
8577: @interval=&EXT("resource.0.interval",$item);
8578: if (ref($navmap)) {
8579: my $res = $navmap->getBySymb($item);
8580: push(@to_test,$res);
8581: }
1.1162 raeburn 8582: } else {
1.1282 raeburn 8583: my $mapsymb = &symbread($item,1);
8584: if ($mapsymb) {
8585: if (ref($navmap)) {
8586: my $mapres = $navmap->getBySymb($mapsymb);
8587: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
8588: foreach my $res (@to_test) {
8589: my $symb = $res->symb();
8590: next if ($symb eq $mapsymb);
8591: if ($symb ne '') {
8592: @interval=&EXT("resource.0.interval",$symb);
8593: if ($interval[1] eq 'map') {
8594: last;
1.1162 raeburn 8595: }
8596: }
8597: }
8598: }
8599: }
8600: }
1.1282 raeburn 8601: }
1.1310 raeburn 8602: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 8603: my $timelimit = $1;
1.1282 raeburn 8604: my $first_access;
8605: if ($type eq 'resource') {
8606: $first_access=&get_first_access($interval[1],$item);
8607: } elsif ($type eq 'map') {
8608: $first_access=&get_first_access($interval[1],undef,$item);
8609: } else {
8610: $first_access=&get_first_access($interval[1]);
8611: }
8612: if ($first_access) {
1.1292 raeburn 8613: my $timesup = $first_access+$timelimit;
1.1282 raeburn 8614: if ($timesup > $now) {
8615: my $activeblock;
8616: foreach my $res (@to_test) {
1.1283 raeburn 8617: if ($res->answerable()) {
1.1282 raeburn 8618: $activeblock = 1;
8619: last;
8620: }
8621: }
8622: if ($activeblock) {
8623: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8624: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8625: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8626: }
8627: }
8628: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8629: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8630: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8631: }
1.1162 raeburn 8632: }
8633: }
8634: }
8635: }
8636: }
8637: }
8638: }
8639: }
8640: }
1.1282 raeburn 8641: return %blockers;
1.1162 raeburn 8642: }
8643:
1.1282 raeburn 8644: sub has_comm_blocking {
8645: my ($priv,$symb,$uri,$blocks) = @_;
8646: my @blockers;
8647: return unless ($env{'request.course.id'});
8648: return unless ($priv eq 'bre');
8649: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8650: return if ($env{'request.state'} eq 'construct');
8651: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
8652: return unless (keys(%cachedblockers) > 0);
8653: my (%possibles,@symbs);
8654: if (!$symb) {
8655: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 8656: }
1.1282 raeburn 8657: if ($symb) {
8658: @symbs = ($symb);
8659: } elsif (keys(%possibles)) {
8660: @symbs = keys(%possibles);
8661: }
8662: my $noblock;
8663: foreach my $symb (@symbs) {
8664: last if ($noblock);
8665: my ($map,$resid,$resurl)=&decode_symb($symb);
8666: foreach my $block (keys(%cachedblockers)) {
8667: if ($block =~ /^firstaccess____(.+)$/) {
8668: my $item = $1;
8669: if (($item eq $map) || ($item eq $symb)) {
8670: $noblock = 1;
8671: last;
8672: }
8673: }
8674: if (ref($cachedblockers{$block}) eq 'HASH') {
8675: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
8676: if ($cachedblockers{$block}{'resources'}{$symb}) {
8677: unless (grep(/^\Q$block\E$/,@blockers)) {
8678: push(@blockers,$block);
8679: }
8680: }
8681: }
1.1162 raeburn 8682: }
1.1282 raeburn 8683: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
8684: if ($cachedblockers{$block}{'maps'}{$map}) {
8685: unless (grep(/^\Q$block\E$/,@blockers)) {
8686: push(@blockers,$block);
8687: }
8688: }
1.1162 raeburn 8689: }
8690: }
8691: }
1.1282 raeburn 8692: return if ($noblock);
8693: return @blockers;
8694: }
1.1162 raeburn 8695: }
8696:
1.1402 raeburn 8697: sub deeplink_check {
8698: my ($priv,$symb,$uri) = @_;
8699: return unless ($env{'request.course.id'});
8700: return unless ($priv eq 'bre');
8701: return if ($env{'request.state'} eq 'construct');
8702: return if ($env{'request.role.adv'});
8703: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8704: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8705: my (%possibles,@symbs);
8706: if (!$symb) {
8707: $symb = &symbread($uri,1,1,1,\%possibles);
8708: }
8709: if ($symb) {
8710: @symbs = ($symb);
8711: } elsif (keys(%possibles)) {
8712: @symbs = keys(%possibles);
8713: }
8714:
8715: my ($login,$switchrole,$allow);
8716: if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
8717: my $key = $1;
8718: my $tinyurl;
8719: my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
8720: if (defined($cached)) {
8721: $tinyurl = $result;
8722: } else {
8723: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
8724: my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
8725: if ($currtiny{$key} ne '') {
8726: $tinyurl = $currtiny{$key};
8727: &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
8728: }
8729: }
8730: if ($tinyurl ne '') {
8731: my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
8732: if ($cnumreq eq $cnum) {
8733: $login = $posslogin;
8734: } else {
8735: $switchrole = 1;
8736: }
8737: }
8738: }
8739: foreach my $symb (@symbs) {
8740: last if ($allow);
8741: my $deeplink = &EXT("resource.0.deeplink",$symb);
8742: if ($deeplink eq '') {
8743: $allow = 1;
8744: } else {
8745: my ($listed,$scope,$access) = split(/,/,$deeplink);
8746: if ($access eq 'any') {
8747: $allow = 1;
8748: } elsif ($login) {
8749: if ($access eq 'only') {
8750: if ($scope eq 'res') {
8751: if ($symb eq $login) {
8752: $allow = 1;
8753: }
8754: } elsif ($scope eq 'map') {
8755: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
8756: } elsif ($scope eq 'rec') {
8757: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
8758: }
8759: } else {
8760: my ($acctype,$item) = split(/:/,$access);
8761: if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
8762: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
8763: my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
8764: if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
8765: $allow = 1;
8766: }
8767: }
8768: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
8769: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
8770: my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
8771: if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
8772: $allow = 1;
8773: }
8774: }
8775: }
8776: }
8777: }
8778: }
8779: }
8780: return if ($allow);
8781: return 1;
8782: }
8783:
1.1282 raeburn 8784: # -------------------------------- Deversion and split uri into path an filename
8785:
1.1133 foxr 8786: #
1.1282 raeburn 8787: # Removes the version from a URI and
1.1133 foxr 8788: # splits it in to its filename and path to the filename.
8789: # Seems like File::Basename could have done this more clearly.
8790: # Parameters:
8791: # $uri - input URI
8792: # Returns:
8793: # Two element list consisting of
8794: # $pathname - the URI up to and excluding the trailing /
8795: # $filename - The part of the URI following the last /
8796: # NOTE:
8797: # Another realization of this is simply:
8798: # use File::Basename;
8799: # ...
8800: # $uri = shift;
8801: # $filename = basename($uri);
8802: # $path = dirname($uri);
8803: # return ($filename, $path);
8804: #
8805: # The implementation below is probably faster however.
8806: #
1.710 albertel 8807: sub split_uri_for_cond {
8808: my $uri=&deversion(&declutter(shift));
8809: my @uriparts=split(/\//,$uri);
8810: my $filename=pop(@uriparts);
8811: my $pathname=join('/',@uriparts);
8812: return ($pathname,$filename);
8813: }
1.232 www 8814: # --------------------------------------------------- Is a resource on the map?
8815:
8816: sub is_on_map {
1.710 albertel 8817: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8818: #Trying to find the conditional for the file
1.620 albertel 8819: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8820: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8821: if ($match) {
1.289 bowersj2 8822: return (1,$1);
8823: } else {
1.434 www 8824: return (0,0);
1.289 bowersj2 8825: }
1.12 www 8826: }
8827:
1.427 www 8828: # --------------------------------------------------------- Get symb from alias
8829:
8830: sub get_symb_from_alias {
8831: my $symb=shift;
8832: my ($map,$resid,$url)=&decode_symb($symb);
8833: # Already is a symb
8834: if ($url) { return $symb; }
8835: # Must be an alias
8836: my $aliassymb='';
8837: my %bighash;
1.620 albertel 8838: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8839: &GDBM_READER(),0640)) {
8840: my $rid=$bighash{'mapalias_'.$symb};
8841: if ($rid) {
8842: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8843: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8844: $resid,$bighash{'src_'.$rid});
1.427 www 8845: }
8846: untie %bighash;
8847: }
8848: return $aliassymb;
8849: }
8850:
1.12 www 8851: # ----------------------------------------------------------------- Define Role
8852:
8853: sub definerole {
8854: if (allowed('mcr','/')) {
1.1326 raeburn 8855: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8856: foreach my $role (split(':',$sysrole)) {
8857: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8858: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8859: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8860: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8861: return "refused:s:$crole&$cqual";
8862: }
8863: }
1.191 harris41 8864: }
1.800 albertel 8865: foreach my $role (split(':',$domrole)) {
8866: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8867: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8868: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8869: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8870: return "refused:d:$crole&$cqual";
8871: }
8872: }
1.191 harris41 8873: }
1.800 albertel 8874: foreach my $role (split(':',$courole)) {
8875: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8876: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8877: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8878: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8879: return "refused:c:$crole&$cqual";
8880: }
8881: }
1.191 harris41 8882: }
1.1326 raeburn 8883: my $uhome;
8884: if (($uname ne '') && ($udom ne '')) {
8885: $uhome = &homeserver($uname,$udom);
8886: return $uhome if ($uhome eq 'no_host');
8887: } else {
8888: $uname = $env{'user.name'};
8889: $udom = $env{'user.domain'};
8890: $uhome = $env{'user.home'};
8891: }
1.620 albertel 8892: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 8893: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8894: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 8895: return reply($command,$uhome);
1.12 www 8896: } else {
8897: return 'refused';
8898: }
1.105 harris41 8899: }
8900:
8901: # ---------------- Make a metadata query against the network of library servers
8902:
8903: sub metadata_query {
1.1237 raeburn 8904: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8905: my %rhash;
1.845 albertel 8906: my %libserv = &all_library();
1.244 matthew 8907: my @server_list = (defined($server_array) ? @$server_array
8908: : keys(%libserv) );
8909: for my $server (@server_list) {
1.1237 raeburn 8910: my $domains = '';
8911: if (ref($domains_hash) eq 'HASH') {
8912: $domains = $domains_hash->{$server};
8913: }
1.118 harris41 8914: unless ($custom or $customshow) {
1.1237 raeburn 8915: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8916: $rhash{$server}=$reply;
8917: }
8918: else {
8919: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 8920: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8921: $server);
8922: $rhash{$server}=$reply;
8923: }
1.112 harris41 8924: }
1.118 harris41 8925: return \%rhash;
1.240 www 8926: }
8927:
8928: # ----------------------------------------- Send log queries and wait for reply
8929:
8930: sub log_query {
8931: my ($uname,$udom,$query,%filters)=@_;
8932: my $uhome=&homeserver($uname,$udom);
8933: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8934: my $uhost=&hostname($uhome);
1.800 albertel 8935: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8936: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8937: $uhome);
1.479 albertel 8938: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8939: return get_query_reply($queryid);
8940: }
8941:
1.818 raeburn 8942: # -------------------------- Update MySQL table for portfolio file
8943:
8944: sub update_portfolio_table {
1.821 raeburn 8945: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8946: if ($group ne '') {
8947: $file_name =~s /^\Q$group\E//;
8948: }
1.818 raeburn 8949: my $homeserver = &homeserver($uname,$udom);
8950: my $queryid=
1.821 raeburn 8951: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8952: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8953: my $reply = &get_query_reply($queryid);
8954: return $reply;
8955: }
8956:
1.899 raeburn 8957: # -------------------------- Update MySQL allusers table
8958:
8959: sub update_allusers_table {
8960: my ($uname,$udom,$names) = @_;
8961: my $homeserver = &homeserver($uname,$udom);
8962: my $queryid=
8963: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8964: 'lastname='.&escape($names->{'lastname'}).'%%'.
8965: 'firstname='.&escape($names->{'firstname'}).'%%'.
8966: 'middlename='.&escape($names->{'middlename'}).'%%'.
8967: 'generation='.&escape($names->{'generation'}).'%%'.
8968: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8969: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8970: return;
1.899 raeburn 8971: }
8972:
1.508 raeburn 8973: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8974:
8975: sub fetch_enrollment_query {
1.511 raeburn 8976: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 8977: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8978: my $maxtries = 1;
1.508 raeburn 8979: if ($context eq 'automated') {
8980: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 8981: $sleep = 2;
8982: $loopmax = 100;
1.547 raeburn 8983: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8984: } else {
8985: $homeserver = &homeserver($cnum,$dom);
8986: }
1.838 albertel 8987: my $host=&hostname($homeserver);
1.506 raeburn 8988: my $cmd = '';
1.1000 raeburn 8989: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8990: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8991: }
8992: $cmd =~ s/%%$//;
8993: $cmd = &escape($cmd);
8994: my $query = 'fetchenrollment';
1.620 albertel 8995: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8996: unless ($queryid=~/^\Q$host\E\_/) {
8997: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8998: return 'error: '.$queryid;
8999: }
1.1317 raeburn 9000: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9001: my $tries = 1;
9002: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 9003: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9004: $tries ++;
9005: }
1.526 raeburn 9006: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9007: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9008: } else {
1.901 albertel 9009: my @responses = split(/:/,$reply);
1.1322 raeburn 9010: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9011: foreach my $line (@responses) {
9012: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9013: $$replyref{$key} = $value;
9014: }
9015: } else {
1.1117 foxr 9016: my $pathname = LONCAPA::tempdir();
1.800 albertel 9017: foreach my $line (@responses) {
9018: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9019: $$replyref{$key} = $value;
9020: if ($value > 0) {
1.800 albertel 9021: foreach my $item (@{$$affiliatesref{$key}}) {
9022: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9023: my $destname = $pathname.'/'.$filename;
9024: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9025: if ($xml_classlist =~ /^error/) {
9026: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9027: } else {
1.1359 raeburn 9028: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9029: print FILE &unescape($xml_classlist);
9030: close(FILE);
1.526 raeburn 9031: } else {
9032: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9033: }
9034: }
9035: }
9036: }
9037: }
9038: }
9039: return 'ok';
9040: }
9041: return 'error';
9042: }
9043:
1.242 www 9044: sub get_query_reply {
1.1317 raeburn 9045: my ($queryid,$sleep,$loopmax) = @_;;
9046: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9047: $sleep = 0.2;
9048: }
9049: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9050: $loopmax = 100;
9051: }
1.1117 foxr 9052: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9053: my $reply='';
1.1317 raeburn 9054: for (1..$loopmax) {
9055: sleep($sleep);
1.240 www 9056: if (-e $replyfile.'.end') {
1.1359 raeburn 9057: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9058: $reply = join('',<$fh>);
9059: close($fh);
1.240 www 9060: } else { return 'error: reply_file_error'; }
1.242 www 9061: return &unescape($reply);
9062: }
1.240 www 9063: }
1.242 www 9064: return 'timeout:'.$queryid;
1.240 www 9065: }
9066:
9067: sub courselog_query {
1.241 www 9068: #
9069: # possible filters:
9070: # url: url or symb
9071: # username
9072: # domain
9073: # action: view, submit, grade
9074: # start: timestamp
9075: # end: timestamp
9076: #
1.240 www 9077: my (%filters)=@_;
1.620 albertel 9078: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9079: if ($filters{'url'}) {
9080: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9081: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9082: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9083: }
1.620 albertel 9084: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9085: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9086: return &log_query($cname,$cdom,'courselog',%filters);
9087: }
9088:
9089: sub userlog_query {
1.858 raeburn 9090: #
9091: # possible filters:
9092: # action: log check role
9093: # start: timestamp
9094: # end: timestamp
9095: #
1.240 www 9096: my ($uname,$udom,%filters)=@_;
9097: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9098: }
9099:
1.506 raeburn 9100: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9101:
9102: sub auto_run {
1.508 raeburn 9103: my ($cnum,$cdom) = @_;
1.876 raeburn 9104: my $response = 0;
9105: my $settings;
9106: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9107: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9108: $settings = $domconfig{'autoenroll'};
9109: if ($settings->{'run'} eq '1') {
9110: $response = 1;
9111: }
9112: } else {
1.934 raeburn 9113: my $homeserver;
9114: if (&is_course($cdom,$cnum)) {
9115: $homeserver = &homeserver($cnum,$cdom);
9116: } else {
9117: $homeserver = &domain($cdom,'primary');
9118: }
9119: if ($homeserver ne 'no_host') {
9120: $response = &reply('autorun:'.$cdom,$homeserver);
9121: }
1.876 raeburn 9122: }
1.506 raeburn 9123: return $response;
9124: }
1.776 albertel 9125:
1.506 raeburn 9126: sub auto_get_sections {
1.508 raeburn 9127: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9128: my $homeserver;
9129: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9130: $homeserver = &homeserver($cnum,$cdom);
9131: }
9132: if (!defined($homeserver)) {
9133: if ($cdom =~ /^$match_domain$/) {
9134: $homeserver = &domain($cdom,'primary');
9135: }
9136: }
9137: my @secs;
9138: if (defined($homeserver)) {
9139: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9140: unless ($response eq 'refused') {
9141: @secs = split(/:/,$response);
9142: }
1.506 raeburn 9143: }
9144: return @secs;
9145: }
1.776 albertel 9146:
1.506 raeburn 9147: sub auto_new_course {
1.1099 raeburn 9148: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9149: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9150: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9151: return $response;
9152: }
1.776 albertel 9153:
1.506 raeburn 9154: sub auto_validate_courseID {
1.508 raeburn 9155: my ($cnum,$cdom,$inst_course_id) = @_;
9156: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9157: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9158: return $response;
9159: }
1.776 albertel 9160:
1.1007 raeburn 9161: sub auto_validate_instcode {
1.1020 raeburn 9162: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9163: my ($homeserver,$response);
9164: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9165: $homeserver = &homeserver($cnum,$cdom);
9166: }
9167: if (!defined($homeserver)) {
9168: if ($cdom =~ /^$match_domain$/) {
9169: $homeserver = &domain($cdom,'primary');
9170: }
9171: }
1.1065 raeburn 9172: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9173: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 9174: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9175: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9176: }
9177:
1.506 raeburn 9178: sub auto_create_password {
1.873 raeburn 9179: my ($cnum,$cdom,$authparam,$udom) = @_;
9180: my ($homeserver,$response);
1.506 raeburn 9181: my $create_passwd = 0;
9182: my $authchk = '';
1.873 raeburn 9183: if ($udom =~ /^$match_domain$/) {
9184: $homeserver = &domain($udom,'primary');
9185: }
9186: if ($homeserver eq '') {
9187: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9188: $homeserver = &homeserver($cnum,$cdom);
9189: }
9190: }
9191: if ($homeserver eq '') {
9192: $authchk = 'nodomain';
1.506 raeburn 9193: } else {
1.873 raeburn 9194: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9195: if ($response eq 'refused') {
9196: $authchk = 'refused';
9197: } else {
1.901 albertel 9198: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9199: }
1.506 raeburn 9200: }
9201: return ($authparam,$create_passwd,$authchk);
9202: }
9203:
1.706 raeburn 9204: sub auto_photo_permission {
9205: my ($cnum,$cdom,$students) = @_;
9206: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9207: my ($outcome,$perm_reqd,$conditions) =
9208: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9209: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9210: return (undef,undef);
9211: }
1.706 raeburn 9212: return ($outcome,$perm_reqd,$conditions);
9213: }
9214:
9215: sub auto_checkphotos {
9216: my ($uname,$udom,$pid) = @_;
9217: my $homeserver = &homeserver($uname,$udom);
9218: my ($result,$resulttype);
9219: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9220: &escape($uname).':'.&escape($pid),
9221: $homeserver));
1.709 albertel 9222: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9223: return (undef,undef);
9224: }
1.706 raeburn 9225: if ($outcome) {
9226: ($result,$resulttype) = split(/:/,$outcome);
9227: }
9228: return ($result,$resulttype);
9229: }
9230:
9231: sub auto_photochoice {
9232: my ($cnum,$cdom) = @_;
9233: my $homeserver = &homeserver($cnum,$cdom);
9234: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9235: &escape($cdom),
9236: $homeserver)));
1.709 albertel 9237: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9238: return (undef,undef);
9239: }
1.706 raeburn 9240: return ($update,$comment);
9241: }
9242:
9243: sub auto_photoupdate {
9244: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9245: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9246: my $host=&hostname($homeserver);
1.706 raeburn 9247: my $cmd = '';
9248: my $maxtries = 1;
1.800 albertel 9249: foreach my $affiliate (keys(%{$affiliatesref})) {
9250: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9251: }
9252: $cmd =~ s/%%$//;
9253: $cmd = &escape($cmd);
9254: my $query = 'institutionalphotos';
9255: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9256: unless ($queryid=~/^\Q$host\E\_/) {
9257: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9258: return 'error: '.$queryid;
9259: }
9260: my $reply = &get_query_reply($queryid);
9261: my $tries = 1;
9262: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9263: $reply = &get_query_reply($queryid);
9264: $tries ++;
9265: }
9266: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9267: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9268: } else {
9269: my @responses = split(/:/,$reply);
9270: my $outcome = shift(@responses);
9271: foreach my $item (@responses) {
9272: my ($key,$value) = split(/=/,$item);
9273: $$photo{$key} = $value;
9274: }
9275: return $outcome;
9276: }
9277: return 'error';
9278: }
9279:
1.521 raeburn 9280: sub auto_instcode_format {
1.793 albertel 9281: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9282: $cat_order) = @_;
1.521 raeburn 9283: my $courses = '';
1.772 raeburn 9284: my @homeservers;
1.521 raeburn 9285: if ($caller eq 'global') {
1.841 albertel 9286: my %servers = &get_servers($codedom,'library');
9287: foreach my $tryserver (keys(%servers)) {
9288: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9289: push(@homeservers,$tryserver);
9290: }
1.584 raeburn 9291: }
1.1022 raeburn 9292: } elsif ($caller eq 'requests') {
9293: if ($codedom =~ /^$match_domain$/) {
9294: my $chome = &domain($codedom,'primary');
9295: unless ($chome eq 'no_host') {
9296: push(@homeservers,$chome);
9297: }
9298: }
1.521 raeburn 9299: } else {
1.772 raeburn 9300: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9301: }
1.793 albertel 9302: foreach my $code (keys(%{$instcodes})) {
9303: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9304: }
9305: chop($courses);
1.772 raeburn 9306: my $ok_response = 0;
9307: my $response;
9308: while (@homeservers > 0 && $ok_response == 0) {
9309: my $server = shift(@homeservers);
9310: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9311: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9312: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9313: split(/:/,$response);
1.772 raeburn 9314: %{$codes} = (%{$codes},&str2hash($codes_str));
9315: push(@{$codetitles},&str2array($codetitles_str));
9316: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9317: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9318: $ok_response = 1;
9319: }
9320: }
9321: if ($ok_response) {
1.521 raeburn 9322: return 'ok';
1.772 raeburn 9323: } else {
9324: return $response;
1.521 raeburn 9325: }
9326: }
9327:
1.792 raeburn 9328: sub auto_instcode_defaults {
9329: my ($domain,$returnhash,$code_order) = @_;
9330: my @homeservers;
1.841 albertel 9331:
9332: my %servers = &get_servers($domain,'library');
9333: foreach my $tryserver (keys(%servers)) {
9334: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9335: push(@homeservers,$tryserver);
9336: }
1.792 raeburn 9337: }
1.841 albertel 9338:
1.792 raeburn 9339: my $response;
1.841 albertel 9340: foreach my $server (@homeservers) {
1.792 raeburn 9341: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9342: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9343:
9344: foreach my $pair (split(/\&/,$response)) {
9345: my ($name,$value)=split(/\=/,$pair);
9346: if ($name eq 'code_order') {
9347: @{$code_order} = split(/\&/,&unescape($value));
9348: } else {
9349: $returnhash->{&unescape($name)}=&unescape($value);
9350: }
9351: }
9352: return 'ok';
1.792 raeburn 9353: }
1.841 albertel 9354:
9355: return $response;
1.1003 raeburn 9356: }
9357:
9358: sub auto_possible_instcodes {
1.1007 raeburn 9359: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9360: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9361: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9362: return;
9363: }
1.1003 raeburn 9364: my (@homeservers,$uhome);
9365: if (defined(&domain($domain,'primary'))) {
9366: $uhome=&domain($domain,'primary');
9367: push(@homeservers,&domain($domain,'primary'));
9368: } else {
9369: my %servers = &get_servers($domain,'library');
9370: foreach my $tryserver (keys(%servers)) {
9371: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9372: push(@homeservers,$tryserver);
9373: }
9374: }
9375: }
9376: my $response;
9377: foreach my $server (@homeservers) {
9378: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9379: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9380: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9381: split(':',$response);
9382: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9383: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9384: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9385: my ($name,$value)=split('=',$item);
9386: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9387: }
9388: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9389: my ($name,$value)=split('=',$item);
9390: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9391: }
9392: return 'ok';
9393: }
9394: return $response;
9395: }
1.792 raeburn 9396:
1.1010 raeburn 9397: sub auto_courserequest_checks {
9398: my ($dom) = @_;
1.1020 raeburn 9399: my ($homeserver,%validations);
9400: if ($dom =~ /^$match_domain$/) {
9401: $homeserver = &domain($dom,'primary');
9402: }
9403: unless ($homeserver eq 'no_host') {
9404: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9405: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9406: my @items = split(/&/,$response);
9407: foreach my $item (@items) {
9408: my ($key,$value) = split('=',$item);
9409: $validations{&unescape($key)} = &thaw_unescape($value);
9410: }
9411: }
9412: }
1.1010 raeburn 9413: return %validations;
9414: }
9415:
1.1020 raeburn 9416: sub auto_courserequest_validation {
1.1255 raeburn 9417: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9418: my ($homeserver,$response);
9419: if ($dom =~ /^$match_domain$/) {
9420: $homeserver = &domain($dom,'primary');
9421: }
1.1255 raeburn 9422: unless ($homeserver eq 'no_host') {
9423: my $customdata;
9424: if (ref($custominfo) eq 'HASH') {
9425: $customdata = &freeze_escape($custominfo);
9426: }
1.1020 raeburn 9427: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9428: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 9429: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9430: $customdata,$homeserver));
1.1020 raeburn 9431: }
9432: return $response;
9433: }
9434:
1.777 albertel 9435: sub auto_validate_class_sec {
1.918 raeburn 9436: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9437: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9438: my $ownerlist;
9439: if (ref($owners) eq 'ARRAY') {
9440: $ownerlist = join(',',@{$owners});
9441: } else {
9442: $ownerlist = $owners;
9443: }
1.773 raeburn 9444: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9445: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9446: return $response;
9447: }
9448:
1.1367 raeburn 9449: sub auto_validate_instclasses {
9450: my ($cdom,$cnum,$owners,$classesref) = @_;
9451: my ($homeserver,%validations);
9452: $homeserver = &homeserver($cnum,$cdom);
9453: unless ($homeserver eq 'no_host') {
9454: my $ownerlist;
9455: if (ref($owners) eq 'ARRAY') {
9456: $ownerlist = join(',',@{$owners});
9457: } else {
9458: $ownerlist = $owners;
9459: }
9460: if (ref($classesref) eq 'HASH') {
9461: my $classes = &freeze_escape($classesref);
9462: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9463: ':'.$cdom.':'.$classes,$homeserver);
9464: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9465: my @items = split(/&/,$response);
9466: foreach my $item (@items) {
9467: my ($key,$value) = split('=',$item);
9468: $validations{&unescape($key)} = &thaw_unescape($value);
9469: }
9470: }
9471: }
9472: }
9473: return %validations;
9474: }
9475:
1.1248 raeburn 9476: sub auto_crsreq_update {
9477: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 9478: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 9479: my ($homeserver,%crsreqresponse);
9480: if ($cdom =~ /^$match_domain$/) {
9481: $homeserver = &domain($cdom,'primary');
9482: }
9483: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9484: my $info;
9485: if (ref($inbound) eq 'HASH') {
9486: $info = &freeze_escape($inbound);
9487: }
9488: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9489: ':'.&escape($action).':'.&escape($ownername).':'.
9490: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 9491: &escape($title).':'.&escape($code).':'.
9492: &escape($accessstart).':'.&escape($accessend).':'.$info,
9493: $homeserver);
1.1248 raeburn 9494: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9495: my @items = split(/&/,$response);
9496: foreach my $item (@items) {
9497: my ($key,$value) = split('=',$item);
9498: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9499: }
9500: }
9501: }
9502: return \%crsreqresponse;
9503: }
9504:
1.1305 raeburn 9505: sub auto_export_grades {
1.1309 raeburn 9506: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9507: my ($homeserver,%exportresponse);
9508: if ($cdom =~ /^$match_domain$/) {
9509: $homeserver = &domain($cdom,'primary');
9510: }
9511: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9512: my $info;
9513: if (ref($inforef) eq 'HASH') {
9514: $info = &freeze_escape($inforef);
9515: }
9516: if (ref($gradesref) eq 'HASH') {
9517: my $grades = &freeze_escape($gradesref);
9518: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9519: $info.':'.$grades,$homeserver);
9520: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9521: my @items = split(/&/,$response);
9522: foreach my $item (@items) {
9523: my ($key,$value) = split('=',$item);
9524: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9525: }
9526: }
9527: }
9528: }
9529: return \%exportresponse;
1.1305 raeburn 9530: }
9531:
1.1287 raeburn 9532: sub check_instcode_cloning {
9533: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9534: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9535: return;
9536: }
9537: my $canclone;
9538: if (@{$code_order} > 0) {
9539: my $instcoderegexp ='^';
9540: my @clonecodes = split(/\&/,$cloner);
9541: foreach my $item (@{$code_order}) {
9542: if (grep(/^\Q$item\E=/,@clonecodes)) {
9543: foreach my $pair (@clonecodes) {
9544: my ($key,$val) = split(/\=/,$pair,2);
9545: $val = &unescape($val);
9546: if ($key eq $item) {
9547: $instcoderegexp .= '('.$val.')';
9548: last;
9549: }
9550: }
9551: } else {
9552: $instcoderegexp .= $codedefaults->{$item};
9553: }
9554: }
9555: $instcoderegexp .= '$';
9556: my (@from,@to);
9557: eval {
9558: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9559: (@to) = ($clonetocode =~ /$instcoderegexp/);
9560: };
9561: if ((@from > 0) && (@to > 0)) {
9562: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9563: if (!@diffs) {
9564: $canclone = 1;
9565: }
9566: }
9567: }
9568: return $canclone;
9569: }
9570:
9571: sub default_instcode_cloning {
9572: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9573: my (%codedefaults,@code_order,$canclone);
9574: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9575: %codedefaults = %{$codedefaultsref};
9576: @code_order = @{$codeorderref};
9577: } elsif ($clonedom) {
9578: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9579: }
9580: if (($domdefclone) && (@code_order)) {
9581: my @clonecodes = split(/\+/,$domdefclone);
9582: my $instcoderegexp ='^';
9583: foreach my $item (@code_order) {
9584: if (grep(/^\Q$item\E$/,@clonecodes)) {
9585: $instcoderegexp .= '('.$codedefaults{$item}.')';
9586: } else {
9587: $instcoderegexp .= $codedefaults{$item};
9588: }
9589: }
9590: $instcoderegexp .= '$';
9591: my (@from,@to);
9592: eval {
9593: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9594: (@to) = ($clonetocode =~ /$instcoderegexp/);
9595: };
9596: if ((@from > 0) && (@to > 0)) {
9597: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9598: if (!@diffs) {
9599: $canclone = 1;
9600: }
9601: }
9602: }
9603: return $canclone;
9604: }
9605:
1.679 raeburn 9606: # ------------------------------------------------------- Course Group routines
9607:
9608: sub get_coursegroups {
1.809 raeburn 9609: my ($cdom,$cnum,$group,$namespace) = @_;
9610: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9611: }
9612:
1.679 raeburn 9613: sub modify_coursegroup {
9614: my ($cdom,$cnum,$groupsettings) = @_;
9615: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9616: }
9617:
1.809 raeburn 9618: sub toggle_coursegroup_status {
9619: my ($cdom,$cnum,$group,$action) = @_;
9620: my ($from_namespace,$to_namespace);
9621: if ($action eq 'delete') {
9622: $from_namespace = 'coursegroups';
9623: $to_namespace = 'deleted_groups';
9624: } else {
9625: $from_namespace = 'deleted_groups';
9626: $to_namespace = 'coursegroups';
9627: }
9628: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9629: if (my $tmp = &error(%curr_group)) {
9630: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9631: return ('read error',$tmp);
9632: } else {
9633: my %savedsettings = %curr_group;
1.809 raeburn 9634: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9635: my $deloutcome;
9636: if ($result eq 'ok') {
1.809 raeburn 9637: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9638: } else {
9639: return ('write error',$result);
9640: }
9641: if ($deloutcome eq 'ok') {
9642: return 'ok';
9643: } else {
9644: return ('delete error',$deloutcome);
9645: }
9646: }
9647: }
9648:
1.679 raeburn 9649: sub modify_group_roles {
1.957 raeburn 9650: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9651: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9652: my $role = 'gr/'.&escape($userprivs);
9653: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9654: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9655: if ($result eq 'ok') {
9656: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9657: }
1.679 raeburn 9658: return $result;
9659: }
9660:
9661: sub modify_coursegroup_membership {
9662: my ($cdom,$cnum,$membership) = @_;
9663: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9664: return $result;
9665: }
9666:
1.682 raeburn 9667: sub get_active_groups {
9668: my ($udom,$uname,$cdom,$cnum) = @_;
9669: my $now = time;
9670: my %groups = ();
9671: foreach my $key (keys(%env)) {
1.811 albertel 9672: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9673: my ($start,$end) = split(/\./,$env{$key});
9674: if (($end!=0) && ($end<$now)) { next; }
9675: if (($start!=0) && ($start>$now)) { next; }
9676: if ($1 eq $cdom && $2 eq $cnum) {
9677: $groups{$3} = $env{$key} ;
9678: }
9679: }
9680: }
9681: return %groups;
9682: }
9683:
1.683 raeburn 9684: sub get_group_membership {
9685: my ($cdom,$cnum,$group) = @_;
9686: return(&dump('groupmembership',$cdom,$cnum,$group));
9687: }
9688:
9689: sub get_users_groups {
9690: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9691: my @usersgroups;
1.683 raeburn 9692: my $cachetime=1800;
9693:
9694: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9695: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9696: if (defined($cached)) {
1.734 albertel 9697: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9698: } else {
9699: $grouplist = '';
1.816 raeburn 9700: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9701: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9702: my $access_end = $env{'course.'.$courseid.
9703: '.default_enrollment_end_date'};
9704: my $now = time;
9705: foreach my $key (keys(%roleshash)) {
9706: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9707: my $group = $1;
9708: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9709: my $start = $2;
9710: my $end = $1;
9711: if ($start == -1) { next; } # deleted from group
9712: if (($start!=0) && ($start>$now)) { next; }
9713: if (($end!=0) && ($end<$now)) {
9714: if ($access_end && $access_end < $now) {
9715: if ($access_end - $end < 86400) {
9716: push(@usersgroups,$group);
1.733 raeburn 9717: }
9718: }
1.817 raeburn 9719: next;
1.733 raeburn 9720: }
1.817 raeburn 9721: push(@usersgroups,$group);
1.683 raeburn 9722: }
9723: }
9724: }
1.817 raeburn 9725: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9726: $grouplist = join(':',@usersgroups);
9727: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9728: }
1.733 raeburn 9729: return @usersgroups;
1.683 raeburn 9730: }
9731:
9732: sub devalidate_getgroups_cache {
9733: my ($udom,$uname,$cdom,$cnum)=@_;
9734: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9735:
1.683 raeburn 9736: my $hashid="$udom:$uname:$courseid";
9737: &devalidate_cache_new('getgroups',$hashid);
9738: }
9739:
1.12 www 9740: # ------------------------------------------------------------------ Plain Text
9741:
9742: sub plaintext {
1.988 raeburn 9743: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9744: if ($short =~ m{^cr/}) {
1.758 albertel 9745: return (split('/',$short))[-1];
9746: }
1.742 raeburn 9747: if (!defined($cid)) {
9748: $cid = $env{'request.course.id'};
9749: }
9750: my %rolenames = (
1.1008 raeburn 9751: Course => 'std',
9752: Community => 'alt1',
1.1305 raeburn 9753: Placement => 'std',
1.742 raeburn 9754: );
1.1037 raeburn 9755: if ($cid ne '') {
9756: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9757: unless ($forcedefault) {
9758: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9759: &Apache::lonlocal::mt_escape(\$roletext);
9760: return &Apache::lonlocal::mt($roletext);
9761: }
9762: }
9763: }
9764: if ((defined($type)) && (defined($rolenames{$type})) &&
9765: (defined($rolenames{$type})) &&
9766: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9767: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9768: } elsif ($cid ne '') {
9769: my $crstype = $env{'course.'.$cid.'.type'};
9770: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9771: (defined($prp{$short}{$rolenames{$crstype}}))) {
9772: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9773: }
1.742 raeburn 9774: }
1.1037 raeburn 9775: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9776: }
9777:
9778: # ----------------------------------------------------------------- Assign Role
9779:
9780: sub assignrole {
1.957 raeburn 9781: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9782: $context)=@_;
1.21 www 9783: my $mrole;
9784: if ($role =~ /^cr\//) {
1.393 www 9785: my $cwosec=$url;
1.811 albertel 9786: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9787: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9788: my $refused = 1;
9789: if ($context eq 'requestcourses') {
9790: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9791: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9792: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9793: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9794: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9795: if ($crsenv{'internal.courseowner'} eq
9796: $env{'user.name'}.':'.$env{'user.domain'}) {
9797: $refused = '';
9798: }
9799: }
9800: }
9801: }
9802: }
9803: if ($refused) {
9804: &logthis('Refused custom assignrole: '.
9805: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9806: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9807: return 'refused';
9808: }
1.104 www 9809: }
1.21 www 9810: $mrole='cr';
1.678 raeburn 9811: } elsif ($role =~ /^gr\//) {
9812: my $cwogrp=$url;
1.811 albertel 9813: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9814: unless (&allowed('mdg',$cwogrp)) {
9815: &logthis('Refused group assignrole: '.
9816: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9817: $env{'user.name'}.' at '.$env{'user.domain'});
9818: return 'refused';
9819: }
9820: $mrole='gr';
1.21 www 9821: } else {
1.82 www 9822: my $cwosec=$url;
1.811 albertel 9823: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9824: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9825: my $refused;
9826: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9827: if (!(&allowed('c'.$role,$url))) {
9828: $refused = 1;
9829: }
9830: } else {
9831: $refused = 1;
9832: }
1.947 raeburn 9833: if ($refused) {
1.1045 raeburn 9834: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377 raeburn 9835: if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045 raeburn 9836: my %crsenv;
9837: if ($role eq 'cc' || $role eq 'co') {
9838: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9839: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9840: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9841: if ($crsenv{'internal.courseowner'} eq
9842: $env{'user.name'}.':'.$env{'user.domain'}) {
9843: $refused = '';
9844: }
9845: }
9846: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9847: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9848: if ($crsenv{'internal.courseowner'} eq
9849: $env{'user.name'}.':'.$env{'user.domain'}) {
9850: $refused = '';
9851: }
9852: }
9853: }
9854: }
1.1368 raeburn 9855: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
9856: if ($role eq 'st') {
9857: $refused = '';
1.1377 raeburn 9858: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368 raeburn 9859: $refused = '';
9860: }
1.1017 raeburn 9861: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9862: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9863: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9864: my $wrongcc;
9865: if ($cnum =~ /^$match_community$/) {
9866: $wrongcc = 1 if ($role eq 'cc');
9867: } else {
9868: $wrongcc = 1 if ($role eq 'co');
9869: }
9870: unless ($wrongcc) {
9871: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9872: if ($crsenv{'internal.courseowner'} eq
9873: $env{'user.name'}.':'.$env{'user.domain'}) {
9874: $refused = '';
9875: }
1.1017 raeburn 9876: }
9877: }
1.1183 raeburn 9878: } elsif ($context eq 'requestauthor') {
9879: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9880: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9881: if ($env{'environment.requestauthor'} eq 'automatic') {
9882: $refused = '';
9883: } else {
9884: my %domdefaults = &get_domain_defaults($udom);
9885: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9886: my $checkbystatus;
9887: if ($env{'user.adv'}) {
9888: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9889: if ($disposition eq 'automatic') {
9890: $refused = '';
9891: } elsif ($disposition eq '') {
9892: $checkbystatus = 1;
9893: }
9894: } else {
9895: $checkbystatus = 1;
9896: }
9897: if ($checkbystatus) {
9898: if ($env{'environment.inststatus'}) {
9899: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9900: foreach my $type (@inststatuses) {
9901: if (($type ne '') &&
9902: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9903: $refused = '';
9904: }
9905: }
9906: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9907: $refused = '';
9908: }
9909: }
9910: }
9911: }
9912: }
1.1017 raeburn 9913: }
9914: if ($refused) {
1.947 raeburn 9915: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9916: ' '.$role.' '.$end.' '.$start.' by '.
9917: $env{'user.name'}.' at '.$env{'user.domain'});
9918: return 'refused';
9919: }
1.932 raeburn 9920: }
1.1131 raeburn 9921: } elsif ($role eq 'au') {
9922: if ($url ne '/'.$udom.'/') {
9923: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9924: ' to assign author role for '.$uname.':'.$udom.
9925: ' in domain: '.$url.' refused (wrong domain).');
9926: return 'refused';
9927: }
1.104 www 9928: }
1.21 www 9929: $mrole=$role;
9930: }
1.620 albertel 9931: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9932: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9933: if ($end) { $command.='_'.$end; }
1.21 www 9934: if ($start) {
9935: if ($end) {
1.81 www 9936: $command.='_'.$start;
1.21 www 9937: } else {
1.81 www 9938: $command.='_0_'.$start;
1.21 www 9939: }
9940: }
1.739 raeburn 9941: my $origstart = $start;
9942: my $origend = $end;
1.957 raeburn 9943: my $delflag;
1.357 www 9944: # actually delete
9945: if ($deleteflag) {
1.373 www 9946: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9947: # modify command to delete the role
1.620 albertel 9948: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9949: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9950: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9951: # set start and finish to negative values for userrolelog
9952: $start=-1;
9953: $end=-1;
1.957 raeburn 9954: $delflag = 1;
1.357 www 9955: }
9956: }
9957: # send command
1.349 www 9958: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9959: # log new user role if status is ok
1.349 www 9960: if ($answer eq 'ok') {
1.663 raeburn 9961: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 9962: if (($role eq 'cc') || ($role eq 'in') ||
9963: ($role eq 'ep') || ($role eq 'ad') ||
9964: ($role eq 'ta') || ($role eq 'st') ||
9965: ($role=~/^cr/) || ($role eq 'gr') ||
9966: ($role eq 'co')) {
1.1200 raeburn 9967: # for course roles, perform group memberships changes triggered by role change.
9968: unless ($role =~ /^gr/) {
9969: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9970: $origstart,$selfenroll,$context);
9971: }
1.1184 raeburn 9972: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9973: $selfenroll,$context);
9974: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 9975: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9976: ($role eq 'da')) {
1.1184 raeburn 9977: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9978: $context);
9979: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9980: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9981: $context);
9982: }
1.1053 raeburn 9983: if ($role eq 'cc') {
9984: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9985: }
1.349 www 9986: }
9987: return $answer;
1.169 harris41 9988: }
9989:
1.1053 raeburn 9990: sub autoupdate_coowners {
9991: my ($url,$end,$start,$uname,$udom) = @_;
9992: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9993: if (($cdom ne '') && ($cnum ne '')) {
9994: my $now = time;
9995: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9996: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9997: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9998: my $instcode = $coursehash{'internal.coursecode'};
9999: if ($instcode ne '') {
1.1056 raeburn 10000: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10001: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10002: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10003: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10004: if ($result eq 'valid') {
10005: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10006: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10007: push(@newcoowners,$coowner);
10008: }
10009: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10010: push(@newcoowners,$uname.':'.$udom);
10011: }
10012: @newcoowners = sort(@newcoowners);
10013: } else {
10014: push(@newcoowners,$uname.':'.$udom);
10015: }
10016: } else {
10017: if ($coursehash{'internal.co-owners'}) {
10018: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10019: unless ($coowner eq $uname.':'.$udom) {
10020: push(@newcoowners,$coowner);
10021: }
10022: }
10023: unless (@newcoowners > 0) {
10024: $delcoowners = 1;
10025: $coowners = '';
10026: }
10027: }
10028: }
10029: if (@newcoowners || $delcoowners) {
10030: &store_coowners($cdom,$cnum,$coursehash{'home'},
10031: $delcoowners,@newcoowners);
10032: }
10033: }
10034: }
10035: }
10036: }
10037: }
10038: }
10039:
10040: sub store_coowners {
10041: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10042: my $cid = $cdom.'_'.$cnum;
10043: my ($coowners,$delresult,$putresult);
10044: if (@newcoowners) {
10045: $coowners = join(',',@newcoowners);
10046: my %coownershash = (
10047: 'internal.co-owners' => $coowners,
10048: );
10049: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10050: if ($putresult eq 'ok') {
10051: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10052: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10053: }
10054: }
10055: }
10056: if ($delcoowners) {
10057: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10058: if ($delresult eq 'ok') {
10059: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10060: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10061: }
10062: }
10063: }
10064: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10065: my %crsinfo =
10066: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10067: if (ref($crsinfo{$cid}) eq 'HASH') {
10068: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10069: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10070: }
10071: }
10072: }
10073:
1.169 harris41 10074: # -------------------------------------------------- Modify user authentication
1.197 www 10075: # Overrides without validation
10076:
1.169 harris41 10077: sub modifyuserauth {
10078: my ($udom,$uname,$umode,$upass)=@_;
10079: my $uhome=&homeserver($uname,$udom);
1.197 www 10080: unless (&allowed('mau',$udom)) { return 'refused'; }
10081: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10082: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10083: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10084: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10085: &escape($upass),$uhome);
1.620 albertel 10086: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10087: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10088: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10089: &log($udom,,$uname,$uhome,
1.620 albertel 10090: 'Authentication changed by '.$env{'user.domain'}.', '.
10091: $env{'user.name'}.', '.$umode.
1.197 www 10092: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 10093: unless ($reply eq 'ok') {
1.197 www 10094: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10095: return 'error: '.$reply;
10096: }
1.170 harris41 10097: return 'ok';
1.80 www 10098: }
10099:
1.81 www 10100: # --------------------------------------------------------------- Modify a user
1.80 www 10101:
1.81 www 10102: sub modifyuser {
1.206 matthew 10103: my ($udom, $uname, $uid,
10104: $umode, $upass, $first,
10105: $middle, $last, $gene,
1.1058 raeburn 10106: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10107: $udom= &LONCAPA::clean_domain($udom);
10108: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10109: my $showcandelete = 'none';
10110: if (ref($candelete) eq 'ARRAY') {
10111: if (@{$candelete} > 0) {
10112: $showcandelete = join(', ',@{$candelete});
10113: }
10114: }
1.81 www 10115: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10116: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10117: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10118: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10119: ' desiredhome not specified').
1.620 albertel 10120: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10121: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10122: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10123: my $newuser;
10124: if ($uhome eq 'no_host') {
10125: $newuser = 1;
1.1368 raeburn 10126: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10127: ($umode eq 'lti')) {
10128: return 'error: more information needed to create new user';
10129: }
1.1075 raeburn 10130: }
1.80 www 10131: # ----------------------------------------------------------------- Create User
1.406 albertel 10132: if (($uhome eq 'no_host') &&
1.1368 raeburn 10133: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80 www 10134: my $unhome='';
1.844 albertel 10135: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10136: $unhome = $desiredhome;
1.620 albertel 10137: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10138: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10139: } else { # load balancing routine for determining $unhome
1.81 www 10140: my $loadm=10000000;
1.841 albertel 10141: my %servers = &get_servers($udom,'library');
10142: foreach my $tryserver (keys(%servers)) {
10143: my $answer=reply('load',$tryserver);
10144: if (($answer=~/\d+/) && ($answer<$loadm)) {
10145: $loadm=$answer;
10146: $unhome=$tryserver;
10147: }
1.80 www 10148: }
10149: }
10150: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10151: return 'error: unable to find a home server for '.$uname.
10152: ' in domain '.$udom;
1.80 www 10153: }
10154: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10155: &escape($upass),$unhome);
10156: unless ($reply eq 'ok') {
10157: return 'error: '.$reply;
10158: }
1.230 stredwic 10159: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10160: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10161: return 'error: unable verify users home machine.';
1.80 www 10162: }
1.209 matthew 10163: } # End of creation of new user
1.80 www 10164: # ---------------------------------------------------------------------- Add ID
10165: if ($uid) {
10166: $uid=~tr/A-Z/a-z/;
10167: my %uidhash=&idrget($udom,$uname);
1.196 www 10168: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10169: && (!$forceid)) {
1.80 www 10170: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10171: return 'error: user id "'.$uid.'" does not match '.
10172: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10173: }
10174: } else {
1.1300 raeburn 10175: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 10176: }
10177: }
10178: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10179: my @tmp=&get('environment',
1.899 raeburn 10180: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10181: 'permanentemail','inststatus'],
1.134 albertel 10182: $udom,$uname);
1.1075 raeburn 10183: my (%names,%oldnames);
1.313 matthew 10184: if ($tmp[0] =~ m/^error:.*/) {
10185: %names=();
10186: } else {
10187: %names = @tmp;
1.1075 raeburn 10188: %oldnames = %names;
1.313 matthew 10189: }
1.388 www 10190: #
1.1058 raeburn 10191: # If name, email and/or uid are blank (e.g., because an uploaded file
10192: # of users did not contain them), do not overwrite existing values
10193: # unless field is in $candelete array ref.
10194: #
10195:
10196: my @fields = ('firstname','middlename','lastname','generation',
10197: 'permanentemail','id');
10198: my %newvalues;
10199: if (ref($candelete) eq 'ARRAY') {
10200: foreach my $field (@fields) {
10201: if (grep(/^\Q$field\E$/,@{$candelete})) {
10202: if ($field eq 'firstname') {
10203: $names{$field} = $first;
10204: } elsif ($field eq 'middlename') {
10205: $names{$field} = $middle;
10206: } elsif ($field eq 'lastname') {
10207: $names{$field} = $last;
10208: } elsif ($field eq 'generation') {
10209: $names{$field} = $gene;
10210: } elsif ($field eq 'permanentemail') {
10211: $names{$field} = $email;
10212: } elsif ($field eq 'id') {
10213: $names{$field} = $uid;
10214: }
10215: }
10216: }
10217: }
1.388 www 10218: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10219: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10220: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10221: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10222: if ($email) {
10223: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10224: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10225: }
1.899 raeburn 10226: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10227: if (defined($inststatus)) {
10228: $names{'inststatus'} = '';
10229: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10230: if (ref($usertypes) eq 'HASH') {
10231: my @okstatuses;
10232: foreach my $item (split(/:/,$inststatus)) {
10233: if (defined($usertypes->{$item})) {
10234: push(@okstatuses,$item);
10235: }
10236: }
10237: if (@okstatuses) {
10238: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10239: }
10240: }
10241: }
1.1075 raeburn 10242: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10243: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10244: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10245: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10246: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10247: } else {
10248: $logmsg .= ' during self creation';
10249: }
1.1075 raeburn 10250: my $changed;
10251: if ($newuser) {
10252: $changed = 1;
10253: } else {
10254: foreach my $field (@fields) {
10255: if ($names{$field} ne $oldnames{$field}) {
10256: $changed = 1;
10257: last;
10258: }
10259: }
10260: }
10261: unless ($changed) {
10262: $logmsg = 'No changes in user information needed for: '.$logmsg;
10263: &logthis($logmsg);
10264: return 'ok';
10265: }
10266: my $reply = &put('environment', \%names, $udom,$uname);
10267: if ($reply ne 'ok') {
10268: return 'error: '.$reply;
10269: }
1.1087 raeburn 10270: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10271: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10272: }
1.1075 raeburn 10273: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10274: &devalidate_cache_new('namescache',$uname.':'.$udom);
10275: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10276: &logthis($logmsg);
1.134 albertel 10277: return 'ok';
1.80 www 10278: }
10279:
1.81 www 10280: # -------------------------------------------------------------- Modify student
1.80 www 10281:
1.81 www 10282: sub modifystudent {
10283: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10284: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 10285: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10286: if (!$cid) {
1.620 albertel 10287: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10288: return 'not_in_class';
10289: }
1.80 www 10290: }
10291: # --------------------------------------------------------------- Make the user
1.81 www 10292: my $reply=&modifyuser
1.209 matthew 10293: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10294: $desiredhome,$email,$inststatus);
1.80 www 10295: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10296: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 10297: # student's environment
1.297 matthew 10298: $uid = undef if (!$forceid);
1.455 albertel 10299: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 10300: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 10301: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10302: return $reply;
10303: }
10304:
10305: sub modify_student_enrollment {
1.1216 raeburn 10306: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 10307: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10308: my ($cdom,$cnum,$chome);
10309: if (!$cid) {
1.620 albertel 10310: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10311: return 'not_in_class';
10312: }
1.620 albertel 10313: $cdom=$env{'course.'.$cid.'.domain'};
10314: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10315: } else {
10316: ($cdom,$cnum)=split(/_/,$cid);
10317: }
1.620 albertel 10318: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10319: if (!$chome) {
1.457 raeburn 10320: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10321: }
1.455 albertel 10322: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10323: # Make sure the user exists
1.81 www 10324: my $uhome=&homeserver($uname,$udom);
10325: if (($uhome eq '') || ($uhome eq 'no_host')) {
10326: return 'error: no such user';
10327: }
1.297 matthew 10328: # Get student data if we were not given enough information
10329: if (!defined($first) || $first eq '' ||
10330: !defined($last) || $last eq '' ||
10331: !defined($uid) || $uid eq '' ||
10332: !defined($middle) || $middle eq '' ||
10333: !defined($gene) || $gene eq '') {
1.294 matthew 10334: # They did not supply us with enough data to enroll the student, so
10335: # we need to pick up more information.
1.297 matthew 10336: my %tmp = &get('environment',
1.294 matthew 10337: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10338: ,$udom,$uname);
10339:
1.800 albertel 10340: #foreach my $key (keys(%tmp)) {
10341: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10342: #}
1.294 matthew 10343: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10344: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10345: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10346: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10347: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10348: }
1.556 albertel 10349: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10350: my $user = "$uname:$udom";
10351: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10352: my $reply=cput('classlist',
1.1148 raeburn 10353: {$user =>
1.1314 raeburn 10354: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10355: $cdom,$cnum);
1.1148 raeburn 10356: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10357: &devalidate_getsection_cache($udom,$uname,$cid);
10358: } else {
1.81 www 10359: return 'error: '.$reply;
10360: }
1.297 matthew 10361: # Add student role to user
1.83 www 10362: my $uurl='/'.$cid;
1.81 www 10363: $uurl=~s/\_/\//g;
10364: if ($usec) {
10365: $uurl.='/'.$usec;
10366: }
1.1148 raeburn 10367: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10368: $selfenroll,$context);
10369: if ($result ne 'ok') {
10370: if ($old_entry{$user} ne '') {
10371: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10372: } else {
10373: $reply = &del('classlist',[$user],$cdom,$cnum);
10374: }
10375: }
10376: return $result;
1.21 www 10377: }
10378:
1.556 albertel 10379: sub format_name {
10380: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10381: my $name;
10382: if ($first ne 'lastname') {
10383: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10384: } else {
10385: if ($lastname=~/\S/) {
10386: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10387: $name=~s/\s+,/,/;
10388: } else {
10389: $name.= $firstname.' '.$middlename.' '.$generation;
10390: }
10391: }
10392: $name=~s/^\s+//;
10393: $name=~s/\s+$//;
10394: $name=~s/\s+/ /g;
10395: return $name;
10396: }
10397:
1.84 www 10398: # ------------------------------------------------- Write to course preferences
10399:
10400: sub writecoursepref {
10401: my ($courseid,%prefs)=@_;
10402: $courseid=~s/^\///;
10403: $courseid=~s/\_/\//g;
10404: my ($cdomain,$cnum)=split(/\//,$courseid);
10405: my $chome=homeserver($cnum,$cdomain);
10406: if (($chome eq '') || ($chome eq 'no_host')) {
10407: return 'error: no such course';
10408: }
10409: my $cstring='';
1.800 albertel 10410: foreach my $pref (keys(%prefs)) {
10411: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10412: }
1.84 www 10413: $cstring=~s/\&$//;
10414: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10415: }
10416:
10417: # ---------------------------------------------------------- Make/modify course
10418:
10419: sub createcourse {
1.741 raeburn 10420: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 10421: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 10422: $url=&declutter($url);
10423: my $cid='';
1.1028 raeburn 10424: if ($context eq 'requestcourses') {
10425: my $can_create = 0;
10426: my ($ownername,$ownerdom) = split(':',$course_owner);
10427: if ($udom eq $ownerdom) {
10428: if (&usertools_access($ownername,$ownerdom,$category,undef,
10429: $context)) {
10430: $can_create = 1;
10431: }
10432: } else {
10433: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10434: $category);
10435: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10436: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10437: if (@curr > 0) {
10438: my @options = qw(approval validate autolimit);
10439: my $optregex = join('|',@options);
10440: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10441: $can_create = 1;
10442: }
10443: }
10444: }
10445: }
10446: if ($can_create) {
10447: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10448: unless (&allowed('ccc',$udom)) {
10449: return 'refused';
10450: }
1.1017 raeburn 10451: }
10452: } else {
10453: return 'refused';
10454: }
1.1028 raeburn 10455: } elsif (!&allowed('ccc',$udom)) {
10456: return 'refused';
1.84 www 10457: }
1.1011 raeburn 10458: # --------------------------------------------------------------- Get Unique ID
10459: my $uname;
10460: if ($cnum =~ /^$match_courseid$/) {
10461: my $chome=&homeserver($cnum,$udom,'true');
10462: if (($chome eq '') || ($chome eq 'no_host')) {
10463: $uname = $cnum;
10464: } else {
1.1038 raeburn 10465: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10466: }
10467: } else {
1.1038 raeburn 10468: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10469: }
10470: return $uname if ($uname =~ /^error/);
10471: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10472: if (!defined($course_server)) {
10473: if (defined(&domain($udom,'primary'))) {
10474: $course_server = &domain($udom,'primary');
10475: } else {
10476: $course_server = $env{'user.home'};
10477: }
10478: }
10479: my %host_servers =
10480: &Apache::lonnet::get_servers($udom,'library');
10481: unless ($host_servers{$course_server}) {
10482: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10483: }
1.84 www 10484: # ------------------------------------------------------------- Make the course
10485: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10486: $course_server);
1.84 www 10487: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10488: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10489: if (($uhome eq '') || ($uhome eq 'no_host')) {
10490: return 'error: no such course';
10491: }
1.271 www 10492: # ----------------------------------------------------------------- Course made
1.516 raeburn 10493: # log existence
1.1029 raeburn 10494: my $now = time;
1.918 raeburn 10495: my $newcourse = {
10496: $udom.'_'.$uname => {
1.921 raeburn 10497: description => $description,
10498: inst_code => $inst_code,
10499: owner => $course_owner,
10500: type => $crstype,
1.1029 raeburn 10501: creator => $env{'user.name'}.':'.
10502: $env{'user.domain'},
10503: created => $now,
10504: context => $context,
1.918 raeburn 10505: },
10506: };
1.921 raeburn 10507: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10508: # set toplevel url
1.271 www 10509: my $topurl=$url;
10510: unless ($nonstandard) {
10511: # ------------------------------------------ For standard courses, make top url
10512: my $mapurl=&clutter($url);
1.278 www 10513: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10514: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10515: <map>
10516: <resource id="1" type="start"></resource>
10517: <resource id="2" src="$mapurl"></resource>
10518: <resource id="3" type="finish"></resource>
10519: <link index="1" from="1" to="2"></link>
10520: <link index="2" from="2" to="3"></link>
10521: </map>
10522: ENDINITMAP
10523: $topurl=&declutter(
1.638 albertel 10524: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10525: );
10526: }
10527: # ----------------------------------------------------------- Write preferences
1.84 www 10528: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10529: ('description' => $description,
10530: 'url' => $topurl,
10531: 'internal.creator' => $env{'user.name'}.':'.
10532: $env{'user.domain'},
10533: 'internal.created' => $now,
10534: 'internal.creationcontext' => $context)
10535: );
1.84 www 10536: return '/'.$udom.'/'.$uname;
10537: }
10538:
1.1011 raeburn 10539: # ------------------------------------------------------------------- Create ID
10540: sub generate_coursenum {
1.1038 raeburn 10541: my ($udom,$crstype) = @_;
1.1011 raeburn 10542: my $domdesc = &domain($udom);
10543: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10544: my $first;
10545: if ($crstype eq 'Community') {
10546: $first = '0';
10547: } else {
10548: $first = int(1+rand(9));
10549: }
10550: my $uname=$first.
1.1011 raeburn 10551: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10552: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10553: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10554: # ----------------------------------------------- Make sure that does not exist
10555: my $uhome=&homeserver($uname,$udom,'true');
10556: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10557: if ($crstype eq 'Community') {
10558: $first = '0';
10559: } else {
10560: $first = int(1+rand(9));
10561: }
10562: $uname=$first.
1.1011 raeburn 10563: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10564: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10565: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10566: $uhome=&homeserver($uname,$udom,'true');
10567: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10568: return 'error: unable to generate unique course-ID';
10569: }
10570: }
10571: return $uname;
10572: }
10573:
1.813 albertel 10574: sub is_course {
1.1167 droeschl 10575: my ($cdom, $cnum) = scalar(@_) == 1 ?
10576: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
10577:
1.1381 raeburn 10578: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10579: my $uhome=&homeserver($cnum,$cdom);
10580: my $iscourse;
10581: if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382 raeburn 10582: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381 raeburn 10583: } else {
10584: my $hashid = $cdom.':'.$cnum;
10585: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10586: unless (defined($cached)) {
10587: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10588: $cnum,undef,undef,'.');
10589: $iscourse = 0;
10590: if (exists($courses{$cdom.'_'.$cnum})) {
10591: $iscourse = 1;
10592: }
10593: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10594: }
10595: }
10596: return unless ($iscourse);
1.1167 droeschl 10597: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10598: }
10599:
1.1015 raeburn 10600: sub store_userdata {
10601: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10602: my $result;
1.1016 raeburn 10603: if ($datakey ne '') {
1.1013 raeburn 10604: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10605: if ($udom eq '' || $uname eq '') {
10606: $udom = $env{'user.domain'};
10607: $uname = $env{'user.name'};
10608: }
10609: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10610: if (($uhome eq '') || ($uhome eq 'no_host')) {
10611: $result = 'error: no_host';
10612: } else {
10613: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10614: $storehash->{'host'} = $perlvar{'lonHostID'};
10615:
10616: my $namevalue='';
10617: foreach my $key (keys(%{$storehash})) {
10618: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10619: }
10620: $namevalue=~s/\&$//;
1.1224 raeburn 10621: unless ($namespace eq 'courserequests') {
10622: $datakey = &escape($datakey);
10623: }
1.1105 raeburn 10624: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10625: $namevalue,$uhome);
1.1013 raeburn 10626: }
10627: } else {
10628: $result = 'error: data to store was not a hash reference';
10629: }
10630: } else {
10631: $result= 'error: invalid requestkey';
10632: }
10633: return $result;
10634: }
10635:
1.21 www 10636: # ---------------------------------------------------------- Assign Custom Role
10637:
10638: sub assigncustomrole {
1.957 raeburn 10639: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10640: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10641: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10642: }
10643:
10644: # ----------------------------------------------------------------- Revoke Role
10645:
10646: sub revokerole {
1.957 raeburn 10647: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10648: my $now=time;
1.965 raeburn 10649: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10650: }
10651:
10652: # ---------------------------------------------------------- Revoke Custom Role
10653:
10654: sub revokecustomrole {
1.957 raeburn 10655: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10656: my $now=time;
1.357 www 10657: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10658: $deleteflag,$selfenroll,$context);
1.17 www 10659: }
10660:
1.533 banghart 10661: # ------------------------------------------------------------ Disk usage
1.535 albertel 10662: sub diskusage {
1.955 raeburn 10663: my ($udom,$uname,$directorypath,$getpropath)=@_;
10664: $directorypath =~ s/\/$//;
10665: my $listing=&reply('du2:'.&escape($directorypath).':'
10666: .&escape($getpropath).':'.&escape($uname).':'
10667: .&escape($udom),homeserver($uname,$udom));
10668: if ($listing eq 'unknown_cmd') {
10669: if ($getpropath) {
10670: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10671: }
10672: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10673: }
1.514 albertel 10674: return $listing;
1.512 banghart 10675: }
10676:
1.566 banghart 10677: sub is_locked {
1.1096 raeburn 10678: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10679: my @check;
10680: my $is_locked;
1.1093 raeburn 10681: push (@check,$file_name);
1.613 albertel 10682: my %locked = &get('file_permissions',\@check,
1.620 albertel 10683: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10684: my ($tmp)=keys(%locked);
10685: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10686:
1.566 banghart 10687: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10688: $is_locked = 'false';
10689: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10690: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10691: $is_locked = 'true';
1.1096 raeburn 10692: if (ref($which) eq 'ARRAY') {
10693: push(@{$which},$entry);
10694: } else {
10695: last;
10696: }
1.745 raeburn 10697: }
10698: }
1.566 banghart 10699: } else {
10700: $is_locked = 'false';
10701: }
1.1093 raeburn 10702: return $is_locked;
1.566 banghart 10703: }
10704:
1.759 albertel 10705: sub declutter_portfile {
10706: my ($file) = @_;
1.833 albertel 10707: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10708: return $file;
10709: }
10710:
1.559 banghart 10711: # ------------------------------------------------------------- Mark as Read Only
10712:
10713: sub mark_as_readonly {
10714: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10715: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10716: my ($tmp)=keys(%current_permissions);
10717: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10718: foreach my $file (@{$files}) {
1.759 albertel 10719: $file = &declutter_portfile($file);
1.561 banghart 10720: push(@{$current_permissions{$file}},$what);
1.559 banghart 10721: }
1.613 albertel 10722: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10723: return;
10724: }
10725:
1.572 banghart 10726: # ------------------------------------------------------------Save Selected Files
10727:
10728: sub save_selected_files {
10729: my ($user, $path, @files) = @_;
10730: my $filename = $user."savedfiles";
1.573 banghart 10731: my @other_files = &files_not_in_path($user, $path);
1.1359 raeburn 10732: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10733: foreach my $file (@files) {
1.620 albertel 10734: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10735: }
10736: foreach my $file (@other_files) {
1.574 banghart 10737: print (OUT $file."\n");
1.572 banghart 10738: }
1.574 banghart 10739: close (OUT);
1.572 banghart 10740: return 'ok';
10741: }
10742:
1.574 banghart 10743: sub clear_selected_files {
10744: my ($user) = @_;
10745: my $filename = $user."savedfiles";
1.1359 raeburn 10746: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10747: print (OUT undef);
10748: close (OUT);
10749: return ("ok");
10750: }
10751:
1.572 banghart 10752: sub files_in_path {
10753: my ($user, $path) = @_;
10754: my $filename = $user."savedfiles";
10755: my %return_files;
1.1359 raeburn 10756: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10757: while (my $line_in = <IN>) {
1.574 banghart 10758: chomp ($line_in);
10759: my @paths_and_file = split (m!/!, $line_in);
10760: my $file_part = pop (@paths_and_file);
10761: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10762: $path_part.='/';
10763: my $path_and_file = $path_part.$file_part;
10764: if ($path_part eq $path) {
10765: $return_files{$file_part}= 'selected';
10766: }
10767: }
1.574 banghart 10768: close (IN);
10769: return (\%return_files);
1.572 banghart 10770: }
10771:
10772: # called in portfolio select mode, to show files selected NOT in current directory
10773: sub files_not_in_path {
10774: my ($user, $path) = @_;
10775: my $filename = $user."savedfiles";
10776: my @return_files;
10777: my $path_part;
1.1359 raeburn 10778: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 10779: while (my $line = <IN>) {
1.572 banghart 10780: #ok, I know it's clunky, but I want it to work
1.800 albertel 10781: my @paths_and_file = split(m|/|, $line);
10782: my $file_part = pop(@paths_and_file);
10783: chomp($file_part);
10784: my $path_part = join('/', @paths_and_file);
1.572 banghart 10785: $path_part .= '/';
10786: my $path_and_file = $path_part.$file_part;
10787: if ($path_part ne $path) {
1.800 albertel 10788: push(@return_files, ($path_and_file));
1.572 banghart 10789: }
10790: }
1.800 albertel 10791: close(OUT);
1.574 banghart 10792: return (@return_files);
1.572 banghart 10793: }
10794:
1.1273 raeburn 10795: #------------------------------Submitted/Handedback Portfolio Files Versioning
10796:
10797: sub portfiles_versioning {
10798: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10799: my $portfolio_root = '/userfiles/portfolio';
10800: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10801: foreach my $file (@{$portfiles}) {
10802: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10803: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10804: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10805: my $getpropath = 1;
10806: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10807: $stu_name,$getpropath);
10808: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10809: my $new_answer =
10810: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10811: if ($new_answer ne 'problem getting file') {
10812: push(@{$versioned_portfiles}, $directory.$new_answer);
10813: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10814: [$symb,$env{'request.course.id'},'graded']);
10815: }
10816: }
10817: }
10818:
10819: sub get_next_version {
10820: my ($answer_name, $answer_ext, $dir_list) = @_;
10821: my $version;
10822: if (ref($dir_list) eq 'ARRAY') {
10823: foreach my $row (@{$dir_list}) {
10824: my ($file) = split(/\&/,$row,2);
10825: my ($file_name,$file_version,$file_ext) =
10826: &file_name_version_ext($file);
10827: if (($file_name eq $answer_name) &&
10828: ($file_ext eq $answer_ext)) {
10829: # gets here if filename and extension match,
10830: # regardless of version
10831: if ($file_version ne '') {
10832: # a versioned file is found so save it for later
10833: if ($file_version > $version) {
10834: $version = $file_version;
10835: }
10836: }
10837: }
10838: }
10839: }
10840: $version ++;
10841: return($version);
10842: }
10843:
10844: sub version_selected_portfile {
10845: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10846: my ($answer_name,$answer_ver,$answer_ext) =
10847: &file_name_version_ext($file_name);
10848: my $new_answer;
10849: $env{'form.copy'} =
10850: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10851: if($env{'form.copy'} eq '-1') {
10852: $new_answer = 'problem getting file';
10853: } else {
10854: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10855: my $copy_result =
10856: &finishuserfileupload($stu_name,$domain,'copy',
10857: '/portfolio'.$directory.$new_answer);
10858: }
10859: undef($env{'form.copy'});
10860: return ($new_answer);
10861: }
10862:
10863: sub file_name_version_ext {
10864: my ($file)=@_;
10865: my @file_parts = split(/\./, $file);
10866: my ($name,$version,$ext);
10867: if (@file_parts > 1) {
10868: $ext=pop(@file_parts);
10869: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10870: $version=pop(@file_parts);
10871: }
10872: $name=join('.',@file_parts);
10873: } else {
10874: $name=join('.',@file_parts);
10875: }
10876: return($name,$version,$ext);
10877: }
10878:
1.745 raeburn 10879: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10880:
1.745 raeburn 10881: sub get_portfile_permissions {
10882: my ($domain,$user) = @_;
1.613 albertel 10883: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10884: my ($tmp)=keys(%current_permissions);
10885: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10886: return \%current_permissions;
10887: }
10888:
10889: #---------------------------------------------Get portfolio file access controls
10890:
1.749 raeburn 10891: sub get_access_controls {
1.745 raeburn 10892: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10893: my %access;
10894: my $real_file = $file;
10895: $file =~ s/\.meta$//;
1.745 raeburn 10896: if (defined($file)) {
1.749 raeburn 10897: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10898: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10899: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10900: }
10901: }
1.745 raeburn 10902: } else {
1.749 raeburn 10903: foreach my $key (keys(%{$current_permissions})) {
10904: if ($key =~ /\0accesscontrol$/) {
10905: if (defined($group)) {
10906: if ($key !~ m-^\Q$group\E/-) {
10907: next;
10908: }
10909: }
10910: my ($fullpath) = split(/\0/,$key);
10911: if (ref($$current_permissions{$key}) eq 'HASH') {
10912: foreach my $control (keys(%{$$current_permissions{$key}})) {
10913: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10914: }
10915: }
10916: }
10917: }
10918: }
10919: return %access;
10920: }
10921:
10922: sub modify_access_controls {
10923: my ($file_name,$changes,$domain,$user)=@_;
10924: my ($outcome,$deloutcome);
10925: my %store_permissions;
10926: my %new_values;
10927: my %new_control;
10928: my %translation;
10929: my @deletions = ();
10930: my $now = time;
10931: if (exists($$changes{'activate'})) {
10932: if (ref($$changes{'activate'}) eq 'HASH') {
10933: my @newitems = sort(keys(%{$$changes{'activate'}}));
10934: my $numnew = scalar(@newitems);
10935: for (my $i=0; $i<$numnew; $i++) {
10936: my $newkey = $newitems[$i];
10937: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10938: if ($newkey =~ /^\d+:/) {
10939: $newkey =~ s/^(\d+)/$newid/;
10940: $translation{$1} = $newid;
10941: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10942: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10943: $translation{$1} = $newid;
10944: }
1.749 raeburn 10945: $new_values{$file_name."\0".$newkey} =
10946: $$changes{'activate'}{$newitems[$i]};
10947: $new_control{$newkey} = $now;
10948: }
10949: }
10950: }
10951: my %todelete;
10952: my %changed_items;
10953: foreach my $action ('delete','update') {
10954: if (exists($$changes{$action})) {
10955: if (ref($$changes{$action}) eq 'HASH') {
10956: foreach my $key (keys(%{$$changes{$action}})) {
10957: my ($itemnum) = ($key =~ /^([^:]+):/);
10958: if ($action eq 'delete') {
10959: $todelete{$itemnum} = 1;
10960: } else {
10961: $changed_items{$itemnum} = $key;
10962: }
10963: }
1.745 raeburn 10964: }
10965: }
1.749 raeburn 10966: }
10967: # get lock on access controls for file.
10968: my $lockhash = {
10969: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10970: ':'.$env{'user.domain'},
10971: };
10972: my $tries = 0;
10973: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10974:
1.1288 damieng 10975: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10976: $tries ++;
1.1289 damieng 10977: sleep(0.1);
1.749 raeburn 10978: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10979: }
10980: if ($gotlock eq 'ok') {
10981: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10982: my ($tmp)=keys(%curr_permissions);
10983: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10984: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10985: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10986: if (ref($curr_controls) eq 'HASH') {
10987: foreach my $control_item (keys(%{$curr_controls})) {
10988: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10989: if (defined($todelete{$itemnum})) {
10990: push(@deletions,$file_name."\0".$control_item);
10991: } else {
10992: if (defined($changed_items{$itemnum})) {
10993: $new_control{$changed_items{$itemnum}} = $now;
10994: push(@deletions,$file_name."\0".$control_item);
10995: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10996: } else {
10997: $new_control{$control_item} = $$curr_controls{$control_item};
10998: }
10999: }
1.745 raeburn 11000: }
11001: }
11002: }
1.970 raeburn 11003: my ($group);
11004: if (&is_course($domain,$user)) {
11005: ($group,my $file) = split(/\//,$file_name,2);
11006: }
1.749 raeburn 11007: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11008: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11009: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11010: # remove lock
11011: my @del_lock = ($file_name."\0".'locked_access_records');
11012: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11013: my $sqlresult =
1.970 raeburn 11014: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11015: $group);
1.749 raeburn 11016: } else {
11017: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11018: }
1.749 raeburn 11019: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11020: }
11021:
1.827 raeburn 11022: sub make_public_indefinitely {
1.1271 raeburn 11023: my (@requrl) = @_;
11024: return &automated_portfile_access('public',\@requrl);
11025: }
11026:
11027: sub automated_portfile_access {
11028: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 11029: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11030: return 'invalid';
11031: }
1.1271 raeburn 11032: my %urls;
11033: if (ref($addsref) eq 'ARRAY') {
11034: foreach my $requrl (@{$addsref}) {
11035: if (&is_portfolio_url($requrl)) {
11036: unless (exists($urls{$requrl})) {
11037: $urls{$requrl} = 'add';
11038: }
11039: }
11040: }
11041: }
11042: if (ref($delsref) eq 'ARRAY') {
11043: foreach my $requrl (@{$delsref}) {
11044: if (&is_portfolio_url($requrl)) {
11045: unless (exists($urls{$requrl})) {
11046: $urls{$requrl} = 'delete';
11047: }
11048: }
11049: }
11050: }
11051: unless (keys(%urls)) {
11052: return 'invalid';
11053: }
11054: my $ip;
11055: if ($accesstype eq 'ip') {
11056: if (ref($info) eq 'HASH') {
11057: if ($info->{'ip'} ne '') {
11058: $ip = $info->{'ip'};
11059: }
11060: }
11061: if ($ip eq '') {
11062: return 'invalid';
11063: }
11064: }
11065: my $errors;
1.827 raeburn 11066: my $now = time;
1.1271 raeburn 11067: my %current_perms;
11068: foreach my $requrl (sort(keys(%urls))) {
11069: my $action;
11070: if ($urls{$requrl} eq 'add') {
11071: $action = 'activate';
11072: } else {
11073: $action = 'none';
11074: }
11075: my $aclnum = 0;
1.827 raeburn 11076: my (undef,$udom,$unum,$file_name,$group) =
11077: &parse_portfolio_url($requrl);
1.1271 raeburn 11078: unless (exists($current_perms{$unum.':'.$udom})) {
11079: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11080: }
11081: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 11082: $group,$file_name);
11083: foreach my $key (keys(%{$access_controls{$file_name}})) {
11084: my ($num,$scope,$end,$start) =
11085: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 11086: if ($scope eq $accesstype) {
11087: if (($start <= $now) && ($end == 0)) {
11088: if ($accesstype eq 'ip') {
11089: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11090: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11091: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11092: if ($urls{$requrl} eq 'add') {
11093: $action = 'none';
11094: last;
11095: } else {
11096: $action = 'delete';
11097: $aclnum = $num;
11098: last;
11099: }
11100: }
11101: }
11102: }
11103: } elsif ($accesstype eq 'public') {
11104: if ($urls{$requrl} eq 'add') {
11105: $action = 'none';
11106: last;
11107: } else {
11108: $action = 'delete';
11109: $aclnum = $num;
11110: last;
11111: }
11112: }
11113: } elsif ($accesstype eq 'public') {
1.827 raeburn 11114: $action = 'update';
11115: $aclnum = $num;
1.1271 raeburn 11116: last;
1.827 raeburn 11117: }
11118: }
11119: }
11120: if ($action eq 'none') {
1.1271 raeburn 11121: next;
1.827 raeburn 11122: } else {
11123: my %changes;
11124: my $newend = 0;
11125: my $newstart = $now;
1.1271 raeburn 11126: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 11127: $changes{$action}{$newkey} = {
1.1271 raeburn 11128: type => $accesstype,
1.827 raeburn 11129: time => {
11130: start => $newstart,
11131: end => $newend,
11132: },
11133: };
1.1271 raeburn 11134: if ($accesstype eq 'ip') {
11135: $changes{$action}{$newkey}{'ip'} = [$ip];
11136: }
1.827 raeburn 11137: my ($outcome,$deloutcome,$new_values,$translation) =
11138: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 11139: unless ($outcome eq 'ok') {
11140: $errors .= $outcome.' ';
11141: }
1.827 raeburn 11142: }
1.1271 raeburn 11143: }
11144: if ($errors) {
11145: $errors =~ s/\s$//;
11146: return $errors;
1.827 raeburn 11147: } else {
1.1271 raeburn 11148: return 'ok';
1.827 raeburn 11149: }
11150: }
11151:
1.745 raeburn 11152: #------------------------------------------------------Get Marked as Read Only
11153:
11154: sub get_marked_as_readonly {
11155: my ($domain,$user,$what,$group) = @_;
11156: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11157: my @readonly_files;
1.629 banghart 11158: my $cmp1=$what;
11159: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11160: while (my ($file_name,$value) = each(%{$current_permissions})) {
11161: if (defined($group)) {
11162: if ($file_name !~ m-^\Q$group\E/-) {
11163: next;
11164: }
11165: }
1.561 banghart 11166: if (ref($value) eq "ARRAY"){
11167: foreach my $stored_what (@{$value}) {
1.629 banghart 11168: my $cmp2=$stored_what;
1.759 albertel 11169: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11170: $cmp2=join('',@{$stored_what});
1.745 raeburn 11171: }
1.629 banghart 11172: if ($cmp1 eq $cmp2) {
1.561 banghart 11173: push(@readonly_files, $file_name);
1.745 raeburn 11174: last;
1.563 banghart 11175: } elsif (!defined($what)) {
11176: push(@readonly_files, $file_name);
1.745 raeburn 11177: last;
1.561 banghart 11178: }
11179: }
1.745 raeburn 11180: }
1.561 banghart 11181: }
11182: return @readonly_files;
11183: }
1.577 banghart 11184: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11185:
1.577 banghart 11186: sub get_marked_as_readonly_hash {
1.745 raeburn 11187: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11188: my %readonly_files;
1.745 raeburn 11189: while (my ($file_name,$value) = each(%{$current_permissions})) {
11190: if (defined($group)) {
11191: if ($file_name !~ m-^\Q$group\E/-) {
11192: next;
11193: }
11194: }
1.577 banghart 11195: if (ref($value) eq "ARRAY"){
11196: foreach my $stored_what (@{$value}) {
1.745 raeburn 11197: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11198: foreach my $lock_descriptor(@{$stored_what}) {
11199: if ($lock_descriptor eq 'graded') {
11200: $readonly_files{$file_name} = 'graded';
11201: } elsif ($lock_descriptor eq 'handback') {
11202: $readonly_files{$file_name} = 'handback';
11203: } else {
11204: if (!exists($readonly_files{$file_name})) {
11205: $readonly_files{$file_name} = 'locked';
11206: }
11207: }
1.745 raeburn 11208: }
1.750 banghart 11209: }
1.577 banghart 11210: }
11211: }
11212: }
11213: return %readonly_files;
11214: }
1.559 banghart 11215: # ------------------------------------------------------------ Unmark as Read Only
11216:
11217: sub unmark_as_readonly {
1.629 banghart 11218: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11219: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11220: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11221: $file_name = &declutter_portfile($file_name);
1.634 albertel 11222: my $symb_crs = $what;
11223: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11224: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11225: my ($tmp)=keys(%current_permissions);
11226: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11227: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11228: foreach my $file (@readonly_files) {
1.759 albertel 11229: my $clean_file = &declutter_portfile($file);
11230: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11231: my $current_locks = $current_permissions{$file};
1.563 banghart 11232: my @new_locks;
11233: my @del_keys;
11234: if (ref($current_locks) eq "ARRAY"){
11235: foreach my $locker (@{$current_locks}) {
1.632 albertel 11236: my $compare=$locker;
1.749 raeburn 11237: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11238: $compare=join('',@{$locker});
1.746 raeburn 11239: if ($compare ne $symb_crs) {
11240: push(@new_locks, $locker);
11241: }
1.563 banghart 11242: }
11243: }
1.650 albertel 11244: if (scalar(@new_locks) > 0) {
1.563 banghart 11245: $current_permissions{$file} = \@new_locks;
11246: } else {
11247: push(@del_keys, $file);
1.613 albertel 11248: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11249: delete($current_permissions{$file});
1.563 banghart 11250: }
11251: }
1.561 banghart 11252: }
1.613 albertel 11253: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11254: return;
11255: }
1.512 banghart 11256:
1.17 www 11257: # ------------------------------------------------------------ Directory lister
11258:
11259: sub dirlist {
1.955 raeburn 11260: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11261: $uri=~s/^\///;
11262: $uri=~s/\/$//;
1.253 stredwic 11263: my ($udom, $uname);
1.955 raeburn 11264: if ($getuserdir) {
1.253 stredwic 11265: $udom = $userdomain;
11266: $uname = $username;
1.955 raeburn 11267: } else {
11268: (undef,$udom,$uname)=split(/\//,$uri);
11269: if(defined($userdomain)) {
11270: $udom = $userdomain;
11271: }
11272: if(defined($username)) {
11273: $uname = $username;
11274: }
1.253 stredwic 11275: }
1.955 raeburn 11276: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11277:
1.955 raeburn 11278: $dirRoot = $perlvar{'lonDocRoot'};
11279: if (defined($getpropath)) {
11280: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11281: $dirRoot =~ s/\/$//;
1.955 raeburn 11282: } elsif (defined($getuserdir)) {
11283: my $subdir=$uname.'__';
11284: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11285: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11286: ."/$udom/$subdir/$uname";
11287: } elsif (defined($alternateRoot)) {
11288: $dirRoot = $alternateRoot;
1.751 banghart 11289: }
1.253 stredwic 11290:
11291: if($udom) {
11292: if($uname) {
1.1135 raeburn 11293: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11294: if ($uhome eq 'no_host') {
11295: return ([],'no_host');
11296: }
1.955 raeburn 11297: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11298: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11299: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11300: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11301: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11302: } else {
11303: @listing_results = map { &unescape($_); } split(/:/,$listing);
11304: }
1.605 matthew 11305: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11306: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11307: @listing_results = split(/:/,$listing);
11308: } else {
11309: @listing_results = map { &unescape($_); } split(/:/,$listing);
11310: }
1.1135 raeburn 11311: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11312: ($listing eq 'rejected') || ($listing eq 'refused') ||
11313: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11314: return ([],$listing);
11315: } else {
11316: return (\@listing_results);
1.1135 raeburn 11317: }
1.955 raeburn 11318: } elsif(!$alternateRoot) {
1.1136 raeburn 11319: my (%allusers,%listerror);
1.841 albertel 11320: my %servers = &get_servers($udom,'library');
1.955 raeburn 11321: foreach my $tryserver (keys(%servers)) {
11322: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11323: &escape($udom),$tryserver);
11324: if ($listing eq 'unknown_cmd') {
11325: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11326: $udom, $tryserver);
11327: } else {
11328: @listing_results = map { &unescape($_); } split(/:/,$listing);
11329: }
1.841 albertel 11330: if ($listing eq 'unknown_cmd') {
11331: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11332: $udom, $tryserver);
11333: @listing_results = split(/:/,$listing);
11334: } else {
11335: @listing_results =
11336: map { &unescape($_); } split(/:/,$listing);
11337: }
1.1136 raeburn 11338: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11339: ($listing eq 'rejected') || ($listing eq 'refused') ||
11340: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11341: $listerror{$tryserver} = $listing;
11342: } else {
1.841 albertel 11343: foreach my $line (@listing_results) {
11344: my ($entry) = split(/&/,$line,2);
11345: $allusers{$entry} = 1;
11346: }
11347: }
1.253 stredwic 11348: }
1.1136 raeburn 11349: my @alluserslist=();
1.800 albertel 11350: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11351: push(@alluserslist,$user.'&user');
1.253 stredwic 11352: }
1.1318 droeschl 11353:
11354: if (!%listerror) {
11355: # no errors
11356: return (\@alluserslist);
11357: } elsif (scalar(keys(%servers)) == 1) {
11358: # one library server, one error
11359: my ($key) = keys(%listerror);
11360: return (\@alluserslist, $listerror{$key});
11361: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11362: # con_lost indicates that we might miss data from at least one
11363: # library server
11364: return (\@alluserslist, 'con_lost');
11365: } else {
11366: # multiple library servers and no con_lost -> data should be
11367: # complete.
11368: return (\@alluserslist);
11369: }
11370:
1.253 stredwic 11371: } else {
1.1136 raeburn 11372: return ([],'missing username');
1.253 stredwic 11373: }
1.955 raeburn 11374: } elsif(!defined($getpropath)) {
1.1136 raeburn 11375: my $path = $perlvar{'lonDocRoot'}.'/res/';
11376: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11377: return (\@all_domains);
1.955 raeburn 11378: } else {
1.1136 raeburn 11379: return ([],'missing domain');
1.275 stredwic 11380: }
11381: }
11382:
11383: # --------------------------------------------- GetFileTimestamp
11384: # This function utilizes dirlist and returns the date stamp for
11385: # when it was last modified. It will also return an error of -1
11386: # if an error occurs
11387:
11388: sub GetFileTimestamp {
1.955 raeburn 11389: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11390: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11391: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11392: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11393: undef,$getuserdir);
11394: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11395: return -1;
11396: }
11397: if (ref($fileref) eq 'ARRAY') {
11398: my @stats = split('&',$fileref->[0]);
1.375 matthew 11399: # @stats contains first the filename, then the stat output
11400: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11401: } else {
11402: return -1;
1.253 stredwic 11403: }
1.26 www 11404: }
11405:
1.712 albertel 11406: sub stat_file {
11407: my ($uri) = @_;
1.787 albertel 11408: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11409:
1.955 raeburn 11410: my ($udom,$uname,$file);
1.712 albertel 11411: if ($uri =~ m-^/(uploaded|editupload)/-) {
11412: ($udom,$uname,$file) =
1.811 albertel 11413: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11414: $file = 'userfiles/'.$file;
11415: }
11416: if ($uri =~ m-^/res/-) {
11417: ($udom,$uname) =
1.807 albertel 11418: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11419: $file = $uri;
11420: }
11421:
11422: if (!$udom || !$uname || !$file) {
11423: # unable to handle the uri
11424: return ();
11425: }
1.956 raeburn 11426: my $getpropath;
11427: if ($file =~ /^userfiles\//) {
11428: $getpropath = 1;
11429: }
1.1136 raeburn 11430: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11431: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11432: return ();
11433: } else {
11434: if (ref($listref) eq 'ARRAY') {
11435: my @stats = split('&',$listref->[0]);
11436: shift(@stats); #filename is first
11437: return @stats;
11438: }
1.712 albertel 11439: }
11440: return ();
11441: }
11442:
1.1313 raeburn 11443: # --------------------------------------------------------- recursedirs
11444: # Recursive function to traverse either a specific user's Authoring Space
11445: # or corresponding Published Resource Space, and populate the hash ref:
11446: # $dirhashref with URLs of all directories, and if $filehashref hash
11447: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11448: # or .rights files in resource space, and .meta, .save, .log, and .bak
11449: # files in Authoring Space.
11450: #
11451: # Inputs:
11452: #
11453: # $is_home - true if current server is home server for user's space
11454: # $context - either: priv, or res respectively for Authoring or Resource Space.
11455: # $docroot - Document root (i.e., /home/httpd/html
11456: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11457: # $relpath - Current path (relative to top level).
11458: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11459: # $filehashref - reference to hash to populate with URLs of files (Optional)
11460: #
11461: # Returns: nothing
11462: #
11463: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11464: #
11465: # Currently used by interface/londocs.pm to create linked select boxes for
11466: # directory and filename to import a Course "Author" resource into a course, and
11467: # also to create linked select boxes for Authoring Space and Directory to choose
11468: # save location for creation of a new "standard" problem from the Course Editor.
11469: #
11470:
11471: sub recursedirs {
11472: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11473: return unless (ref($dirhashref) eq 'HASH');
11474: my $currpath = $docroot.$toppath;
11475: if ($relpath) {
11476: $currpath .= "/$relpath";
11477: }
11478: my $savefile;
11479: if (ref($filehashref)) {
11480: $savefile = 1;
11481: }
11482: if ($is_home) {
11483: if (opendir(my $dirh,$currpath)) {
11484: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11485: next if ($item eq '');
11486: if (-d "$currpath/$item") {
11487: my $newpath;
11488: if ($relpath) {
11489: $newpath = "$relpath/$item";
11490: } else {
11491: $newpath = $item;
11492: }
11493: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11494: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11495: } elsif ($savefile) {
11496: if ($context eq 'priv') {
11497: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11498: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11499: }
11500: } else {
11501: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11502: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11503: }
11504: }
11505: }
11506: }
11507: closedir($dirh);
11508: }
11509: } else {
11510: my ($dirlistref,$listerror) =
11511: &dirlist($toppath.$relpath);
11512: my @dir_lines;
11513: my $dirptr=16384;
11514: if (ref($dirlistref) eq 'ARRAY') {
11515: foreach my $dir_line (sort
11516: {
11517: my ($afile)=split('&',$a,2);
11518: my ($bfile)=split('&',$b,2);
11519: return (lc($afile) cmp lc($bfile));
11520: } (@{$dirlistref})) {
11521: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11522: split(/\&/,$dir_line,16);
11523: $item =~ s/\s+$//;
11524: next if (($item =~ /^\.\.?$/) || ($obs));
11525: if ($dirptr&$testdir) {
11526: my $newpath;
11527: if ($relpath) {
11528: $newpath = "$relpath/$item";
11529: } else {
11530: $relpath = '/';
11531: $newpath = $item;
11532: }
11533: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11534: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11535: } elsif ($savefile) {
11536: if ($context eq 'priv') {
11537: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11538: $filehashref->{$relpath}{$item} = 1;
11539: }
11540: } else {
11541: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11542: $filehashref->{$relpath}{$item} = 1;
11543: }
11544: }
11545: }
11546: }
11547: }
11548: }
11549: return;
11550: }
11551:
1.26 www 11552: # -------------------------------------------------------- Value of a Condition
11553:
1.713 albertel 11554: # gets the value of a specific preevaluated condition
11555: # stored in the string $env{user.state.<cid>}
11556: # or looks up a condition reference in the bighash and if if hasn't
11557: # already been evaluated recurses into docondval to get the value of
11558: # the condition, then memoizing it to
11559: # $env{user.state.<cid>.<condition>}
1.40 www 11560: sub directcondval {
11561: my $number=shift;
1.620 albertel 11562: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11563: &Apache::lonuserstate::evalstate();
11564: }
1.713 albertel 11565: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11566: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11567: } elsif ($number =~ /^_/) {
11568: my $sub_condition;
11569: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11570: &GDBM_READER(),0640)) {
11571: $sub_condition=$bighash{'conditions'.$number};
11572: untie(%bighash);
11573: }
11574: my $value = &docondval($sub_condition);
1.949 raeburn 11575: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11576: return $value;
11577: }
1.620 albertel 11578: if ($env{'user.state.'.$env{'request.course.id'}}) {
11579: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11580: } else {
11581: return 2;
11582: }
11583: }
11584:
1.713 albertel 11585: # get the collection of conditions for this resource
1.26 www 11586: sub condval {
11587: my $condidx=shift;
1.54 www 11588: my $allpathcond='';
1.713 albertel 11589: foreach my $cond (split(/\|/,$condidx)) {
11590: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11591: $allpathcond.=
11592: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11593: }
1.191 harris41 11594: }
1.54 www 11595: $allpathcond=~s/\|$//;
1.713 albertel 11596: return &docondval($allpathcond);
11597: }
11598:
11599: #evaluates an expression of conditions
11600: sub docondval {
11601: my ($allpathcond) = @_;
11602: my $result=0;
11603: if ($env{'request.course.id'}
11604: && defined($allpathcond)) {
11605: my $operand='|';
11606: my @stack;
11607: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11608: if ($chunk eq '(') {
11609: push @stack,($operand,$result);
11610: } elsif ($chunk eq ')') {
11611: my $before=pop @stack;
11612: if (pop @stack eq '&') {
11613: $result=$result>$before?$before:$result;
11614: } else {
11615: $result=$result>$before?$result:$before;
11616: }
11617: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11618: $operand=$chunk;
11619: } else {
11620: my $new=directcondval($chunk);
11621: if ($operand eq '&') {
11622: $result=$result>$new?$new:$result;
11623: } else {
11624: $result=$result>$new?$result:$new;
11625: }
11626: }
11627: }
1.26 www 11628: }
11629: return $result;
1.421 albertel 11630: }
11631:
11632: # ---------------------------------------------------- Devalidate courseresdata
11633:
11634: sub devalidatecourseresdata {
11635: my ($coursenum,$coursedomain)=@_;
11636: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11637: &devalidate_cache_new('courseres',$hashid);
1.28 www 11638: }
11639:
1.763 www 11640:
1.200 www 11641: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11642: #
11643: # Parameters:
11644: # $coursenum - Number of the course.
11645: # $coursedomain - Domain at which the course was created.
11646: # Returns:
11647: # A hash of the course parameters along (I think) with timestamps
11648: # and version info.
1.877 foxr 11649:
1.624 albertel 11650: sub get_courseresdata {
11651: my ($coursenum,$coursedomain)=@_;
1.200 www 11652: my $coursehom=&homeserver($coursenum,$coursedomain);
11653: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11654: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11655: my %dumpreply;
1.417 albertel 11656: unless (defined($cached)) {
1.624 albertel 11657: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11658: $result=\%dumpreply;
1.251 albertel 11659: my ($tmp) = keys(%dumpreply);
11660: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11661: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11662: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11663: return $tmp;
1.416 albertel 11664: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11665: $result=undef;
1.599 albertel 11666: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11667: }
11668: }
1.624 albertel 11669: return $result;
11670: }
11671:
1.633 albertel 11672: sub devalidateuserresdata {
11673: my ($uname,$udom)=@_;
11674: my $hashid="$udom:$uname";
11675: &devalidate_cache_new('userres',$hashid);
11676: }
11677:
1.624 albertel 11678: sub get_userresdata {
11679: my ($uname,$udom)=@_;
11680: #most student don\'t have any data set, check if there is some data
11681: if (&EXT_cache_status($udom,$uname)) { return undef; }
11682:
11683: my $hashid="$udom:$uname";
11684: my ($result,$cached)=&is_cached_new('userres',$hashid);
11685: if (!defined($cached)) {
11686: my %resourcedata=&dump('resourcedata',$udom,$uname);
11687: $result=\%resourcedata;
11688: &do_cache_new('userres',$hashid,$result,600);
11689: }
11690: my ($tmp)=keys(%$result);
11691: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11692: return $result;
11693: }
11694: #error 2 occurs when the .db doesn't exist
11695: if ($tmp!~/error: 2 /) {
1.1294 raeburn 11696: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11697: &logthis("<font color=\"blue\">WARNING:".
11698: " Trying to get resource data for ".
11699: $uname." at ".$udom.": ".
11700: $tmp."</font>");
11701: }
1.624 albertel 11702: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11703: #&EXT_cache_set($udom,$uname);
11704: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11705: undef($tmp); # not really an error so don't send it back
1.624 albertel 11706: }
11707: return $tmp;
11708: }
1.879 foxr 11709: #----------------------------------------------- resdata - return resource data
11710: # Purpose:
11711: # Return resource data for either users or for a course.
11712: # Parameters:
11713: # $name - Course/user name.
11714: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 11715: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 11716: # $mapp - decluttered URL of enclosing map
11717: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
11718: # $recurseup - Ref to array of map URLs, starting with map containing
11719: # $mapp up through hierarchy of nested maps to top level map.
11720: # $courseid - CourseID (first part of param identifier).
11721: # $modifier - Middle part of param identifier.
11722: # $what - Last part of param identifier.
1.879 foxr 11723: # @which - Array of names of resources desired.
11724: # Returns:
11725: # The value of the first reasource in @which that is found in the
11726: # resource hash.
11727: # Exceptional Conditions:
11728: # If the $type passed in is not valid (not the string 'course' or
11729: # 'user', an undefined reference is returned.
11730: # If none of the resources are found, an undef is returned
1.624 albertel 11731: sub resdata {
1.1301 raeburn 11732: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11733: $modifier,$what,@which)=@_;
1.624 albertel 11734: my $result;
11735: if ($type eq 'course') {
11736: $result=&get_courseresdata($name,$domain);
11737: } elsif ($type eq 'user') {
11738: $result=&get_userresdata($name,$domain);
11739: }
11740: if (!ref($result)) { return $result; }
1.251 albertel 11741: foreach my $item (@which) {
1.1301 raeburn 11742: if ($item->[1] eq 'course') {
11743: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11744: unless ($$recursed) {
1.1302 raeburn 11745: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 11746: $$recursed = 1;
11747: }
11748: foreach my $item (@${recurseup}) {
11749: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11750: last if (defined($result->{$norecursechk}));
11751: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11752: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11753: }
11754: }
11755: }
11756: if (defined($result->{$item->[0]})) {
1.927 albertel 11757: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11758: }
1.250 albertel 11759: }
1.291 albertel 11760: return undef;
1.200 www 11761: }
11762:
1.1360 raeburn 11763: sub get_domain_lti {
11764: my ($cdom,$context) = @_;
11765: my ($name,%lti);
11766: if ($context eq 'consumer') {
11767: $name = 'ltitools';
11768: } elsif ($context eq 'provider') {
11769: $name = 'lti';
11770: } else {
11771: return %lti;
11772: }
11773: my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298 raeburn 11774: if (defined($cached)) {
11775: if (ref($result) eq 'HASH') {
1.1360 raeburn 11776: %lti = %{$result};
1.1298 raeburn 11777: }
11778: } else {
1.1360 raeburn 11779: my %domconfig = &get_dom('configuration',[$name],$cdom);
11780: if (ref($domconfig{$name}) eq 'HASH') {
11781: %lti = %{$domconfig{$name}};
11782: my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11783: if (ref($encdomconfig{$name}) eq 'HASH') {
11784: foreach my $id (keys(%lti)) {
11785: if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344 raeburn 11786: foreach my $item ('key','secret') {
1.1360 raeburn 11787: $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344 raeburn 11788: }
11789: }
11790: }
11791: }
1.1298 raeburn 11792: }
11793: my $cachetime = 24*60*60;
1.1360 raeburn 11794: &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298 raeburn 11795: }
1.1360 raeburn 11796: return %lti;
1.1298 raeburn 11797: }
11798:
1.1236 raeburn 11799: sub get_numsuppfiles {
11800: my ($cnum,$cdom,$ignorecache)=@_;
11801: my $hashid=$cnum.':'.$cdom;
11802: my ($suppcount,$cached);
11803: unless ($ignorecache) {
11804: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11805: }
11806: unless (defined($cached)) {
11807: my $chome=&homeserver($cnum,$cdom);
11808: unless ($chome eq 'no_host') {
1.1366 raeburn 11809: ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236 raeburn 11810: my $suppmap = 'supplemental.sequence';
1.1366 raeburn 11811: ($suppcount,$supptools,$errors) =
11812: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11813: $supptools,$errors);
1.1236 raeburn 11814: }
11815: &do_cache_new('suppcount',$hashid,$suppcount,600);
11816: }
11817: return $suppcount;
11818: }
11819:
1.379 matthew 11820: #
11821: # EXT resource caching routines
11822: #
11823:
1.1302 raeburn 11824: {
11825: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11826: #
11827: # The course for which we cache
11828: my $cachedmapkey='';
11829: # The cached recursive maps for this course
11830: my %cachedmaps=();
11831: # When this was last done
11832: my $cachedmaptime='';
11833:
1.379 matthew 11834: sub clear_EXT_cache_status {
1.383 albertel 11835: &delenv('cache.EXT.');
1.379 matthew 11836: }
11837:
11838: sub EXT_cache_status {
11839: my ($target_domain,$target_user) = @_;
1.383 albertel 11840: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11841: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11842: # We know already the user has no data
11843: return 1;
11844: } else {
11845: return 0;
11846: }
11847: }
11848:
11849: sub EXT_cache_set {
11850: my ($target_domain,$target_user) = @_;
1.383 albertel 11851: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11852: #&appenv({$cachename => time});
1.379 matthew 11853: }
11854:
1.28 www 11855: # --------------------------------------------------------- Value of a Variable
1.58 www 11856: sub EXT {
1.715 albertel 11857:
1.1228 raeburn 11858: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11859: unless ($varname) { return ''; }
1.218 albertel 11860: #get real user name/domain, courseid and symb
11861: my $courseid;
1.359 albertel 11862: my $publicuser;
1.427 www 11863: if ($symbparm) {
11864: $symbparm=&get_symb_from_alias($symbparm);
11865: }
1.218 albertel 11866: if (!($uname && $udom)) {
1.790 albertel 11867: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11868: if (!$symbparm) { $symbparm=$cursymb; }
11869: } else {
1.620 albertel 11870: $courseid=$env{'request.course.id'};
1.218 albertel 11871: }
1.48 www 11872: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11873: my $rest;
1.320 albertel 11874: if (defined($therest[0])) {
1.48 www 11875: $rest=join('.',@therest);
11876: } else {
11877: $rest='';
11878: }
1.320 albertel 11879:
1.57 www 11880: my $qualifierrest=$qualifier;
11881: if ($rest) { $qualifierrest.='.'.$rest; }
11882: my $spacequalifierrest=$space;
11883: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11884: if ($realm eq 'user') {
1.48 www 11885: # --------------------------------------------------------------- user.resource
11886: if ($space eq 'resource') {
1.651 albertel 11887: if ( (defined($Apache::lonhomework::parsing_a_problem)
11888: || defined($Apache::lonhomework::parsing_a_task))
11889: &&
1.744 albertel 11890: ($symbparm eq &symbread()) ) {
11891: # if we are in the middle of processing the resource the
11892: # get the value we are planning on committing
11893: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11894: return $Apache::lonhomework::results{$qualifierrest};
11895: } else {
11896: return $Apache::lonhomework::history{$qualifierrest};
11897: }
1.335 albertel 11898: } else {
1.359 albertel 11899: my %restored;
1.620 albertel 11900: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11901: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11902: } else {
11903: %restored=&restore($symbparm,$courseid,$udom,$uname);
11904: }
1.335 albertel 11905: return $restored{$qualifierrest};
11906: }
1.48 www 11907: # ----------------------------------------------------------------- user.access
11908: } elsif ($space eq 'access') {
1.218 albertel 11909: # FIXME - not supporting calls for a specific user
1.48 www 11910: return &allowed($qualifier,$rest);
11911: # ------------------------------------------ user.preferences, user.environment
11912: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11913: if (($uname eq $env{'user.name'}) &&
11914: ($udom eq $env{'user.domain'})) {
11915: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11916: } else {
1.359 albertel 11917: my %returnhash;
11918: if (!$publicuser) {
11919: %returnhash=&userenvironment($udom,$uname,
11920: $qualifierrest);
11921: }
1.218 albertel 11922: return $returnhash{$qualifierrest};
11923: }
1.48 www 11924: # ----------------------------------------------------------------- user.course
11925: } elsif ($space eq 'course') {
1.218 albertel 11926: # FIXME - not supporting calls for a specific user
1.620 albertel 11927: return $env{join('.',('request.course',$qualifier))};
1.48 www 11928: # ------------------------------------------------------------------- user.role
11929: } elsif ($space eq 'role') {
1.218 albertel 11930: # FIXME - not supporting calls for a specific user
1.620 albertel 11931: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11932: if ($qualifier eq 'value') {
11933: return $role;
11934: } elsif ($qualifier eq 'extent') {
11935: return $where;
11936: }
11937: # ----------------------------------------------------------------- user.domain
11938: } elsif ($space eq 'domain') {
1.218 albertel 11939: return $udom;
1.48 www 11940: # ------------------------------------------------------------------- user.name
11941: } elsif ($space eq 'name') {
1.218 albertel 11942: return $uname;
1.48 www 11943: # ---------------------------------------------------- Any other user namespace
1.29 www 11944: } else {
1.359 albertel 11945: my %reply;
11946: if (!$publicuser) {
11947: %reply=&get($space,[$qualifierrest],$udom,$uname);
11948: }
11949: return $reply{$qualifierrest};
1.48 www 11950: }
1.236 www 11951: } elsif ($realm eq 'query') {
11952: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11953: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11954: [$spacequalifierrest]);
1.620 albertel 11955: return $env{'form.'.$spacequalifierrest};
1.236 www 11956: } elsif ($realm eq 'request') {
1.48 www 11957: # ------------------------------------------------------------- request.browser
11958: if ($space eq 'browser') {
1.1145 bisitz 11959: return $env{'browser.'.$qualifier};
1.57 www 11960: # ------------------------------------------------------------ request.filename
11961: } else {
1.620 albertel 11962: return $env{'request.'.$spacequalifierrest};
1.29 www 11963: }
1.28 www 11964: } elsif ($realm eq 'course') {
1.48 www 11965: # ---------------------------------------------------------- course.description
1.620 albertel 11966: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11967: } elsif ($realm eq 'resource') {
1.165 www 11968:
1.620 albertel 11969: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11970: if (!$symbparm) { $symbparm=&symbread(); }
11971: }
1.693 albertel 11972:
1.1232 raeburn 11973: if ($qualifier eq '') {
11974: if ($space eq 'title') {
11975: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11976: return &gettitle($symbparm);
11977: }
1.693 albertel 11978:
1.1232 raeburn 11979: if ($space eq 'map') {
11980: my ($map) = &decode_symb($symbparm);
11981: return &symbread($map);
11982: }
11983: if ($space eq 'maptitle') {
11984: my ($map) = &decode_symb($symbparm);
11985: return &gettitle($map);
11986: }
11987: if ($space eq 'filename') {
11988: if ($symbparm) {
11989: return &clutter((&decode_symb($symbparm))[2]);
11990: }
11991: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11992: }
1.1232 raeburn 11993:
1.1233 raeburn 11994: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11995: if ($space eq 'visibleparts') {
11996: my $navmap = Apache::lonnavmaps::navmap->new();
11997: my $item;
11998: if (ref($navmap)) {
11999: my $res = $navmap->getBySymb($symbparm);
12000: my $parts = $res->parts();
12001: if (ref($parts) eq 'ARRAY') {
12002: $item = join(',',@{$parts});
12003: }
12004: undef($navmap);
1.1232 raeburn 12005: }
1.1233 raeburn 12006: return $item;
1.1232 raeburn 12007: }
12008: }
12009: }
1.693 albertel 12010:
1.1301 raeburn 12011: my ($section, $group, @groups, @recurseup, $recursed);
12012: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 12013: if (($courseid eq '') && ($cid)) {
12014: $courseid = $cid;
12015: }
12016: if (($symbparm && $courseid) &&
12017: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 12018:
1.218 albertel 12019: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 12020:
1.60 www 12021: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 12022: my $symbp=$symbparm;
1.1301 raeburn 12023: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 12024: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 12025: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 12026: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 12027: if (($env{'user.name'} eq $uname) &&
12028: ($env{'user.domain'} eq $udom)) {
12029: $section=$env{'request.course.sec'};
1.733 raeburn 12030: @groups = split(/:/,$env{'request.course.groups'});
12031: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 12032: } else {
1.539 albertel 12033: if (! defined($usection)) {
1.551 albertel 12034: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 12035: } else {
12036: $section = $usection;
12037: }
1.733 raeburn 12038: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 12039: }
12040:
12041: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12042: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 12043: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 12044: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12045:
1.593 albertel 12046: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 12047: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 12048: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 12049: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 12050:
1.60 www 12051: # ----------------------------------------------------------- first, check user
1.624 albertel 12052:
1.1301 raeburn 12053: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12054: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 12055: ([$courselevelr,'resource'],
12056: [$courselevelm,'map' ],
1.1301 raeburn 12057: [$courseleveli,'map' ],
1.927 albertel 12058: [$courselevel, 'course' ]));
1.931 albertel 12059: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 12060:
1.594 albertel 12061: # ------------------------------------------------ second, check some of course
1.684 raeburn 12062: my $coursereply;
1.691 raeburn 12063: if (@groups > 0) {
12064: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 12065: $recurseparm,$mapparm,$spacequalifierrest,
12066: $mapp,\$recursed,\@recurseup);
12067: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 12068: }
1.96 www 12069:
1.684 raeburn 12070: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 12071: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12072: 'course',$mapp,\$recursed,\@recurseup,
12073: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 12074: ([$seclevelr, 'resource'],
12075: [$seclevelm, 'map' ],
1.1301 raeburn 12076: [$secleveli, 'map' ],
1.927 albertel 12077: [$seclevel, 'course' ],
12078: [$courselevelr,'resource']));
12079: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 12080:
1.60 www 12081: # ------------------------------------------------------ third, check map parms
1.218 albertel 12082: my %parmhash=();
12083: my $thisparm='';
12084: if (tie(%parmhash,'GDBM_File',
1.620 albertel 12085: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 12086: &GDBM_READER(),0640)) {
1.218 albertel 12087: $thisparm=$parmhash{$symbparm};
12088: untie(%parmhash);
12089: }
1.927 albertel 12090: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 12091: }
1.594 albertel 12092: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 12093:
12094: my $what = $spacequalifierrest;
12095: $what=~s/\./\_/;
1.282 albertel 12096: my $filename;
12097: if (!$symbparm) { $symbparm=&symbread(); }
12098: if ($symbparm) {
1.409 www 12099: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 12100: } else {
1.620 albertel 12101: $filename=$env{'request.filename'};
1.282 albertel 12102: }
1.1362 raeburn 12103: my $toolsymb;
12104: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12105: $toolsymb = $symbparm;
12106: }
12107: my $metadata=&metadata($filename,$what,$toolsymb);
1.927 albertel 12108: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362 raeburn 12109: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927 albertel 12110: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 12111:
1.1301 raeburn 12112: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 12113: if ($symbparm && defined($courseid) &&
1.620 albertel 12114: $courseid eq $env{'request.course.id'}) {
1.624 albertel 12115: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12116: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12117: 'course',$mapp,\$recursed,\@recurseup,
12118: $courseid,'.',$spacequalifierrest,
1.927 albertel 12119: ([$courselevelm,'map' ],
1.1301 raeburn 12120: [$courseleveli,'map' ],
1.927 albertel 12121: [$courselevel, 'course']));
12122: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 12123: }
1.145 www 12124: # ------------------------------------------------------------------ Cascade up
1.218 albertel 12125: unless ($space eq '0') {
1.336 albertel 12126: my @parts=split(/_/,$space);
12127: my $id=pop(@parts);
12128: my $part=join('_',@parts);
12129: if ($part eq '') { $part='0'; }
1.927 albertel 12130: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 12131: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 12132: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 12133: }
1.395 albertel 12134: if ($recurse) { return undef; }
1.1362 raeburn 12135: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927 albertel 12136: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 12137: # ---------------------------------------------------- Any other user namespace
12138: } elsif ($realm eq 'environment') {
12139: # ----------------------------------------------------------------- environment
1.620 albertel 12140: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12141: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 12142: } else {
1.770 albertel 12143: if ($uname eq 'anonymous' && $udom eq '') {
12144: return '';
12145: }
1.219 albertel 12146: my %returnhash=&userenvironment($udom,$uname,
12147: $spacequalifierrest);
12148: return $returnhash{$spacequalifierrest};
12149: }
1.28 www 12150: } elsif ($realm eq 'system') {
1.48 www 12151: # ----------------------------------------------------------------- system.time
12152: if ($space eq 'time') {
12153: return time;
12154: }
1.696 albertel 12155: } elsif ($realm eq 'server') {
12156: # ----------------------------------------------------------------- system.time
12157: if ($space eq 'name') {
12158: return $ENV{'SERVER_NAME'};
12159: }
1.28 www 12160: }
1.48 www 12161: return '';
1.61 www 12162: }
12163:
1.927 albertel 12164: sub get_reply {
12165: my ($reply_value) = @_;
1.940 raeburn 12166: if (ref($reply_value) eq 'ARRAY') {
12167: if (wantarray) {
12168: return @$reply_value;
12169: }
12170: return $reply_value->[0];
12171: } else {
12172: return $reply_value;
1.927 albertel 12173: }
12174: }
12175:
1.691 raeburn 12176: sub check_group_parms {
1.1301 raeburn 12177: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12178: $recursed,$recurseupref) = @_;
12179: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12180: [$what,'course']);
12181: my $coursereply;
1.691 raeburn 12182: foreach my $group (@{$groups}) {
1.1301 raeburn 12183: my @groupitems = ();
1.691 raeburn 12184: foreach my $level (@levels) {
1.927 albertel 12185: my $item = $courseid.'.['.$group.'].'.$level->[0];
12186: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 12187: }
1.1301 raeburn 12188: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12189: $env{'course.'.$courseid.'.domain'},
12190: 'course',$mapp,$recursed,$recurseupref,
12191: $courseid,'.['.$group.'].',$what,
12192: @groupitems);
12193: last if (defined($coursereply));
1.691 raeburn 12194: }
12195: return $coursereply;
12196: }
12197:
1.1301 raeburn 12198: sub get_map_hierarchy {
1.1302 raeburn 12199: my ($mapname,$courseid) = @_;
12200: my @recurseup = ();
1.1301 raeburn 12201: if ($mapname) {
1.1302 raeburn 12202: if (($cachedmapkey eq $courseid) &&
12203: (abs($cachedmaptime-time)<5)) {
12204: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12205: return @{$cachedmaps{$mapname}};
12206: }
12207: }
1.1301 raeburn 12208: my $navmap = Apache::lonnavmaps::navmap->new();
12209: if (ref($navmap)) {
12210: @recurseup = $navmap->recurseup_maps($mapname);
12211: undef($navmap);
1.1302 raeburn 12212: $cachedmaps{$mapname} = \@recurseup;
12213: $cachedmaptime=time;
12214: $cachedmapkey=$courseid;
1.1301 raeburn 12215: }
12216: }
12217: return @recurseup;
12218: }
12219:
1.1302 raeburn 12220: }
12221:
1.691 raeburn 12222: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 12223: my ($courseid,@groups) = @_;
12224: @groups = sort(@groups);
1.691 raeburn 12225: return @groups;
12226: }
12227:
1.395 albertel 12228: sub packages_tab_default {
1.1362 raeburn 12229: my ($uri,$varname,$toolsymb)=@_;
1.395 albertel 12230: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 12231:
12232: my (@extension,@specifics,$do_default);
1.1362 raeburn 12233: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395 albertel 12234: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 12235: if ($pack_type eq 'default') {
12236: $do_default=1;
12237: } elsif ($pack_type eq 'extension') {
12238: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 12239: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 12240: # only look at packages defaults for packages that this id is
1.738 albertel 12241: push(@specifics,[$package,$pack_type,$pack_part]);
12242: }
12243: }
12244: # first look for a package that matches the requested part id
12245: foreach my $package (@specifics) {
12246: my (undef,$pack_type,$pack_part)=@{$package};
12247: next if ($pack_part ne $part);
12248: if (defined($packagetab{"$pack_type&$name&default"})) {
12249: return $packagetab{"$pack_type&$name&default"};
12250: }
12251: }
12252: # look for any possible matching non extension_ package
12253: foreach my $package (@specifics) {
12254: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 12255: if (defined($packagetab{"$pack_type&$name&default"})) {
12256: return $packagetab{"$pack_type&$name&default"};
12257: }
1.585 albertel 12258: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 12259: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12260: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 12261: }
12262: }
1.738 albertel 12263: # look for any posible extension_ match
12264: foreach my $package (@extension) {
12265: my ($package,$pack_type)=@{$package};
12266: if (defined($packagetab{"$pack_type&$name&default"})) {
12267: return $packagetab{"$pack_type&$name&default"};
12268: }
12269: if (defined($packagetab{$package."&$name&default"})) {
12270: return $packagetab{$package."&$name&default"};
12271: }
12272: }
12273: # look for a global default setting
12274: if ($do_default && defined($packagetab{"default&$name&default"})) {
12275: return $packagetab{"default&$name&default"};
12276: }
1.395 albertel 12277: return undef;
12278: }
12279:
1.334 albertel 12280: sub add_prefix_and_part {
12281: my ($prefix,$part)=@_;
12282: my $keyroot;
12283: if (defined($prefix) && $prefix !~ /^__/) {
12284: # prefix that has a part already
12285: $keyroot=$prefix;
12286: } elsif (defined($prefix)) {
12287: # prefix that is missing a part
12288: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12289: } else {
12290: # no prefix at all
12291: if (defined($part)) { $keyroot='_'.$part; }
12292: }
12293: return $keyroot;
12294: }
12295:
1.71 www 12296: # ---------------------------------------------------------------- Get metadata
12297:
1.599 albertel 12298: my %metaentry;
1.1070 www 12299: my %importedpartids;
1.1369 raeburn 12300: my %importedrespids;
1.71 www 12301: sub metadata {
1.1362 raeburn 12302: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71 www 12303: $uri=&declutter($uri);
1.288 albertel 12304: # if it is a non metadata possible uri return quickly
1.529 albertel 12305: if (($uri eq '') ||
12306: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 12307: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 12308: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 12309: return undef;
12310: }
1.1261 raeburn 12311: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 12312: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 12313: return undef;
1.288 albertel 12314: }
1.73 www 12315: my $filename=$uri;
12316: $uri=~s/\.meta$//;
1.172 www 12317: #
12318: # Is the metadata already cached?
1.177 www 12319: # Look at timestamp of caching
1.172 www 12320: # Everything is cached by the main uri, libraries are never directly cached
12321: #
1.428 albertel 12322: if (!defined($liburi)) {
1.599 albertel 12323: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 12324: if (defined($cached)) { return $result->{':'.$what}; }
12325: }
1.1362 raeburn 12326:
12327: #
12328: # If the uri is for an external tool the file from
12329: # which metadata should be retrieved depends on whether
12330: # the tool had been configured to be gradable (set in the Course
12331: # Editor or Resource Editor).
12332: #
12333: # If a valid symb has been included as the third arg in the call
12334: # to &metadata() that can be used to retrieve the value of
12335: # parameter_0_gradable set for the resource, and included in the
12336: # uploaded map containing the tool. The value is retrieved via
12337: # &EXT(), if a valid symb is available. Otherwise the value of
12338: # gradable in the exttool_$marker.db file for the tool instance
1.1364 raeburn 12339: # is retrieved via &get().
12340: #
12341: # When lonuserstate::traceroute() calls lonnet::EXT() for
12342: # hiddenresource and encrypturl (during course initialization)
12343: # the map-level parameter for resource.0.gradable included in the
12344: # uploaded map containing the tool will not yet have been stored
12345: # in the user_course_parms.db file for the user's session, so in
12346: # this case fall back to retrieving gradable status from the
12347: # exttool_$marker.db file.
1.1362 raeburn 12348: #
12349: # In order to avoid an infinite loop, &metadata() will return
12350: # before a call to &EXT(), if the uri is for an external tool
12351: # and the $what for which metadata is being requested is
12352: # parameter_0_gradable or 0_gradable.
12353: #
12354:
12355: if ($uri =~ /ext\.tool$/) {
12356: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12357: return;
12358: } else {
12359: my ($checked,$use_passback);
12360: if ($toolsymb ne '') {
12361: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364 raeburn 12362: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362 raeburn 12363: $checked = 1;
12364: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12365: $use_passback = 1;
12366: }
12367: }
12368: }
12369: unless ($checked) {
12370: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12371: $marker=~s/\D//g;
1.1363 raeburn 12372: if ($marker) {
1.1362 raeburn 12373: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12374: $use_passback = $toolsettings{'gradable'};
12375: }
12376: }
12377: if ($use_passback) {
12378: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12379: } else {
12380: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12381: }
12382: }
12383: }
12384:
1.428 albertel 12385: {
1.1069 www 12386: # Imported parts would go here
1.1369 raeburn 12387: my @origfiletagids=();
1.1069 www 12388: my $importedparts=0;
1.1369 raeburn 12389:
12390: # Imported responseids would go here
12391: my $importedresponses=0;
1.172 www 12392: #
12393: # Is this a recursive call for a library?
12394: #
1.599 albertel 12395: # if (! exists($metacache{$uri})) {
12396: # $metacache{$uri}={};
12397: # }
1.924 albertel 12398: my $cachetime = 60*60;
1.171 www 12399: if ($liburi) {
12400: $liburi=&declutter($liburi);
12401: $filename=$liburi;
1.401 bowersj2 12402: } else {
1.599 albertel 12403: &devalidate_cache_new('meta',$uri);
12404: undef(%metaentry);
1.401 bowersj2 12405: }
1.140 www 12406: my %metathesekeys=();
1.73 www 12407: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 12408: my $metastring;
1.1140 www 12409: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 12410: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 12411: $metastring =
1.929 albertel 12412: &Apache::lonnet::ssi_body($which,
1.924 albertel 12413: ('grade_target' => 'meta'));
12414: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 12415: } elsif (($uri !~ m -^(editupload)/-) &&
12416: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 12417: my $file=&filelocation('',&clutter($filename));
1.599 albertel 12418: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 12419: $metastring=&getfile($file);
1.489 albertel 12420: }
1.208 albertel 12421: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 12422: my $token;
1.140 www 12423: undef %metathesekeys;
1.71 www 12424: while ($token=$parser->get_token) {
1.339 albertel 12425: if ($token->[0] eq 'S') {
12426: if (defined($token->[2]->{'package'})) {
1.172 www 12427: #
12428: # This is a package - get package info
12429: #
1.339 albertel 12430: my $package=$token->[2]->{'package'};
12431: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12432: if (defined($token->[2]->{'id'})) {
12433: $keyroot.='_'.$token->[2]->{'id'};
12434: }
1.599 albertel 12435: if ($metaentry{':packages'}) {
12436: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 12437: } else {
1.599 albertel 12438: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 12439: }
1.736 albertel 12440: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 12441: my $part=$keyroot;
12442: $part=~s/^\_//;
1.736 albertel 12443: if ($pack_entry=~/^\Q$package\E\&/ ||
12444: $pack_entry=~/^\Q$package\E_0\&/) {
12445: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 12446: # ignore package.tab specified default values
12447: # here &package_tab_default() will fetch those
12448: if ($subp eq 'default') { next; }
1.736 albertel 12449: my $value=$packagetab{$pack_entry};
1.432 albertel 12450: my $unikey;
12451: if ($pack =~ /_0$/) {
12452: $unikey='parameter_0_'.$name;
12453: $part=0;
12454: } else {
12455: $unikey='parameter'.$keyroot.'_'.$name;
12456: }
1.339 albertel 12457: if ($subp eq 'display') {
12458: $value.=' [Part: '.$part.']';
12459: }
1.599 albertel 12460: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 12461: $metathesekeys{$unikey}=1;
1.599 albertel 12462: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12463: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 12464: }
1.599 albertel 12465: if (defined($metaentry{':'.$unikey.'.default'})) {
12466: $metaentry{':'.$unikey}=
12467: $metaentry{':'.$unikey.'.default'};
1.356 albertel 12468: }
1.339 albertel 12469: }
12470: }
12471: } else {
1.172 www 12472: #
12473: # This is not a package - some other kind of start tag
1.339 albertel 12474: #
12475: my $entry=$token->[1];
1.1068 www 12476: my $unikey='';
1.175 www 12477:
1.339 albertel 12478: if ($entry eq 'import') {
1.175 www 12479: #
12480: # Importing a library here
1.339 albertel 12481: #
1.1067 www 12482: my $location=$parser->get_text('/import');
12483: my $dir=$filename;
12484: $dir=~s|[^/]*$||;
12485: $location=&filelocation($dir,$location);
1.1369 raeburn 12486:
12487: my $importid=$token->[2]->{'id'};
1.1068 www 12488: my $importmode=$token->[2]->{'importmode'};
1.1369 raeburn 12489: #
12490: # Check metadata for imported file to
12491: # see if it contained response items
12492: #
1.1372 raeburn 12493: my ($origfile,@libfilekeys);
1.1370 raeburn 12494: my %currmetaentry = %metaentry;
1.1372 raeburn 12495: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12496: $depthcount+1));
12497: if (grep(/^responseorder$/,@libfilekeys)) {
12498: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12499: undef,$depthcount+1);
12500: if ($libresponseorder ne '') {
12501: if ($#origfiletagids<0) {
12502: undef(%importedrespids);
12503: undef(%importedpartids);
12504: }
1.1373 raeburn 12505: my @respids = split(/\s*,\s*/,$libresponseorder);
12506: if (@respids) {
12507: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12508: }
12509: if ($importedrespids{$importid} ne '') {
1.1372 raeburn 12510: $importedresponses = 1;
1.1369 raeburn 12511: # We need to get the original file and the imported file to get the response order correct
12512: # Load and inspect original file
1.1372 raeburn 12513: if ($#origfiletagids<0) {
12514: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12515: $origfile=&getfile($origfilelocation);
12516: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12517: }
1.1369 raeburn 12518: }
12519: }
12520: }
1.1370 raeburn 12521: # Do not overwrite contents of %metaentry hash for resource itself with
12522: # hash populated for imported library file
12523: %metaentry = %currmetaentry;
12524: undef(%currmetaentry);
1.1374 raeburn 12525: if ($importmode eq 'part') {
1.1068 www 12526: # Import as part(s)
1.1069 www 12527: $importedparts=1;
12528: # We need to get the original file and the imported file to get the part order correct
12529: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369 raeburn 12530: # Load and inspect original file if we didn't do that already
12531: if ($#origfiletagids<0) {
12532: undef(%importedrespids);
12533: undef(%importedpartids);
12534: if ($origfile eq '') {
12535: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12536: $origfile=&getfile($origfilelocation);
12537: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12538: }
1.1070 www 12539: }
1.1372 raeburn 12540: my @impfilepartids;
12541: # If <partorder> tag is included in metadata for the imported file
12542: # get the parts in the imported file from that.
12543: if (grep(/^partorder$/,@libfilekeys)) {
12544: %currmetaentry = %metaentry;
12545: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12546: $depthcount+1);
12547: %metaentry = %currmetaentry;
12548: undef(%currmetaentry);
12549: if ($libpartorder ne '') {
12550: @impfilepartids=split(/\s*,\s*/,$libpartorder);
12551: }
12552: } else {
12553: # If no <partorder> tag available, load and inspect imported file
12554: my $impfile=&getfile($location);
12555: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12556: }
1.1069 www 12557: if ($#impfilepartids>=0) {
12558: # This problem had parts
1.1070 www 12559: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 12560: } else {
12561: # Importing by turning a single problem into a problem part
12562: # It gets the import-tags ID as part-ID
12563: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 12564: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 12565: }
1.1068 www 12566: } else {
1.1374 raeburn 12567: # Import as problem or as normal import
12568: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12569: unless ($importmode eq 'problem') {
1.1068 www 12570: # Normal import
1.1374 raeburn 12571: if (defined($token->[2]->{'id'})) {
12572: $unikey.='_'.$token->[2]->{'id'};
12573: }
12574: }
12575: # Check metadata for imported file to
12576: # see if it contained parts
12577: if (grep(/^partorder$/,@libfilekeys)) {
12578: %currmetaentry = %metaentry;
12579: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12580: $depthcount+1);
12581: %metaentry = %currmetaentry;
12582: undef(%currmetaentry);
12583: if ($libpartorder ne '') {
12584: $importedparts = 1;
12585: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12586: }
12587: }
1.1067 www 12588: }
1.339 albertel 12589: if ($depthcount<20) {
1.736 albertel 12590: my $metadata =
1.1362 raeburn 12591: &metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736 albertel 12592: $depthcount+1);
12593: foreach my $meta (split(',',$metadata)) {
12594: $metaentry{':'.$meta}=$metaentry{':'.$meta};
12595: $metathesekeys{$meta}=1;
1.339 albertel 12596: }
1.1068 www 12597: }
1.1067 www 12598: } else {
12599: #
12600: # Not importing, some other kind of non-package, non-library start tag
12601: #
12602: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12603: if (defined($token->[2]->{'id'})) {
12604: $unikey.='_'.$token->[2]->{'id'};
12605: }
1.339 albertel 12606: if (defined($token->[2]->{'name'})) {
12607: $unikey.='_'.$token->[2]->{'name'};
12608: }
12609: $metathesekeys{$unikey}=1;
1.736 albertel 12610: foreach my $param (@{$token->[3]}) {
12611: $metaentry{':'.$unikey.'.'.$param} =
12612: $token->[2]->{$param};
1.339 albertel 12613: }
12614: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 12615: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 12616: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12617: # only ws inside the tag, and not in default, so use default
12618: # as value
1.599 albertel 12619: $metaentry{':'.$unikey}=$default;
1.908 albertel 12620: } elsif ( $internaltext =~ /\S/ ) {
12621: # something interesting inside the tag
12622: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 12623: } else {
1.908 albertel 12624: # no interesting values, don't set a default
1.339 albertel 12625: }
1.172 www 12626: # end of not-a-package not-a-library import
1.339 albertel 12627: }
1.172 www 12628: # end of not-a-package start tag
1.339 albertel 12629: }
1.172 www 12630: # the next is the end of "start tag"
1.339 albertel 12631: }
12632: }
1.483 albertel 12633: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 12634: $extension = lc($extension);
12635: if ($extension eq 'htm') { $extension='html'; }
12636:
1.737 albertel 12637: foreach my $key (keys(%packagetab)) {
1.483 albertel 12638: #no specific packages #how's our extension
12639: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 12640: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 12641: \%metathesekeys);
12642: }
1.883 albertel 12643:
12644: if (!exists($metaentry{':packages'})
12645: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 12646: foreach my $key (keys(%packagetab)) {
1.483 albertel 12647: #no specific packages well let's get default then
12648: if ($key!~/^default&/) { next; }
1.488 albertel 12649: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 12650: \%metathesekeys);
12651: }
12652: }
1.338 www 12653: # are there custom rights to evaluate
1.599 albertel 12654: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 12655:
1.338 www 12656: #
12657: # Importing a rights file here
1.339 albertel 12658: #
12659: unless ($depthcount) {
1.599 albertel 12660: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 12661: my $dir=$filename;
12662: $dir=~s|[^/]*$||;
12663: $location=&filelocation($dir,$location);
1.736 albertel 12664: my $rights_metadata =
1.1362 raeburn 12665: &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736 albertel 12666: $depthcount+1);
12667: foreach my $rights (split(',',$rights_metadata)) {
12668: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12669: $metathesekeys{$rights}=1;
1.339 albertel 12670: }
12671: }
12672: }
1.737 albertel 12673: # uniqifiy package listing
12674: my %seen;
12675: my @uniq_packages =
12676: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12677: $metaentry{':packages'} = join(',',@uniq_packages);
12678:
1.1369 raeburn 12679: if (($importedresponses) || ($importedparts)) {
12680: if ($importedparts) {
1.1070 www 12681: # We had imported parts and need to rebuild partorder
1.1369 raeburn 12682: $metaentry{':partorder'}='';
12683: $metathesekeys{'partorder'}=1;
12684: }
12685: if ($importedresponses) {
12686: # We had imported responses and need to rebuil responseorder
12687: $metaentry{':responseorder'}='';
12688: $metathesekeys{'responseorder'}=1;
12689: }
12690: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12691: my $origid = $origfiletagids[$index+1];
12692: if ($origfiletagids[$index] eq 'part') {
12693: # Original part, part of the problem
12694: if ($importedparts) {
12695: $metaentry{':partorder'}.=','.$origid;
12696: }
12697: } elsif ($origfiletagids[$index] eq 'import') {
12698: if ($importedparts) {
12699: # We have imported parts at this position
1.1373 raeburn 12700: if ($importedpartids{$origid} ne '') {
12701: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12702: }
1.1369 raeburn 12703: }
12704: if ($importedresponses) {
12705: # We have imported responses at this position
1.1373 raeburn 12706: if ($importedrespids{$origid} ne '') {
12707: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369 raeburn 12708: }
12709: }
12710: } else {
12711: # Original response item, part of the problem
12712: if ($importedresponses) {
12713: $metaentry{':responseorder'}.=','.$origid;
12714: }
12715: }
12716: }
12717: if ($importedparts) {
12718: $metaentry{':partorder'}=~s/^\,//;
12719: }
12720: if ($importedresponses) {
12721: $metaentry{':responseorder'}=~s/^\,//;
12722: }
1.1070 www 12723: }
1.737 albertel 12724: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12725: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 12726: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371 raeburn 12727: unless ($liburi) {
12728: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12729: }
1.177 www 12730: # this is the end of "was not already recently cached
1.71 www 12731: }
1.599 albertel 12732: return $metaentry{':'.$what};
1.261 albertel 12733: }
12734:
1.488 albertel 12735: sub metadata_create_package_def {
1.483 albertel 12736: my ($uri,$key,$package,$metathesekeys)=@_;
12737: my ($pack,$name,$subp)=split(/\&/,$key);
12738: if ($subp eq 'default') { next; }
12739:
1.599 albertel 12740: if (defined($metaentry{':packages'})) {
12741: $metaentry{':packages'}.=','.$package;
1.483 albertel 12742: } else {
1.599 albertel 12743: $metaentry{':packages'}=$package;
1.483 albertel 12744: }
12745: my $value=$packagetab{$key};
12746: my $unikey;
12747: $unikey='parameter_0_'.$name;
1.599 albertel 12748: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12749: $$metathesekeys{$unikey}=1;
1.599 albertel 12750: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12751: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12752: }
1.599 albertel 12753: if (defined($metaentry{':'.$unikey.'.default'})) {
12754: $metaentry{':'.$unikey}=
12755: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12756: }
12757: }
12758:
1.261 albertel 12759: sub metadata_generate_part0 {
12760: my ($metadata,$metacache,$uri) = @_;
12761: my %allnames;
1.737 albertel 12762: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 12763: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 12764: my $part=$$metacache{':'.$metakey.'.part'};
12765: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 12766: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 12767: $allnames{$name}=$part;
12768: }
12769: }
12770: }
12771: foreach my $name (keys(%allnames)) {
12772: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 12773: my $key=":parameter_0_$name";
1.261 albertel 12774: $$metacache{"$key.part"}='0';
12775: $$metacache{"$key.name"}=$name;
1.428 albertel 12776: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 12777: $allnames{$name}.'_'.$name.
12778: '.type'};
1.428 albertel 12779: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 12780: '.display'};
1.644 www 12781: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 12782: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 12783: $$metacache{"$key.display"}=$olddis;
12784: }
1.71 www 12785: }
12786:
1.764 albertel 12787: # ------------------------------------------------------ Devalidate title cache
12788:
12789: sub devalidate_title_cache {
12790: my ($url)=@_;
12791: if (!$env{'request.course.id'}) { return; }
12792: my $symb=&symbread($url);
12793: if (!$symb) { return; }
12794: my $key=$env{'request.course.id'}."\0".$symb;
12795: &devalidate_cache_new('title',$key);
12796: }
12797:
1.1014 droeschl 12798: # ------------------------------------------------- Get the title of a course
12799:
12800: sub current_course_title {
12801: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12802: }
1.301 www 12803: # ------------------------------------------------- Get the title of a resource
12804:
12805: sub gettitle {
12806: my $urlsymb=shift;
12807: my $symb=&symbread($urlsymb);
1.534 albertel 12808: if ($symb) {
1.620 albertel 12809: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12810: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12811: if (defined($cached)) {
12812: return $result;
12813: }
1.534 albertel 12814: my ($map,$resid,$url)=&decode_symb($symb);
12815: my $title='';
1.907 albertel 12816: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12817: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12818: } else {
12819: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12820: &GDBM_READER(),0640)) {
12821: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12822: $title=$bighash{'title_'.$mapid.'.'.$resid};
12823: untie(%bighash);
12824: }
1.534 albertel 12825: }
12826: $title=~s/\&colon\;/\:/gs;
12827: if ($title) {
1.1159 www 12828: # Remember both $symb and $title for dynamic metadata
12829: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12830: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12831: # Cache this title and then return it
1.599 albertel 12832: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12833: }
12834: $urlsymb=$url;
12835: }
12836: my $title=&metadata($urlsymb,'title');
12837: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12838: return $title;
1.301 www 12839: }
1.613 albertel 12840:
1.614 albertel 12841: sub get_slot {
12842: my ($which,$cnum,$cdom)=@_;
12843: if (!$cnum || !$cdom) {
1.790 albertel 12844: (undef,my $courseid)=&whichuser();
1.620 albertel 12845: $cdom=$env{'course.'.$courseid.'.domain'};
12846: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 12847: }
1.703 albertel 12848: my $key=join("\0",'slots',$cdom,$cnum,$which);
12849: my %slotinfo;
12850: if (exists($remembered{$key})) {
12851: $slotinfo{$which} = $remembered{$key};
12852: } else {
12853: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12854: &Apache::lonhomework::showhash(%slotinfo);
12855: my ($tmp)=keys(%slotinfo);
12856: if ($tmp=~/^error:/) { return (); }
12857: $remembered{$key} = $slotinfo{$which};
12858: }
1.616 albertel 12859: if (ref($slotinfo{$which}) eq 'HASH') {
12860: return %{$slotinfo{$which}};
12861: }
12862: return $slotinfo{$which};
1.614 albertel 12863: }
1.1150 raeburn 12864:
12865: sub get_reservable_slots {
12866: my ($cnum,$cdom,$uname,$udom) = @_;
12867: my $now = time;
12868: my $reservable_info;
12869: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12870: if (exists($remembered{$key})) {
12871: $reservable_info = $remembered{$key};
12872: } else {
12873: my %resv;
12874: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12875: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12876: $reservable_info = \%resv;
12877: $remembered{$key} = $reservable_info;
12878: }
12879: return $reservable_info;
12880: }
12881:
12882: sub get_course_slots {
12883: my ($cnum,$cdom) = @_;
12884: my $hashid=$cnum.':'.$cdom;
12885: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12886: if (defined($cached)) {
12887: if (ref($result) eq 'HASH') {
12888: return %{$result};
12889: }
12890: } else {
12891: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12892: my ($tmp) = keys(%slots);
12893: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 12894: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 12895: return %slots;
12896: }
12897: }
12898: return;
12899: }
12900:
12901: sub devalidate_slots_cache {
12902: my ($cnum,$cdom)=@_;
12903: my $hashid=$cnum.':'.$cdom;
12904: &devalidate_cache_new('allslots',$hashid);
12905: }
12906:
1.1181 raeburn 12907: sub get_coursechange {
12908: my ($cdom,$cnum) = @_;
12909: if ($cdom eq '' || $cnum eq '') {
12910: return unless ($env{'request.course.id'});
12911: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12912: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12913: }
12914: my $hashid=$cdom.'_'.$cnum;
12915: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12916: if ((defined($cached)) && ($change ne '')) {
12917: return $change;
12918: } else {
12919: my %crshash;
12920: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12921: if ($crshash{'internal.contentchange'} eq '') {
12922: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12923: if ($change eq '') {
12924: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12925: $change = $crshash{'internal.created'};
12926: }
12927: } else {
12928: $change = $crshash{'internal.contentchange'};
12929: }
12930: my $cachetime = 600;
12931: &do_cache_new('crschange',$hashid,$change,$cachetime);
12932: }
12933: return $change;
12934: }
12935:
12936: sub devalidate_coursechange_cache {
12937: my ($cnum,$cdom)=@_;
12938: my $hashid=$cnum.':'.$cdom;
12939: &devalidate_cache_new('crschange',$hashid);
12940: }
12941:
1.31 www 12942: # ------------------------------------------------- Update symbolic store links
12943:
12944: sub symblist {
12945: my ($mapname,%newhash)=@_;
1.438 www 12946: $mapname=&deversion(&declutter($mapname));
1.31 www 12947: my %hash;
1.620 albertel 12948: if (($env{'request.course.fn'}) && (%newhash)) {
12949: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12950: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 12951: foreach my $url (keys(%newhash)) {
1.711 albertel 12952: next if ($url eq 'last_known'
12953: && $env{'form.no_update_last_known'});
12954: $hash{declutter($url)}=&encode_symb($mapname,
12955: $newhash{$url}->[1],
12956: $newhash{$url}->[0]);
1.191 harris41 12957: }
1.31 www 12958: if (untie(%hash)) {
12959: return 'ok';
12960: }
12961: }
12962: }
12963: return 'error';
1.212 www 12964: }
12965:
12966: # --------------------------------------------------------------- Verify a symb
12967:
12968: sub symbverify {
1.1190 raeburn 12969: my ($symb,$thisurl,$encstate)=@_;
1.510 www 12970: my $thisfn=$thisurl;
1.439 www 12971: $thisfn=&declutter($thisfn);
1.215 www 12972: # direct jump to resource in page or to a sequence - will construct own symbs
12973: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12974: # check URL part
1.409 www 12975: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12976:
1.431 www 12977: unless ($url eq $thisfn) { return 0; }
1.213 www 12978:
1.216 www 12979: $symb=&symbclean($symb);
1.510 www 12980: $thisurl=&deversion($thisurl);
1.439 www 12981: $thisfn=&deversion($thisfn);
1.213 www 12982:
12983: my %bighash;
12984: my $okay=0;
1.431 www 12985:
1.620 albertel 12986: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12987: &GDBM_READER(),0640)) {
1.1204 raeburn 12988: my $noclutter;
1.1032 raeburn 12989: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12990: $thisurl =~ s/\?.+$//;
1.1204 raeburn 12991: if ($map =~ m{^uploaded/.+\.page$}) {
12992: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12993: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12994: $noclutter = 1;
12995: }
12996: }
12997: my $ids;
12998: if ($noclutter) {
12999: $ids=$bighash{'ids_'.$thisurl};
13000: } else {
13001: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 13002: }
1.1102 raeburn 13003: unless ($ids) {
13004: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
13005: $ids=$bighash{$idkey};
1.216 www 13006: }
13007: if ($ids) {
13008: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 13009: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 13010: $symb =~ s/\?.+$//;
1.1202 raeburn 13011: }
1.800 albertel 13012: foreach my $id (split(/\,/,$ids)) {
13013: my ($mapid,$resid)=split(/\./,$id);
1.216 www 13014: if (
13015: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 13016: eq $symb) {
13017: if (ref($encstate)) {
13018: $$encstate = $bighash{'encrypted_'.$id};
13019: }
1.620 albertel 13020: if (($env{'request.role.adv'}) ||
1.1101 raeburn 13021: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13022: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 13023: $okay=1;
1.1202 raeburn 13024: last;
1.582 albertel 13025: }
13026: }
1.216 www 13027: }
13028: }
1.213 www 13029: untie(%bighash);
13030: }
13031: return $okay;
1.31 www 13032: }
13033:
1.210 www 13034: # --------------------------------------------------------------- Clean-up symb
13035:
13036: sub symbclean {
13037: my $symb=shift;
1.568 albertel 13038: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 13039: # remove version from map
13040: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 13041:
1.210 www 13042: # remove version from URL
13043: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 13044:
1.507 www 13045: # remove wrapper
13046:
1.510 www 13047: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 13048: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 13049: return $symb;
1.409 www 13050: }
13051:
13052: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 13053:
13054: sub encode_symb {
13055: my ($map,$resid,$url)=@_;
13056: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13057: }
1.409 www 13058:
13059: sub decode_symb {
1.568 albertel 13060: my $symb=shift;
13061: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13062: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 13063: return (&fixversion($map),$resid,&fixversion($url));
13064: }
13065:
13066: sub fixversion {
13067: my $fn=shift;
1.609 banghart 13068: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 13069: my %bighash;
13070: my $uri=&clutter($fn);
1.620 albertel 13071: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 13072: # is this cached?
1.599 albertel 13073: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 13074: if (defined($cached)) { return $result; }
13075: # unfortunately not cached, or expired
1.620 albertel 13076: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 13077: &GDBM_READER(),0640)) {
13078: if ($bighash{'version_'.$uri}) {
13079: my $version=$bighash{'version_'.$uri};
1.444 www 13080: unless (($version eq 'mostrecent') ||
13081: ($version==&getversion($uri))) {
1.440 www 13082: $uri=~s/\.(\w+)$/\.$version\.$1/;
13083: }
13084: }
13085: untie %bighash;
1.413 www 13086: }
1.599 albertel 13087: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 13088: }
13089:
13090: sub deversion {
13091: my $url=shift;
13092: $url=~s/\.\d+\.(\w+)$/\.$1/;
13093: return $url;
1.210 www 13094: }
13095:
1.31 www 13096: # ------------------------------------------------------ Return symb list entry
13097:
13098: sub symbread {
1.1282 raeburn 13099: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 13100: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 13101: if (defined($env{$cache_str})) {
13102: if ($ignorecachednull) {
13103: return $env{$cache_str} unless ($env{$cache_str} eq '');
13104: } else {
13105: return $env{$cache_str};
13106: }
13107: }
1.242 www 13108: # no filename provided? try from environment
1.1265 raeburn 13109: unless ($thisfn) {
1.620 albertel 13110: if ($env{'request.symb'}) {
13111: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 13112: }
1.620 albertel 13113: $thisfn=$env{'request.filename'};
1.44 www 13114: }
1.569 albertel 13115: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 13116: # is that filename actually a symb? Verify, clean, and return
13117: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 13118: if (&symbverify($thisfn,$1)) {
1.620 albertel 13119: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 13120: }
1.242 www 13121: }
1.44 www 13122: $thisfn=declutter($thisfn);
1.31 www 13123: my %hash;
1.37 www 13124: my %bighash;
13125: my $syval='';
1.620 albertel 13126: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 13127: my $targetfn = $thisfn;
1.609 banghart 13128: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 13129: $targetfn = 'adm/wrapper/'.$thisfn;
13130: }
1.687 albertel 13131: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13132: $targetfn=$1;
13133: }
1.620 albertel 13134: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 13135: &GDBM_READER(),0640)) {
1.481 raeburn 13136: $syval=$hash{$targetfn};
1.37 www 13137: untie(%hash);
13138: }
13139: # ---------------------------------------------------------- There was an entry
13140: if ($syval) {
1.601 albertel 13141: #unless ($syval=~/\_\d+$/) {
1.620 albertel 13142: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 13143: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13144: #return $env{$cache_str}='';
1.601 albertel 13145: #}
13146: #$syval.=$1;
13147: #}
1.37 www 13148: } else {
13149: # ------------------------------------------------------- Was not in symb table
1.620 albertel 13150: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13151: &GDBM_READER(),0640)) {
1.37 www 13152: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 13153: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 13154: unless ($ids) {
13155: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 13156: }
13157: unless ($ids) {
13158: # alias?
13159: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 13160: }
1.37 www 13161: if ($ids) {
13162: # ------------------------------------------------------------------- Has ID(s)
13163: my @possibilities=split(/\,/,$ids);
1.39 www 13164: if ($#possibilities==0) {
13165: # ----------------------------------------------- There is only one possibility
1.37 www 13166: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 13167: $syval=&encode_symb($bighash{'map_id_'.$mapid},
13168: $resid,$thisfn);
1.1282 raeburn 13169: if (ref($possibles) eq 'HASH') {
13170: $possibles->{$syval} = 1;
13171: }
13172: if ($checkforblock) {
13173: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
13174: if (@blockers) {
13175: $syval = '';
13176: return;
13177: }
13178: }
13179: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 13180: # ------------------------------------------ There is more than one possibility
13181: my $realpossible=0;
1.800 albertel 13182: foreach my $id (@possibilities) {
13183: my $file=$bighash{'src_'.$id};
1.1282 raeburn 13184: my $canaccess;
13185: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13186: $canaccess = 1;
13187: } else {
13188: $canaccess = &allowed('bre',$file);
13189: }
13190: if ($canaccess) {
13191: my ($mapid,$resid)=split(/\./,$id);
13192: if ($bighash{'map_type_'.$mapid} ne 'page') {
13193: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13194: $resid,$thisfn);
13195: if (ref($possibles) eq 'HASH') {
13196: $possibles->{$syval} = 1;
13197: }
13198: if ($checkforblock) {
13199: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
13200: unless (@blockers > 0) {
13201: $syval = $poss_syval;
13202: $realpossible++;
13203: }
13204: } else {
13205: $syval = $poss_syval;
13206: $realpossible++;
13207: }
13208: }
1.39 www 13209: }
1.191 harris41 13210: }
1.39 www 13211: if ($realpossible!=1) { $syval=''; }
1.249 www 13212: } else {
13213: $syval='';
1.37 www 13214: }
13215: }
1.1282 raeburn 13216: untie(%bighash);
1.481 raeburn 13217: }
1.31 www 13218: }
1.62 www 13219: if ($syval) {
1.620 albertel 13220: return $env{$cache_str}=$syval;
1.62 www 13221: }
1.31 www 13222: }
1.949 raeburn 13223: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13224: return $env{$cache_str}='';
1.31 www 13225: }
13226:
13227: # ---------------------------------------------------------- Return random seed
13228:
1.32 www 13229: sub numval {
13230: my $txt=shift;
13231: $txt=~tr/A-J/0-9/;
13232: $txt=~tr/a-j/0-9/;
13233: $txt=~tr/K-T/0-9/;
13234: $txt=~tr/k-t/0-9/;
13235: $txt=~tr/U-Z/0-5/;
13236: $txt=~tr/u-z/0-5/;
13237: $txt=~s/\D//g;
1.564 albertel 13238: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 13239: return int($txt);
1.368 albertel 13240: }
13241:
1.484 albertel 13242: sub numval2 {
13243: my $txt=shift;
13244: $txt=~tr/A-J/0-9/;
13245: $txt=~tr/a-j/0-9/;
13246: $txt=~tr/K-T/0-9/;
13247: $txt=~tr/k-t/0-9/;
13248: $txt=~tr/U-Z/0-5/;
13249: $txt=~tr/u-z/0-5/;
13250: $txt=~s/\D//g;
13251: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13252: my $total;
13253: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 13254: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 13255: return int($total);
13256: }
13257:
1.575 albertel 13258: sub numval3 {
13259: use integer;
13260: my $txt=shift;
13261: $txt=~tr/A-J/0-9/;
13262: $txt=~tr/a-j/0-9/;
13263: $txt=~tr/K-T/0-9/;
13264: $txt=~tr/k-t/0-9/;
13265: $txt=~tr/U-Z/0-5/;
13266: $txt=~tr/u-z/0-5/;
13267: $txt=~s/\D//g;
13268: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13269: my $total;
13270: foreach my $val (@txts) { $total+=$val; }
13271: if ($_64bit) { $total=(($total<<32)>>32); }
13272: return $total;
13273: }
13274:
1.675 albertel 13275: sub digest {
13276: my ($data)=@_;
13277: my $digest=&Digest::MD5::md5($data);
13278: my ($a,$b,$c,$d)=unpack("iiii",$digest);
13279: my ($e,$f);
13280: {
13281: use integer;
13282: $e=($a+$b);
13283: $f=($c+$d);
13284: if ($_64bit) {
13285: $e=(($e<<32)>>32);
13286: $f=(($f<<32)>>32);
13287: }
13288: }
13289: if (wantarray) {
13290: return ($e,$f);
13291: } else {
13292: my $g;
13293: {
13294: use integer;
13295: $g=($e+$f);
13296: if ($_64bit) {
13297: $g=(($g<<32)>>32);
13298: }
13299: }
13300: return $g;
13301: }
13302: }
13303:
1.368 albertel 13304: sub latest_rnd_algorithm_id {
1.675 albertel 13305: return '64bit5';
1.366 albertel 13306: }
1.32 www 13307:
1.503 albertel 13308: sub get_rand_alg {
13309: my ($courseid)=@_;
1.790 albertel 13310: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 13311: if ($courseid) {
1.620 albertel 13312: return $env{"course.$courseid.rndseed"};
1.503 albertel 13313: }
13314: return &latest_rnd_algorithm_id();
13315: }
13316:
1.562 albertel 13317: sub validCODE {
13318: my ($CODE)=@_;
13319: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13320: return 0;
13321: }
13322:
1.491 albertel 13323: sub getCODE {
1.620 albertel 13324: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 13325: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13326: defined($Apache::lonhomework::parsing_a_task) ) &&
13327: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 13328: return $Apache::lonhomework::history{'resource.CODE'};
13329: }
13330: return undef;
13331: }
1.1133 foxr 13332: #
13333: # Determines the random seed for a specific context:
13334: #
13335: # parameters:
13336: # symb - in course context the symb for the seed.
13337: # course_id - The course id of the form domain_coursenum.
13338: # domain - Domain for the user.
13339: # course - Course for the user.
13340: # cenv - environment of the course.
13341: #
13342: # NOTE:
13343: # All parameters are picked out of the environment if missing
13344: # or not defined.
13345: # If a symb cannot be determined the current time is used instead.
13346: #
13347: # For a given well defined symb, courside, domain, username,
13348: # and course environment, the seed is reproducible.
13349: #
1.31 www 13350: sub rndseed {
1.1133 foxr 13351: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 13352: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 13353: if (!defined($symb)) {
1.366 albertel 13354: unless ($symb=$wsymb) { return time; }
13355: }
1.1146 foxr 13356: if (!defined $courseid) {
13357: $courseid=$wcourseid;
13358: }
13359: if (!defined $domain) { $domain=$wdomain; }
13360: if (!defined $username) { $username=$wusername }
1.1133 foxr 13361:
13362: my $which;
13363: if (defined($cenv->{'rndseed'})) {
13364: $which = $cenv->{'rndseed'};
13365: } else {
13366: $which =&get_rand_alg($courseid);
13367: }
1.491 albertel 13368: if (defined(&getCODE())) {
1.1133 foxr 13369:
1.675 albertel 13370: if ($which eq '64bit5') {
13371: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13372: } elsif ($which eq '64bit4') {
1.575 albertel 13373: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13374: } else {
13375: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13376: }
1.675 albertel 13377: } elsif ($which eq '64bit5') {
13378: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 13379: } elsif ($which eq '64bit4') {
13380: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 13381: } elsif ($which eq '64bit3') {
13382: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 13383: } elsif ($which eq '64bit2') {
13384: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 13385: } elsif ($which eq '64bit') {
13386: return &rndseed_64bit($symb,$courseid,$domain,$username);
13387: }
13388: return &rndseed_32bit($symb,$courseid,$domain,$username);
13389: }
13390:
13391: sub rndseed_32bit {
13392: my ($symb,$courseid,$domain,$username)=@_;
13393: {
13394: use integer;
13395: my $symbchck=unpack("%32C*",$symb) << 27;
13396: my $symbseed=numval($symb) << 22;
13397: my $namechck=unpack("%32C*",$username) << 17;
13398: my $nameseed=numval($username) << 12;
13399: my $domainseed=unpack("%32C*",$domain) << 7;
13400: my $courseseed=unpack("%32C*",$courseid);
13401: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 13402: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13403: #&logthis("rndseed :$num:$symb");
1.564 albertel 13404: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 13405: return $num;
13406: }
13407: }
13408:
13409: sub rndseed_64bit {
13410: my ($symb,$courseid,$domain,$username)=@_;
13411: {
13412: use integer;
13413: my $symbchck=unpack("%32S*",$symb) << 21;
13414: my $symbseed=numval($symb) << 10;
13415: my $namechck=unpack("%32S*",$username);
13416:
13417: my $nameseed=numval($username) << 21;
13418: my $domainseed=unpack("%32S*",$domain) << 10;
13419: my $courseseed=unpack("%32S*",$courseid);
13420:
13421: my $num1=$symbchck+$symbseed+$namechck;
13422: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13423: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13424: #&logthis("rndseed :$num:$symb");
1.564 albertel 13425: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 13426: return "$num1,$num2";
1.155 albertel 13427: }
1.366 albertel 13428: }
13429:
1.443 albertel 13430: sub rndseed_64bit2 {
13431: my ($symb,$courseid,$domain,$username)=@_;
13432: {
13433: use integer;
13434: # strings need to be an even # of cahracters long, it it is odd the
13435: # last characters gets thrown away
13436: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13437: my $symbseed=numval($symb) << 10;
13438: my $namechck=unpack("%32S*",$username.' ');
13439:
13440: my $nameseed=numval($username) << 21;
1.501 albertel 13441: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13442: my $courseseed=unpack("%32S*",$courseid.' ');
13443:
13444: my $num1=$symbchck+$symbseed+$namechck;
13445: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13446: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13447: #&logthis("rndseed :$num:$symb");
1.803 albertel 13448: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 13449: return "$num1,$num2";
13450: }
13451: }
13452:
13453: sub rndseed_64bit3 {
13454: my ($symb,$courseid,$domain,$username)=@_;
13455: {
13456: use integer;
13457: # strings need to be an even # of cahracters long, it it is odd the
13458: # last characters gets thrown away
13459: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13460: my $symbseed=numval2($symb) << 10;
13461: my $namechck=unpack("%32S*",$username.' ');
13462:
13463: my $nameseed=numval2($username) << 21;
1.443 albertel 13464: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13465: my $courseseed=unpack("%32S*",$courseid.' ');
13466:
13467: my $num1=$symbchck+$symbseed+$namechck;
13468: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13469: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13470: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 13471: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13472:
1.503 albertel 13473: return "$num1:$num2";
1.443 albertel 13474: }
13475: }
13476:
1.575 albertel 13477: sub rndseed_64bit4 {
13478: my ($symb,$courseid,$domain,$username)=@_;
13479: {
13480: use integer;
13481: # strings need to be an even # of cahracters long, it it is odd the
13482: # last characters gets thrown away
13483: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13484: my $symbseed=numval3($symb) << 10;
13485: my $namechck=unpack("%32S*",$username.' ');
13486:
13487: my $nameseed=numval3($username) << 21;
13488: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13489: my $courseseed=unpack("%32S*",$courseid.' ');
13490:
13491: my $num1=$symbchck+$symbseed+$namechck;
13492: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13493: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13494: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 13495: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13496:
1.575 albertel 13497: return "$num1:$num2";
13498: }
13499: }
13500:
1.675 albertel 13501: sub rndseed_64bit5 {
13502: my ($symb,$courseid,$domain,$username)=@_;
13503: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13504: return "$num1:$num2";
13505: }
13506:
1.366 albertel 13507: sub rndseed_CODE_64bit {
13508: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 13509: {
1.366 albertel 13510: use integer;
1.443 albertel 13511: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 13512: my $symbseed=numval2($symb);
1.491 albertel 13513: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13514: my $CODEseed=numval(&getCODE());
1.443 albertel 13515: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 13516: my $num1=$symbseed+$CODEchck;
13517: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13518: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13519: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 13520: if ($_64bit) { $num1=(($num1<<32)>>32); }
13521: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 13522: return "$num1:$num2";
1.366 albertel 13523: }
13524: }
13525:
1.575 albertel 13526: sub rndseed_CODE_64bit4 {
13527: my ($symb,$courseid,$domain,$username)=@_;
13528: {
13529: use integer;
13530: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13531: my $symbseed=numval3($symb);
13532: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13533: my $CODEseed=numval3(&getCODE());
13534: my $courseseed=unpack("%32S*",$courseid.' ');
13535: my $num1=$symbseed+$CODEchck;
13536: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13537: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13538: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 13539: if ($_64bit) { $num1=(($num1<<32)>>32); }
13540: if ($_64bit) { $num2=(($num2<<32)>>32); }
13541: return "$num1:$num2";
13542: }
13543: }
13544:
1.675 albertel 13545: sub rndseed_CODE_64bit5 {
13546: my ($symb,$courseid,$domain,$username)=@_;
13547: my $code = &getCODE();
13548: my ($num1,$num2)=&digest("$symb,$courseid,$code");
13549: return "$num1:$num2";
13550: }
13551:
1.366 albertel 13552: sub setup_random_from_rndseed {
13553: my ($rndseed)=@_;
1.503 albertel 13554: if ($rndseed =~/([,:])/) {
1.1262 raeburn 13555: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13556: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13557: &Math::Random::random_set_seed_from_phrase($rndseed);
13558: } else {
13559: &Math::Random::random_set_seed($num1,$num2);
13560: }
1.366 albertel 13561: } else {
13562: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 13563: }
1.36 albertel 13564: }
13565:
1.474 albertel 13566: sub latest_receipt_algorithm_id {
1.835 albertel 13567: return 'receipt3';
1.474 albertel 13568: }
13569:
1.480 www 13570: sub recunique {
13571: my $fucourseid=shift;
13572: my $unique;
1.835 albertel 13573: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13574: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13575: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 13576: } else {
13577: $unique=$perlvar{'lonReceipt'};
13578: }
13579: return unpack("%32C*",$unique);
13580: }
13581:
13582: sub recprefix {
13583: my $fucourseid=shift;
13584: my $prefix;
1.835 albertel 13585: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13586: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13587: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 13588: } else {
13589: $prefix=$perlvar{'lonHostID'};
13590: }
13591: return unpack("%32C*",$prefix);
13592: }
13593:
1.76 www 13594: sub ireceipt {
1.474 albertel 13595: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 13596:
13597: my $return =&recprefix($fucourseid).'-';
13598:
13599: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13600: $env{'request.state'} eq 'construct') {
13601: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13602: return $return;
13603: }
13604:
1.76 www 13605: my $cuname=unpack("%32C*",$funame);
13606: my $cudom=unpack("%32C*",$fudom);
13607: my $cucourseid=unpack("%32C*",$fucourseid);
13608: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 13609: my $cunique=&recunique($fucourseid);
1.474 albertel 13610: my $cpart=unpack("%32S*",$part);
1.835 albertel 13611: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13612:
1.790 albertel 13613: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 13614:
13615: $return.= ($cunique%$cuname+
13616: $cunique%$cudom+
13617: $cusymb%$cuname+
13618: $cusymb%$cudom+
13619: $cucourseid%$cuname+
13620: $cucourseid%$cudom+
13621: $cpart%$cuname+
13622: $cpart%$cudom);
13623: } else {
13624: $return.= ($cunique%$cuname+
13625: $cunique%$cudom+
13626: $cusymb%$cuname+
13627: $cusymb%$cudom+
13628: $cucourseid%$cuname+
13629: $cucourseid%$cudom);
13630: }
13631: return $return;
1.76 www 13632: }
13633:
13634: sub receipt {
1.474 albertel 13635: my ($part)=@_;
1.790 albertel 13636: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 13637: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 13638: }
1.260 ng 13639:
1.790 albertel 13640: sub whichuser {
13641: my ($passedsymb)=@_;
13642: my ($symb,$courseid,$domain,$name,$publicuser);
13643: if (defined($env{'form.grade_symb'})) {
13644: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13645: my $allowed=&allowed('vgr',$tmp_courseid);
13646: if (!$allowed &&
13647: exists($env{'request.course.sec'}) &&
13648: $env{'request.course.sec'} !~ /^\s*$/) {
13649: $allowed=&allowed('vgr',$tmp_courseid.
13650: '/'.$env{'request.course.sec'});
13651: }
13652: if ($allowed) {
13653: ($symb)=&get_env_multiple('form.grade_symb');
13654: $courseid=$tmp_courseid;
13655: ($domain)=&get_env_multiple('form.grade_domain');
13656: ($name)=&get_env_multiple('form.grade_username');
13657: return ($symb,$courseid,$domain,$name,$publicuser);
13658: }
13659: }
13660: if (!$passedsymb) {
13661: $symb=&symbread();
13662: } else {
13663: $symb=$passedsymb;
13664: }
13665: $courseid=$env{'request.course.id'};
13666: $domain=$env{'user.domain'};
13667: $name=$env{'user.name'};
13668: if ($name eq 'public' && $domain eq 'public') {
13669: if (!defined($env{'form.username'})) {
13670: $env{'form.username'}.=time.rand(10000000);
13671: }
13672: $name.=$env{'form.username'};
13673: }
13674: return ($symb,$courseid,$domain,$name,$publicuser);
13675:
13676: }
13677:
1.36 albertel 13678: # ------------------------------------------------------------ Serves up a file
1.472 albertel 13679: # returns either the contents of the file or
13680: # -1 if the file doesn't exist
1.481 raeburn 13681: #
13682: # if the target is a file that was uploaded via DOCS,
13683: # a check will be made to see if a current copy exists on the local server,
13684: # if it does this will be served, otherwise a copy will be retrieved from
13685: # the home server for the course and stored in /home/httpd/html/userfiles on
13686: # the local server.
1.472 albertel 13687:
1.36 albertel 13688: sub getfile {
1.538 albertel 13689: my ($file) = @_;
1.609 banghart 13690: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 13691: &repcopy($file);
13692: return &readfile($file);
13693: }
13694:
13695: sub repcopy_userfile {
13696: my ($file)=@_;
1.1142 raeburn 13697: my $londocroot = $perlvar{'lonDocRoot'};
13698: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 13699: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 13700: my ($cdom,$cnum,$filename) =
1.811 albertel 13701: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 13702: my $uri="/uploaded/$cdom/$cnum/$filename";
13703: if (-e "$file") {
1.828 www 13704: # we already have a local copy, check it out
1.538 albertel 13705: my @fileinfo = stat($file);
1.828 www 13706: my $rtncode;
13707: my $info;
1.538 albertel 13708: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 13709: if ($lwpresp ne 'ok') {
1.828 www 13710: # there is no such file anymore, even though we had a local copy
1.482 albertel 13711: if ($rtncode eq '404') {
1.538 albertel 13712: unlink($file);
1.482 albertel 13713: }
13714: return -1;
13715: }
13716: if ($info < $fileinfo[9]) {
1.828 www 13717: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 13718: return 'ok';
1.828 www 13719: } else {
13720: # the file is outdated, get rid of it
13721: unlink($file);
1.482 albertel 13722: }
1.828 www 13723: }
13724: # one way or the other, at this point, we don't have the file
13725: # construct the correct path for the file
13726: my @parts = ($cdom,$cnum);
13727: if ($filename =~ m|^(.+)/[^/]+$|) {
13728: push @parts, split(/\//,$1);
13729: }
13730: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13731: foreach my $part (@parts) {
13732: $path .= '/'.$part;
13733: if (!-e $path) {
13734: mkdir($path,0770);
1.482 albertel 13735: }
13736: }
1.828 www 13737: # now the path exists for sure
13738: # get a user agent
13739: my $transferfile=$file.'.in.transfer';
13740: # FIXME: this should flock
13741: if (-e $transferfile) { return 'ok'; }
13742: my $request;
13743: $uri=~s/^\///;
1.980 raeburn 13744: my $homeserver = &homeserver($cnum,$cdom);
1.1398 raeburn 13745: my $hostname = &hostname($homeserver);
1.980 raeburn 13746: my $protocol = $protocol{$homeserver};
13747: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 13748: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345 raeburn 13749: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828 www 13750: # did it work?
13751: if ($response->is_error()) {
13752: unlink($transferfile);
13753: &logthis("Userfile repcopy failed for $uri");
13754: return -1;
13755: }
13756: # worked, rename the transfer file
13757: rename($transferfile,$file);
1.607 raeburn 13758: return 'ok';
1.481 raeburn 13759: }
13760:
1.517 albertel 13761: sub tokenwrapper {
13762: my $uri=shift;
1.980 raeburn 13763: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 13764: $uri=~s|^/||;
1.620 albertel 13765: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 13766: my $token=$1;
1.552 albertel 13767: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13768: if ($udom && $uname && $file) {
13769: $file=~s|(\?\.*)*$||;
1.949 raeburn 13770: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 13771: my $homeserver = &homeserver($uname,$udom);
1.1397 raeburn 13772: my $hostname = &hostname($homeserver);
1.980 raeburn 13773: my $protocol = $protocol{$homeserver};
13774: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 13775: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 13776: (($uri=~/\?/)?'&':'?').'token='.$token.
13777: '&tokenissued='.$perlvar{'lonHostID'};
13778: } else {
13779: return '/adm/notfound.html';
13780: }
13781: }
13782:
1.828 www 13783: # call with reqtype HEAD: get last modification time
13784: # call with reqtype GET: get the file contents
13785: # Do not call this with reqtype GET for large files! It loads everything into memory
13786: #
1.481 raeburn 13787: sub getuploaded {
13788: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13789: $uri=~s/^\///;
1.980 raeburn 13790: my $homeserver = &homeserver($cnum,$cdom);
1.1397 raeburn 13791: my $hostname = &hostname($homeserver);
1.980 raeburn 13792: my $protocol = $protocol{$homeserver};
13793: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 13794: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 13795: my $request=new HTTP::Request($reqtype,$uri);
1.1345 raeburn 13796: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481 raeburn 13797: $$rtncode = $response->code;
1.482 albertel 13798: if (! $response->is_success()) {
13799: return 'failed';
13800: }
13801: if ($reqtype eq 'HEAD') {
1.486 www 13802: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13803: } elsif ($reqtype eq 'GET') {
13804: $$info = $response->content;
1.472 albertel 13805: }
1.482 albertel 13806: return 'ok';
1.36 albertel 13807: }
13808:
1.481 raeburn 13809: sub readfile {
13810: my $file = shift;
13811: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13812: my $fh;
1.1359 raeburn 13813: open($fh,"<",$file);
1.481 raeburn 13814: my $a='';
1.800 albertel 13815: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13816: return $a;
13817: }
13818:
1.36 albertel 13819: sub filelocation {
1.590 banghart 13820: my ($dir,$file) = @_;
13821: my $location;
13822: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13823:
13824: if ($file =~ m-^/adm/-) {
13825: $file=~s-^/adm/wrapper/-/-;
13826: $file=~s-^/adm/coursedocs/showdoc/-/-;
13827: }
1.882 albertel 13828:
1.1139 www 13829: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13830: $location = $file;
1.609 banghart 13831: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13832: my ($udom,$uname,$filename)=
1.811 albertel 13833: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13834: my $home=&homeserver($uname,$udom);
13835: my $is_me=0;
13836: my @ids=¤t_machine_ids();
13837: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13838: if ($is_me) {
1.1117 foxr 13839: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13840: } else {
13841: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13842: $udom.'/'.$uname.'/'.$filename;
13843: }
1.882 albertel 13844: } elsif ($file =~ m-^/adm/-) {
13845: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 13846: } else {
13847: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 13848: $file=~s:^/(res|priv)/:/:;
13849: my $space=$1;
1.590 banghart 13850: if ( !( $file =~ m:^/:) ) {
13851: $location = $dir. '/'.$file;
13852: } else {
1.1142 raeburn 13853: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 13854: }
1.59 albertel 13855: }
1.590 banghart 13856: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 13857: while ($location=~m{/\.\./}) {
13858: if ($location =~ m{/[^/]+/\.\./}) {
13859: $location=~ s{/[^/]+/\.\./}{/}g;
13860: } else {
13861: $location=~ s{/\.\./}{/}g;
13862: }
13863: } #remove dir/..
1.590 banghart 13864: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13865: return $location;
1.46 www 13866: }
1.36 albertel 13867:
1.46 www 13868: sub hreflocation {
13869: my ($dir,$file)=@_;
1.980 raeburn 13870: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 13871: $file=filelocation($dir,$file);
1.700 albertel 13872: } elsif ($file=~m-^/adm/-) {
13873: $file=~s-^/adm/wrapper/-/-;
13874: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 13875: }
13876: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13877: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13878: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 13879: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13880: {/uploaded/$1/$2/}x;
1.46 www 13881: }
1.913 albertel 13882: if ($file=~ m{^/userfiles/}) {
13883: $file =~ s{^/userfiles/}{/uploaded/};
13884: }
1.462 albertel 13885: return $file;
1.465 albertel 13886: }
13887:
1.1139 www 13888:
13889:
13890:
13891:
1.465 albertel 13892: sub current_machine_domains {
1.853 albertel 13893: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13894: }
13895:
13896: sub machine_domains {
13897: my ($hostname) = @_;
1.465 albertel 13898: my @domains;
1.838 albertel 13899: my %hostname = &all_hostnames();
1.465 albertel 13900: while( my($id, $name) = each(%hostname)) {
1.467 matthew 13901: # &logthis("-$id-$name-$hostname-");
1.465 albertel 13902: if ($hostname eq $name) {
1.844 albertel 13903: push(@domains,&host_domain($id));
1.465 albertel 13904: }
13905: }
13906: return @domains;
13907: }
13908:
13909: sub current_machine_ids {
1.853 albertel 13910: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13911: }
13912:
13913: sub machine_ids {
13914: my ($hostname) = @_;
13915: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 13916: my @ids;
1.888 albertel 13917: my %name_to_host = &all_names();
1.889 albertel 13918: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13919: return @{ $name_to_host{$hostname} };
13920: }
13921: return;
1.31 www 13922: }
13923:
1.824 raeburn 13924: sub additional_machine_domains {
13925: my @domains;
1.1359 raeburn 13926: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 13927: while( my $line = <$fh>) {
13928: $line =~ s/\s//g;
13929: push(@domains,$line);
13930: }
13931: return @domains;
13932: }
13933:
13934: sub default_login_domain {
13935: my $domain = $perlvar{'lonDefDomain'};
13936: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13937: foreach my $posdom (¤t_machine_domains(),
13938: &additional_machine_domains()) {
13939: if (lc($posdom) eq lc($testdomain)) {
13940: $domain=$posdom;
13941: last;
13942: }
13943: }
13944: return $domain;
13945: }
13946:
1.1398 raeburn 13947: sub uses_sts {
13948: my ($ignore_cache) = @_;
13949: my $lonhost = $perlvar{'lonHostID'};
13950: my $hostname = &hostname($lonhost);
13951: my $sts_on;
13952: if ($protocol{$lonhost} eq 'https') {
13953: my $cachetime = 12*3600;
13954: if (!$ignore_cache) {
13955: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13956: if (defined($cached)) {
13957: return $sts_on;
13958: }
13959: }
13960: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13961: my $request=new HTTP::Request('HEAD',$url);
13962: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
13963: if ($response->is_success) {
13964: my $has_sts = $response->header('Strict-Transport-Security');
13965: if ($has_sts eq '') {
13966: $sts_on = 0;
13967: } else {
13968: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13969: my $maxage = $1;
13970: if ($maxage) {
13971: $sts_on = 1;
13972: } else {
13973: $sts_on = 0;
13974: }
13975: } else {
13976: $sts_on = 0;
13977: }
13978: }
13979: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13980: }
13981: }
13982: return;
13983: }
13984:
1.31 www 13985: # ------------------------------------------------------------- Declutters URLs
13986:
13987: sub declutter {
13988: my $thisfn=shift;
1.569 albertel 13989: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 13990: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13991: $thisfn=~s{^/home/httpd/html}{};
13992: }
1.31 www 13993: $thisfn=~s/^\///;
1.697 albertel 13994: $thisfn=~s|^adm/wrapper/||;
13995: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 13996: $thisfn=~s/^res\///;
1.1172 bisitz 13997: $thisfn=~s/^priv\///;
1.1032 raeburn 13998: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13999: $thisfn=~s/\?.+$//;
14000: }
1.268 www 14001: return $thisfn;
14002: }
14003:
14004: # ------------------------------------------------------------- Clutter up URLs
14005:
14006: sub clutter {
14007: my $thisfn='/'.&declutter(shift);
1.887 albertel 14008: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 14009: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 14010: $thisfn='/res'.$thisfn;
14011: }
1.1031 raeburn 14012: if ($thisfn !~m|^/adm|) {
14013: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 14014: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 14015: } else {
14016: my ($ext) = ($thisfn =~ /\.(\w+)$/);
14017: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 14018: if ($embstyle eq 'ssi'
14019: || ($embstyle eq 'hdn')
14020: || ($embstyle eq 'rat')
14021: || ($embstyle eq 'prv')
14022: || ($embstyle eq 'ign')) {
14023: #do nothing with these
14024: } elsif (($embstyle eq 'img')
1.695 albertel 14025: || ($embstyle eq 'emb')
14026: || ($embstyle eq 'wrp')) {
14027: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 14028: } elsif ($embstyle eq 'unk'
14029: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 14030: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 14031: } else {
1.718 www 14032: # &logthis("Got a blank emb style");
1.695 albertel 14033: }
1.694 albertel 14034: }
1.1343 raeburn 14035: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 14036: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 14037: }
1.31 www 14038: return $thisfn;
1.12 www 14039: }
14040:
1.787 albertel 14041: sub clutter_with_no_wrapper {
14042: my $uri = &clutter(shift);
14043: if ($uri =~ m-^/adm/-) {
14044: $uri =~ s-^/adm/wrapper/-/-;
14045: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
14046: }
14047: return $uri;
14048: }
14049:
1.557 albertel 14050: sub freeze_escape {
14051: my ($value)=@_;
14052: if (ref($value)) {
14053: $value=&nfreeze($value);
14054: return '__FROZEN__'.&escape($value);
14055: }
14056: return &escape($value);
14057: }
14058:
1.11 www 14059:
1.557 albertel 14060: sub thaw_unescape {
14061: my ($value)=@_;
14062: if ($value =~ /^__FROZEN__/) {
14063: substr($value,0,10,undef);
14064: $value=&unescape($value);
14065: return &thaw($value);
14066: }
14067: return &unescape($value);
14068: }
14069:
1.436 albertel 14070: sub correct_line_ends {
14071: my ($result)=@_;
14072: $$result =~s/\r\n/\n/mg;
14073: $$result =~s/\r/\n/mg;
1.415 albertel 14074: }
1.1 albertel 14075: # ================================================================ Main Program
14076:
1.184 www 14077: sub goodbye {
1.204 albertel 14078: &logthis("Starting Shut down");
1.443 albertel 14079: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 14080: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 14081: #converted
1.599 albertel 14082: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 14083: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14084: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14085: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 14086: #1.1 only
1.870 albertel 14087: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14088: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14089: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14090: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14091: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 14092: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14093: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 14094: &flushcourselogs();
14095: &logthis("Shutting down");
14096: }
14097:
1.852 albertel 14098: sub get_dns {
1.1210 raeburn 14099: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 14100: if (!$ignore_cache) {
14101: my ($content,$cached)=
14102: &Apache::lonnet::is_cached_new('dns',$url);
14103: if ($cached) {
1.1210 raeburn 14104: &$func($content,$hashref);
1.869 albertel 14105: return;
14106: }
14107: }
14108:
14109: my %alldns;
1.1379 raeburn 14110: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14111: foreach my $dns (<$config>) {
14112: next if ($dns !~ /^\^(\S*)/x);
14113: my $line = $1;
14114: my ($host,$protocol) = split(/:/,$line);
14115: if ($protocol ne 'https') {
14116: $protocol = 'http';
14117: }
14118: $alldns{$host} = $protocol;
1.979 raeburn 14119: }
1.1379 raeburn 14120: close($config);
1.869 albertel 14121: }
14122: while (%alldns) {
1.1263 raeburn 14123: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979 raeburn 14124: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345 raeburn 14125: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979 raeburn 14126: delete($alldns{$dns});
1.852 albertel 14127: next if ($response->is_error());
1.1379 raeburn 14128: if ($url eq '/adm/dns/loncapaCRL') {
14129: return &$func($response);
14130: } else {
14131: my @content = split("\n",$response->content);
14132: unless ($nocache) {
14133: &do_cache_new('dns',$url,\@content,30*24*60*60);
14134: }
14135: &$func(\@content,$hashref);
14136: return;
14137: }
14138: }
14139: my $which = (split('/',$url,4))[3];
14140: if ($which eq 'loncapaCRL') {
14141: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14142: if (-e $diskfile) {
14143: &logthis("unable to contact DNS, on disk file $diskfile not updated");
14144: } else {
14145: &logthis("unable to contact DNS, no on disk file $diskfile available");
14146: }
14147: } else {
14148: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14149: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14150: my @content = <$config>;
14151: close($config);
14152: &$func(\@content,$hashref);
14153: }
1.852 albertel 14154: }
1.1210 raeburn 14155: return;
14156: }
14157:
14158: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 14159: sub parse_dns_checksums_tab {
1.1210 raeburn 14160: my ($lines,$hashref) = @_;
1.1264 raeburn 14161: my $lonhost = $perlvar{'lonHostID'};
14162: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 14163: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 14164: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14165: my $webconfdir = '/etc/httpd/conf';
14166: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14167: $webconfdir = '/etc/apache2';
14168: } elsif ($distro =~ /^sles(\d+)$/) {
14169: if ($1 >= 10) {
14170: $webconfdir = '/etc/apache2';
14171: }
14172: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14173: if ($1 >= 10.0) {
14174: $webconfdir = '/etc/apache2';
14175: }
14176: }
1.1210 raeburn 14177: my ($release,$timestamp) = split(/\-/,$loncaparev);
14178: my (%chksum,%revnum);
14179: if (ref($lines) eq 'ARRAY') {
14180: chomp(@{$lines});
1.1238 raeburn 14181: my $version = shift(@{$lines});
14182: if ($version eq $release) {
1.1210 raeburn 14183: foreach my $line (@{$lines}) {
1.1238 raeburn 14184: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 14185: if ($file =~ m{^/etc/httpd/conf}) {
14186: if ($webconfdir eq '/etc/apache2') {
14187: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14188: }
14189: }
1.1238 raeburn 14190: $chksum{$file} = $shasum;
14191: $revnum{$file} = $version;
1.1210 raeburn 14192: }
14193: if (ref($hashref) eq 'HASH') {
14194: %{$hashref} = (
14195: sums => \%chksum,
14196: versions => \%revnum,
14197: );
14198: }
14199: }
14200: }
1.869 albertel 14201: return;
1.852 albertel 14202: }
1.1210 raeburn 14203:
14204: sub fetch_dns_checksums {
1.1238 raeburn 14205: my %checksums;
14206: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 14207: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 14208: my ($release,$timestamp) = split(/\-/,$loncaparev);
14209: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 14210: \%checksums);
1.1210 raeburn 14211: return \%checksums;
14212: }
14213:
1.1379 raeburn 14214: sub fetch_crl_pemfile {
14215: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14216: }
14217:
14218: sub save_crl_pem {
14219: my ($response) = @_;
1.1380 raeburn 14220: my ($msg,$hadchanges);
1.1379 raeburn 14221: if (ref($response)) {
14222: my $now = time;
14223: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14224: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14225: if (open(my $fh,'>',"$tmpcrl")) {
14226: print $fh $response->content;
14227: close($fh);
14228: if (-e $lonca) {
14229: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14230: my $check = <PIPE>;
14231: close(PIPE);
14232: chomp($check);
14233: if ($check eq 'verify OK') {
14234: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380 raeburn 14235: my $backup;
1.1379 raeburn 14236: if (-e $dest) {
1.1380 raeburn 14237: if (&File::Copy::move($dest,"$dest.bak")) {
14238: $backup = 'ok';
14239: }
1.1379 raeburn 14240: }
14241: if (&File::Copy::move($tmpcrl,$dest)) {
14242: $msg = 'ok';
1.1380 raeburn 14243: if ($backup) {
14244: my (%oldnums,%newnums);
14245: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14246: while (<PIPE>) {
14247: $oldnums{(split(/:/))[1]} = 1;
14248: }
14249: close(PIPE);
14250: }
14251: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14252: while(<PIPE>) {
14253: $newnums{(split(/:/))[1]} = 1;
14254: }
14255: close(PIPE);
14256: }
14257: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14258: unless (exists($oldnums{$key})) {
14259: $hadchanges = 1;
14260: last;
14261: }
14262: }
14263: unless ($hadchanges) {
14264: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14265: unless (exists($newnums{$key})) {
14266: $hadchanges = 1;
14267: last;
14268: }
14269: }
14270: }
14271: }
1.1379 raeburn 14272: }
14273: } else {
14274: unlink($tmpcrl);
14275: }
14276: } else {
14277: unlink($tmpcrl);
14278: }
14279: } else {
14280: unlink($tmpcrl);
14281: }
14282: }
14283: }
1.1380 raeburn 14284: return ($msg,$hadchanges);
1.1379 raeburn 14285: }
14286:
1.327 albertel 14287: # ------------------------------------------------------------ Read domain file
14288: {
1.852 albertel 14289: my $loaded;
1.846 albertel 14290: my %domain;
14291:
1.852 albertel 14292: sub parse_domain_tab {
14293: my ($lines) = @_;
14294: foreach my $line (@$lines) {
14295: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 14296:
1.846 albertel 14297: chomp($line);
1.852 albertel 14298: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 14299: my %this_domain;
14300: foreach my $field ('description', 'auth_def', 'auth_arg_def',
14301: 'lang_def', 'city', 'longi', 'lati',
14302: 'primary') {
14303: $this_domain{$field} = shift(@elements);
14304: }
14305: $domain{$name} = \%this_domain;
1.852 albertel 14306: }
14307: }
1.864 albertel 14308:
14309: sub reset_domain_info {
14310: undef($loaded);
14311: undef(%domain);
14312: }
14313:
1.852 albertel 14314: sub load_domain_tab {
1.1293 raeburn 14315: my ($ignore_cache,$nocache) = @_;
14316: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 14317: my $fh;
1.1359 raeburn 14318: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 14319: my @lines = <$fh>;
14320: &parse_domain_tab(\@lines);
1.448 albertel 14321: }
1.852 albertel 14322: close($fh);
14323: $loaded = 1;
1.327 albertel 14324: }
1.846 albertel 14325:
14326: sub domain {
1.852 albertel 14327: &load_domain_tab() if (!$loaded);
14328:
1.846 albertel 14329: my ($name,$what) = @_;
14330: return if ( !exists($domain{$name}) );
14331:
14332: if (!$what) {
14333: return $domain{$name}{'description'};
14334: }
14335: return $domain{$name}{$what};
14336: }
1.974 raeburn 14337:
14338: sub domain_info {
14339: &load_domain_tab() if (!$loaded);
14340: return %domain;
14341: }
14342:
1.327 albertel 14343: }
14344:
14345:
1.1 albertel 14346: # ------------------------------------------------------------- Read hosts file
14347: {
1.838 albertel 14348: my %hostname;
1.844 albertel 14349: my %hostdom;
1.845 albertel 14350: my %libserv;
1.852 albertel 14351: my $loaded;
1.888 albertel 14352: my %name_to_host;
1.1074 raeburn 14353: my %internetdom;
1.1107 raeburn 14354: my %LC_dns_serv;
1.852 albertel 14355:
14356: sub parse_hosts_tab {
14357: my ($file) = @_;
14358: foreach my $configline (@$file) {
14359: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 14360: chomp($configline);
14361: if ($configline =~ /^\^/) {
14362: if ($configline =~ /^\^([\w.\-]+)/) {
14363: $LC_dns_serv{$1} = 1;
14364: }
14365: next;
14366: }
1.1074 raeburn 14367: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 14368: $name=~s/\s//g;
14369: if ($id && $domain && $role && $name) {
1.1351 raeburn 14370: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14371: my $curr = $hostname{$id};
14372: my $skip;
14373: if (ref($name_to_host{$curr}) eq 'ARRAY') {
14374: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14375: $skip = 1;
14376: } else {
14377: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14378: }
14379: }
14380: unless ($skip) {
14381: push(@{$name_to_host{$name}},$id);
14382: }
14383: } else {
14384: push(@{$name_to_host{$name}},$id);
14385: }
1.852 albertel 14386: $hostname{$id}=$name;
14387: $hostdom{$id}=$domain;
14388: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 14389: if (defined($protocol)) {
14390: if ($protocol eq 'https') {
14391: $protocol{$id} = $protocol;
14392: } else {
14393: $protocol{$id} = 'http';
14394: }
1.968 raeburn 14395: } else {
1.969 raeburn 14396: $protocol{$id} = 'http';
1.968 raeburn 14397: }
1.1074 raeburn 14398: if (defined($intdom)) {
14399: $internetdom{$id} = $intdom;
14400: }
1.852 albertel 14401: }
14402: }
14403: }
1.864 albertel 14404:
14405: sub reset_hosts_info {
1.897 albertel 14406: &purge_remembered();
1.864 albertel 14407: &reset_domain_info();
14408: &reset_hosts_ip_info();
1.1339 raeburn 14409: undef(%internetdom);
1.892 albertel 14410: undef(%name_to_host);
1.864 albertel 14411: undef(%hostname);
14412: undef(%hostdom);
14413: undef(%libserv);
14414: undef($loaded);
14415: }
1.1 albertel 14416:
1.852 albertel 14417: sub load_hosts_tab {
1.1293 raeburn 14418: my ($ignore_cache,$nocache) = @_;
14419: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359 raeburn 14420: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 14421: my @config = <$config>;
14422: &parse_hosts_tab(\@config);
14423: close($config);
14424: $loaded=1;
1.1 albertel 14425: }
1.852 albertel 14426:
1.838 albertel 14427: sub hostname {
1.852 albertel 14428: &load_hosts_tab() if (!$loaded);
14429:
1.838 albertel 14430: my ($lonid) = @_;
14431: return $hostname{$lonid};
14432: }
1.845 albertel 14433:
1.838 albertel 14434: sub all_hostnames {
1.852 albertel 14435: &load_hosts_tab() if (!$loaded);
14436:
1.838 albertel 14437: return %hostname;
14438: }
1.845 albertel 14439:
1.888 albertel 14440: sub all_names {
1.1293 raeburn 14441: my ($ignore_cache,$nocache) = @_;
14442: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 14443:
14444: return %name_to_host;
14445: }
14446:
1.974 raeburn 14447: sub all_host_domain {
14448: &load_hosts_tab() if (!$loaded);
14449: return %hostdom;
14450: }
14451:
1.1339 raeburn 14452: sub all_host_intdom {
14453: &load_hosts_tab() if (!$loaded);
14454: return %internetdom;
14455: }
14456:
1.845 albertel 14457: sub is_library {
1.852 albertel 14458: &load_hosts_tab() if (!$loaded);
14459:
1.845 albertel 14460: return exists($libserv{$_[0]});
14461: }
14462:
14463: sub all_library {
1.852 albertel 14464: &load_hosts_tab() if (!$loaded);
14465:
1.845 albertel 14466: return %libserv;
14467: }
14468:
1.1062 droeschl 14469: sub unique_library {
14470: #2x reverse removes all hostnames that appear more than once
14471: my %unique = reverse &all_library();
14472: return reverse %unique;
14473: }
14474:
1.841 albertel 14475: sub get_servers {
1.852 albertel 14476: &load_hosts_tab() if (!$loaded);
14477:
1.841 albertel 14478: my ($domain,$type) = @_;
14479: my %possible_hosts = ($type eq 'library') ? %libserv
14480: : %hostname;
14481: my %result;
1.842 albertel 14482: if (ref($domain) eq 'ARRAY') {
14483: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 14484: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 14485: $result{$host} = $hostname;
14486: }
14487: }
14488: } else {
14489: while ( my ($host,$hostname) = each(%possible_hosts)) {
14490: if ($hostdom{$host} eq $domain) {
14491: $result{$host} = $hostname;
14492: }
1.841 albertel 14493: }
14494: }
14495: return %result;
14496: }
1.845 albertel 14497:
1.1062 droeschl 14498: sub get_unique_servers {
14499: my %unique = reverse &get_servers(@_);
14500: return reverse %unique;
14501: }
14502:
1.844 albertel 14503: sub host_domain {
1.852 albertel 14504: &load_hosts_tab() if (!$loaded);
14505:
1.844 albertel 14506: my ($lonid) = @_;
14507: return $hostdom{$lonid};
14508: }
14509:
1.841 albertel 14510: sub all_domains {
1.852 albertel 14511: &load_hosts_tab() if (!$loaded);
14512:
1.841 albertel 14513: my %seen;
14514: my @uniq = grep(!$seen{$_}++, values(%hostdom));
14515: return @uniq;
14516: }
1.1074 raeburn 14517:
14518: sub internet_dom {
14519: &load_hosts_tab() if (!$loaded);
14520:
14521: my ($lonid) = @_;
14522: return $internetdom{$lonid};
14523: }
1.1107 raeburn 14524:
14525: sub is_LC_dns {
14526: &load_hosts_tab() if (!$loaded);
14527:
14528: my ($hostname) = @_;
14529: return exists($LC_dns_serv{$hostname});
14530: }
14531:
1.1 albertel 14532: }
14533:
1.847 albertel 14534: {
14535: my %iphost;
1.856 albertel 14536: my %name_to_ip;
14537: my %lonid_to_ip;
1.869 albertel 14538:
1.847 albertel 14539: sub get_hosts_from_ip {
14540: my ($ip) = @_;
14541: my %iphosts = &get_iphost();
14542: if (ref($iphosts{$ip})) {
14543: return @{$iphosts{$ip}};
14544: }
14545: return;
1.839 albertel 14546: }
1.864 albertel 14547:
14548: sub reset_hosts_ip_info {
14549: undef(%iphost);
14550: undef(%name_to_ip);
14551: undef(%lonid_to_ip);
14552: }
1.856 albertel 14553:
14554: sub get_host_ip {
14555: my ($lonid) = @_;
14556: if (exists($lonid_to_ip{$lonid})) {
14557: return $lonid_to_ip{$lonid};
14558: }
14559: my $name=&hostname($lonid);
14560: my $ip = gethostbyname($name);
14561: return if (!$ip || length($ip) ne 4);
14562: $ip=inet_ntoa($ip);
14563: $name_to_ip{$name} = $ip;
14564: $lonid_to_ip{$lonid} = $ip;
14565: return $ip;
14566: }
1.847 albertel 14567:
14568: sub get_iphost {
1.1293 raeburn 14569: my ($ignore_cache,$nocache) = @_;
1.894 albertel 14570:
1.869 albertel 14571: if (!$ignore_cache) {
14572: if (%iphost) {
14573: return %iphost;
14574: }
14575: my ($ip_info,$cached)=
14576: &Apache::lonnet::is_cached_new('iphost','iphost');
14577: if ($cached) {
14578: %iphost = %{$ip_info->[0]};
14579: %name_to_ip = %{$ip_info->[1]};
14580: %lonid_to_ip = %{$ip_info->[2]};
14581: return %iphost;
14582: }
14583: }
1.894 albertel 14584:
14585: # get yesterday's info for fallback
14586: my %old_name_to_ip;
14587: my ($ip_info,$cached)=
14588: &Apache::lonnet::is_cached_new('iphost','iphost');
14589: if ($cached) {
14590: %old_name_to_ip = %{$ip_info->[1]};
14591: }
14592:
1.1293 raeburn 14593: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 14594: foreach my $name (keys(%name_to_host)) {
1.847 albertel 14595: my $ip;
14596: if (!exists($name_to_ip{$name})) {
14597: $ip = gethostbyname($name);
14598: if (!$ip || length($ip) ne 4) {
1.894 albertel 14599: if (defined($old_name_to_ip{$name})) {
14600: $ip = $old_name_to_ip{$name};
14601: &logthis("Can't find $name defaulting to old $ip");
14602: } else {
14603: &logthis("Name $name no IP found");
14604: next;
14605: }
14606: } else {
14607: $ip=inet_ntoa($ip);
1.847 albertel 14608: }
14609: $name_to_ip{$name} = $ip;
14610: } else {
14611: $ip = $name_to_ip{$name};
1.653 albertel 14612: }
1.888 albertel 14613: foreach my $id (@{ $name_to_host{$name} }) {
14614: $lonid_to_ip{$id} = $ip;
14615: }
14616: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 14617: }
1.1293 raeburn 14618: unless ($nocache) {
14619: &do_cache_new('iphost','iphost',
14620: [\%iphost,\%name_to_ip,\%lonid_to_ip],
14621: 48*60*60);
14622: }
1.869 albertel 14623:
1.847 albertel 14624: return %iphost;
1.598 albertel 14625: }
14626:
1.992 raeburn 14627: #
14628: # Given a DNS returns the loncapa host name for that DNS
14629: #
14630: sub host_from_dns {
14631: my ($dns) = @_;
14632: my @hosts;
14633: my $ip;
14634:
1.993 raeburn 14635: if (exists($name_to_ip{$dns})) {
1.992 raeburn 14636: $ip = $name_to_ip{$dns};
14637: }
14638: if (!$ip) {
14639: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14640: if (length($ip) == 4) {
14641: $ip = &IO::Socket::inet_ntoa($ip);
14642: }
14643: }
14644: if ($ip) {
14645: @hosts = get_hosts_from_ip($ip);
14646: return $hosts[0];
14647: }
14648: return undef;
1.986 foxr 14649: }
1.992 raeburn 14650:
1.1074 raeburn 14651: sub get_internet_names {
14652: my ($lonid) = @_;
14653: return if ($lonid eq '');
14654: my ($idnref,$cached)=
14655: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14656: if ($cached) {
14657: return $idnref;
14658: }
14659: my $ip = &get_host_ip($lonid);
14660: my @hosts = &get_hosts_from_ip($ip);
14661: my %iphost = &get_iphost();
14662: my (@idns,%seen);
14663: foreach my $id (@hosts) {
14664: my $dom = &host_domain($id);
14665: my $prim_id = &domain($dom,'primary');
14666: my $prim_ip = &get_host_ip($prim_id);
14667: next if ($seen{$prim_ip});
14668: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14669: foreach my $id (@{$iphost{$prim_ip}}) {
14670: my $intdom = &internet_dom($id);
14671: unless (grep(/^\Q$intdom\E$/,@idns)) {
14672: push(@idns,$intdom);
14673: }
14674: }
14675: }
14676: $seen{$prim_ip} = 1;
14677: }
1.1219 raeburn 14678: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 14679: }
14680:
1.986 foxr 14681: }
14682:
1.1079 raeburn 14683: sub all_loncaparevs {
1.1249 raeburn 14684: 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 14685: }
14686:
1.1227 raeburn 14687: # ---------------------------------------------------------- Read loncaparev table
14688: {
14689: sub load_loncaparevs {
14690: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359 raeburn 14691: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227 raeburn 14692: while (my $configline=<$config>) {
14693: chomp($configline);
14694: my ($hostid,$loncaparev)=split(/:/,$configline);
14695: $loncaparevs{$hostid}=$loncaparev;
14696: }
14697: close($config);
14698: }
14699: }
14700: }
14701: }
14702:
14703: # ---------------------------------------------------------- Read serverhostID table
14704: {
14705: sub load_serverhomeIDs {
14706: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359 raeburn 14707: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227 raeburn 14708: while (my $configline=<$config>) {
14709: chomp($configline);
14710: my ($name,$id)=split(/:/,$configline);
14711: $serverhomeIDs{$name}=$id;
14712: }
14713: close($config);
14714: }
14715: }
14716: }
14717: }
14718:
14719:
1.862 albertel 14720: BEGIN {
14721:
14722: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14723: unless ($readit) {
14724: {
14725: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14726: %perlvar = (%perlvar,%{$configvars});
14727: }
14728:
14729:
1.1 albertel 14730: # ------------------------------------------------------ Read spare server file
14731: {
1.1359 raeburn 14732: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 14733:
14734: while (my $configline=<$config>) {
14735: chomp($configline);
1.284 matthew 14736: if ($configline) {
1.784 albertel 14737: my ($host,$type) = split(':',$configline,2);
1.785 albertel 14738: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 14739: push(@{ $spareid{$type} }, $host);
1.1 albertel 14740: }
14741: }
1.448 albertel 14742: close($config);
1.1 albertel 14743: }
1.11 www 14744: # ------------------------------------------------------------ Read permissions
14745: {
1.1359 raeburn 14746: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 14747:
14748: while (my $configline=<$config>) {
1.448 albertel 14749: chomp($configline);
14750: if ($configline) {
14751: my ($role,$perm)=split(/ /,$configline);
14752: if ($perm ne '') { $pr{$role}=$perm; }
14753: }
1.11 www 14754: }
1.448 albertel 14755: close($config);
1.11 www 14756: }
14757:
14758: # -------------------------------------------- Read plain texts for permissions
14759: {
1.1359 raeburn 14760: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 14761:
14762: while (my $configline=<$config>) {
1.448 albertel 14763: chomp($configline);
14764: if ($configline) {
1.742 raeburn 14765: my ($short,@plain)=split(/:/,$configline);
14766: %{$prp{$short}} = ();
14767: if (@plain > 0) {
14768: $prp{$short}{'std'} = $plain[0];
14769: for (my $i=1; $i<@plain; $i++) {
14770: $prp{$short}{'alt'.$i} = $plain[$i];
14771: }
14772: }
1.448 albertel 14773: }
1.135 www 14774: }
1.448 albertel 14775: close($config);
1.135 www 14776: }
14777:
14778: # ---------------------------------------------------------- Read package table
14779: {
1.1359 raeburn 14780: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 14781:
14782: while (my $configline=<$config>) {
1.483 albertel 14783: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 14784: chomp($configline);
14785: my ($short,$plain)=split(/:/,$configline);
14786: my ($pack,$name)=split(/\&/,$short);
14787: if ($plain ne '') {
14788: $packagetab{$pack.'&'.$name.'&name'}=$name;
14789: $packagetab{$short}=$plain;
14790: }
1.11 www 14791: }
1.448 albertel 14792: close($config);
1.329 matthew 14793: }
14794:
1.1073 raeburn 14795: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 14796:
14797: &load_loncaparevs();
1.1073 raeburn 14798:
1.1074 raeburn 14799: # ---------------------------------------------------------- Read serverhostID table
14800:
1.1227 raeburn 14801: &load_serverhomeIDs();
14802:
14803: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 14804: {
14805: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14806: if (-e $file) {
14807: my $parser = HTML::LCParser->new($file);
14808: while (my $token = $parser->get_token()) {
14809: if ($token->[0] eq 'S') {
14810: my $item = $token->[1];
14811: my $name = $token->[2]{'name'};
14812: my $value = $token->[2]{'value'};
1.1285 raeburn 14813: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 14814: my $namematch = $token->[2]{'namematch'};
14815: if ($item eq 'parameter') {
14816: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14817: my $release = $parser->get_text();
14818: $release =~ s/(^\s*|\s*$ )//gx;
14819: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14820: }
14821: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 14822: my $release = $parser->get_text();
14823: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 14824: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 14825: }
14826: }
14827: }
14828: }
1.1073 raeburn 14829: }
14830:
1.1138 raeburn 14831: # ---------------------------------------------------------- Read managers table
14832: {
14833: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359 raeburn 14834: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 14835: while (my $configline=<$config>) {
14836: chomp($configline);
14837: next if ($configline =~ /^\#/);
14838: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14839: $managerstab{$configline} = 1;
14840: }
14841: }
14842: close($config);
14843: }
14844: }
14845: }
14846:
1.329 matthew 14847: # ------------- set up temporary directory
14848: {
1.1117 foxr 14849: $tmpdir = LONCAPA::tempdir();
1.329 matthew 14850:
1.11 www 14851: }
14852:
1.1405 raeburn 14853: # ------------- set default texengine (domain default overrides this)
14854: {
14855: $deftex = LONCAPA::texengine();
14856: }
14857:
1.794 albertel 14858: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14859: 'compress_threshold'=> 20_000,
14860: });
1.185 www 14861:
1.281 www 14862: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 14863: $dumpcount=0;
1.958 www 14864: $locknum=0;
1.22 www 14865:
1.163 harris41 14866: &logtouch();
1.672 albertel 14867: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 14868: $readit=1;
1.564 albertel 14869: {
14870: use integer;
14871: my $test=(2**32)+1;
1.568 albertel 14872: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 14873: &logthis(" Detected 64bit platform ($_64bit)");
14874: }
1.195 www 14875: }
1.1 albertel 14876: }
1.179 www 14877:
1.1 albertel 14878: 1;
1.191 harris41 14879: __END__
14880:
1.243 albertel 14881: =pod
14882:
1.191 harris41 14883: =head1 NAME
14884:
1.243 albertel 14885: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 14886:
14887: =head1 SYNOPSIS
14888:
1.243 albertel 14889: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 14890:
14891: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14892:
1.243 albertel 14893: Common parameters:
14894:
14895: =over 4
14896:
14897: =item *
14898:
14899: $uname : an internal username (if $cname expecting a course Id specifically)
14900:
14901: =item *
14902:
14903: $udom : a domain (if $cdom expecting a course's domain specifically)
14904:
14905: =item *
14906:
14907: $symb : a resource instance identifier
14908:
14909: =item *
14910:
14911: $namespace : the name of a .db file that contains the data needed or
14912: being set.
14913:
14914: =back
14915:
1.394 bowersj2 14916: =head1 OVERVIEW
1.191 harris41 14917:
1.394 bowersj2 14918: lonnet provides subroutines which interact with the
14919: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14920: about classes, users, and resources.
1.243 albertel 14921:
14922: For many of these objects you can also use this to store data about
14923: them or modify them in various ways.
1.191 harris41 14924:
1.394 bowersj2 14925: =head2 Symbs
1.191 harris41 14926:
1.394 bowersj2 14927: To identify a specific instance of a resource, LON-CAPA uses symbols
14928: or "symbs"X<symb>. These identifiers are built from the URL of the
14929: map, the resource number of the resource in the map, and the URL of
14930: the resource itself. The latter is somewhat redundant, but might help
14931: if maps change.
14932:
14933: An example is
14934:
14935: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14936:
14937: The respective map entry is
14938:
14939: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14940: title="Problem 2">
14941: </resource>
14942:
14943: Symbs are used by the random number generator, as well as to store and
14944: restore data specific to a certain instance of for example a problem.
14945:
14946: =head2 Storing And Retrieving Data
14947:
14948: X<store()>X<cstore()>X<restore()>Three of the most important functions
14949: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14950: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14951: is is the non-critical message twin of cstore. These functions are for
14952: handlers to store a perl hash to a user's permanent data space in an
14953: easy manner, and to retrieve it again on another call. It is expected
14954: that a handler would use this once at the beginning to retrieve data,
14955: and then again once at the end to send only the new data back.
14956:
14957: The data is stored in the user's data directory on the user's
14958: homeserver under the ID of the course.
14959:
14960: The hash that is returned by restore will have all of the previous
14961: value for all of the elements of the hash.
14962:
14963: Example:
14964:
14965: #creating a hash
14966: my %hash;
14967: $hash{'foo'}='bar';
14968:
14969: #storing it
14970: &Apache::lonnet::cstore(\%hash);
14971:
14972: #changing a value
14973: $hash{'foo'}='notbar';
14974:
14975: #adding a new value
14976: $hash{'bar'}='foo';
14977: &Apache::lonnet::cstore(\%hash);
14978:
14979: #retrieving the hash
14980: my %history=&Apache::lonnet::restore();
14981:
14982: #print the hash
14983: foreach my $key (sort(keys(%history))) {
14984: print("\%history{$key} = $history{$key}");
14985: }
14986:
14987: Will print out:
1.191 harris41 14988:
1.394 bowersj2 14989: %history{1:foo} = bar
14990: %history{1:keys} = foo:timestamp
14991: %history{1:timestamp} = 990455579
14992: %history{2:bar} = foo
14993: %history{2:foo} = notbar
14994: %history{2:keys} = foo:bar:timestamp
14995: %history{2:timestamp} = 990455580
14996: %history{bar} = foo
14997: %history{foo} = notbar
14998: %history{timestamp} = 990455580
14999: %history{version} = 2
15000:
15001: Note that the special hash entries C<keys>, C<version> and
15002: C<timestamp> were added to the hash. C<version> will be equal to the
15003: total number of versions of the data that have been stored. The
15004: C<timestamp> attribute will be the UNIX time the hash was
15005: stored. C<keys> is available in every historical section to list which
15006: keys were added or changed at a specific historical revision of a
15007: hash.
15008:
15009: B<Warning>: do not store the hash that restore returns directly. This
15010: will cause a mess since it will restore the historical keys as if the
15011: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 15012:
1.394 bowersj2 15013: Calling convention:
1.191 harris41 15014:
1.1225 raeburn 15015: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 15016: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 15017:
1.394 bowersj2 15018: For more detailed information, see lonnet specific documentation.
1.191 harris41 15019:
1.394 bowersj2 15020: =head1 RETURN MESSAGES
1.191 harris41 15021:
1.394 bowersj2 15022: =over 4
1.191 harris41 15023:
1.394 bowersj2 15024: =item * B<con_lost>: unable to contact remote host
1.191 harris41 15025:
1.394 bowersj2 15026: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15027: when the connection is brought back up
1.191 harris41 15028:
1.394 bowersj2 15029: =item * B<con_failed>: unable to contact remote host and unable to save message
15030: for later delivery
1.191 harris41 15031:
1.967 bisitz 15032: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 15033:
1.394 bowersj2 15034: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 15035: that was requested
1.191 harris41 15036:
1.243 albertel 15037: =back
1.191 harris41 15038:
1.243 albertel 15039: =head1 PUBLIC SUBROUTINES
1.191 harris41 15040:
1.243 albertel 15041: =head2 Session Environment Functions
1.191 harris41 15042:
1.243 albertel 15043: =over 4
1.191 harris41 15044:
1.394 bowersj2 15045: =item *
15046: X<appenv()>
1.949 raeburn 15047: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 15048: the user envirnoment file, and will be restored for each access this
1.620 albertel 15049: user makes during this session, also modifies the %env for the current
1.949 raeburn 15050: process. Optional rolesarrayref - if defined contains a reference to an array
15051: of roles which are exempt from the restriction on modifying user.role entries
15052: in the user's environment.db and in %env.
1.191 harris41 15053:
15054: =item *
1.394 bowersj2 15055: X<delenv()>
1.987 raeburn 15056: B<delenv($delthis,$regexp)>: removes all items from the session
15057: environment file that begin with $delthis. If the
15058: optional second arg - $regexp - is true, $delthis is treated as a
15059: regular expression, otherwise \Q$delthis\E is used.
15060: The values are also deleted from the current processes %env.
1.191 harris41 15061:
1.795 albertel 15062: =item * get_env_multiple($name)
15063:
15064: gets $name from the %env hash, it seemlessly handles the cases where multiple
15065: values may be defined and end up as an array ref.
15066:
15067: returns an array of values
15068:
1.243 albertel 15069: =back
15070:
15071: =head2 User Information
1.191 harris41 15072:
1.243 albertel 15073: =over 4
1.191 harris41 15074:
15075: =item *
1.394 bowersj2 15076: X<queryauthenticate()>
15077: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 15078: authentication scheme
15079:
15080: =item *
1.394 bowersj2 15081: X<authenticate()>
1.1073 raeburn 15082: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 15083: authenticate user from domain's lib servers (first use the current
15084: one). C<$upass> should be the users password.
1.1073 raeburn 15085: $checkdefauth is optional (value is 1 if a check should be made to
15086: authenticate user using default authentication method, and allow
15087: account creation if username does not have account in the domain).
15088: $clientcancheckhost is optional (value is 1 if checking whether the
15089: server can host will occur on the client side in lonauth.pm).
1.191 harris41 15090:
15091: =item *
1.394 bowersj2 15092: X<homeserver()>
15093: B<homeserver($uname,$udom)>: find the server which has
15094: the user's directory and files (there must be only one), this caches
15095: the answer, and also caches if there is a borken connection.
1.191 harris41 15096:
15097: =item *
1.394 bowersj2 15098: X<idget()>
1.1300 raeburn 15099: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
15100: a list of student/employee IDs or clicker IDs
15101: (student/employee IDs are a unique resource in a domain, there must be
15102: only 1 ID per username, and only 1 username per ID in a specific domain).
15103: clickerIDs are not necessarily unique, as students might share clickers.
15104: (returns hash: id=>name,id=>name)
1.191 harris41 15105:
15106: =item *
1.394 bowersj2 15107: X<idrget()>
15108: B<idrget($udom,@unames)>: find the IDs behind a list of
15109: usernames (returns hash: name=>id,name=>id)
1.191 harris41 15110:
15111: =item *
1.394 bowersj2 15112: X<idput()>
1.1300 raeburn 15113: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
15114: names and associated student/employee IDs or clicker IDs.
15115:
15116: =item *
15117: X<iddel()>
15118: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
15119: student/employee ID or clicker ID username look-ups from domain.
15120: The homeserver ($uhome) and namespace ($namespace) are optional.
15121: If no $uhome is provided, it will be determined usig &homeserver()
15122: for each user. If no $namespace is provided, the default is ids.
15123:
15124: =item *
15125: X<updateclickers()>
15126: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
15127: clicker ID-to-username look-ups in clickers.db on library server.
15128: Permitted actions are add or del (i.e., add or delete). The
15129: clickers.db contains clickerID as keys (escaped), and each corresponding
15130: value is an escaped comma-separated list of usernames (for whom the
15131: library server is the homeserver), who registered that particular ID.
15132: If $critical is true, the update will be sent via &critical, otherwise
15133: &reply() will be used.
1.191 harris41 15134:
15135: =item *
1.394 bowersj2 15136: X<rolesinit()>
1.1169 droeschl 15137: B<rolesinit($udom,$username)>: get user privileges.
15138: returns user role, first access and timer interval hashes
1.243 albertel 15139:
15140: =item *
1.1171 droeschl 15141: X<privileged()>
15142: B<privileged($username,$domain)>: returns a true if user has a
15143: privileged and active role (i.e. su or dc), false otherwise.
15144:
15145: =item *
1.551 albertel 15146: X<getsection()>
15147: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 15148: course $cname, return section name/number or '' for "not in course"
15149: and '-1' for "no section"
15150:
15151: =item *
1.394 bowersj2 15152: X<userenvironment()>
15153: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 15154: passed in @what from the requested user's environment, returns a hash
15155:
1.858 raeburn 15156: =item *
15157: X<userlog_query()>
1.859 albertel 15158: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15159: activity.log file. %filters defines filters applied when parsing the
15160: log file. These can be start or end timestamps, or the type of action
15161: - log to look for Login or Logout events, check for Checkin or
15162: Checkout, role for role selection. The response is in the form
15163: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
15164: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 15165:
1.243 albertel 15166: =back
15167:
15168: =head2 User Roles
15169:
15170: =over 4
15171:
15172: =item *
15173:
1.1284 raeburn 15174: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
15175: returns codes for allowed actions.
15176:
15177: The first argument is required, all others are optional.
15178:
15179: $priv is the privilege being checked.
15180: $uri contains additional information about what is being checked for access (e.g.,
15181: URL, course ID etc.).
15182: $symb is the unique resource instance identifier in a course; if needed,
15183: but not provided, it will be retrieved via a call to &symbread().
15184: $role is the role for which a priv is being checked (only used if priv is evb).
15185: $clientip is the user's IP address (only used when checking for access to portfolio
15186: files).
15187: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
15188: prevents recursive calls to &allowed.
15189:
1.243 albertel 15190: F: full access
15191: U,I,K: authentication modes (cxx only)
15192: '': forbidden
15193: 1: user needs to choose course
15194: 2: browse allowed
1.766 albertel 15195: A: passphrase authentication needed
1.1284 raeburn 15196: B: access temporarily blocked because of a blocking event in a course.
1.1402 raeburn 15197: D: access blocked because access is required via session initiated via deep-link
1.243 albertel 15198:
15199: =item *
15200:
1.1192 raeburn 15201: constructaccess($url,$setpriv) : check for access to construction space URL
15202:
15203: See if the owner domain and name in the URL match those in the
15204: expected environment. If so, return three element list
15205: ($ownername,$ownerdomain,$ownerhome).
15206:
15207: Otherwise return the null string.
15208:
15209: If second argument 'setpriv' is true, it assigns the privileges,
15210: and returns the same three element list, unless the owner has
15211: blocked "ad hoc" Domain Coordinator access to the Author Space,
15212: in which case the null string is returned.
15213:
15214: =item *
15215:
1.1326 raeburn 15216: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15217: define a custom role rolename set privileges in format of lonTabs/roles.tab
15218: for system, domain, and course level. $uname and $udom are optional (current
15219: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 15220:
15221: =item *
15222:
1.988 raeburn 15223: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
15224: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 15225: $type is Course (default) or Community.
1.988 raeburn 15226: If $forcedefault evaluates to true, text returned will be default
15227: text for $type. Otherwise, if this is a course, the text returned
15228: will be a custom name for the role (if defined in the course's
15229: environment). If no custom name is defined the default is returned.
15230:
1.832 raeburn 15231: =item *
15232:
1.1219 raeburn 15233: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 15234: All arguments are optional. Returns a hash of a roles, either for
15235: co-author/assistant author roles for a user's Construction Space
1.906 albertel 15236: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 15237: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15238: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15239: For each key, value is set to colon-separated start and end times for
15240: the role. If no username and domain are specified, will default to
1.934 raeburn 15241: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 15242: of role statuses (active, future or previous), roles
15243: (e.g., cc,in, st etc.) and domains of the roles which can be used
15244: to restrict the list of roles reported. If no array ref is
15245: provided for types, will default to return only active roles.
1.834 albertel 15246:
1.1195 raeburn 15247: =item *
15248:
15249: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 15250: user: $uname:$udom has a role in the course: $cdom_$cnum.
15251:
15252: Additional optional arguments are: $type (if role checking is to be restricted
15253: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 15254: available roles) or future (roles available in the future), and
15255: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 15256: have active Domain Coordinator role in course's domain or in additional
15257: domains (specified in 'Domains to check for privileged users' in course
15258: environment -- set via: Course Settings -> Classlists and staff listing).
15259:
15260: =item *
15261:
15262: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15263: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15264: $possdomains and $possroles are optional array refs -- to domains to check and
15265: roles to check. If $possdomains is not specified, a dump will be done of the
15266: users' roles.db to check for a dc or su role in any domain. This can be
15267: time consuming if &privileged is called repeatedly (e.g., when displaying a
15268: classlist), so in such cases, supplying a $possdomains array is preferred, as
15269: this then allows &privileged_by_domain() to be used, which caches the identity
15270: of privileged users, eliminating the need for repeated calls to &dump().
15271:
15272: =item *
15273:
15274: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15275: where the outer hash keys are domains specified in the $possdomains array ref,
15276: next inner hash keys are privileged roles specified in the $roles array ref,
15277: and the innermost hash contains key = value pairs for username:domain = end:start
15278: for active or future "privileged" users with that role in that domain. To avoid
15279: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15280: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 15281:
1.243 albertel 15282: =back
15283:
15284: =head2 User Modification
15285:
15286: =over 4
15287:
15288: =item *
15289:
1.957 raeburn 15290: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 15291: user for the level given by URL. Optional start and end dates (leave empty
15292: string or zero for "no date")
1.191 harris41 15293:
15294: =item *
15295:
1.243 albertel 15296: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15297: change a users, password, possible return values are: ok,
15298: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15299: refused
1.191 harris41 15300:
15301: =item *
15302:
1.243 albertel 15303: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 15304:
15305: =item *
15306:
1.1058 raeburn 15307: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15308: $forceid,$desiredhome,$email,$inststatus,$candelete) :
15309:
15310: will update user information (firstname,middlename,lastname,generation,
15311: permanentemail), and if forceid is true, student/employee ID also.
15312: A user's institutional affiliation(s) can also be updated.
15313: User information fields will not be overwritten with empty entries
15314: unless the field is included in the $candelete array reference.
15315: This array is included when a single user is modified via "Manage Users",
15316: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 15317:
15318: =item *
15319:
1.286 matthew 15320: modifystudent
15321:
1.957 raeburn 15322: modify a student's enrollment and identification information.
1.1235 raeburn 15323: The course id is resolved based on the current user's environment.
15324: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 15325: associated with a course.
15326:
1.297 matthew 15327: This call is essentially a wrapper for lonnet::modifyuser and
15328: lonnet::modify_student_enrollment
1.286 matthew 15329:
15330: Inputs:
15331:
15332: =over 4
15333:
1.957 raeburn 15334: =item B<$udom> Student's loncapa domain
1.286 matthew 15335:
1.957 raeburn 15336: =item B<$uname> Student's loncapa login name
1.286 matthew 15337:
1.964 bisitz 15338: =item B<$uid> Student/Employee ID
1.286 matthew 15339:
1.957 raeburn 15340: =item B<$umode> Student's authentication mode
1.286 matthew 15341:
1.957 raeburn 15342: =item B<$upass> Student's password
1.286 matthew 15343:
1.957 raeburn 15344: =item B<$first> Student's first name
1.286 matthew 15345:
1.957 raeburn 15346: =item B<$middle> Student's middle name
1.286 matthew 15347:
1.957 raeburn 15348: =item B<$last> Student's last name
1.286 matthew 15349:
1.957 raeburn 15350: =item B<$gene> Student's generation
1.286 matthew 15351:
1.957 raeburn 15352: =item B<$usec> Student's section in course
1.286 matthew 15353:
15354: =item B<$end> Unix time of the roles expiration
15355:
15356: =item B<$start> Unix time of the roles start date
15357:
15358: =item B<$forceid> If defined, allow $uid to be changed
15359:
15360: =item B<$desiredhome> server to use as home server for student
15361:
1.957 raeburn 15362: =item B<$email> Student's permanent e-mail address
15363:
15364: =item B<$type> Type of enrollment (auto or manual)
15365:
1.963 raeburn 15366: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
15367:
15368: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 15369:
1.963 raeburn 15370: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 15371:
1.963 raeburn 15372: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 15373:
1.1216 raeburn 15374: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15375:
15376: =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 15377:
1.286 matthew 15378: =back
1.297 matthew 15379:
15380: =item *
15381:
15382: modify_student_enrollment
15383:
1.1235 raeburn 15384: Change a student's enrollment status in a class. The environment variable
1.297 matthew 15385: 'role.request.course' must be defined for this function to proceed.
15386:
15387: Inputs:
15388:
15389: =over 4
15390:
1.1235 raeburn 15391: =item $udom, student's domain
1.297 matthew 15392:
1.1235 raeburn 15393: =item $uname, student's name
1.297 matthew 15394:
1.1235 raeburn 15395: =item $uid, student's user id
1.297 matthew 15396:
1.1235 raeburn 15397: =item $first, student's first name
1.297 matthew 15398:
15399: =item $middle
15400:
15401: =item $last
15402:
15403: =item $gene
15404:
15405: =item $usec
15406:
15407: =item $end
15408:
15409: =item $start
15410:
1.957 raeburn 15411: =item $type
15412:
15413: =item $locktype
15414:
15415: =item $cid
15416:
15417: =item $selfenroll
15418:
15419: =item $context
15420:
1.1216 raeburn 15421: =item $credits, number of credits student will earn from this class
15422:
1.1314 raeburn 15423: =item $instsec, institutional course section code for student
15424:
1.297 matthew 15425: =back
15426:
1.191 harris41 15427:
15428: =item *
15429:
1.243 albertel 15430: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15431: custom role; give a custom role to a user for the level given by URL. Specify
15432: name and domain of role author, and role name
1.191 harris41 15433:
15434: =item *
15435:
1.243 albertel 15436: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 15437:
15438: =item *
15439:
1.243 albertel 15440: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15441:
15442: =back
15443:
15444: =head2 Course Infomation
15445:
15446: =over 4
1.191 harris41 15447:
15448: =item *
15449:
1.1118 foxr 15450: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 15451: specified course id, including all environment settings for the
15452: course, the description of the course will be in the hash under the
15453: key 'description'
1.191 harris41 15454:
1.1118 foxr 15455: $options is an optional parameter that if supplied is a hash reference that controls
15456: what how this function works. It has the following key/values:
15457:
15458: =over 4
15459:
15460: =item freshen_cache
15461:
15462: If defined, and the environment cache for the course is valid, it is
15463: returned in the returned hash.
15464:
15465: =item one_time
15466:
15467: If defined, the last cache time is set to _now_
15468:
15469: =item user
15470:
15471: If defined, the supplied username is used instead of the current user.
15472:
15473:
15474: =back
15475:
1.191 harris41 15476: =item *
15477:
1.624 albertel 15478: resdata($name,$domain,$type,@which) : request for current parameter
15479: setting for a specific $type, where $type is either 'course' or 'user',
15480: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 15481: answers for 10 minutes.
1.243 albertel 15482:
1.877 foxr 15483: =item *
15484:
15485: get_courseresdata($courseid, $domain) : dump the entire course resource
15486: data base, returning a hash that is keyed by the resource name and has
15487: values that are the resource value. I believe that the timestamps and
15488: versions are also returned.
15489:
1.1236 raeburn 15490: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15491: supplemental content area. This routine caches the number of files for
15492: 10 minutes.
15493:
1.243 albertel 15494: =back
15495:
15496: =head2 Course Modification
15497:
15498: =over 4
1.191 harris41 15499:
15500: =item *
15501:
1.243 albertel 15502: writecoursepref($courseid,%prefs) : write preferences (environment
15503: database) for a course
1.191 harris41 15504:
15505: =item *
15506:
1.1011 raeburn 15507: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15508:
15509: =item *
15510:
1.1038 raeburn 15511: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 15512:
1.1167 droeschl 15513: =item *
15514:
15515: is_course($courseid), is_course($cdom, $cnum)
15516:
15517: Accepts either a combined $courseid (in the form of domain_courseid) or the
15518: two component version $cdom, $cnum. It checks if the specified course exists.
15519:
15520: Returns:
15521: undef if the course doesn't exist, otherwise
15522: in scalar context the combined courseid.
15523: in list context the two components of the course identifier, domain and
15524: courseid.
15525:
1.243 albertel 15526: =back
15527:
1.1401 raeburn 15528: =head2 Bubblesheet Configuration
15529:
15530: =over 4
15531:
15532: =item *
15533:
15534: get_scantron_config($which)
15535:
15536: $which - the name of the configuration to parse from the file.
15537:
15538: Parses and returns the bubblesheet configuration line selected as a
15539: hash of configuration file fields.
15540:
15541:
15542: Returns:
15543: If the named configuration is not in the file, an empty
15544: hash is returned.
15545:
15546: a hash with the fields
15547: name - internal name for the this configuration setup
15548: description - text to display to operator that describes this config
15549: CODElocation - if 0 or the string 'none'
15550: - no CODE exists for this config
15551: if -1 || the string 'letter'
15552: - a CODE exists for this config and is
15553: a string of letters
15554: Unsupported value (but planned for future support)
15555: if a positive integer
15556: - The CODE exists as the first n items from
15557: the question section of the form
15558: if the string 'number'
15559: - The CODE exists for this config and is
15560: a string of numbers
15561: CODEstart - (only matter if a CODE exists) column in the line where
15562: the CODE starts
15563: CODElength - length of the CODE
15564: IDstart - column where the student/employee ID starts
15565: IDlength - length of the student/employee ID info
15566: Qstart - column where the information from the bubbled
15567: 'questions' start
15568: Qlength - number of columns comprising a single bubble line from
15569: the sheet. (usually either 1 or 10)
15570: Qon - either a single character representing the character used
15571: to signal a bubble was chosen in the positional setup, or
15572: the string 'letter' if the letter of the chosen bubble is
15573: in the final, or 'number' if a number representing the
15574: chosen bubble is in the file (1->A 0->J)
15575: Qoff - the character used to represent that a bubble was
15576: left blank
15577: PaperID - if the scanning process generates a unique number for each
15578: sheet scanned the column that this ID number starts in
15579: PaperIDlength - number of columns that comprise the unique ID number
15580: for the sheet of paper
15581: FirstName - column that the first name starts in
15582: FirstNameLength - number of columns that the first name spans
15583: LastName - column that the last name starts in
15584: LastNameLength - number of columns that the last name spans
15585: BubblesPerRow - number of bubbles available in each row used to
15586: bubble an answer. (If not specified, 10 assumed).
15587:
15588:
15589: =item *
15590:
15591: get_scantronformat_file($cdom)
15592:
15593: $cdom - the course's domain (optional); if not supplied, uses
15594: domain for current $env{'request.course.id'}.
15595:
15596: Returns an array containing lines from the scantron format file for
15597: the domain of the course.
15598:
15599: If a url for a custom.tab file is listed in domain's configuration.db,
15600: lines are from this file.
15601:
15602: Otherwise, if a default.tab has been published in RES space by the
15603: domainconfig user, lines are from this file.
15604:
15605: Otherwise, fall back to getting lines from the legacy file on the
15606: local server: /home/httpd/lonTabs/default_scantronformat.tab
15607:
15608: =back
15609:
1.243 albertel 15610: =head2 Resource Subroutines
15611:
15612: =over 4
1.191 harris41 15613:
15614: =item *
15615:
1.243 albertel 15616: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 15617:
15618: =item *
15619:
1.243 albertel 15620: repcopy($filename) : subscribes to the requested file, and attempts to
15621: replicate from the owning library server, Might return
1.607 raeburn 15622: 'unavailable', 'not_found', 'forbidden', 'ok', or
15623: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 15624: resource. Expects the local filesystem pathname
15625: (/home/httpd/html/res/....)
15626:
15627: =back
15628:
15629: =head2 Resource Information
15630:
15631: =over 4
1.191 harris41 15632:
15633: =item *
15634:
1.1228 raeburn 15635: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
15636: and returns the value of a variety of different possible values,
15637: $varname should be a request string, and the other parameters can be
15638: used to specify who and what one is asking about. Ordinarily, $cid
15639: does not need to be specified, as it is retrived from
15640: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15641: within lonuserstate::loadmap() when initializing a course, before
15642: $env{'request.course.id'} has been set, so it needs to be provided
15643: in that one case.
1.243 albertel 15644:
15645: Possible values for $varname are environment.lastname (or other item
15646: from the envirnment hash), user.name (or someother aspect about the
15647: user), resource.0.maxtries (or some other part and parameter of a
15648: resource)
1.204 albertel 15649:
15650: =item *
15651:
1.243 albertel 15652: directcondval($number) : get current value of a condition; reads from a state
15653: string
1.204 albertel 15654:
15655: =item *
15656:
1.243 albertel 15657: condval($condidx) : value of condition index based on state
1.204 albertel 15658:
15659: =item *
15660:
1.1362 raeburn 15661: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243 albertel 15662: resource's metadata, $what should be either a specific key, or either
15663: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362 raeburn 15664: packages that this resource currently uses, the last 3 arguments are
15665: only used internally for recursive metadata.
15666:
15667: the toolsymb is only used where the uri is for an external tool (for which
15668: the uri as well as the symb are guaranteed to be unique).
1.243 albertel 15669:
1.1371 raeburn 15670: this function automatically caches all requests except any made recursively
15671: to retrieve a list of metadata keys for an imported library file ($liburi is
15672: defined).
1.191 harris41 15673:
15674: =item *
15675:
1.243 albertel 15676: metadata_query($query,$custom,$customshow) : make a metadata query against the
15677: network of library servers; returns file handle of where SQL and regex results
15678: will be stored for query
1.191 harris41 15679:
15680: =item *
15681:
1.1282 raeburn 15682: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15683: return symbolic list entry (all arguments optional).
15684:
15685: Args: filename is the filename (including path) for the file for which a symb
15686: is required; donotrecurse, if true will prevent calls to allowed() being made
15687: to check access status if more than one resource was found in the bighash
15688: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15689: a randompick); ignorecachednull, if true will prevent a symb of '' being
15690: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15691: cause possible symbs to be checked to determine if they are subject to content
15692: blocking, if so they will not be included as possible symbs; possibles is a
15693: ref to a hash, which, as a side effect, will be populated with all possible
15694: symbs (content blocking not tested).
15695:
1.243 albertel 15696: returns the data handle
1.191 harris41 15697:
15698: =item *
15699:
1.1190 raeburn 15700: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15701: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 15702: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 15703: on failure, user must be in a course, as it assumes the existence of
15704: the course initial hash, and uses $env('request.course.id'}. The third
15705: arg is an optional reference to a scalar. If this arg is passed in the
15706: call to symbverify, it will be set to 1 if the symb has been set to be
15707: encrypted; otherwise it will be null.
1.191 harris41 15708:
15709: =item *
15710:
1.243 albertel 15711: symbclean($symb) : removes versions numbers from a symb, returns the
15712: cleaned symb
1.191 harris41 15713:
15714: =item *
15715:
1.243 albertel 15716: is_on_map($uri) : checks if the $uri is somewhere on the current
15717: course map, user must be in a course for it to work.
1.191 harris41 15718:
15719: =item *
15720:
1.243 albertel 15721: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 15722:
15723: =item *
15724:
1.243 albertel 15725: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15726: a random seed, all arguments are optional, if they aren't sent it uses the
15727: environment to derive them. Note: if symb isn't sent and it can't get one
15728: from &symbread it will use the current time as its return value
1.191 harris41 15729:
15730: =item *
15731:
1.243 albertel 15732: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15733: unfakeable, receipt
1.191 harris41 15734:
15735: =item *
15736:
1.620 albertel 15737: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 15738:
15739: =item *
15740:
1.243 albertel 15741: countacc($url) : count the number of accesses to a given URL
1.191 harris41 15742:
15743: =item *
15744:
1.243 albertel 15745: 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 15746:
15747: =item *
15748:
1.243 albertel 15749: 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 15750:
15751: =item *
15752:
1.243 albertel 15753: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 15754:
15755: =item *
15756:
1.243 albertel 15757: devalidate($symb) : devalidate temporary spreadsheet calculations,
15758: forcing spreadsheet to reevaluate the resource scores next time.
15759:
1.1195 raeburn 15760: =item *
15761:
1.1196 raeburn 15762: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15763: when viewing in course context.
1.1195 raeburn 15764:
1.1196 raeburn 15765: input: six args -- filename (decluttered), course number, course domain,
15766: url, symb (if registered) and group (if this is a
15767: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 15768:
1.1196 raeburn 15769: output: array of five scalars --
1.1195 raeburn 15770: $cfile -- url for file editing if editable on current server
15771: $home -- homeserver of resource (i.e., for author if published,
15772: or course if uploaded.).
15773: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 15774: $forceedit -- 1 if icon/link should be to go to edit mode
15775: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 15776:
15777: =item *
15778:
15779: is_course_upload($file,$cnum,$cdom)
15780:
15781: Used in course context to determine if current file was uploaded to
15782: the course (i.e., would be found in /userfiles/docs on the course's
15783: homeserver.
15784:
15785: input: 3 args -- filename (decluttered), course number and course domain.
15786: output: boolean -- 1 if file was uploaded.
15787:
1.243 albertel 15788: =back
15789:
15790: =head2 Storing/Retreiving Data
15791:
15792: =over 4
1.191 harris41 15793:
15794: =item *
15795:
1.1269 raeburn 15796: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15797: permanently for this url; hashref needs to be given and should be a \%hashname;
15798: the remaining args aren't required and if they aren't passed or are '' they will
15799: be derived from the env (with the exception of $laststore, which is an
15800: optional arg used when a user's submission is stored in grading).
15801: $laststore is $version=$timestamp, where $version is the most recent version
15802: number retrieved for the corresponding $symb in the $namespace db file, and
15803: $timestamp is the timestamp for that transaction (UNIX time).
15804: $laststore is currently only passed when cstore() is called by
15805: structuretags::finalize_storage().
1.191 harris41 15806:
15807: =item *
15808:
1.1269 raeburn 15809: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15810: but uses critical subroutine
1.191 harris41 15811:
15812: =item *
15813:
1.243 albertel 15814: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15815: all args are optional
1.191 harris41 15816:
15817: =item *
15818:
1.717 albertel 15819: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15820: dumps the complete (or key matching regexp) namespace into a hash
15821: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15822: normally &store()ed into
15823:
15824: $range should be either an integer '100' (give me the first 100
15825: matching records)
15826: or be two integers sperated by a - with no spaces
15827: '30-50' (give me the 30th through the 50th matching
15828: records)
15829:
15830:
15831: =item *
15832:
1.1269 raeburn 15833: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 15834: replaces a &store() version of data with a replacement set of data
15835: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 15836: reference. If $tolog is true, the transaction is logged in the courselog
15837: with an action=PUTSTORE.
1.717 albertel 15838:
15839: =item *
15840:
1.243 albertel 15841: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15842: works very similar to store/cstore, but all data is stored in a
15843: temporary location and can be reset using tmpreset, $storehash should
15844: be a hash reference, returns nothing on success
1.191 harris41 15845:
15846: =item *
15847:
1.243 albertel 15848: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15849: similar to restore, but all data is stored in a temporary location and
15850: can be reset using tmpreset. Returns a hash of values on success,
15851: error string otherwise.
1.191 harris41 15852:
15853: =item *
15854:
1.243 albertel 15855: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15856: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 15857:
15858: =item *
15859:
1.243 albertel 15860: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15861: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 15862:
15863: =item *
15864:
1.243 albertel 15865: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15866: namesp ($udom and $uname are optional)
1.191 harris41 15867:
15868: =item *
15869:
1.702 albertel 15870: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 15871: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 15872: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 15873:
1.702 albertel 15874: $range should be either an integer '100' (give me the first 100
15875: matching records)
15876: or be two integers sperated by a - with no spaces
15877: '30-50' (give me the 30th through the 50th matching
15878: records)
1.449 matthew 15879: =item *
15880:
15881: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15882: $store can be a scalar, an array reference, or if the amount to be
15883: incremented is > 1, a hash reference.
15884:
15885: ($udom and $uname are optional)
1.191 harris41 15886:
15887: =item *
15888:
1.243 albertel 15889: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15890: ($udom and $uname are optional)
1.191 harris41 15891:
15892: =item *
15893:
1.243 albertel 15894: cput($namespace,$storehash,$udom,$uname) : critical put
15895: ($udom and $uname are optional)
1.191 harris41 15896:
15897: =item *
15898:
1.748 albertel 15899: newput($namespace,$storehash,$udom,$uname) :
15900:
15901: Attempts to store the items in the $storehash, but only if they don't
15902: currently exist, if this succeeds you can be certain that you have
15903: successfully created a new key value pair in the $namespace db.
15904:
15905:
15906: Args:
15907: $namespace: name of database to store values to
15908: $storehash: hashref to store to the db
15909: $udom: (optional) domain of user containing the db
15910: $uname: (optional) name of user caontaining the db
15911:
15912: Returns:
15913: 'ok' -> succeeded in storing all keys of $storehash
15914: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15915: least <key> already existed in the db (other
15916: requested keys may also already exist)
1.967 bisitz 15917: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 15918: 'con_lost' -> unable to contact request server
15919: 'refused' -> action was not allowed by remote machine
15920:
15921:
15922: =item *
15923:
1.243 albertel 15924: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15925: reference filled in from namesp (encrypts the return communication)
15926: ($udom and $uname are optional)
1.191 harris41 15927:
15928: =item *
15929:
1.243 albertel 15930: log($udom,$name,$home,$message) : write to permanent log for user; use
15931: critical subroutine
15932:
1.806 raeburn 15933: =item *
15934:
1.860 raeburn 15935: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15936: array reference filled in from namespace found in domain level on either
15937: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 15938:
15939: =item *
15940:
1.860 raeburn 15941: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15942: domain level either on specified domain server ($uhome) or primary domain
15943: server ($udom and $uhome are optional)
1.806 raeburn 15944:
1.943 raeburn 15945: =item *
15946:
1.1240 raeburn 15947: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15948: for: authentication, language, quotas, timezone, date locale, and portal URL in
15949: the target domain.
15950:
15951: May also include additional key => value pairs for the following groups:
15952:
15953: =over
15954:
15955: =item
15956: disk quotas (MB allocated by default to portfolios and authoring spaces).
15957:
15958: =over
15959:
15960: =item defaultquota, authorquota
15961:
15962: =back
15963:
15964: =item
15965: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15966: portfolio for users).
15967:
15968: =over
15969:
15970: =item
15971: aboutme, blog, webdav, portfolio
15972:
15973: =back
15974:
15975: =item
15976: requestcourses: ability to request courses, and how requests are processed.
15977:
15978: =over
15979:
15980: =item
1.1305 raeburn 15981: official, unofficial, community, textbook, placement
1.1240 raeburn 15982:
15983: =back
15984:
15985: =item
15986: inststatus: types of institutional affiliation, and order in which they are displayed.
15987:
15988: =over
15989:
15990: =item
1.1256 raeburn 15991: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 15992:
15993: =back
15994:
15995: =item
15996: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15997: for course's uploaded content.
15998:
15999: =over
16000:
16001: =item
1.1246 raeburn 16002: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 16003: communityquota, textbookquota, placementquota
1.1240 raeburn 16004:
16005: =back
16006:
16007: =item
16008: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16009: on your servers.
16010:
16011: =over
16012:
16013: =item
16014: remotesessions, hostedsessions
16015:
16016: =back
16017:
16018: =back
16019:
16020: In cases where a domain coordinator has never used the "Set Domain Configuration"
16021: utility to create a configuration.db file on a domain's primary library server
16022: only the following domain defaults: auth_def, auth_arg_def, lang_def
16023: -- corresponding values are authentication type (internal, krb4, krb5,
16024: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
16025: will be available. Values are retrieved from cache (if current), unless the
16026: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16027: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16028:
16029: Typical usage:
1.943 raeburn 16030:
1.1240 raeburn 16031: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 16032:
1.243 albertel 16033: =back
16034:
16035: =head2 Network Status Functions
16036:
16037: =over 4
1.191 harris41 16038:
16039: =item *
16040:
1.1137 raeburn 16041: dirlist() : return directory list based on URI (first arg).
16042:
16043: Inputs: 1 required, 5 optional.
16044:
16045: =over
16046:
16047: =item
16048: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16049:
16050: =item
16051: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
16052:
16053: =item
16054: $username - username of user/course to be listed. Extracted from $uri if absent.
16055:
16056: =item
16057: $getpropath - boolean: 1 if prepend path using &propath().
16058:
16059: =item
16060: $getuserdir - boolean: 1 if prepend path for "userfiles".
16061:
16062: =item
16063: $alternateRoot - path to prepend in place of path from $uri.
16064:
16065: =back
16066:
16067: Returns: Array of up to two items.
16068:
16069: =over
16070:
16071: a reference to an array of files/subdirectories
16072:
16073: =over
16074:
16075: Each element in the array of files/subdirectories is a & separated list of
16076: item name and the result of running stat on the item. If dirlist was requested
16077: for a file instead of a directory, the item name will be ''. For a directory
16078: listing, if the item is a metadata file, the element will end &N&M
16079: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16080: default copyright set (1).
16081:
16082: =back
16083:
16084: a scalar containing error condition (if encountered).
16085:
16086: =over
16087:
16088: =item
16089: no_host (no homeserver identified for $username:$domain).
16090:
16091: =item
16092: no_such_host (server contacted for listing not identified as valid host).
16093:
16094: =item
16095: con_lost (connection to remote server failed).
16096:
16097: =item
16098: refused (invalid $username:$domain received on lond side).
16099:
16100: =item
16101: no_such_dir (directory at specified path on lond side does not exist).
16102:
16103: =item
16104: empty (directory at specified path on lond side is empty).
16105:
16106: =over
16107:
16108: This is currently not encountered because the &ls3, &ls2,
16109: &ls (_handler) routines on the lond side do not filter out
16110: . and .. from a directory listing.
16111:
16112: =back
16113:
16114: =back
16115:
16116: =back
1.191 harris41 16117:
16118: =item *
16119:
1.243 albertel 16120: spareserver() : find server with least workload from spare.tab
16121:
1.986 foxr 16122:
16123: =item *
16124:
16125: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16126: if there is no corresponding loncapa host.
16127:
1.243 albertel 16128: =back
16129:
1.986 foxr 16130:
1.243 albertel 16131: =head2 Apache Request
16132:
16133: =over 4
1.191 harris41 16134:
16135: =item *
16136:
1.243 albertel 16137: ssi($url,%hash) : server side include, does a complete request cycle on url to
16138: localhost, posts hash
16139:
16140: =back
16141:
16142: =head2 Data to String to Data
16143:
16144: =over 4
1.191 harris41 16145:
16146: =item *
16147:
1.243 albertel 16148: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16149: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 16150:
16151: =item *
16152:
1.243 albertel 16153: hashref2str($hashref) : convert a hashref into a string complete with
16154: escaping and '=' and '&' separators, supports elements that are
16155: arrayrefs and hashrefs
1.191 harris41 16156:
16157: =item *
16158:
1.243 albertel 16159: arrayref2str($arrayref) : convert an arrayref into a string complete
16160: with escaping and '&' separators, supports elements that are arrayrefs
16161: and hashrefs
1.191 harris41 16162:
16163: =item *
16164:
1.243 albertel 16165: str2hash($string) : convert string to hash using unescaping and
16166: splitting on '=' and '&', supports elements that are arrayrefs and
16167: hashrefs
1.191 harris41 16168:
16169: =item *
16170:
1.243 albertel 16171: str2array($string) : convert string to hash using unescaping and
16172: splitting on '&', supports elements that are arrayrefs and hashrefs
16173:
16174: =back
16175:
16176: =head2 Logging Routines
16177:
16178:
16179: These routines allow one to make log messages in the lonnet.log and
16180: lonnet.perm logfiles.
1.191 harris41 16181:
1.1119 foxr 16182: =over 4
16183:
1.191 harris41 16184: =item *
16185:
1.243 albertel 16186: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 16187:
16188: =item *
16189:
1.243 albertel 16190: logthis() : append message to the normal lonnet.log file, it gets
16191: preiodically rolled over and deleted.
1.191 harris41 16192:
16193: =item *
16194:
1.243 albertel 16195: logperm() : append a permanent message to lonnet.perm.log, this log
16196: file never gets deleted by any automated portion of the system, only
16197: messages of critical importance should go in here.
16198:
1.1119 foxr 16199:
1.243 albertel 16200: =back
16201:
16202: =head2 General File Helper Routines
16203:
16204: =over 4
1.191 harris41 16205:
16206: =item *
16207:
1.481 raeburn 16208: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16209: (a) files in /uploaded
16210: (i) If a local copy of the file exists -
16211: compares modification date of local copy with last-modified date for
16212: definitive version stored on home server for course. If local copy is
16213: stale, requests a new version from the home server and stores it.
16214: If the original has been removed from the home server, then local copy
16215: is unlinked.
16216: (ii) If local copy does not exist -
16217: requests the file from the home server and stores it.
16218:
16219: If $caller is 'uploadrep':
16220: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16221: for request for files originally uploaded via DOCS.
16222: - returns 'ok' if fresh local copy now available, -1 otherwise.
16223:
16224: Otherwise:
16225: This indicates a call from the content generation phase of the request.
16226: - returns the entire contents of the file or -1.
16227:
16228: (b) files in /res
16229: - returns the entire contents of a file or -1;
16230: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 16231:
1.712 albertel 16232:
16233: =item *
16234:
16235: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16236: reference
16237:
16238: returns either a stat() list of data about the file or an empty list
16239: if the file doesn't exist or couldn't find out about it (connection
16240: problems or user unknown)
16241:
1.191 harris41 16242: =item *
16243:
1.243 albertel 16244: filelocation($dir,$file) : returns file system location of a file
16245: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16246: directory that relative $file lookups are to looked in ($dir of /a/dir
16247: and a file of ../bob will become /a/bob)
1.191 harris41 16248:
16249: =item *
16250:
16251: hreflocation($dir,$file) : returns file system location or a URL; same as
16252: filelocation except for hrefs
16253:
16254: =item *
16255:
1.1261 raeburn 16256: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16257: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 16258:
1.243 albertel 16259: =back
16260:
1.608 albertel 16261: =head2 Usererfile file routines (/uploaded*)
16262:
16263: =over 4
16264:
16265: =item *
16266:
16267: userfileupload(): main rotine for putting a file in a user or course's
16268: filespace, arguments are,
16269:
1.620 albertel 16270: formname - required - this is the name of the element in $env where the
1.608 albertel 16271: filename, and the contents of the file to create/modifed exist
1.620 albertel 16272: the filename is in $env{'form.'.$formname.'.filename'} and the
16273: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 16274: context - if coursedoc, store the file in the course of the active role
16275: of the current user;
16276: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16277: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 16278: subdir - required - subdirectory to put the file in under ../userfiles/
16279: if undefined, it will be placed in "unknown"
16280:
16281: (This routine calls clean_filename() to remove any dangerous
16282: characters from the filename, and then calls finuserfileupload() to
16283: complete the transaction)
16284:
16285: returns either the url of the uploaded file (/uploaded/....) if successful
16286: and /adm/notfound.html if unsuccessful
16287:
16288: =item *
16289:
16290: clean_filename(): routine for cleaing a filename up for storage in
16291: userfile space, argument is:
16292:
16293: filename - proposed filename
16294:
16295: returns: the new clean filename
16296:
16297: =item *
16298:
1.1090 raeburn 16299: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 16300: userspace, probably shouldn't be called directly
16301:
16302: docuname: username or courseid of destination for the file
16303: docudom: domain of user/course of destination for the file
16304: formname: same as for userfileupload()
1.1090 raeburn 16305: fname: filename (including subdirectories) for the file
16306: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401 raeburn 16307: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 16308: allfiles: reference to hash used to store objects found by parser
16309: codebase: reference to hash used for codebases of java objects found by parser
16310: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16311: thumbheight: height (pixels) of thumbnail to be created for uploaded image
16312: resizewidth: width to be used to resize image using resizeImage from ImageMagick
16313: resizeheight: height to be used to resize image using resizeImage from ImageMagick
16314: context: if 'overwrite', will move the uploaded file from its temporary location to
16315: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 16316: mimetype: reference to scalar to accommodate mime type determined
16317: from File::MMagic if $parser = parse.
1.608 albertel 16318:
16319: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 16320: and /adm/notfound.html if unsuccessful (or an error message if context
16321: was 'overwrite').
16322:
1.608 albertel 16323:
16324: =item *
16325:
16326: renameuserfile(): renames an existing userfile to a new name
16327:
16328: Args:
16329: docuname: username or courseid of destination for the file
16330: docudom: domain of user/course of destination for the file
16331: old: current file name (including any subdirs under userfiles)
16332: new: desired file name (including any subdirs under userfiles)
16333:
16334: =item *
16335:
16336: mkdiruserfile(): creates a directory is a userfiles dir
16337:
16338: Args:
16339: docuname: username or courseid of destination for the file
16340: docudom: domain of user/course of destination for the file
16341: dir: dir to create (including any subdirs under userfiles)
16342:
16343: =item *
16344:
16345: removeuserfile(): removes a file that exists in userfiles
16346:
16347: Args:
16348: docuname: username or courseid of destination for the file
16349: docudom: domain of user/course of destination for the file
16350: fname: filname to delete (including any subdirs under userfiles)
16351:
16352: =item *
16353:
16354: removeuploadedurl(): convience function for removeuserfile()
16355:
16356: Args:
16357: url: a full /uploaded/... url to delete
16358:
1.747 albertel 16359: =item *
16360:
16361: get_portfile_permissions():
16362: Args:
16363: domain: domain of user or course contain the portfolio files
16364: user: name of user or num of course contain the portfolio files
16365: Returns:
16366: hashref of a dump of the proper file_permissions.db
16367:
16368:
16369: =item *
16370:
16371: get_access_controls():
16372:
16373: Args:
16374: current_permissions: the hash ref returned from get_portfile_permissions()
16375: group: (optional) the group you want the files associated with
16376: file: (optional) the file you want access info on
16377:
16378: Returns:
1.749 raeburn 16379: a hash (keys are file names) of hashes containing
16380: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16381: values are XML containing access control settings (see below)
1.747 albertel 16382:
16383: Internal notes:
16384:
1.749 raeburn 16385: access controls are stored in file_permissions.db as key=value pairs.
16386: key -> path to file/file_name\0uniqueID:scope_end_start
16387: where scope -> public,guest,course,group,domains or users.
16388: end -> UNIX time for end of access (0 -> no end date)
16389: start -> UNIX time for start of access
16390:
16391: value -> XML description of access control
16392: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16393: <start></start>
16394: <end></end>
16395:
16396: <password></password> for scope type = guest
16397:
16398: <domain></domain> for scope type = course or group
16399: <number></number>
16400: <roles id="">
16401: <role></role>
16402: <access></access>
16403: <section></section>
16404: <group></group>
16405: </roles>
16406:
16407: <dom></dom> for scope type = domains
16408:
16409: <users> for scope type = users
16410: <user>
16411: <uname></uname>
16412: <udom></udom>
16413: </user>
16414: </users>
16415: </scope>
16416:
16417: Access data is also aggregated for each file in an additional key=value pair:
16418: key -> path to file/file_name\0accesscontrol
16419: value -> reference to hash
16420: hash contains key = value pairs
16421: where key = uniqueID:scope_end_start
16422: value = UNIX time record was last updated
16423:
16424: Used to improve speed of look-ups of access controls for each file.
16425:
16426: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16427:
1.1198 raeburn 16428: =item *
16429:
1.749 raeburn 16430: modify_access_controls():
16431:
16432: Modifies access controls for a portfolio file
16433: Args
16434: 1. file name
16435: 2. reference to hash of required changes,
16436: 3. domain
16437: 4. username
16438: where domain,username are the domain of the portfolio owner
16439: (either a user or a course)
16440:
16441: Returns:
16442: 1. result of additions or updates ('ok' or 'error', with error message).
16443: 2. result of deletions ('ok' or 'error', with error message).
16444: 3. reference to hash of any new or updated access controls.
16445: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16446: key = integer (inbound ID)
1.1198 raeburn 16447: value = uniqueID
16448:
16449: =item *
16450:
16451: get_timebased_id():
16452:
16453: Attempts to get a unique timestamp-based suffix for use with items added to a
16454: course via the Course Editor (e.g., folders, composite pages,
16455: group bulletin boards).
16456:
16457: Args: (first three required; six others optional)
16458:
16459: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16460: docssequence, or name of group
16461:
16462: 2. keyid (alphanumeric): name of temporary locking key in hash,
16463: e.g., num, boardids
16464:
16465: 3. namespace: name of gdbm file used to store suffixes already assigned;
16466: file will be named nohist_namespace.db
16467:
16468: 4. cdom: domain of course; default is current course domain from %env
16469:
16470: 5. cnum: course number; default is current course number from %env
16471:
16472: 6. idtype: set to concat if an additional digit is to be appended to the
16473: unix timestamp to form the suffix, if the plain timestamp is already
16474: in use. Default is to not do this, but simply increment the unix
16475: timestamp by 1 until a unique key is obtained.
16476:
16477: 7. who: holder of locking key; defaults to user:domain for user.
16478:
16479: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
16480: retrying); default is 3.
16481:
16482: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
16483:
16484: Returns:
16485:
16486: 1. suffix obtained (numeric)
16487:
16488: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16489:
16490: 3. error: contains (localized) error message if an error occurred.
16491:
1.747 albertel 16492:
1.608 albertel 16493: =back
16494:
1.243 albertel 16495: =head2 HTTP Helper Routines
16496:
16497: =over 4
16498:
1.191 harris41 16499: =item *
16500:
16501: escape() : unpack non-word characters into CGI-compatible hex codes
16502:
16503: =item *
16504:
16505: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16506:
1.243 albertel 16507: =back
16508:
16509: =head1 PRIVATE SUBROUTINES
16510:
16511: =head2 Underlying communication routines (Shouldn't call)
16512:
16513: =over 4
16514:
16515: =item *
16516:
16517: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16518:
16519: =item *
16520:
16521: reply() : uses subreply to send a message to remote machine, logs all failures
16522:
16523: =item *
16524:
16525: critical() : passes a critical message to another server; if cannot
16526: get through then place message in connection buffer directory and
16527: returns con_delayed, if incapable of saving message, returns
16528: con_failed
16529:
16530: =item *
16531:
16532: reconlonc() : tries to reconnect lonc client processes.
16533:
16534: =back
16535:
16536: =head2 Resource Access Logging
16537:
16538: =over 4
16539:
16540: =item *
16541:
16542: flushcourselogs() : flush (save) buffer logs and access logs
16543:
16544: =item *
16545:
16546: courselog($what) : save message for course in hash
16547:
16548: =item *
16549:
16550: courseacclog($what) : save message for course using &courselog(). Perform
16551: special processing for specific resource types (problems, exams, quizzes, etc).
16552:
1.191 harris41 16553: =item *
16554:
16555: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16556: as a PerlChildExitHandler
1.243 albertel 16557:
16558: =back
16559:
16560: =head2 Other
16561:
16562: =over 4
16563:
16564: =item *
16565:
16566: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 16567:
16568: =back
16569:
16570: =cut
1.877 foxr 16571:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>