Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1407
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1407 ! raeburn 4: # $Id: lonnet.pm,v 1.1406 2019/02/26 14:42:27 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.202 matthew 1255: }
1256: return $answer;
1.1 albertel 1257: }
1258:
1.169 harris41 1259: # ----------------------- Try to determine user's current authentication scheme
1260:
1261: sub queryauthenticate {
1262: my ($uname,$udom)=@_;
1.456 albertel 1263: my $uhome=&homeserver($uname,$udom);
1264: if (!$uhome) {
1265: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1266: return 'no_host';
1267: }
1268: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1269: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1270: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1271: }
1.456 albertel 1272: return $answer;
1.169 harris41 1273: }
1274:
1.1 albertel 1275: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1276:
1.1 albertel 1277: sub authenticate {
1.1073 raeburn 1278: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1279: $upass=&escape($upass);
1280: $uname= &LONCAPA::clean_username($uname);
1.836 www 1281: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1282: my $newhome;
1.836 www 1283: if ((!$uhome) || ($uhome eq 'no_host')) {
1284: # Maybe the machine was offline and only re-appeared again recently?
1285: &reconlonc();
1286: # One more
1.952 raeburn 1287: $uhome=&homeserver($uname,$udom,1);
1288: if (($uhome eq 'no_host') && $checkdefauth) {
1289: if (defined(&domain($udom,'primary'))) {
1290: $newhome=&domain($udom,'primary');
1291: }
1292: if ($newhome ne '') {
1293: $uhome = $newhome;
1294: }
1295: }
1.836 www 1296: if ((!$uhome) || ($uhome eq 'no_host')) {
1297: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1298: return 'no_host';
1299: }
1.1 albertel 1300: }
1.1073 raeburn 1301: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1302: if ($answer eq 'authorized') {
1.952 raeburn 1303: if ($newhome) {
1304: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1305: return 'no_account_on_host';
1306: } else {
1307: &logthis("User $uname at $udom authorized by $uhome");
1308: return $uhome;
1309: }
1.471 albertel 1310: }
1311: if ($answer eq 'non_authorized') {
1312: &logthis("User $uname at $udom rejected by $uhome");
1313: return 'no_host';
1.9 www 1314: }
1.471 albertel 1315: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1316: return 'no_host';
1317: }
1318:
1.1073 raeburn 1319: sub can_host_session {
1.1074 raeburn 1320: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1321: my $canhost = 1;
1.1074 raeburn 1322: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1323: if (ref($remotesessions) eq 'HASH') {
1324: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1325: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1326: $canhost = 0;
1327: } else {
1328: $canhost = 1;
1329: }
1330: }
1331: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1332: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1333: $canhost = 1;
1334: } else {
1335: $canhost = 0;
1336: }
1337: }
1338: if ($canhost) {
1339: if ($remotesessions->{'version'} ne '') {
1340: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1341: if ($reqmajor ne '' && $reqminor ne '') {
1342: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1343: my $major = $1;
1344: my $minor = $2;
1345: if (($major < $reqmajor ) ||
1346: (($major == $reqmajor) && ($minor < $reqminor))) {
1347: $canhost = 0;
1348: }
1349: } else {
1350: $canhost = 0;
1351: }
1352: }
1353: }
1354: }
1355: }
1356: if ($canhost) {
1357: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1358: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1359: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1360: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1361: if (($uint_dom ne '') &&
1362: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1363: $canhost = 0;
1364: } else {
1365: $canhost = 1;
1366: }
1367: }
1368: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1369: if (($uint_dom ne '') &&
1370: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1371: $canhost = 1;
1372: } else {
1373: $canhost = 0;
1374: }
1375: }
1376: }
1377: }
1378: return $canhost;
1379: }
1380:
1.1083 raeburn 1381: sub spare_can_host {
1382: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1383: my $canhost=1;
1.1279 raeburn 1384: my $try_server_hostname = &hostname($try_server);
1385: my $serverhomeID = &get_server_homeID($try_server_hostname);
1386: my $serverhomedom = &host_domain($serverhomeID);
1387: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1388: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1389: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1390: $canhost = 0;
1391: }
1392: }
1393: if (($canhost) && ($uint_dom)) {
1394: my @intdoms;
1395: my $internet_names = &get_internet_names($try_server);
1396: if (ref($internet_names) eq 'ARRAY') {
1397: @intdoms = @{$internet_names};
1398: }
1399: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1400: my $remoterev = &get_server_loncaparev(undef,$try_server);
1401: $canhost = &can_host_session($udom,$try_server,$remoterev,
1402: $remotesessions,
1403: $defdomdefaults{'hostedsessions'});
1404: }
1.1083 raeburn 1405: }
1406: return $canhost;
1407: }
1408:
1.1123 raeburn 1409: sub this_host_spares {
1410: my ($dom) = @_;
1.1126 raeburn 1411: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1412: my @hosts = ¤t_machine_ids();
1413: foreach my $lonhost (@hosts) {
1414: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1415: $dom_in_use = $dom;
1416: $lonhost_in_use = $lonhost;
1.1123 raeburn 1417: last;
1418: }
1419: }
1.1126 raeburn 1420: if ($dom_in_use ne '') {
1421: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1422: }
1423: if (ref($result) ne 'HASH') {
1424: $lonhost_in_use = $perlvar{'lonHostID'};
1425: $dom_in_use = &host_domain($lonhost_in_use);
1426: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1427: if (ref($result) ne 'HASH') {
1428: $result = \%spareid;
1429: }
1430: }
1431: return $result;
1432: }
1433:
1434: sub spares_for_offload {
1435: my ($dom_in_use,$lonhost_in_use) = @_;
1436: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1437: if (defined($cached)) {
1438: return $result;
1439: } else {
1.1126 raeburn 1440: my $cachetime = 60*60*24;
1441: my %domconfig =
1442: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1443: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1444: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1445: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1446: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1447: }
1448: }
1449: }
1450: }
1.1126 raeburn 1451: return;
1.1123 raeburn 1452: }
1453:
1.1129 raeburn 1454: sub get_lonbalancer_config {
1455: my ($servers) = @_;
1456: my ($currbalancer,$currtargets);
1457: if (ref($servers) eq 'HASH') {
1458: foreach my $server (keys(%{$servers})) {
1459: my %what = (
1460: spareid => 1,
1461: perlvar => 1,
1462: );
1463: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1464: if ($result eq 'ok') {
1465: if (ref($returnhash) eq 'HASH') {
1466: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1467: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1468: $currbalancer = $server;
1469: $currtargets = {};
1470: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1471: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1472: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1473: }
1474: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1475: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1476: }
1477: }
1478: last;
1479: }
1480: }
1481: }
1482: }
1483: }
1484: }
1485: return ($currbalancer,$currtargets);
1486: }
1487:
1488: sub check_loadbalancing {
1.1331 raeburn 1489: my ($uname,$udom,$caller) = @_;
1.1191 raeburn 1490: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391 raeburn 1491: $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129 raeburn 1492: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1493: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1494: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1495: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1496: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1497: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1498: my $domneedscache;
1.1129 raeburn 1499: my $cachetime = 60*60*24;
1500:
1501: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1502: $dom_in_use = $udom;
1503: $homeintdom = 1;
1504: } else {
1505: $dom_in_use = $serverhomedom;
1506: }
1507: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1508: unless (defined($cached)) {
1509: my %domconfig =
1510: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1511: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1512: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1513: } else {
1514: $domneedscache = $dom_in_use;
1.1129 raeburn 1515: }
1516: }
1517: if (ref($result) eq 'HASH') {
1.1391 raeburn 1518: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1519: &check_balancer_result($result,@hosts);
1.1129 raeburn 1520: if ($is_balancer) {
1521: if (ref($currrules) eq 'HASH') {
1522: if ($homeintdom) {
1523: if ($uname ne '') {
1524: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1525: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1526: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1527: $rule_in_effect = $currrules->{'_LC_author'};
1528: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1529: $rule_in_effect = $currrules->{'_LC_adv'}
1530: }
1531: }
1532: if ($rule_in_effect eq '') {
1533: my %userenv = &userenvironment($udom,$uname,'inststatus');
1534: if ($userenv{'inststatus'} ne '') {
1535: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1536: my ($othertitle,$usertypes,$types) =
1537: &Apache::loncommon::sorted_inst_types($udom);
1538: if (ref($types) eq 'ARRAY') {
1539: foreach my $type (@{$types}) {
1540: if (grep(/^\Q$type\E$/,@statuses)) {
1541: if (exists($currrules->{$type})) {
1542: $rule_in_effect = $currrules->{$type};
1543: }
1544: }
1545: }
1546: }
1547: } else {
1548: if (exists($currrules->{'default'})) {
1549: $rule_in_effect = $currrules->{'default'};
1550: }
1551: }
1552: }
1553: } else {
1554: if (exists($currrules->{'default'})) {
1555: $rule_in_effect = $currrules->{'default'};
1556: }
1557: }
1558: } else {
1559: if ($currrules->{'_LC_external'} ne '') {
1560: $rule_in_effect = $currrules->{'_LC_external'};
1561: }
1562: }
1563: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1564: $uname,$udom);
1565: }
1566: }
1567: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1568: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1569: unless (defined($cached)) {
1570: my %domconfig =
1571: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1572: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1573: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1574: } else {
1575: $domneedscache = $serverhomedom;
1.1129 raeburn 1576: }
1577: }
1578: if (ref($result) eq 'HASH') {
1.1391 raeburn 1579: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1580: &check_balancer_result($result,@hosts);
1581: if ($is_balancer) {
1.1129 raeburn 1582: if (ref($currrules) eq 'HASH') {
1583: if ($currrules->{'_LC_internetdom'} ne '') {
1584: $rule_in_effect = $currrules->{'_LC_internetdom'};
1585: }
1586: }
1587: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1588: $uname,$udom);
1589: }
1590: } else {
1591: if ($perlvar{'lonBalancer'} eq 'yes') {
1592: $is_balancer = 1;
1593: $offloadto = &this_host_spares($dom_in_use);
1594: }
1.1307 raeburn 1595: unless (defined($cached)) {
1596: $domneedscache = $serverhomedom;
1597: }
1.1129 raeburn 1598: }
1599: } else {
1600: if ($perlvar{'lonBalancer'} eq 'yes') {
1601: $is_balancer = 1;
1602: $offloadto = &this_host_spares($dom_in_use);
1603: }
1.1307 raeburn 1604: unless (defined($cached)) {
1605: $domneedscache = $serverhomedom;
1606: }
1607: }
1608: if ($domneedscache) {
1609: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1610: }
1.1176 raeburn 1611: if ($is_balancer) {
1612: my $lowest_load = 30000;
1613: if (ref($offloadto) eq 'HASH') {
1614: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1615: foreach my $try_server (@{$offloadto->{'primary'}}) {
1616: ($otherserver,$lowest_load) =
1617: &compare_server_load($try_server,$otherserver,$lowest_load);
1618: }
1.1129 raeburn 1619: }
1.1176 raeburn 1620: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1621:
1.1176 raeburn 1622: if (!$found_server) {
1623: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1624: foreach my $try_server (@{$offloadto->{'default'}}) {
1625: ($otherserver,$lowest_load) =
1626: &compare_server_load($try_server,$otherserver,$lowest_load);
1627: }
1628: }
1629: }
1630: } elsif (ref($offloadto) eq 'ARRAY') {
1631: if (@{$offloadto} == 1) {
1632: $otherserver = $offloadto->[0];
1633: } elsif (@{$offloadto} > 1) {
1634: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1635: ($otherserver,$lowest_load) =
1636: &compare_server_load($try_server,$otherserver,$lowest_load);
1637: }
1638: }
1639: }
1.1331 raeburn 1640: unless ($caller eq 'login') {
1641: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1642: $is_balancer = 0;
1643: if ($uname ne '' && $udom ne '') {
1644: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389 raeburn 1645: &appenv({'user.loadbalexempt' => $lonhost,
1.1331 raeburn 1646: 'user.loadbalcheck.time' => time});
1647: }
1.1176 raeburn 1648: }
1.1129 raeburn 1649: }
1650: }
1.1389 raeburn 1651: unless ($homeintdom) {
1652: undef($setcookie);
1653: }
1.1129 raeburn 1654: }
1.1391 raeburn 1655: return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129 raeburn 1656: }
1657:
1.1191 raeburn 1658: sub check_balancer_result {
1659: my ($result,@hosts) = @_;
1.1391 raeburn 1660: my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1661: if (ref($result) eq 'HASH') {
1662: if ($result->{'lonhost'} ne '') {
1663: my $currbalancer = $result->{'lonhost'};
1664: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1665: $is_balancer = 1;
1666: $currtargets = $result->{'targets'};
1667: $currrules = $result->{'rules'};
1668: }
1.1391 raeburn 1669: $dom_balancers = $currbalancer;
1.1191 raeburn 1670: } else {
1.1391 raeburn 1671: if (keys(%{$result})) {
1672: foreach my $key (keys(%{$result})) {
1673: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1674: (ref($result->{$key}) eq 'HASH')) {
1675: $is_balancer = 1;
1676: $currrules = $result->{$key}{'rules'};
1677: $currtargets = $result->{$key}{'targets'};
1678: $setcookie = $result->{$key}{'cookie'};
1679: last;
1680: }
1.1191 raeburn 1681: }
1.1391 raeburn 1682: $dom_balancers = join(',',sort(keys(%{$result})));
1.1191 raeburn 1683: }
1684: }
1685: }
1.1391 raeburn 1686: return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1687: }
1688:
1.1129 raeburn 1689: sub get_loadbalancer_targets {
1690: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1691: my $offloadto;
1.1175 raeburn 1692: if ($rule_in_effect eq 'none') {
1693: return [$perlvar{'lonHostID'}];
1694: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1695: $offloadto = $currtargets;
1696: } else {
1697: if ($rule_in_effect eq 'homeserver') {
1698: my $homeserver = &homeserver($uname,$udom);
1699: if ($homeserver ne 'no_host') {
1700: $offloadto = [$homeserver];
1701: }
1702: } elsif ($rule_in_effect eq 'externalbalancer') {
1703: my %domconfig =
1704: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1705: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1706: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1707: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1708: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1709: }
1710: }
1711: } else {
1.1178 raeburn 1712: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1713: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1714: if (&hostname($remotebalancer) ne '') {
1715: $offloadto = [$remotebalancer];
1716: }
1717: }
1718: } elsif (&hostname($rule_in_effect) ne '') {
1719: $offloadto = [$rule_in_effect];
1720: }
1721: }
1722: return $offloadto;
1723: }
1724:
1.1127 raeburn 1725: sub internet_dom_servers {
1726: my ($dom) = @_;
1727: my (%uniqservers,%servers);
1728: my $primaryserver = &hostname(&domain($dom,'primary'));
1729: my @machinedoms = &machine_domains($primaryserver);
1730: foreach my $mdom (@machinedoms) {
1731: my %currservers = %servers;
1732: my %server = &get_servers($mdom);
1733: %servers = (%currservers,%server);
1734: }
1735: my %by_hostname;
1736: foreach my $id (keys(%servers)) {
1737: push(@{$by_hostname{$servers{$id}}},$id);
1738: }
1739: foreach my $hostname (sort(keys(%by_hostname))) {
1740: if (@{$by_hostname{$hostname}} > 1) {
1741: my $match = 0;
1742: foreach my $id (@{$by_hostname{$hostname}}) {
1743: if (&host_domain($id) eq $dom) {
1744: $uniqservers{$id} = $hostname;
1745: $match = 1;
1746: }
1747: }
1748: unless ($match) {
1749: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1750: }
1751: } else {
1752: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1753: }
1754: }
1755: return %uniqservers;
1756: }
1757:
1.1347 raeburn 1758: sub trusted_domains {
1759: my ($cmdtype,$calldom) = @_;
1.1349 raeburn 1760: my ($trusted,$untrusted);
1.1347 raeburn 1761: if (&domain($calldom) eq '') {
1.1349 raeburn 1762: return ($trusted,$untrusted);
1.1347 raeburn 1763: }
1.1395 raeburn 1764: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349 raeburn 1765: return ($trusted,$untrusted);
1.1347 raeburn 1766: }
1767: my $callprimary = &domain($calldom,'primary');
1768: my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
1769: if ($intcalldom eq '') {
1.1349 raeburn 1770: return ($trusted,$untrusted);
1.1347 raeburn 1771: }
1772:
1773: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
1774: unless (defined($cached)) {
1775: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
1776: &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1777: $trustconfig = $domconfig{'trust'};
1778: }
1779: if (ref($trustconfig)) {
1780: my (%possexc,%possinc,@allexc,@allinc);
1781: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1782: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1783: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1784: }
1785: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395 raeburn 1786: $possinc{$intcalldom} = 1;
1.1347 raeburn 1787: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1788: }
1789: }
1790: if (keys(%possexc)) {
1791: if (keys(%possinc)) {
1792: foreach my $key (sort(keys(%possexc))) {
1793: next if ($key eq $intcalldom);
1794: unless ($possinc{$key}) {
1795: push(@allexc,$key);
1796: }
1797: }
1798: } else {
1799: @allexc = sort(keys(%possexc));
1800: }
1801: }
1802: if (keys(%possinc)) {
1803: $possinc{$intcalldom} = 1;
1804: @allinc = sort(keys(%possinc));
1805: }
1806: if ((@allexc > 0) || (@allinc > 0)) {
1807: my %doms_by_intdom;
1808: my %allintdoms = &all_host_intdom();
1809: my %alldoms = &all_host_domain();
1810: foreach my $key (%allintdoms) {
1811: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1812: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1813: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1814: }
1815: } else {
1816: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1817: }
1818: }
1819: foreach my $exc (@allexc) {
1820: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395 raeburn 1821: push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347 raeburn 1822: }
1823: }
1824: foreach my $inc (@allinc) {
1825: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395 raeburn 1826: push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347 raeburn 1827: }
1828: }
1829: }
1830: }
1.1349 raeburn 1831: return ($trusted,$untrusted);
1.1347 raeburn 1832: }
1833:
1834: sub will_trust {
1835: my ($cmdtype,$domain,$possdom) = @_;
1836: return 1 if ($domain eq $possdom);
1837: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1838: my $willtrust;
1839: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1840: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1841: $willtrust = 1;
1842: }
1843: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1844: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1845: $willtrust = 1;
1846: }
1847: } else {
1848: $willtrust = 1;
1849: }
1850: return $willtrust;
1851: }
1852:
1.1 albertel 1853: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1854:
1.599 albertel 1855: my %homecache;
1.1 albertel 1856: sub homeserver {
1.230 stredwic 1857: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1858: my $index="$uname:$udom";
1.426 albertel 1859:
1.599 albertel 1860: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1861:
1862: my %servers = &get_servers($udom,'library');
1863: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1864: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1865: exists($badServerCache{$tryserver}));
1.841 albertel 1866:
1867: my $answer=reply("home:$udom:$uname",$tryserver);
1868: if ($answer eq 'found') {
1869: delete($badServerCache{$tryserver});
1870: return $homecache{$index}=$tryserver;
1871: } elsif ($answer eq 'no_host') {
1872: $badServerCache{$tryserver}=1;
1873: }
1.1 albertel 1874: }
1875: return 'no_host';
1.70 www 1876: }
1877:
1.1300 raeburn 1878: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1879:
1880: sub idget {
1.1300 raeburn 1881: my ($udom,$idsref,$namespace)=@_;
1.70 www 1882: my %returnhash=();
1.1300 raeburn 1883: my @ids=();
1884: if (ref($idsref) eq 'ARRAY') {
1885: @ids = @{$idsref};
1886: } else {
1887: return %returnhash;
1888: }
1889: if ($namespace eq '') {
1890: $namespace = 'ids';
1891: }
1.70 www 1892:
1.841 albertel 1893: my %servers = &get_servers($udom,'library');
1894: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1895: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1896: if ($namespace eq 'ids') {
1897: $idlist=~tr/A-Z/a-z/;
1898: }
1899: my $reply;
1900: if ($namespace eq 'ids') {
1901: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1902: } else {
1903: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1904: }
1.841 albertel 1905: my @answer=();
1906: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1907: @answer=split(/\&/,$reply);
1908: } ;
1909: my $i;
1910: for ($i=0;$i<=$#ids;$i++) {
1911: if ($answer[$i]) {
1.1299 raeburn 1912: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1913: }
1.841 albertel 1914: }
1.1300 raeburn 1915: }
1.70 www 1916: return %returnhash;
1917: }
1918:
1919: # ------------------------------------- Find the IDs behind a list of usernames
1920:
1921: sub idrget {
1922: my ($udom,@unames)=@_;
1923: my %returnhash=();
1.800 albertel 1924: foreach my $uname (@unames) {
1925: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1926: }
1.70 www 1927: return %returnhash;
1928: }
1929:
1.1300 raeburn 1930: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 1931:
1932: sub idput {
1.1300 raeburn 1933: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 1934: my %servers=();
1.1300 raeburn 1935: my %ids=();
1936: my %byid = ();
1937: if (ref($idsref) eq 'HASH') {
1938: %ids=%{$idsref};
1939: }
1940: if ($namespace eq '') {
1941: $namespace = 'ids';
1942: }
1.800 albertel 1943: foreach my $uname (keys(%ids)) {
1944: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 1945: if ($uhom eq '') {
1946: $uhom=&homeserver($uname,$udom);
1947: }
1.70 www 1948: if ($uhom ne 'no_host') {
1.800 albertel 1949: my $esc_unam=&escape($uname);
1.1300 raeburn 1950: if ($namespace eq 'ids') {
1951: my $id=&escape($ids{$uname});
1952: $id=~tr/A-Z/a-z/;
1953: my $esc_unam=&escape($uname);
1954: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 1955: } else {
1.1300 raeburn 1956: my @currids = split(/,/,$ids{$uname});
1957: foreach my $id (@currids) {
1958: $byid{$uhom}{$id} .= $uname.',';
1959: }
1960: }
1961: }
1962: }
1963: if ($namespace eq 'clickers') {
1964: foreach my $server (keys(%byid)) {
1965: if (ref($byid{$server}) eq 'HASH') {
1966: foreach my $id (keys(%{$byid{$server}})) {
1967: $byid{$server} =~ s/,$//;
1968: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
1969: }
1.70 www 1970: }
1971: }
1.191 harris41 1972: }
1.800 albertel 1973: foreach my $server (keys(%servers)) {
1.1300 raeburn 1974: $servers{$server} =~ s/\&$//;
1975: if ($namespace eq 'ids') {
1976: &critical('idput:'.$udom.':'.$servers{$server},$server);
1977: } else {
1978: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
1979: }
1.191 harris41 1980: }
1.344 www 1981: }
1982:
1.1300 raeburn 1983: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 1984:
1985: sub iddel {
1.1300 raeburn 1986: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 1987: my %result=();
1.1300 raeburn 1988: my %ids=();
1989: my %byid = ();
1990: if (ref($idshashref) eq 'HASH') {
1991: %ids=%{$idshashref};
1992: } else {
1.1231 raeburn 1993: return %result;
1994: }
1.1300 raeburn 1995: if ($namespace eq '') {
1996: $namespace = 'ids';
1997: }
1.1231 raeburn 1998: my %servers=();
1.1300 raeburn 1999: while (my ($id,$unamestr) = each(%ids)) {
2000: if ($namespace eq 'ids') {
2001: my $uhom = $uhome;
2002: if ($uhom eq '') {
2003: $uhom=&homeserver($unamestr,$udom);
2004: }
2005: if ($uhom ne 'no_host') {
2006: $servers{$uhom}.='&'.&escape($id);
2007: }
2008: } else {
2009: my @curritems = split(/,/,$ids{$id});
2010: foreach my $uname (@curritems) {
2011: my $uhom = $uhome;
2012: if ($uhom eq '') {
2013: $uhom=&homeserver($uname,$udom);
2014: }
2015: if ($uhom ne 'no_host') {
2016: $byid{$uhom}{$id} .= $uname.',';
2017: }
2018: }
1.1231 raeburn 2019: }
1.1300 raeburn 2020: }
2021: if ($namespace eq 'clickers') {
2022: foreach my $server (keys(%byid)) {
2023: if (ref($byid{$server}) eq 'HASH') {
2024: foreach my $id (keys(%{$byid{$server}})) {
2025: $byid{$server}{$id} =~ s/,$//;
2026: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
2027: }
1.1231 raeburn 2028: }
2029: }
2030: }
2031: foreach my $server (keys(%servers)) {
1.1300 raeburn 2032: $servers{$server} =~ s/\&$//;
2033: if ($namespace eq 'ids') {
2034: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
2035: } elsif ($namespace eq 'clickers') {
2036: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
2037: }
1.1231 raeburn 2038: }
2039: return %result;
2040: }
2041:
1.1300 raeburn 2042: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
2043:
2044: sub updateclickers {
2045: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
2046: my %clickers;
2047: if (ref($idshashref) eq 'HASH') {
2048: %clickers=%{$idshashref};
2049: } else {
2050: return;
2051: }
2052: my $items='';
2053: foreach my $item (keys(%clickers)) {
2054: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
2055: }
2056: $items=~s/\&$//;
2057: my $request = "updateclickers:$udom:$action:$items";
2058: if ($critical) {
2059: return &critical($request,$uhome);
2060: } else {
2061: return &reply($request,$uhome);
2062: }
2063: }
2064:
1.1023 raeburn 2065: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 2066: sub dump_dom {
1.1165 droeschl 2067: my ($namespace, $udom, $regexp) = @_;
2068:
2069: $udom ||= $env{'user.domain'};
2070:
2071: return () unless $udom;
2072:
2073: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 2074: }
2075:
1.1023 raeburn 2076: # ------------------------------------------ get items from domain db files
1.806 raeburn 2077:
2078: sub get_dom {
1.860 raeburn 2079: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 2080: return if ($udom eq 'public');
1.806 raeburn 2081: my $items='';
2082: foreach my $item (@$storearr) {
2083: $items.=&escape($item).'&';
2084: }
2085: $items=~s/\&$//;
1.860 raeburn 2086: if (!$udom) {
2087: $udom=$env{'user.domain'};
1.1267 raeburn 2088: return if ($udom eq 'public');
1.860 raeburn 2089: if (defined(&domain($udom,'primary'))) {
2090: $uhome=&domain($udom,'primary');
2091: } else {
1.874 albertel 2092: undef($uhome);
1.860 raeburn 2093: }
2094: } else {
2095: if (!$uhome) {
2096: if (defined(&domain($udom,'primary'))) {
2097: $uhome=&domain($udom,'primary');
2098: }
2099: }
2100: }
2101: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344 raeburn 2102: my $rep;
2103: if ($namespace =~ /^enc/) {
2104: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
2105: } else {
2106: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
2107: }
1.866 raeburn 2108: my %returnhash;
1.875 albertel 2109: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 2110: return %returnhash;
2111: }
1.806 raeburn 2112: my @pairs=split(/\&/,$rep);
2113: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2114: return @pairs;
2115: }
2116: my $i=0;
2117: foreach my $item (@$storearr) {
2118: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2119: $i++;
2120: }
2121: return %returnhash;
2122: } else {
1.880 banghart 2123: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 2124: }
2125: }
2126:
2127: # -------------------------------------------- put items in domain db files
2128:
2129: sub put_dom {
1.860 raeburn 2130: my ($namespace,$storehash,$udom,$uhome)=@_;
2131: if (!$udom) {
2132: $udom=$env{'user.domain'};
2133: if (defined(&domain($udom,'primary'))) {
2134: $uhome=&domain($udom,'primary');
2135: } else {
1.874 albertel 2136: undef($uhome);
1.860 raeburn 2137: }
2138: } else {
2139: if (!$uhome) {
2140: if (defined(&domain($udom,'primary'))) {
2141: $uhome=&domain($udom,'primary');
2142: }
2143: }
2144: }
2145: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 2146: my $items='';
2147: foreach my $item (keys(%$storehash)) {
2148: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2149: }
2150: $items=~s/\&$//;
1.1344 raeburn 2151: if ($namespace =~ /^enc/) {
2152: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2153: } else {
2154: return &reply("putdom:$udom:$namespace:$items",$uhome);
2155: }
1.806 raeburn 2156: } else {
1.860 raeburn 2157: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 2158: }
2159: }
2160:
1.1023 raeburn 2161: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 2162: sub newput_dom {
1.1023 raeburn 2163: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 2164: my $result;
2165: if (!$udom) {
2166: $udom=$env{'user.domain'};
2167: }
1.1023 raeburn 2168: if ($udom) {
2169: my $uname = &get_domainconfiguser($udom);
2170: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 2171: }
2172: return $result;
2173: }
2174:
1.1023 raeburn 2175: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 2176: sub del_dom {
1.1023 raeburn 2177: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 2178: if (ref($storearr) eq 'ARRAY') {
2179: if (!$udom) {
2180: $udom=$env{'user.domain'};
2181: }
1.1023 raeburn 2182: if ($udom) {
2183: my $uname = &get_domainconfiguser($udom);
2184: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 2185: }
2186: }
2187: }
2188:
1.1023 raeburn 2189: # ----------------------------------construct domainconfig user for a domain
2190: sub get_domainconfiguser {
2191: my ($udom) = @_;
2192: return $udom.'-domainconfig';
2193: }
2194:
1.837 raeburn 2195: sub retrieve_inst_usertypes {
2196: my ($udom) = @_;
2197: my (%returnhash,@order);
1.989 raeburn 2198: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2199: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2200: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 2201: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2202: } else {
2203: if (defined(&domain($udom,'primary'))) {
2204: my $uhome=&domain($udom,'primary');
2205: my $rep=&reply("inst_usertypes:$udom",$uhome);
2206: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 2207: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2208: return (\%returnhash,\@order);
2209: }
2210: my ($hashitems,$orderitems) = split(/:/,$rep);
2211: my @pairs=split(/\&/,$hashitems);
2212: foreach my $item (@pairs) {
2213: my ($key,$value)=split(/=/,$item,2);
2214: $key = &unescape($key);
2215: next if ($key =~ /^error: 2 /);
2216: $returnhash{$key}=&thaw_unescape($value);
2217: }
2218: my @esc_order = split(/\&/,$orderitems);
2219: foreach my $item (@esc_order) {
2220: push(@order,&unescape($item));
2221: }
2222: } else {
1.1256 raeburn 2223: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2224: }
1.1256 raeburn 2225: return (\%returnhash,\@order);
1.837 raeburn 2226: }
2227: }
2228:
1.868 raeburn 2229: sub is_domainimage {
2230: my ($url) = @_;
1.1306 raeburn 2231: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 2232: if (&domain($1) ne '') {
2233: return '1';
2234: }
2235: }
2236: return;
2237: }
2238:
1.899 raeburn 2239: sub inst_directory_query {
2240: my ($srch) = @_;
2241: my $udom = $srch->{'srchdomain'};
2242: my %results;
2243: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2244: my $outcome;
1.899 raeburn 2245: if ($homeserver ne '') {
1.1357 raeburn 2246: unless ($homeserver eq $perlvar{'lonHostID'}) {
2247: if ($srch->{'srchby'} eq 'email') {
2248: my $lcrev = &get_server_loncaparev(undef,$homeserver);
2249: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2250: if (($major eq '' && $minor eq '') || ($major < 2) ||
2251: (($major == 2) && ($minor < 12))) {
2252: return;
2253: }
2254: }
2255: }
1.904 albertel 2256: my $queryid=&reply("querysend:instdirsearch:".
2257: &escape($srch->{'srchby'}).':'.
2258: &escape($srch->{'srchterm'}).':'.
2259: &escape($srch->{'srchtype'}),$homeserver);
2260: my $host=&hostname($homeserver);
2261: if ($queryid !~/^\Q$host\E\_/) {
1.1343 raeburn 2262: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2263: return;
2264: }
2265: my $response = &get_query_reply($queryid);
2266: my $maxtries = 5;
2267: my $tries = 1;
2268: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2269: $response = &get_query_reply($queryid);
2270: $tries ++;
2271: }
2272:
2273: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2274: if ($response eq 'unavailable') {
2275: $outcome = $response;
2276: } else {
2277: $outcome = 'ok';
2278: my @matches = split(/\n/,$response);
2279: foreach my $match (@matches) {
2280: my ($key,$value) = split(/=/,$match);
2281: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2282: }
1.899 raeburn 2283: }
2284: }
2285: }
1.909 raeburn 2286: return ($outcome,%results);
1.899 raeburn 2287: }
2288:
2289: sub usersearch {
2290: my ($srch) = @_;
2291: my $dom = $srch->{'srchdomain'};
2292: my %results;
2293: my %libserv = &all_library();
2294: my $query = 'usersearch';
2295: foreach my $tryserver (keys(%libserv)) {
2296: if (&host_domain($tryserver) eq $dom) {
1.1357 raeburn 2297: unless ($tryserver eq $perlvar{'lonHostID'}) {
2298: if ($srch->{'srchby'} eq 'email') {
2299: my $lcrev = &get_server_loncaparev(undef,$tryserver);
2300: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2301: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2302: (($major == 2) && ($minor < 12)));
2303: }
2304: }
1.899 raeburn 2305: my $host=&hostname($tryserver);
2306: my $queryid=
1.911 raeburn 2307: &reply("querysend:".&escape($query).':'.
2308: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2309: &escape($srch->{'srchtype'}).':'.
2310: &escape($srch->{'srchterm'}),$tryserver);
2311: if ($queryid !~/^\Q$host\E\_/) {
2312: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2313: next;
1.899 raeburn 2314: }
2315: my $reply = &get_query_reply($queryid);
2316: my $maxtries = 1;
2317: my $tries = 1;
2318: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2319: $reply = &get_query_reply($queryid);
2320: $tries ++;
2321: }
2322: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2323: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2324: } else {
1.911 raeburn 2325: my @matches;
2326: if ($reply =~ /\n/) {
2327: @matches = split(/\n/,$reply);
2328: } else {
2329: @matches = split(/\&/,$reply);
2330: }
1.899 raeburn 2331: foreach my $match (@matches) {
2332: my ($uname,$udom,%userhash);
1.911 raeburn 2333: foreach my $entry (split(/:/,$match)) {
2334: my ($key,$value) =
2335: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2336: $userhash{$key} = $value;
2337: if ($key eq 'username') {
2338: $uname = $value;
2339: } elsif ($key eq 'domain') {
2340: $udom = $value;
1.911 raeburn 2341: }
1.899 raeburn 2342: }
2343: $results{$uname.':'.$udom} = \%userhash;
2344: }
2345: }
2346: }
2347: }
2348: return %results;
2349: }
2350:
1.912 raeburn 2351: sub get_instuser {
2352: my ($udom,$uname,$id) = @_;
2353: my $homeserver = &domain($udom,'primary');
2354: my ($outcome,%results);
2355: if ($homeserver ne '') {
2356: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2357: &escape($id).':'.&escape($udom),$homeserver);
2358: my $host=&hostname($homeserver);
2359: if ($queryid !~/^\Q$host\E\_/) {
2360: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2361: return;
2362: }
2363: my $response = &get_query_reply($queryid);
2364: my $maxtries = 5;
2365: my $tries = 1;
2366: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2367: $response = &get_query_reply($queryid);
2368: $tries ++;
2369: }
2370: if (!&error($response) && $response ne 'refused') {
2371: if ($response eq 'unavailable') {
2372: $outcome = $response;
2373: } else {
2374: $outcome = 'ok';
2375: my @matches = split(/\n/,$response);
2376: foreach my $match (@matches) {
2377: my ($key,$value) = split(/=/,$match);
2378: $results{&unescape($key)} = &thaw_unescape($value);
2379: }
2380: }
2381: }
2382: }
2383: my %userinfo;
2384: if (ref($results{$uname}) eq 'HASH') {
2385: %userinfo = %{$results{$uname}};
2386: }
2387: return ($outcome,%userinfo);
2388: }
2389:
1.1290 raeburn 2390: sub get_multiple_instusers {
2391: my ($udom,$users,$caller) = @_;
2392: my ($outcome,$results);
2393: if (ref($users) eq 'HASH') {
2394: my $count = keys(%{$users});
2395: my $requested = &freeze_escape($users);
2396: my $homeserver = &domain($udom,'primary');
2397: if ($homeserver ne '') {
2398: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2399: my $host=&hostname($homeserver);
2400: if ($queryid !~/^\Q$host\E\_/) {
2401: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2402: ' for host: '.$homeserver.'in domain '.$udom);
2403: return ($outcome,$results);
2404: }
2405: my $response = &get_query_reply($queryid);
2406: my $maxtries = 5;
2407: if ($count > 100) {
2408: $maxtries = 1+int($count/20);
2409: }
2410: my $tries = 1;
2411: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2412: $response = &get_query_reply($queryid);
2413: $tries ++;
2414: }
2415: if ($response eq '') {
2416: $results = {};
2417: foreach my $key (keys(%{$users})) {
2418: my ($uname,$id);
2419: if ($caller eq 'id') {
2420: $id = $key;
2421: } else {
2422: $uname = $key;
2423: }
2424: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2425: $outcome = $resp;
1.1290 raeburn 2426: if ($resp eq 'ok') {
2427: %{$results} = (%{$results}, %info);
2428: } else {
2429: last;
2430: }
2431: }
2432: } elsif(!&error($response) && ($response ne 'refused')) {
2433: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2434: $outcome = $response;
2435: } else {
1.1291 raeburn 2436: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2437: if ($outcome eq 'ok') {
2438: $results = &thaw_unescape($userdata);
2439: }
2440: }
2441: }
2442: }
2443: }
2444: return ($outcome,$results);
2445: }
2446:
1.912 raeburn 2447: sub inst_rulecheck {
1.923 raeburn 2448: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2449: my %returnhash;
2450: if ($udom ne '') {
2451: if (ref($rules) eq 'ARRAY') {
2452: @{$rules} = map {&escape($_);} (@{$rules});
2453: my $rulestr = join(':',@{$rules});
2454: my $homeserver=&domain($udom,'primary');
2455: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2456: my $response;
2457: if ($item eq 'username') {
2458: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2459: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2460: $homeserver));
1.923 raeburn 2461: } elsif ($item eq 'id') {
2462: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2463: ':'.&escape($id).':'.$rulestr,
2464: $homeserver));
1.945 raeburn 2465: } elsif ($item eq 'selfcreate') {
2466: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2467: &escape($udom).':'.&escape($uname).
2468: ':'.$rulestr,$homeserver));
1.923 raeburn 2469: }
1.912 raeburn 2470: if ($response ne 'refused') {
2471: my @pairs=split(/\&/,$response);
2472: foreach my $item (@pairs) {
2473: my ($key,$value)=split(/=/,$item,2);
2474: $key = &unescape($key);
2475: next if ($key =~ /^error: 2 /);
2476: $returnhash{$key}=&thaw_unescape($value);
2477: }
2478: }
2479: }
2480: }
2481: }
2482: return %returnhash;
2483: }
2484:
2485: sub inst_userrules {
1.923 raeburn 2486: my ($udom,$check) = @_;
1.912 raeburn 2487: my (%ruleshash,@ruleorder);
2488: if ($udom ne '') {
2489: my $homeserver=&domain($udom,'primary');
2490: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2491: my $response;
2492: if ($check eq 'id') {
2493: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2494: $homeserver);
1.943 raeburn 2495: } elsif ($check eq 'email') {
2496: $response=&reply('instemailrules:'.&escape($udom),
2497: $homeserver);
1.923 raeburn 2498: } else {
2499: $response=&reply('instuserrules:'.&escape($udom),
2500: $homeserver);
2501: }
1.912 raeburn 2502: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2503: ($response ne 'unknown_cmd') &&
1.912 raeburn 2504: ($response ne 'no_such_host')) {
2505: my ($hashitems,$orderitems) = split(/:/,$response);
2506: my @pairs=split(/\&/,$hashitems);
2507: foreach my $item (@pairs) {
2508: my ($key,$value)=split(/=/,$item,2);
2509: $key = &unescape($key);
2510: next if ($key =~ /^error: 2 /);
2511: $ruleshash{$key}=&thaw_unescape($value);
2512: }
2513: my @esc_order = split(/\&/,$orderitems);
2514: foreach my $item (@esc_order) {
2515: push(@ruleorder,&unescape($item));
2516: }
2517: }
2518: }
2519: }
2520: return (\%ruleshash,\@ruleorder);
2521: }
2522:
1.976 raeburn 2523: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2524:
2525: sub get_domain_defaults {
1.1240 raeburn 2526: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2527: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2528: my $cachetime = 60*60*24;
1.1240 raeburn 2529: unless ($ignore_cache) {
2530: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2531: if (defined($cached)) {
2532: if (ref($result) eq 'HASH') {
2533: return %{$result};
2534: }
1.943 raeburn 2535: }
2536: }
2537: my %domdefaults;
2538: my %domconfig =
1.989 raeburn 2539: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2540: 'requestcourses','inststatus',
1.1183 raeburn 2541: 'coursedefaults','usersessions',
1.1258 raeburn 2542: 'requestauthor','selfenrollment',
1.1320 raeburn 2543: 'coursecategories','ssl','autoenroll',
1.1332 raeburn 2544: 'trust','helpsettings'],$domain);
1.1305 raeburn 2545: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2546: if (ref($domconfig{'defaults'}) eq 'HASH') {
2547: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2548: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2549: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2550: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2551: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2552: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340 raeburn 2553: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2554: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2555: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2556: } else {
2557: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2558: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2559: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2560: }
1.976 raeburn 2561: if (ref($domconfig{'quotas'}) eq 'HASH') {
2562: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2563: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2564: } else {
2565: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2566: }
1.1177 raeburn 2567: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2568: foreach my $item (@usertools) {
2569: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2570: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2571: }
2572: }
1.1229 raeburn 2573: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2574: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2575: }
1.976 raeburn 2576: }
1.985 raeburn 2577: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2578: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2579: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2580: }
2581: }
1.1183 raeburn 2582: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2583: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2584: }
1.989 raeburn 2585: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2586: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2587: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2588: }
2589: }
1.1047 raeburn 2590: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2591: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2592: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2593: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2594: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2595: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2596: }
1.1254 raeburn 2597: foreach my $type (@coursetypes) {
2598: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2599: unless ($type eq 'community') {
2600: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2601: }
2602: }
2603: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2604: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2605: }
1.1277 raeburn 2606: if ($domdefaults{'postsubmit'} eq 'on') {
2607: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2608: $domdefaults{$type.'postsubtimeout'} =
2609: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2610: }
2611: }
1.1230 raeburn 2612: }
1.1286 raeburn 2613: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2614: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2615: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2616: if (@clonecodes) {
2617: $domdefaults{'canclone'} = join('+',@clonecodes);
2618: }
2619: }
2620: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2621: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2622: }
1.1356 raeburn 2623: if ($domconfig{'coursedefaults'}{'texengine'}) {
2624: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2625: }
1.1047 raeburn 2626: }
1.1073 raeburn 2627: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2628: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2629: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2630: }
2631: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2632: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2633: }
1.1279 raeburn 2634: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2635: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2636: }
1.1073 raeburn 2637: }
1.1254 raeburn 2638: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2639: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2640: my @settings = ('types','registered','enroll_dates','access_dates','section',
2641: 'approval','limit');
2642: foreach my $type (@coursetypes) {
2643: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2644: my @mgrdc = ();
2645: foreach my $item (@settings) {
2646: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2647: push(@mgrdc,$item);
2648: }
2649: }
2650: if (@mgrdc) {
2651: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2652: }
2653: }
2654: }
2655: }
2656: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2657: foreach my $type (@coursetypes) {
2658: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2659: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2660: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2661: }
2662: }
2663: }
2664: }
2665: }
1.1258 raeburn 2666: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2667: $domdefaults{'catauth'} = 'std';
2668: $domdefaults{'catunauth'} = 'std';
2669: if ($domconfig{'coursecategories'}{'auth'}) {
2670: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2671: }
2672: if ($domconfig{'coursecategories'}{'unauth'}) {
2673: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2674: }
2675: }
1.1315 raeburn 2676: if (ref($domconfig{'ssl'}) eq 'HASH') {
2677: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2678: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2679: }
1.1338 raeburn 2680: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2681: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2682: }
2683: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2684: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315 raeburn 2685: }
2686: }
1.1320 raeburn 2687: if (ref($domconfig{'trust'}) eq 'HASH') {
2688: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2689: foreach my $prefix (@prefixes) {
2690: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2691: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2692: }
2693: }
2694: }
1.1314 raeburn 2695: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2696: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2697: }
1.1332 raeburn 2698: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2699: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2700: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2701: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2702: }
2703: }
1.1219 raeburn 2704: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2705: return %domdefaults;
2706: }
2707:
1.1311 raeburn 2708: sub course_portal_url {
2709: my ($cnum,$cdom) = @_;
2710: my $chome = &homeserver($cnum,$cdom);
2711: my $hostname = &hostname($chome);
2712: my $protocol = $protocol{$chome};
2713: $protocol = 'http' if ($protocol ne 'https');
2714: my %domdefaults = &get_domain_defaults($cdom);
2715: my $firsturl;
2716: if ($domdefaults{'portal_def'}) {
2717: $firsturl = $domdefaults{'portal_def'};
2718: } else {
2719: $firsturl = $protocol.'://'.$hostname;
2720: }
2721: return $firsturl;
2722: }
2723:
1.1407 ! raeburn 2724: # --------------------------------------------- Get domain config for passwords
! 2725:
! 2726: sub get_passwdconf {
! 2727: my ($dom) = @_;
! 2728: my (%passwdconf,$gotconf,$lookup);
! 2729: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
! 2730: if (defined($cached)) {
! 2731: if (ref($result) eq 'HASH') {
! 2732: %passwdconf = %{$result};
! 2733: $gotconf = 1;
! 2734: }
! 2735: }
! 2736: unless ($gotconf) {
! 2737: my %domconfig = &get_dom('configuration',['passwords'],$dom);
! 2738: if (ref($domconfig{'passwords'}) eq 'HASH') {
! 2739: %passwdconf = %{$domconfig{'passwords'}};
! 2740: }
! 2741: my $cachetime = 24*60*60;
! 2742: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
! 2743: }
! 2744: return %passwdconf;
! 2745: }
! 2746:
1.344 www 2747: # --------------------------------------------------- Assign a key to a student
2748:
2749: sub assign_access_key {
1.364 www 2750: #
2751: # a valid key looks like uname:udom#comments
2752: # comments are being appended
2753: #
1.498 www 2754: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2755: $kdom=
1.620 albertel 2756: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2757: $knum=
1.620 albertel 2758: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2759: $cdom=
1.620 albertel 2760: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2761: $cnum=
1.620 albertel 2762: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2763: $udom=$env{'user.name'} unless (defined($udom));
2764: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2765: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2766: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2767: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2768: # assigned to this person
2769: # - this should not happen,
1.345 www 2770: # unless something went wrong
2771: # the first time around
2772: # ready to assign
1.364 www 2773: $logentry=$1.'; '.$logentry;
1.496 www 2774: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2775: $kdom,$knum) eq 'ok') {
1.345 www 2776: # key now belongs to user
1.346 www 2777: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2778: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2779: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2780: return 'ok';
2781: } else {
2782: return
2783: 'error: Count not permanently assign key, will need to be re-entered later.';
2784: }
2785: } else {
2786: return 'error: Could not assign key, try again later.';
2787: }
1.364 www 2788: } elsif (!$existing{$ckey}) {
1.345 www 2789: # the key does not exist
2790: return 'error: The key does not exist';
2791: } else {
2792: # the key is somebody else's
2793: return 'error: The key is already in use';
2794: }
1.344 www 2795: }
2796:
1.364 www 2797: # ------------------------------------------ put an additional comment on a key
2798:
2799: sub comment_access_key {
2800: #
2801: # a valid key looks like uname:udom#comments
2802: # comments are being appended
2803: #
2804: my ($ckey,$cdom,$cnum,$logentry)=@_;
2805: $cdom=
1.620 albertel 2806: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2807: $cnum=
1.620 albertel 2808: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2809: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2810: if ($existing{$ckey}) {
2811: $existing{$ckey}.='; '.$logentry;
2812: # ready to assign
1.367 www 2813: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2814: $cdom,$cnum) eq 'ok') {
2815: return 'ok';
2816: } else {
2817: return 'error: Count not store comment.';
2818: }
2819: } else {
2820: # the key does not exist
2821: return 'error: The key does not exist';
2822: }
2823: }
2824:
1.344 www 2825: # ------------------------------------------------------ Generate a set of keys
2826:
2827: sub generate_access_keys {
1.364 www 2828: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2829: $cdom=
1.620 albertel 2830: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2831: $cnum=
1.620 albertel 2832: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2833: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2834: unless (($cdom) && ($cnum)) { return 0; }
2835: if ($number>10000) { return 0; }
2836: sleep(2); # make sure don't get same seed twice
2837: srand(time()^($$+($$<<15))); # from "Programming Perl"
2838: my $total=0;
2839: for (my $i=1;$i<=$number;$i++) {
2840: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2841: sprintf("%lx",int(100000*rand)).'-'.
2842: sprintf("%lx",int(100000*rand));
2843: $newkey=~s/1/g/g; # folks mix up 1 and l
2844: $newkey=~s/0/h/g; # and also 0 and O
2845: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2846: if ($existing{$newkey}) {
2847: $i--;
2848: } else {
1.364 www 2849: if (&put('accesskeys',
2850: { $newkey => '# generated '.localtime().
1.620 albertel 2851: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2852: '; '.$logentry },
2853: $cdom,$cnum) eq 'ok') {
1.344 www 2854: $total++;
2855: }
2856: }
2857: }
1.620 albertel 2858: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2859: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2860: return $total;
2861: }
2862:
2863: # ------------------------------------------------------- Validate an accesskey
2864:
2865: sub validate_access_key {
2866: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2867: $cdom=
1.620 albertel 2868: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2869: $cnum=
1.620 albertel 2870: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2871: $udom=$env{'user.domain'} unless (defined($udom));
2872: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2873: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2874: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2875: }
2876:
2877: # ------------------------------------- Find the section of student in a course
1.652 albertel 2878: sub devalidate_getsection_cache {
2879: my ($udom,$unam,$courseid)=@_;
2880: my $hashid="$udom:$unam:$courseid";
2881: &devalidate_cache_new('getsection',$hashid);
2882: }
1.298 matthew 2883:
1.815 albertel 2884: sub courseid_to_courseurl {
2885: my ($courseid) = @_;
2886: #already url style courseid
2887: return $courseid if ($courseid =~ m{^/});
2888:
2889: if (exists($env{'course.'.$courseid.'.num'})) {
2890: my $cnum = $env{'course.'.$courseid.'.num'};
2891: my $cdom = $env{'course.'.$courseid.'.domain'};
2892: return "/$cdom/$cnum";
2893: }
2894:
2895: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2896: if (exists($courseinfo{'num'})) {
2897: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2898: }
2899:
2900: return undef;
2901: }
2902:
1.298 matthew 2903: sub getsection {
2904: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2905: my $cachetime=1800;
1.551 albertel 2906:
2907: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2908: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2909: if (defined($cached)) { return $result; }
2910:
1.298 matthew 2911: my %Pending;
2912: my %Expired;
2913: #
2914: # Each role can either have not started yet (pending), be active,
2915: # or have expired.
2916: #
2917: # If there is an active role, we are done.
2918: #
2919: # If there is more than one role which has not started yet,
2920: # choose the one which will start sooner
2921: # If there is one role which has not started yet, return it.
2922: #
2923: # If there is more than one expired role, choose the one which ended last.
2924: # If there is a role which has expired, return it.
2925: #
1.815 albertel 2926: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2927: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2928: foreach my $key (keys(%roleshash)) {
1.479 albertel 2929: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2930: my $section=$1;
2931: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2932: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2933: my $now=time;
1.548 albertel 2934: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2935: $Expired{$end}=$section;
2936: next;
2937: }
1.548 albertel 2938: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2939: $Pending{$start}=$section;
2940: next;
2941: }
1.599 albertel 2942: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2943: }
2944: #
2945: # Presumedly there will be few matching roles from the above
2946: # loop and the sorting time will be negligible.
2947: if (scalar(keys(%Pending))) {
2948: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2949: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2950: }
2951: if (scalar(keys(%Expired))) {
2952: my @sorted = sort {$a <=> $b} keys(%Expired);
2953: my $time = pop(@sorted);
1.599 albertel 2954: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2955: }
1.599 albertel 2956: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2957: }
1.70 www 2958:
1.599 albertel 2959: sub save_cache {
2960: &purge_remembered();
1.722 albertel 2961: #&Apache::loncommon::validate_page();
1.620 albertel 2962: undef(%env);
1.780 albertel 2963: undef($env_loaded);
1.599 albertel 2964: }
1.452 albertel 2965:
1.599 albertel 2966: my $to_remember=-1;
2967: my %remembered;
2968: my %accessed;
2969: my $kicks=0;
2970: my $hits=0;
1.849 albertel 2971: sub make_key {
2972: my ($name,$id) = @_;
1.872 albertel 2973: if (length($id) > 65
2974: && length(&escape($id)) > 200) {
2975: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2976: }
1.849 albertel 2977: return &escape($name.':'.$id);
2978: }
2979:
1.599 albertel 2980: sub devalidate_cache_new {
2981: my ($name,$id,$debug) = @_;
2982: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 2983: my $remembered_id=$name.':'.$id;
1.849 albertel 2984: $id=&make_key($name,$id);
1.599 albertel 2985: $memcache->delete($id);
1.1319 damieng 2986: delete($remembered{$remembered_id});
2987: delete($accessed{$remembered_id});
1.599 albertel 2988: }
2989:
2990: sub is_cached_new {
2991: my ($name,$id,$debug) = @_;
1.1319 damieng 2992: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
2993: if (exists($remembered{$remembered_id})) {
2994: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2995: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2996: $hits++;
1.1319 damieng 2997: return ($remembered{$remembered_id},1);
1.599 albertel 2998: }
1.1319 damieng 2999: $id=&make_key($name,$id);
1.599 albertel 3000: my $value = $memcache->get($id);
3001: if (!(defined($value))) {
3002: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 3003: return (undef,undef);
1.416 albertel 3004: }
1.599 albertel 3005: if ($value eq '__undef__') {
3006: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3007: $value=undef;
3008: }
1.1319 damieng 3009: &make_room($remembered_id,$value,$debug);
1.599 albertel 3010: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3011: return ($value,1);
3012: }
3013:
3014: sub do_cache_new {
3015: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 3016: my $remembered_id=$name.':'.$id;
1.849 albertel 3017: $id=&make_key($name,$id);
1.599 albertel 3018: my $setvalue=$value;
3019: if (!defined($setvalue)) {
3020: $setvalue='__undef__';
3021: }
1.623 albertel 3022: if (!defined($time) ) {
3023: $time=600;
3024: }
1.599 albertel 3025: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 3026: my $result = $memcache->set($id,$setvalue,$time);
3027: if (! $result) {
1.872 albertel 3028: &logthis("caching of id -> $id failed");
1.910 albertel 3029: $memcache->disconnect_all();
1.872 albertel 3030: }
1.600 albertel 3031: # need to make a copy of $value
1.1319 damieng 3032: &make_room($remembered_id,$value,$debug);
1.599 albertel 3033: return $value;
3034: }
3035:
3036: sub make_room {
1.1319 damieng 3037: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 3038:
1.1319 damieng 3039: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 3040: : $value;
1.599 albertel 3041: if ($to_remember<0) { return; }
1.1319 damieng 3042: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3043: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3044: my $to_kick;
3045: my $max_time=0;
3046: foreach my $other (keys(%accessed)) {
3047: if (&tv_interval($accessed{$other}) > $max_time) {
3048: $to_kick=$other;
3049: $max_time=&tv_interval($accessed{$other});
3050: }
3051: }
3052: delete($remembered{$to_kick});
3053: delete($accessed{$to_kick});
3054: $kicks++;
3055: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 3056: return;
3057: }
3058:
1.599 albertel 3059: sub purge_remembered {
1.604 albertel 3060: #&logthis("Tossing ".scalar(keys(%remembered)));
3061: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 3062: undef(%remembered);
3063: undef(%accessed);
1.428 albertel 3064: }
1.70 www 3065: # ------------------------------------- Read an entry from a user's environment
3066:
3067: sub userenvironment {
3068: my ($udom,$unam,@what)=@_;
1.976 raeburn 3069: my $items;
3070: foreach my $item (@what) {
3071: $items.=&escape($item).'&';
3072: }
3073: $items=~s/\&$//;
1.70 www 3074: my %returnhash=();
1.1009 raeburn 3075: my $uhome = &homeserver($unam,$udom);
3076: unless ($uhome eq 'no_host') {
3077: my @answer=split(/\&/,
3078: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 3079: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3080: return %returnhash;
3081: }
1.1009 raeburn 3082: my $i;
3083: for ($i=0;$i<=$#what;$i++) {
3084: $returnhash{$what[$i]}=&unescape($answer[$i]);
3085: }
1.70 www 3086: }
3087: return %returnhash;
1.1 albertel 3088: }
3089:
1.617 albertel 3090: # ---------------------------------------------------------- Get a studentphoto
3091: sub studentphoto {
3092: my ($udom,$unam,$ext) = @_;
3093: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 3094: if (defined($env{'request.course.id'})) {
1.708 raeburn 3095: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 3096: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3097: return(&retrievestudentphoto($udom,$unam,$ext));
3098: } else {
3099: my ($result,$perm_reqd)=
1.707 albertel 3100: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 3101: if ($result eq 'ok') {
3102: if (!($perm_reqd eq 'yes')) {
3103: return(&retrievestudentphoto($udom,$unam,$ext));
3104: }
3105: }
3106: }
3107: }
3108: } else {
3109: my ($result,$perm_reqd) =
1.707 albertel 3110: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 3111: if ($result eq 'ok') {
3112: if (!($perm_reqd eq 'yes')) {
3113: return(&retrievestudentphoto($udom,$unam,$ext));
3114: }
3115: }
3116: }
3117: return '/adm/lonKaputt/lonlogo_broken.gif';
3118: }
3119:
3120: sub retrievestudentphoto {
3121: my ($udom,$unam,$ext,$type) = @_;
3122: my $home=&Apache::lonnet::homeserver($unam,$udom);
3123: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
3124: if ($ret eq 'ok') {
3125: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3126: if ($type eq 'thumbnail') {
3127: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3128: }
3129: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
3130: return $tokenurl;
3131: } else {
3132: if ($type eq 'thumbnail') {
3133: return '/adm/lonKaputt/genericstudent_tn.gif';
3134: } else {
3135: return '/adm/lonKaputt/lonlogo_broken.gif';
3136: }
1.617 albertel 3137: }
3138: }
3139:
1.263 www 3140: # -------------------------------------------------------------------- New chat
3141:
3142: sub chatsend {
1.724 raeburn 3143: my ($newentry,$anon,$group)=@_;
1.620 albertel 3144: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3145: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3146: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 3147: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 3148: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 3149: &escape($newentry)).':'.$group,$chome);
1.292 www 3150: }
3151:
3152: # ------------------------------------------ Find current version of a resource
3153:
3154: sub getversion {
3155: my $fname=&clutter(shift);
1.1189 raeburn 3156: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3157: return ¤tversion(&filelocation('',$fname));
3158: }
3159:
3160: sub currentversion {
3161: my $fname=shift;
3162: my $author=$fname;
3163: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3164: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3165: my $home=&homeserver($uname,$udom);
1.292 www 3166: if ($home eq 'no_host') {
3167: return -1;
3168: }
1.1112 www 3169: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3170: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3171: return -1;
3172: }
1.1112 www 3173: return $answer;
1.263 www 3174: }
3175:
1.1111 www 3176: #
3177: # Return special version number of resource if set by override, empty otherwise
3178: #
3179: sub usedversion {
3180: my $fname=shift;
3181: unless ($fname) { $fname=$env{'request.uri'}; }
3182: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3183: if ($urlversion) { return $urlversion; }
3184: return '';
3185: }
3186:
1.1 albertel 3187: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3188:
1.1 albertel 3189: sub subscribe {
3190: my $fname=shift;
1.761 raeburn 3191: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3192: $fname=~s/[\n\r]//g;
1.1 albertel 3193: my $author=$fname;
3194: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3195: my ($udom,$uname)=split(/\//,$author);
3196: my $home=homeserver($uname,$udom);
1.335 albertel 3197: if ($home eq 'no_host') {
3198: return 'not_found';
1.1 albertel 3199: }
3200: my $answer=reply("sub:$fname",$home);
1.64 www 3201: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3202: $answer.=' by '.$home;
3203: }
1.1 albertel 3204: return $answer;
3205: }
3206:
1.8 www 3207: # -------------------------------------------------------------- Replicate file
3208:
3209: sub repcopy {
3210: my $filename=shift;
1.23 www 3211: $filename=~s/\/+/\//g;
1.1142 raeburn 3212: my $londocroot = $perlvar{'lonDocRoot'};
3213: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3214: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3215: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3216: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3217: return &repcopy_userfile($filename);
3218: }
1.532 albertel 3219: $filename=~s/[\n\r]//g;
1.8 www 3220: my $transname="$filename.in.transfer";
1.828 www 3221: # FIXME: this should flock
1.607 raeburn 3222: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3223: my $remoteurl=subscribe($filename);
1.64 www 3224: if ($remoteurl =~ /^con_lost by/) {
3225: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3226: return 'unavailable';
1.8 www 3227: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3228: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3229: return 'not_found';
1.64 www 3230: } elsif ($remoteurl =~ /^rejected by/) {
3231: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3232: return 'forbidden';
1.20 www 3233: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3234: return 'ok';
1.8 www 3235: } else {
1.290 www 3236: my $author=$filename;
3237: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3238: my ($udom,$uname)=split(/\//,$author);
3239: my $home=homeserver($uname,$udom);
3240: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3241: my @parts=split(/\//,$filename);
3242: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3243: if ($path ne "$londocroot/res") {
1.8 www 3244: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3245: return 'bad_request';
1.8 www 3246: }
3247: my $count;
3248: for ($count=5;$count<$#parts;$count++) {
3249: $path.="/$parts[$count]";
3250: if ((-e $path)!=1) {
3251: mkdir($path,0777);
3252: }
3253: }
3254: my $request=new HTTP::Request('GET',"$remoteurl");
1.1345 raeburn 3255: my $response;
3256: if ($remoteurl =~ m{/raw/}) {
3257: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3258: } else {
3259: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3260: }
1.8 www 3261: if ($response->is_error()) {
3262: unlink($transname);
3263: my $message=$response->status_line;
1.672 albertel 3264: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3265: ." LWP get: $message: $filename</font>");
1.607 raeburn 3266: return 'unavailable';
1.8 www 3267: } else {
1.16 www 3268: if ($remoteurl!~/\.meta$/) {
3269: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345 raeburn 3270: my $mresponse;
3271: if ($remoteurl =~ m{/raw/}) {
3272: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3273: } else {
3274: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3275: }
1.16 www 3276: if ($mresponse->is_error()) {
3277: unlink($filename.'.meta');
3278: &logthis(
1.672 albertel 3279: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3280: }
3281: }
1.8 www 3282: rename($transname,$filename);
1.607 raeburn 3283: return 'ok';
1.8 www 3284: }
1.290 www 3285: }
1.8 www 3286: }
1.330 www 3287: }
3288:
3289: # ------------------------------------------------ Get server side include body
3290: sub ssi_body {
1.381 albertel 3291: my ($filelink,%form)=@_;
1.606 matthew 3292: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3293: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3294: }
1.953 www 3295: my $output='';
3296: my $response;
1.980 raeburn 3297: if ($filelink=~/^https?\:/) {
1.954 raeburn 3298: ($output,$response)=&externalssi($filelink);
1.953 www 3299: } else {
1.1004 droeschl 3300: $filelink .= $filelink=~/\?/ ? '&' : '?';
3301: $filelink .= 'inhibitmenu=yes';
1.953 www 3302: ($output,$response)=&ssi($filelink,%form);
3303: }
1.778 albertel 3304: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3305: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3306: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3307: if (wantarray) {
3308: return ($output, $response);
3309: } else {
3310: return $output;
3311: }
1.8 www 3312: }
3313:
1.15 www 3314: # --------------------------------------------------------- Server Side Include
3315:
1.782 albertel 3316: sub absolute_url {
3317: my ($host_name) = @_;
3318: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3319: if ($host_name eq '') {
3320: $host_name = $ENV{'SERVER_NAME'};
3321: }
3322: return $protocol.$host_name;
3323: }
3324:
1.942 foxr 3325: #
3326: # Server side include.
3327: # Parameters:
3328: # fn Possibly encrypted resource name/id.
3329: # form Hash that describes how the rendering should be done
3330: # and other things.
1.944 foxr 3331: # Returns:
1.950 raeburn 3332: # Scalar context: The content of the response.
3333: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3334: #
1.15 www 3335: sub ssi {
3336:
1.944 foxr 3337: my ($fn,%form)=@_;
1.23 www 3338: my $request;
1.711 albertel 3339:
3340: $form{'no_update_last_known'}=1;
1.895 albertel 3341: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3342: if (%form) {
1.782 albertel 3343: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 3344: $request->content(join('&',map {
3345: my $name = escape($_);
3346: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3347: ? join("&$name=", map {escape($_) } @{$form{$_}})
3348: : &escape($form{$_}) );
3349: } keys(%form)));
1.23 www 3350: } else {
1.782 albertel 3351: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3352: }
3353:
1.15 www 3354: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345 raeburn 3355: my $lonhost = $perlvar{'lonHostID'};
1.1385 raeburn 3356: my $islocal;
3357: if (($env{'request.course.id'}) &&
3358: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3359: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3360: ($form{'grade_symb'} ne '') &&
3361: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3362: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
3363: $islocal = 1;
3364: }
1.1384 raeburn 3365: my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385 raeburn 3366: '','','',$islocal);
1.1182 foxr 3367:
1.944 foxr 3368: if (wantarray) {
1.1345 raeburn 3369: return ($response->content, $response);
1.944 foxr 3370: } else {
1.1345 raeburn 3371: return $response->content;
1.942 foxr 3372: }
1.324 www 3373: }
3374:
3375: sub externalssi {
3376: my ($url)=@_;
3377: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 3378: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954 raeburn 3379: if (wantarray) {
3380: return ($response->content, $response);
3381: } else {
3382: return $response->content;
3383: }
1.15 www 3384: }
1.254 www 3385:
1.1354 raeburn 3386:
3387: # If the local copy of a replicated resource is outdated, trigger a
3388: # connection from the homeserver to flush the delayed queue. If no update
3389: # happens, remove local copies of outdated resource (and corresponding
3390: # metadata file).
3391:
1.1352 raeburn 3392: sub remove_stale_resfile {
3393: my ($url) = @_;
1.1354 raeburn 3394: my $removed;
1.1352 raeburn 3395: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3396: my $audom = $1;
3397: my $auname = $2;
1.1353 raeburn 3398: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352 raeburn 3399: my $homeserver = &homeserver($auname,$audom);
3400: unless (($homeserver eq 'no_host') ||
3401: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3402: my $fname = &filelocation('',$url);
3403: if (-e $fname) {
3404: my $hostname = &hostname($homeserver);
3405: if ($hostname) {
1.1397 raeburn 3406: my $protocol = $protocol{$homeserver};
3407: $protocol = 'http' if ($protocol ne 'https');
1.1352 raeburn 3408: my $uri = &declutter($url);
3409: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3410: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3411: if ($response->is_success()) {
3412: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3413: my $locmodtime = (stat($fname))[9];
3414: if ($locmodtime < $remmodtime) {
1.1354 raeburn 3415: my $stale;
3416: my $answer = &reply('pong',$homeserver);
3417: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3418: sleep(0.2);
3419: $locmodtime = (stat($fname))[9];
3420: if ($locmodtime < $remmodtime) {
3421: my $posstransfer = $fname.'.in.transfer';
3422: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3423: $removed = 1;
3424: } else {
3425: $stale = 1;
3426: }
3427: } else {
3428: $removed = 1;
3429: }
3430: } else {
3431: $stale = 1;
3432: }
3433: if ($stale) {
3434: unlink($fname);
3435: if ($uri!~/\.meta$/) {
3436: unlink($fname.'.meta');
3437: }
3438: &reply("unsub:$fname",$homeserver);
3439: $removed = 1;
1.1352 raeburn 3440: }
3441: }
3442: }
3443: }
3444: }
3445: }
3446: }
3447: }
1.1354 raeburn 3448: return $removed;
1.1352 raeburn 3449: }
3450:
1.492 albertel 3451: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3452:
3453: sub allowuploaded {
3454: my ($srcurl,$url)=@_;
3455: $url=&clutter(&declutter($url));
3456: my $dir=$url;
3457: $dir=~s/\/[^\/]+$//;
3458: my %httpref=();
3459: my $httpurl=&hreflocation('',$url);
3460: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3461: &Apache::lonnet::appenv(\%httpref);
1.254 www 3462: }
1.477 raeburn 3463:
1.1193 raeburn 3464: #
3465: # Determine if the current user should be able to edit a particular resource,
3466: # when viewing in course context.
3467: # (a) When viewing resource used to determine if "Edit" item is included in
3468: # Functions.
3469: # (b) When displaying folder contents in course editor, used to determine if
3470: # "Edit" link will be displayed alongside resource.
3471: #
1.1196 raeburn 3472: # input: six args -- filename (decluttered), course number, course domain,
3473: # url, symb (if registered) and group (if this is a group
3474: # item -- e.g., bulletin board, group page etc.).
3475: # output: array of five scalars --
1.1193 raeburn 3476: # $cfile -- url for file editing if editable on current server
3477: # $home -- homeserver of resource (i.e., for author if published,
3478: # or course if uploaded.).
3479: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3480: # $forceedit -- 1 if icon/link should be to go to edit mode
3481: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3482: #
3483:
3484: sub can_edit_resource {
1.1194 raeburn 3485: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3486: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3487: #
3488: # For aboutme pages user can only edit his/her own.
3489: #
1.1199 raeburn 3490: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3491: my ($sdom,$sname) = ($1,$2);
3492: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3493: $home = $env{'user.home'};
3494: $cfile = $resurl;
3495: if ($env{'form.forceedit'}) {
3496: $forceview = 1;
3497: } else {
3498: $forceedit = 1;
3499: }
3500: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3501: } else {
3502: return;
3503: }
3504: }
3505:
3506: if ($env{'request.course.id'}) {
3507: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3508: if ($group ne '') {
3509: # if this is a group homepage or group bulletin board, check group privs
3510: my $allowed = 0;
1.1197 raeburn 3511: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3512: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3513: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3514: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3515: $allowed = 1;
3516: }
1.1197 raeburn 3517: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3518: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3519: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3520: $allowed = 1;
3521: }
3522: }
3523: if ($allowed) {
3524: $home=&homeserver($cnum,$cdom);
3525: if ($env{'form.forceedit'}) {
3526: $forceview = 1;
3527: } else {
3528: $forceedit = 1;
3529: }
3530: $cfile = $resurl;
3531: } else {
3532: return;
3533: }
3534: } else {
1.1208 raeburn 3535: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3536: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3537: return;
3538: }
3539: } elsif (!$crsedit) {
1.1194 raeburn 3540: #
3541: # No edit allowed where CC has switched to student role.
3542: #
3543: return;
3544: }
3545: }
3546: }
3547:
1.1193 raeburn 3548: if ($file ne '') {
3549: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3550: if (&is_course_upload($file,$cnum,$cdom)) {
3551: $uploaded = 1;
3552: $incourse = 1;
1.1193 raeburn 3553: if ($file =~/\.(htm|html|css|js|txt)$/) {
3554: $cfile = &hreflocation('',$file);
1.1201 raeburn 3555: if ($env{'form.forceedit'}) {
3556: $forceview = 1;
3557: } else {
3558: $forceedit = 1;
3559: }
1.1194 raeburn 3560: }
3561: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3562: $incourse = 1;
3563: if ($env{'form.forceedit'}) {
3564: $forceview = 1;
3565: } else {
3566: $forceedit = 1;
3567: }
3568: $cfile = $resurl;
3569: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3570: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3571: $incourse = 1;
3572: if ($env{'form.forceedit'}) {
3573: $forceview = 1;
3574: } else {
3575: $forceedit = 1;
3576: }
3577: $cfile = $resurl;
1.1199 raeburn 3578: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3579: $incourse = 1;
3580: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3581: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3582: $incourse = 1;
1.1199 raeburn 3583: if ($env{'form.forceedit'}) {
3584: $forceview = 1;
3585: } else {
3586: $forceedit = 1;
3587: }
3588: $cfile = $resurl;
1.1343 raeburn 3589: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3590: $incourse = 1;
3591: if ($env{'form.forceedit'}) {
3592: $forceview = 1;
3593: } else {
3594: $forceedit = 1;
3595: }
3596: $cfile = $resurl;
1.1208 raeburn 3597: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3598: $incourse = 1;
3599: if ($env{'form.forceedit'}) {
3600: $forceview = 1;
3601: } else {
3602: $forceedit = 1;
3603: }
3604: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3605: }
3606: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3607: my $template = '/res/lib/templates/simpleproblem.problem';
3608: if (&is_on_map($template)) {
3609: $incourse = 1;
3610: $forceview = 1;
3611: $cfile = $template;
1.1193 raeburn 3612: }
1.1199 raeburn 3613: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3614: $incourse = 1;
3615: if ($env{'form.forceedit'}) {
3616: $forceview = 1;
3617: } else {
3618: $forceedit = 1;
3619: }
3620: $cfile = $resurl;
1.1343 raeburn 3621: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298 raeburn 3622: $incourse = 1;
3623: if ($env{'form.forceedit'}) {
3624: $forceview = 1;
3625: } else {
3626: $forceedit = 1;
3627: }
3628: $cfile = $resurl;
1.1199 raeburn 3629: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3630: $incourse = 1;
3631: $forceview = 1;
3632: if ($symb) {
3633: my ($map,$id,$res)=&decode_symb($symb);
3634: $env{'request.symb'} = $symb;
3635: $cfile = &clutter($res);
3636: } else {
3637: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3638: my $escfile = &unescape($cfile);
1.1343 raeburn 3639: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3640: $cfile = '/adm/wrapper'.$escfile;
3641: } else {
3642: $escfile =~ s{^http://}{};
3643: $cfile = &escape("/adm/wrapper/ext/$escfile");
3644: }
1.1199 raeburn 3645: }
1.1234 raeburn 3646: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3647: if ($env{'form.forceedit'}) {
3648: $forceview = 1;
3649: } else {
3650: $forceedit = 1;
3651: }
3652: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3653: }
3654: }
1.1194 raeburn 3655: if ($uploaded || $incourse) {
3656: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3657: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3658: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3659: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3660: # Check that the user has permission to edit this resource
3661: my $setpriv = 1;
3662: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3663: if (defined($cfudom)) {
3664: $home=&homeserver($cfuname,$cfudom);
3665: $cfile=$file;
3666: }
3667: }
1.1194 raeburn 3668: if (($cfile ne '') && (!$incourse || $uploaded) &&
3669: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3670: my @ids=¤t_machine_ids();
3671: unless (grep(/^\Q$home\E$/,@ids)) {
3672: $switchserver=1;
3673: }
3674: }
3675: }
1.1194 raeburn 3676: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3677: }
3678:
3679: sub is_course_upload {
3680: my ($file,$cnum,$cdom) = @_;
3681: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3682: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3683: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3684: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3685: return 1;
3686: }
3687: return;
3688: }
3689:
1.1194 raeburn 3690: sub in_course {
1.1195 raeburn 3691: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3692: if ($hideprivileged) {
3693: my $skipuser;
1.1219 raeburn 3694: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3695: my @possdoms = ($cdom);
3696: if ($coursehash{'checkforpriv'}) {
3697: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3698: }
3699: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3700: $skipuser = 1;
3701: if ($coursehash{'nothideprivileged'}) {
3702: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3703: my $user;
3704: if ($item =~ /:/) {
3705: $user = $item;
3706: } else {
3707: $user = join(':',split(/[\@]/,$item));
3708: }
3709: if ($user eq $uname.':'.$udom) {
3710: undef($skipuser);
3711: last;
3712: }
3713: }
3714: }
3715: if ($skipuser) {
3716: return 0;
3717: }
3718: }
3719: }
1.1194 raeburn 3720: $type ||= 'any';
3721: if (!defined($cdom) || !defined($cnum)) {
3722: my $cid = $env{'request.course.id'};
3723: $cdom = $env{'course.'.$cid.'.domain'};
3724: $cnum = $env{'course.'.$cid.'.num'};
3725: }
3726: my $typesref;
1.1195 raeburn 3727: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3728: $typesref = ['active','previous','future'];
3729: } elsif ($type eq 'previous' || $type eq 'future') {
3730: $typesref = [$type];
3731: }
3732: my %roles = &get_my_roles($uname,$udom,'userroles',
3733: $typesref,undef,[$cdom]);
3734: my ($tmp) = keys(%roles);
3735: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3736: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3737: if (@course_roles > 0) {
3738: return 1;
3739: }
3740: return 0;
3741: }
3742:
1.478 albertel 3743: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3744: # input: action, courseID, current domain, intended
1.637 raeburn 3745: # path to file, source of file, instruction to parse file for objects,
3746: # ref to hash for embedded objects,
3747: # ref to hash for codebase of java objects.
1.1095 raeburn 3748: # reference to scalar to accommodate mime type determined
3749: # from File::MMagic if $parser = parse.
1.637 raeburn 3750: #
1.485 raeburn 3751: # output: url to file (if action was uploaddoc),
3752: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3753: #
1.478 albertel 3754: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3755: # course.
1.477 raeburn 3756: #
1.478 albertel 3757: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3758: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3759: # course's home server.
1.477 raeburn 3760: #
1.478 albertel 3761: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3762: # be copied from $source (current location) to
3763: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3764: # and will then be copied to
3765: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3766: # course's home server.
1.485 raeburn 3767: #
1.481 raeburn 3768: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3769: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3770: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3771: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3772: # in course's home server.
1.637 raeburn 3773: #
1.477 raeburn 3774:
3775: sub process_coursefile {
1.1095 raeburn 3776: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3777: $mimetype)=@_;
1.477 raeburn 3778: my $fetchresult;
1.638 albertel 3779: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3780: if ($action eq 'propagate') {
1.638 albertel 3781: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3782: $home);
1.481 raeburn 3783: } else {
1.477 raeburn 3784: my $fpath = '';
3785: my $fname = $file;
1.478 albertel 3786: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3787: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3788: my $filepath = &build_filepath($fpath);
1.481 raeburn 3789: if ($action eq 'copy') {
3790: if ($source eq '') {
3791: $fetchresult = 'no source file';
3792: return $fetchresult;
3793: } else {
3794: my $destination = $filepath.'/'.$fname;
3795: rename($source,$destination);
3796: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3797: $home);
1.481 raeburn 3798: }
3799: } elsif ($action eq 'uploaddoc') {
1.1359 raeburn 3800: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3801: print $fh $env{'form.'.$source};
1.481 raeburn 3802: close($fh);
1.637 raeburn 3803: if ($parser eq 'parse') {
1.1024 raeburn 3804: my $mm = new File::MMagic;
1.1095 raeburn 3805: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3806: if ($type eq 'text/html') {
1.1024 raeburn 3807: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3808: unless ($parse_result eq 'ok') {
3809: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3810: }
1.637 raeburn 3811: }
1.1095 raeburn 3812: if (ref($mimetype)) {
3813: $$mimetype = $type;
3814: }
1.637 raeburn 3815: }
1.477 raeburn 3816: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3817: $home);
1.481 raeburn 3818: if ($fetchresult eq 'ok') {
3819: return '/uploaded/'.$fpath.'/'.$fname;
3820: } else {
3821: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3822: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3823: return '/adm/notfound.html';
3824: }
1.477 raeburn 3825: }
3826: }
1.485 raeburn 3827: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3828: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3829: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3830: }
3831: return $fetchresult;
3832: }
3833:
1.637 raeburn 3834: sub build_filepath {
3835: my ($fpath) = @_;
3836: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3837: unless ($fpath eq '') {
3838: my @parts=split('/',$fpath);
3839: foreach my $part (@parts) {
3840: $filepath.= '/'.$part;
3841: if ((-e $filepath)!=1) {
3842: mkdir($filepath,0777);
3843: }
3844: }
3845: }
3846: return $filepath;
3847: }
3848:
3849: sub store_edited_file {
1.638 albertel 3850: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3851: my $file = $primary_url;
3852: $file =~ s#^/uploaded/$docudom/$docuname/##;
3853: my $fpath = '';
3854: my $fname = $file;
3855: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3856: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3857: my $filepath = &build_filepath($fpath);
1.1359 raeburn 3858: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3859: print $fh $content;
3860: close($fh);
1.638 albertel 3861: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3862: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3863: $home);
1.637 raeburn 3864: if ($$fetchresult eq 'ok') {
3865: return '/uploaded/'.$fpath.'/'.$fname;
3866: } else {
1.638 albertel 3867: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3868: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3869: return '/adm/notfound.html';
3870: }
3871: }
3872:
1.531 albertel 3873: sub clean_filename {
1.831 albertel 3874: my ($fname,$args)=@_;
1.315 www 3875: # Replace Windows backslashes by forward slashes
1.257 www 3876: $fname=~s/\\/\//g;
1.831 albertel 3877: if (!$args->{'keep_path'}) {
3878: # Get rid of everything but the actual filename
3879: $fname=~s/^.*\/([^\/]+)$/$1/;
3880: }
1.315 www 3881: # Replace spaces by underscores
3882: $fname=~s/\s+/\_/g;
1.1406 raeburn 3883: # Transliterate non-ascii text to ascii
3884: my $lang = &Apache::lonlocal::current_language();
3885: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 3886: # Replace all other weird characters by nothing
1.831 albertel 3887: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3888: # Replace all .\d. sequences with _\d. so they no longer look like version
3889: # numbers
3890: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3891: return $fname;
3892: }
1.1406 raeburn 3893:
1.1051 raeburn 3894: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3895: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3896: # image with the same aspect ratio as the original, but with dimensions which do
3897: # not exceed $resizewidth and $resizeheight.
3898:
1.984 neumanie 3899: sub resizeImage {
1.1051 raeburn 3900: my ($img_path,$resizewidth,$resizeheight) = @_;
3901: my $ima = Image::Magick->new;
3902: my $resized;
3903: if (-e $img_path) {
3904: $ima->Read($img_path);
3905: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3906: my $width = $ima->Get('width');
3907: my $height = $ima->Get('height');
3908: if ($width > $resizewidth) {
3909: my $factor = $width/$resizewidth;
3910: my $newheight = $height/$factor;
3911: $ima->Scale(width=>$resizewidth,height=>$newheight);
3912: $resized = 1;
3913: }
3914: }
3915: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3916: my $width = $ima->Get('width');
3917: my $height = $ima->Get('height');
3918: if ($height > $resizeheight) {
3919: my $factor = $height/$resizeheight;
3920: my $newwidth = $width/$factor;
3921: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3922: $resized = 1;
3923: }
3924: }
3925: if ($resized) {
3926: $ima->Write($img_path);
3927: }
3928: }
3929: return;
1.977 amueller 3930: }
3931:
1.608 albertel 3932: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3933: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3934: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3935: # $context - possible values: coursedoc, existingfile, overwrite,
1.1401 raeburn 3936: # canceloverwrite, scantron or ''.
1.1090 raeburn 3937: # if 'coursedoc': upload to the current course
3938: # if 'existingfile': write file to tmp/overwrites directory
3939: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3940: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3941: # $subdir - directory in userfile to store the file into
1.1401 raeburn 3942: # $parser - instruction to parse file for objects ($parser = parse) or
3943: # if context is 'scantron', $parser is hashref of csv column mapping
3944: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
3945: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 3946: # $allfiles - reference to hash for embedded objects
3947: # $codebase - reference to hash for codebase of java objects
3948: # $desuname - username for permanent storage of uploaded file
3949: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3950: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3951: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3952: # $resizewidth - width (pixels) to which to resize uploaded image
3953: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3954: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3955: # from File::MMagic.
1.858 raeburn 3956: #
1.686 albertel 3957: # output: url of file in userspace, or error: <message>
3958: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3959:
1.531 albertel 3960: sub userfileupload {
1.1090 raeburn 3961: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3962: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3963: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3964: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3965: $fname=&clean_filename($fname);
1.1090 raeburn 3966: # See if there is anything left
1.257 www 3967: unless ($fname) { return 'error: no uploaded file'; }
1.1406 raeburn 3968: # If filename now begins with a . prepend unix timestamp _ milliseconds
3969: if ($fname =~ /^\./) {
3970: my ($s,$usec) = &gettimeofday();
3971: while (length($usec) < 6) {
3972: $usec = '0'.$usec;
3973: }
3974: $fname = $s.'_'.substr($usec,0,3).$fname;
3975: }
1.1090 raeburn 3976: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3977: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3978: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3979: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3980: my $now = time;
1.1090 raeburn 3981: my $filepath;
1.1095 raeburn 3982: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3983: $filepath = 'tmp/helprequests/'.$now;
3984: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3985: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3986: '_'.$env{'user.domain'}.'/pending';
3987: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3988: my ($docuname,$docudom);
1.1350 raeburn 3989: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3990: $docudom = $destudom;
3991: } else {
3992: $docudom = $env{'user.domain'};
3993: }
1.1350 raeburn 3994: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3995: $docuname = $destuname;
3996: } else {
3997: $docuname = $env{'user.name'};
3998: }
3999: if (exists($env{'form.group'})) {
4000: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4001: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4002: }
4003: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4004: if ($context eq 'canceloverwrite') {
4005: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4006: if (-e $tempfile) {
4007: my @info = stat($tempfile);
4008: if ($info[9] eq $env{'form.timestamp'}) {
4009: unlink($tempfile);
4010: }
4011: }
4012: return;
1.523 raeburn 4013: }
4014: }
1.1090 raeburn 4015: # Create the directory if not present
1.741 raeburn 4016: my @parts=split(/\//,$filepath);
4017: my $fullpath = $perlvar{'lonDaemons'};
4018: for (my $i=0;$i<@parts;$i++) {
4019: $fullpath .= '/'.$parts[$i];
4020: if ((-e $fullpath)!=1) {
4021: mkdir($fullpath,0777);
4022: }
4023: }
1.1359 raeburn 4024: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 4025: print $fh $env{'form.'.$formname};
4026: close($fh);
1.1090 raeburn 4027: if ($context eq 'existingfile') {
4028: my @info = stat($fullpath.'/'.$fname);
4029: return ($fullpath.'/'.$fname,$info[9]);
4030: } else {
4031: return $fullpath.'/'.$fname;
4032: }
1.523 raeburn 4033: }
1.995 raeburn 4034: if ($subdir eq 'scantron') {
4035: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 4036: } else {
1.995 raeburn 4037: $fname="$subdir/$fname";
4038: }
1.1090 raeburn 4039: if ($context eq 'coursedoc') {
1.638 albertel 4040: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4041: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 4042: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 4043: return &finishuserfileupload($docuname,$docudom,
4044: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 4045: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 4046: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 4047: } else {
1.1218 raeburn 4048: if ($env{'form.folder'}) {
4049: $fname=$env{'form.folder'}.'/'.$fname;
4050: }
1.638 albertel 4051: return &process_coursefile('uploaddoc',$docuname,$docudom,
4052: $fname,$formname,$parser,
1.1095 raeburn 4053: $allfiles,$codebase,$mimetype);
1.481 raeburn 4054: }
1.719 banghart 4055: } elsif (defined($destuname)) {
4056: my $docuname=$destuname;
4057: my $docudom=$destudom;
1.860 raeburn 4058: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4059: $parser,$allfiles,$codebase,
1.1051 raeburn 4060: $thumbwidth,$thumbheight,
1.1095 raeburn 4061: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4062: } else {
1.638 albertel 4063: my $docuname=$env{'user.name'};
4064: my $docudom=$env{'user.domain'};
1.1220 raeburn 4065: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 4066: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4067: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4068: }
1.860 raeburn 4069: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4070: $parser,$allfiles,$codebase,
1.1051 raeburn 4071: $thumbwidth,$thumbheight,
1.1095 raeburn 4072: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4073: }
1.271 www 4074: }
4075:
4076: sub finishuserfileupload {
1.860 raeburn 4077: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4078: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4079: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4080: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4081:
1.860 raeburn 4082: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4083: $file=$fname;
4084: if ($fname=~m|/|) {
4085: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4086: $path.=$fnamepath.'/';
4087: }
1.259 www 4088: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4089: my $count;
4090: for ($count=4;$count<=$#parts;$count++) {
4091: $filepath.="/$parts[$count]";
4092: if ((-e $filepath)!=1) {
4093: mkdir($filepath,0777);
4094: }
4095: }
1.984 neumanie 4096:
1.258 www 4097: # Save the file
4098: {
1.1359 raeburn 4099: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4100: &logthis('Failed to create '.$filepath.'/'.$file);
4101: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4102: return '/adm/notfound.html';
4103: }
1.1090 raeburn 4104: if ($context eq 'overwrite') {
1.1117 foxr 4105: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4106: my $target = $filepath.'/'.$file;
4107: if (-e $source) {
4108: my @info = stat($source);
4109: if ($info[9] eq $env{'form.timestamp'}) {
4110: unless (&File::Copy::move($source,$target)) {
4111: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4112: return "Moving from $source failed";
4113: }
4114: } else {
4115: return "Temporary file: $source had unexpected date/time for last modification";
4116: }
4117: } else {
4118: return "Temporary file: $source missing";
4119: }
4120: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4121: &logthis('Failed to write to '.$filepath.'/'.$file);
4122: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4123: return '/adm/notfound.html';
4124: }
1.570 albertel 4125: close(FH);
1.1051 raeburn 4126: if ($resizewidth && $resizeheight) {
4127: my $mm = new File::MMagic;
4128: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4129: if ($mime_type =~ m{^image/}) {
4130: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4131: }
1.977 amueller 4132: }
1.258 www 4133: }
1.1152 raeburn 4134: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4135: if (ref($mimetype)) {
4136: if ($$mimetype eq '') {
4137: my $mm = new File::MMagic;
4138: my $type = $mm->checktype_filename($filepath.'/'.$file);
4139: $$mimetype = $type;
4140: }
4141: }
4142: }
1.1401 raeburn 4143: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4144: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4145: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4146: $allfiles,$codebase);
4147: unless ($parse_result eq 'ok') {
4148: &logthis('Failed to parse '.$filepath.$file.
4149: ' for embedded media: '.$parse_result);
4150: }
1.637 raeburn 4151: }
1.1401 raeburn 4152: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4153: my $format = $env{'form.scantron_format'};
4154: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4155: }
1.860 raeburn 4156: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4157: my $input = $filepath.'/'.$file;
4158: my $output = $filepath.'/'.'tn-'.$file;
4159: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359 raeburn 4160: my @args = ('convert','-sample',$thumbsize,$input,$output);
4161: system({$args[0]} @args);
1.860 raeburn 4162: if (-e $filepath.'/'.'tn-'.$file) {
4163: $fetchthumb = 1;
4164: }
4165: }
1.858 raeburn 4166:
1.259 www 4167: # Notify homeserver to grep it
4168: #
1.984 neumanie 4169: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4170: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4171: if ($fetchresult eq 'ok') {
1.860 raeburn 4172: if ($fetchthumb) {
4173: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4174: if ($thumbresult ne 'ok') {
4175: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4176: $docuhome.': '.$thumbresult);
4177: }
4178: }
1.259 www 4179: #
1.258 www 4180: # Return the URL to it
1.494 albertel 4181: return '/uploaded/'.$path.$file;
1.263 www 4182: } else {
1.494 albertel 4183: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4184: ': '.$fetchresult);
1.263 www 4185: return '/adm/notfound.html';
1.858 raeburn 4186: }
1.493 albertel 4187: }
4188:
1.637 raeburn 4189: sub extract_embedded_items {
1.961 raeburn 4190: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4191: my @state = ();
1.1164 raeburn 4192: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4193: my %javafiles = (
4194: codebase => '',
4195: code => '',
4196: archive => ''
4197: );
4198: my %mediafiles = (
4199: src => '',
4200: movie => '',
4201: );
1.648 raeburn 4202: my $p;
4203: if ($content) {
4204: $p = HTML::LCParser->new($content);
4205: } else {
1.961 raeburn 4206: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4207: }
1.641 albertel 4208: while (my $t=$p->get_token()) {
1.640 albertel 4209: if ($t->[0] eq 'S') {
4210: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4211: push(@state, $tagname);
1.648 raeburn 4212: if (lc($tagname) eq 'allow') {
4213: &add_filetype($allfiles,$attr->{'src'},'src');
4214: }
1.640 albertel 4215: if (lc($tagname) eq 'img') {
4216: &add_filetype($allfiles,$attr->{'src'},'src');
4217: }
1.886 albertel 4218: if (lc($tagname) eq 'a') {
1.1222 raeburn 4219: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 4220: &add_filetype($allfiles,$attr->{'href'},'href');
4221: }
1.886 albertel 4222: }
1.645 raeburn 4223: if (lc($tagname) eq 'script') {
1.1164 raeburn 4224: my $src;
1.645 raeburn 4225: if ($attr->{'archive'} =~ /\.jar$/i) {
4226: &add_filetype($allfiles,$attr->{'archive'},'archive');
4227: } else {
1.1164 raeburn 4228: if ($attr->{'src'} ne '') {
4229: $src = $attr->{'src'};
4230: &add_filetype($allfiles,$src,'src');
4231: }
4232: }
4233: my $text = $p->get_trimmed_text();
4234: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4235: my @swfargs = split(/,/,$1);
4236: foreach my $item (@swfargs) {
4237: $item =~ s/["']//g;
4238: $item =~ s/^\s+//;
4239: $item =~ s/\s+$//;
4240: }
4241: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4242: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4243: push(@{$related{$swfargs[0]}},$swfargs[2]);
4244: } else {
4245: $related{$swfargs[0]} = [$swfargs[2]];
4246: }
4247: }
1.645 raeburn 4248: }
4249: }
4250: if (lc($tagname) eq 'link') {
4251: if (lc($attr->{'rel'}) eq 'stylesheet') {
4252: &add_filetype($allfiles,$attr->{'href'},'href');
4253: }
4254: }
1.640 albertel 4255: if (lc($tagname) eq 'object' ||
4256: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4257: foreach my $item (keys(%javafiles)) {
4258: $javafiles{$item} = '';
4259: }
1.1164 raeburn 4260: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4261: $lastids{lc($tagname)} = $attr->{'id'};
4262: }
1.640 albertel 4263: }
4264: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4265: my $name = lc($attr->{'name'});
4266: foreach my $item (keys(%javafiles)) {
4267: if ($name eq $item) {
4268: $javafiles{$item} = $attr->{'value'};
4269: last;
4270: }
4271: }
1.1164 raeburn 4272: my $pathfrom;
1.640 albertel 4273: foreach my $item (keys(%mediafiles)) {
4274: if ($name eq $item) {
1.1164 raeburn 4275: $pathfrom = $attr->{'value'};
4276: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4277: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4278: last;
4279: }
4280: }
1.1164 raeburn 4281: if ($name eq 'flashvars') {
4282: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4283: }
4284: if ($pathfrom ne '') {
4285: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4286: $pathfrom);
4287: }
1.640 albertel 4288: }
4289: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4290: foreach my $item (keys(%javafiles)) {
4291: if ($attr->{$item}) {
4292: $javafiles{$item} = $attr->{$item};
4293: last;
4294: }
4295: }
4296: foreach my $item (keys(%mediafiles)) {
4297: if ($attr->{$item}) {
4298: &add_filetype($allfiles,$attr->{$item},$item);
4299: last;
4300: }
4301: }
1.1164 raeburn 4302: if (lc($tagname) eq 'embed') {
4303: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4304: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4305: $attr->{'src'});
4306: }
4307: }
1.640 albertel 4308: }
1.1243 raeburn 4309: if (lc($tagname) eq 'iframe') {
4310: my $src = $attr->{'src'} ;
4311: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4312: &add_filetype($allfiles,$src,'src');
4313: } elsif ($src =~ m{^/}) {
4314: if ($env{'request.course.id'}) {
4315: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4316: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4317: my $url = &hreflocation('',$fullpath);
4318: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4319: my $relpath = $1;
4320: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4321: &add_filetype($allfiles,$1,'src');
4322: }
4323: }
4324: }
4325: }
4326: }
1.1164 raeburn 4327: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 4328: pop(@state);
1.1164 raeburn 4329: }
1.640 albertel 4330: } elsif ($t->[0] eq 'E') {
4331: my ($tagname) = ($t->[1]);
4332: if ($javafiles{'codebase'} ne '') {
4333: $javafiles{'codebase'} .= '/';
4334: }
4335: if (lc($tagname) eq 'applet' ||
4336: lc($tagname) eq 'object' ||
4337: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4338: ) {
4339: foreach my $item (keys(%javafiles)) {
4340: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4341: my $file=$javafiles{'codebase'}.$javafiles{$item};
4342: &add_filetype($allfiles,$file,$item);
4343: }
4344: }
4345: }
4346: pop @state;
4347: }
4348: }
1.1164 raeburn 4349: foreach my $id (sort(keys(%flashvars))) {
4350: if ($shockwave{$id} ne '') {
4351: my @pairs = split(/\&/,$flashvars{$id});
4352: foreach my $pair (@pairs) {
4353: my ($key,$value) = split(/\=/,$pair);
4354: if ($key eq 'thumb') {
4355: &add_filetype($allfiles,$value,$key);
4356: } elsif ($key eq 'content') {
4357: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4358: my ($ext) = ($value =~ /\.([^.]+)$/);
4359: if ($ext ne '') {
4360: &add_filetype($allfiles,$path.$value,$ext);
4361: }
4362: }
4363: }
4364: }
4365: }
1.637 raeburn 4366: return 'ok';
4367: }
4368:
1.639 albertel 4369: sub add_filetype {
4370: my ($allfiles,$file,$type)=@_;
4371: if (exists($allfiles->{$file})) {
4372: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4373: push(@{$allfiles->{$file}}, &escape($type));
4374: }
4375: } else {
4376: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4377: }
4378: }
4379:
1.1164 raeburn 4380: sub embedded_dependency {
4381: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4382: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4383: if (($identifier ne '') &&
4384: (ref($related->{$identifier}) eq 'ARRAY') &&
4385: ($pathfrom ne '')) {
4386: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4387: foreach my $dep (@{$related->{$identifier}}) {
4388: &add_filetype($allfiles,$path.$dep,'object');
4389: }
4390: }
4391: }
4392: return;
4393: }
4394:
1.1401 raeburn 4395: sub bubblesheet_converter {
4396: my ($cdom,$fullpath,$config,$format) = @_;
4397: if ((&domain($cdom) ne '') &&
1.1403 raeburn 4398: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401 raeburn 4399: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404 raeburn 4400: my (%csvcols,%csvoptions);
4401: if (ref($config->{'fields'}) eq 'HASH') {
4402: %csvcols = %{$config->{'fields'}};
4403: }
4404: if (ref($config->{'options'}) eq 'HASH') {
4405: %csvoptions = %{$config->{'options'}};
4406: }
1.1401 raeburn 4407: my %csvbynum = reverse(%csvcols);
4408: my %scantronconf = &get_scantron_config($format,$cdom);
4409: if (keys(%scantronconf)) {
4410: my %bynum = (
4411: $scantronconf{CODEstart} => 'CODEstart',
4412: $scantronconf{IDstart} => 'IDstart',
4413: $scantronconf{PaperID} => 'PaperID',
4414: $scantronconf{FirstName} => 'FirstName',
4415: $scantronconf{LastName} => 'LastName',
4416: $scantronconf{Qstart} => 'Qstart',
4417: );
4418: my @ordered;
4419: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403 raeburn 4420: push(@ordered,$bynum{$item});
1.1401 raeburn 4421: }
4422: my %mapstart = (
4423: CODEstart => 'CODE',
4424: IDstart => 'ID',
4425: PaperID => 'PaperID',
4426: FirstName => 'FirstName',
4427: LastName => 'LastName',
4428: Qstart => 'FirstQuestion',
4429: );
4430: my %maplength = (
4431: CODEstart => 'CODElength',
4432: IDstart => 'IDlength',
4433: PaperID => 'PaperIDlength',
4434: FirstName => 'FirstNamelength',
4435: LastName => 'LastNamelength',
4436: );
4437: if (open(my $fh,'<',$fullpath)) {
4438: my $output;
1.1403 raeburn 4439: my %lettdig = &letter_to_digits();
4440: my %diglett = reverse(%lettdig);
4441: my $numletts = scalar(keys(%lettdig));
1.1404 raeburn 4442: my $num = 0;
1.1401 raeburn 4443: while (my $line=<$fh>) {
1.1404 raeburn 4444: $num ++;
4445: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401 raeburn 4446: $line =~ s{[\r\n]+$}{};
4447: my %found;
4448: my @values = split(/,/,$line);
4449: my ($qstart,$record);
4450: for (my $i=0; $i<@values; $i++) {
1.1403 raeburn 4451: if ((($qstart ne '') && ($i > $qstart)) ||
4452: ($csvbynum{$i} eq 'FirstQuestion')) {
4453: if ($values[$i] eq '') {
4454: $values[$i] = $scantronconf{'Qoff'};
4455: } elsif ($scantronconf{'Qon'} eq 'number') {
4456: if ($values[$i] =~ /^[A-Ja-j]$/) {
4457: $values[$i] = $lettdig{uc($values[$i])};
4458: }
4459: } elsif ($scantronconf{'Qon'} eq 'letter') {
4460: if ($values[$i] =~ /^[0-9]$/) {
4461: $values[$i] = $diglett{$values[$i]};
4462: }
4463: } else {
4464: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4465: my $digit;
4466: if ($values[$i] =~ /^[A-Ja-j]$/) {
4467: $digit = $lettdig{uc($values[$i])}-1;
4468: if ($values[$i] eq 'J') {
4469: $digit += $numletts;
4470: }
4471: } elsif ($values[$i] =~ /^[0-9]$/) {
4472: $digit = $values[$i]-1;
4473: if ($values[$i] eq '0') {
4474: $digit += $numletts;
4475: }
4476: }
4477: my $qval='';
4478: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4479: if ($j == $digit) {
4480: $qval .= $scantronconf{'Qon'};
4481: } else {
4482: $qval .= $scantronconf{'Qoff'};
4483: }
4484: }
4485: $values[$i] = $qval;
4486: }
4487: }
4488: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4489: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4490: }
4491: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4492: if ($numblank > 0) {
4493: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4494: }
1.1401 raeburn 4495: if ($csvbynum{$i} eq 'FirstQuestion') {
4496: $qstart = $i;
1.1403 raeburn 4497: $found{$csvbynum{$i}} = $values[$i];
1.1401 raeburn 4498: } else {
1.1403 raeburn 4499: $found{'FirstQuestion'} .= $values[$i];
4500: }
4501: } elsif (exists($csvbynum{$i})) {
1.1404 raeburn 4502: if ($csvoptions{'rem'}) {
4503: $values[$i] =~ s/^\s+//;
4504: }
4505: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403 raeburn 4506: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4507: $values[$i] = '0'.$values[$i];
1.1401 raeburn 4508: }
4509: }
4510: $found{$csvbynum{$i}} = $values[$i];
4511: }
4512: }
4513: foreach my $item (@ordered) {
4514: my $currlength = 1+length($record);
4515: my $numspaces = $scantronconf{$item} - $currlength;
4516: if ($numspaces > 0) {
4517: $record .= (' ' x $numspaces);
4518: }
4519: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4520: unless ($item eq 'Qstart') {
4521: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4522: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4523: }
4524: }
4525: $record .= $found{$mapstart{$item}};
4526: }
4527: }
4528: $output .= "$record\n";
4529: }
4530: close($fh);
4531: if ($output) {
4532: if (open(my $fh,'>',$fullpath)) {
4533: print $fh $output;
4534: close($fh);
4535: }
4536: }
4537: }
4538: }
4539: return;
4540: }
4541: }
4542:
1.1403 raeburn 4543: sub letter_to_digits {
4544: my %lettdig = (
4545: A => 1,
4546: B => 2,
4547: C => 3,
4548: D => 4,
4549: E => 5,
4550: F => 6,
4551: G => 7,
4552: H => 8,
4553: I => 9,
4554: J => 0,
4555: );
4556: return %lettdig;
4557: }
4558:
1.1401 raeburn 4559: sub get_scantron_config {
4560: my ($which,$cdom) = @_;
4561: my @lines = &get_scantronformat_file($cdom);
4562: my %config;
4563: #FIXME probably should move to XML it has already gotten a bit much now
4564: foreach my $line (@lines) {
4565: my ($name,$descrip)=split(/:/,$line);
4566: if ($name ne $which ) { next; }
4567: chomp($line);
4568: my @config=split(/:/,$line);
4569: $config{'name'}=$config[0];
4570: $config{'description'}=$config[1];
4571: $config{'CODElocation'}=$config[2];
4572: $config{'CODEstart'}=$config[3];
4573: $config{'CODElength'}=$config[4];
4574: $config{'IDstart'}=$config[5];
4575: $config{'IDlength'}=$config[6];
4576: $config{'Qstart'}=$config[7];
4577: $config{'Qlength'}=$config[8];
4578: $config{'Qoff'}=$config[9];
4579: $config{'Qon'}=$config[10];
4580: $config{'PaperID'}=$config[11];
4581: $config{'PaperIDlength'}=$config[12];
4582: $config{'FirstName'}=$config[13];
4583: $config{'FirstNamelength'}=$config[14];
4584: $config{'LastName'}=$config[15];
4585: $config{'LastNamelength'}=$config[16];
4586: $config{'BubblesPerRow'}=$config[17];
4587: last;
4588: }
4589: return %config;
4590: }
4591:
4592: sub get_scantronformat_file {
4593: my ($cdom) = @_;
4594: if ($cdom eq '') {
4595: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4596: }
4597: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4598: my $gottab = 0;
4599: my @lines;
4600: if (ref($domconfig{'scantron'}) eq 'HASH') {
4601: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4602: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4603: if ($formatfile ne '-1') {
4604: @lines = split("\n",$formatfile,-1);
4605: $gottab = 1;
4606: }
4607: }
4608: }
4609: if (!$gottab) {
4610: my $confname = $cdom.'-domainconfig';
4611: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4612: my $formatfile = &getfile($default);
4613: if ($formatfile ne '-1') {
4614: @lines = split("\n",$formatfile,-1);
4615: $gottab = 1;
4616: }
4617: }
4618: if (!$gottab) {
4619: my @domains = ¤t_machine_domains();
4620: if (grep(/^\Q$cdom\E$/,@domains)) {
4621: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4622: @lines = <$fh>;
4623: close($fh);
1.1403 raeburn 4624: }
1.1401 raeburn 4625: } else {
4626: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4627: @lines = <$fh>;
4628: close($fh);
4629: }
4630: }
4631: }
4632: return @lines;
4633: }
4634:
1.493 albertel 4635: sub removeuploadedurl {
1.984 neumanie 4636: my ($url)=@_;
4637: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4638: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4639: }
4640:
4641: sub removeuserfile {
4642: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4643: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4644: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4645: if ($result eq 'ok') {
1.798 raeburn 4646: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4647: my $metafile = $fname.'.meta';
4648: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4649: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4650: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4651: my $sqlresult =
1.823 albertel 4652: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4653: 'portfolio_metadata',$group,
4654: 'delete');
1.798 raeburn 4655: }
4656: }
4657: return $result;
1.257 www 4658: }
1.15 www 4659:
1.530 albertel 4660: sub mkdiruserfile {
4661: my ($docuname,$docudom,$dir)=@_;
4662: my $home=&homeserver($docuname,$docudom);
4663: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4664: }
4665:
1.531 albertel 4666: sub renameuserfile {
4667: my ($docuname,$docudom,$old,$new)=@_;
4668: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4669: my $result = &reply("renameuserfile:$docudom:$docuname:".
4670: &escape("$old").':'.&escape("$new"),$home);
4671: if ($result eq 'ok') {
4672: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4673: my $oldmeta = $old.'.meta';
4674: my $newmeta = $new.'.meta';
4675: my $metaresult =
4676: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4677: my $url = "/uploaded/$docudom/$docuname/$old";
4678: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4679: my $sqlresult =
1.823 albertel 4680: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4681: 'portfolio_metadata',$group,
4682: 'delete');
1.798 raeburn 4683: }
4684: }
4685: return $result;
1.531 albertel 4686: }
4687:
1.14 www 4688: # ------------------------------------------------------------------------- Log
4689:
4690: sub log {
4691: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4692: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4693: }
4694:
4695: # ------------------------------------------------------------------ Course Log
1.352 www 4696: #
4697: # This routine flushes several buffers of non-mission-critical nature
4698: #
1.157 www 4699:
4700: sub flushcourselogs {
1.352 www 4701: &logthis('Flushing log buffers');
4702: #
4703: # course logs
4704: # This is a log of all transactions in a course, which can be used
4705: # for data mining purposes
4706: #
4707: # It also collects the courseid database, which lists last transaction
4708: # times and course titles for all courseids
4709: #
4710: my %courseidbuffer=();
1.921 raeburn 4711: foreach my $crsid (keys(%courselogs)) {
1.352 www 4712: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4713: &escape($courselogs{$crsid}),
4714: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4715: delete $courselogs{$crsid};
4716: } else {
4717: &logthis('Failed to flush log buffer for '.$crsid);
4718: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4719: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4720: " exceeded maximum size, deleting.</font>");
4721: delete $courselogs{$crsid};
4722: }
1.352 www 4723: }
1.920 raeburn 4724: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4725: 'description' => $coursedescrbuf{$crsid},
4726: 'inst_code' => $courseinstcodebuf{$crsid},
4727: 'type' => $coursetypebuf{$crsid},
4728: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4729: };
1.191 harris41 4730: }
1.352 www 4731: #
4732: # Write course id database (reverse lookup) to homeserver of courses
4733: # Is used in pickcourse
4734: #
1.840 albertel 4735: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4736: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4737: $courseidbuffer{$crs_home},
4738: $crs_home,'timeonly');
1.352 www 4739: }
4740: #
4741: # File accesses
4742: # Writes to the dynamic metadata of resources to get hit counts, etc.
4743: #
1.449 matthew 4744: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4745: if ($entry =~ /___count$/) {
4746: my ($dom,$name);
1.807 albertel 4747: ($dom,$name,undef)=
1.811 albertel 4748: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4749: if (! defined($dom) || $dom eq '' ||
4750: ! defined($name) || $name eq '') {
1.620 albertel 4751: my $cid = $env{'request.course.id'};
4752: $dom = $env{'request.'.$cid.'.domain'};
4753: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4754: }
1.450 matthew 4755: my $value = $accesshash{$entry};
4756: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4757: my %temphash=($url => $value);
1.449 matthew 4758: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4759: if ($result eq 'ok') {
4760: delete $accesshash{$entry};
4761: }
4762: } else {
1.811 albertel 4763: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4764: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4765: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4766: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4767: delete $accesshash{$entry};
4768: }
1.185 www 4769: }
1.191 harris41 4770: }
1.352 www 4771: #
4772: # Roles
4773: # Reverse lookup of user roles for course faculty/staff and co-authorship
4774: #
1.800 albertel 4775: foreach my $entry (keys(%userrolehash)) {
1.351 www 4776: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4777: split(/\:/,$entry);
4778: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4779: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4780: $rudom,$runame) eq 'ok') {
4781: delete $userrolehash{$entry};
4782: }
4783: }
1.662 raeburn 4784: #
1.1334 raeburn 4785: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4786: #
4787: my %domrolebuffer = ();
1.1000 raeburn 4788: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4789: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4790: if ($domrolebuffer{$rudom}) {
4791: $domrolebuffer{$rudom}.='&'.&escape($entry).
4792: '='.&escape($domainrolehash{$entry});
4793: } else {
4794: $domrolebuffer{$rudom}.=&escape($entry).
4795: '='.&escape($domainrolehash{$entry});
4796: }
4797: delete $domainrolehash{$entry};
4798: }
4799: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 4800: my %servers;
4801: if (defined(&domain($dom,'primary'))) {
4802: my $primary=&domain($dom,'primary');
4803: my $hostname=&hostname($primary);
4804: $servers{$primary} = $hostname;
4805: } else {
4806: %servers = &get_servers($dom,'library');
4807: }
1.841 albertel 4808: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 4809: if (&reply('domroleput:'.$dom.':'.
4810: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4811: last;
4812: } else {
1.841 albertel 4813: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4814: }
1.662 raeburn 4815: }
4816: }
1.186 www 4817: $dumpcount++;
1.157 www 4818: }
4819:
4820: sub courselog {
4821: my $what=shift;
1.158 www 4822: $what=time.':'.$what;
1.620 albertel 4823: unless ($env{'request.course.id'}) { return ''; }
4824: $coursedombuf{$env{'request.course.id'}}=
4825: $env{'course.'.$env{'request.course.id'}.'.domain'};
4826: $coursenumbuf{$env{'request.course.id'}}=
4827: $env{'course.'.$env{'request.course.id'}.'.num'};
4828: $coursehombuf{$env{'request.course.id'}}=
4829: $env{'course.'.$env{'request.course.id'}.'.home'};
4830: $coursedescrbuf{$env{'request.course.id'}}=
4831: $env{'course.'.$env{'request.course.id'}.'.description'};
4832: $courseinstcodebuf{$env{'request.course.id'}}=
4833: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4834: $courseownerbuf{$env{'request.course.id'}}=
4835: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4836: $coursetypebuf{$env{'request.course.id'}}=
4837: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4838: if (defined $courselogs{$env{'request.course.id'}}) {
4839: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4840: } else {
1.620 albertel 4841: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4842: }
1.620 albertel 4843: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4844: &flushcourselogs();
4845: }
1.158 www 4846: }
4847:
4848: sub courseacclog {
4849: my $fnsymb=shift;
1.620 albertel 4850: unless ($env{'request.course.id'}) { return ''; }
4851: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4852: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4853: $what.=':POST';
1.583 matthew 4854: # FIXME: Probably ought to escape things....
1.800 albertel 4855: foreach my $key (keys(%env)) {
4856: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4857: my $formitem = $1;
4858: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4859: $what.=':'.$formitem.'='.$env{$key};
4860: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4861: $what.=':'.$formitem.'='.$env{$key};
4862: }
1.158 www 4863: }
1.191 harris41 4864: }
1.583 matthew 4865: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4866: # FIXME: We should not be depending on a form parameter that someone
4867: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4868: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4869: $what.= ':POST';
4870: # FIXME: Probably ought to escape things....
4871: foreach my $element ('courseexp','crsfulltext','crsrelated',
4872: 'crsdiscuss') {
1.620 albertel 4873: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4874: }
4875: }
1.158 www 4876: }
4877: &courselog($what);
1.149 www 4878: }
4879:
1.185 www 4880: sub countacc {
4881: my $url=&declutter(shift);
1.458 matthew 4882: return if (! defined($url) || $url eq '');
1.620 albertel 4883: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4884: #
4885: # Mark that this url was used in this course
4886: #
1.620 albertel 4887: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4888: #
4889: # Increase the access count for this resource in this child process
4890: #
1.281 www 4891: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4892: $accesshash{$key}++;
1.185 www 4893: }
1.349 www 4894:
1.361 www 4895: sub linklog {
4896: my ($from,$to)=@_;
4897: $from=&declutter($from);
4898: $to=&declutter($to);
4899: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4900: $accesshash{$to.'___'.$from.'___goto'}=1;
4901: }
1.1160 www 4902:
4903: sub statslog {
4904: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4905: if ($users<2) { return; }
4906: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4907: 'course' => $env{'request.course.id'},
4908: 'sections' => '"all"',
4909: 'num_students' => $users,
4910: 'part' => $part,
4911: 'symb' => $symb,
4912: 'mean_tries' => $av_attempts,
4913: 'deg_of_diff' => $degdiff});
4914: foreach my $key (keys(%dynstore)) {
4915: $accesshash{$key}=$dynstore{$key};
4916: }
4917: }
1.361 www 4918:
1.349 www 4919: sub userrolelog {
4920: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4921: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4922: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4923: $userrolehash
4924: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4925: =$tend.':'.$tstart;
1.662 raeburn 4926: }
1.1169 droeschl 4927: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4928: $userrolehash
4929: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4930: =$tend.':'.$tstart;
4931: }
1.1334 raeburn 4932: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4933: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4934: $domainrolehash
4935: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4936: = $tend.':'.$tstart;
4937: }
1.351 www 4938: }
4939:
1.957 raeburn 4940: sub courserolelog {
4941: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 4942: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4943: my $cdom = $1;
4944: my $cnum = $2;
4945: my $sec = $3;
4946: my $namespace = 'rolelog';
4947: my %storehash = (
4948: role => $trole,
4949: start => $tstart,
4950: end => $tend,
4951: selfenroll => $selfenroll,
4952: context => $context,
4953: );
4954: if ($trole eq 'gr') {
4955: $namespace = 'groupslog';
4956: $storehash{'group'} = $sec;
4957: } else {
4958: $storehash{'section'} = $sec;
4959: }
1.1188 raeburn 4960: &write_log('course',$namespace,\%storehash,$delflag,$username,
4961: $domain,$cnum,$cdom);
1.1184 raeburn 4962: if (($trole ne 'st') || ($sec ne '')) {
4963: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4964: }
4965: }
4966: return;
4967: }
4968:
1.1184 raeburn 4969: sub domainrolelog {
4970: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4971: if ($area =~ m{^/($match_domain)/$}) {
4972: my $cdom = $1;
4973: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4974: my $namespace = 'rolelog';
4975: my %storehash = (
4976: role => $trole,
4977: start => $tstart,
4978: end => $tend,
4979: context => $context,
4980: );
1.1188 raeburn 4981: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4982: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4983: }
4984: return;
4985:
4986: }
4987:
4988: sub coauthorrolelog {
4989: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4990: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4991: my $audom = $1;
4992: my $auname = $2;
4993: my $namespace = 'rolelog';
4994: my %storehash = (
4995: role => $trole,
4996: start => $tstart,
4997: end => $tend,
4998: context => $context,
4999: );
1.1188 raeburn 5000: &write_log('author',$namespace,\%storehash,$delflag,$username,
5001: $domain,$auname,$audom);
1.1184 raeburn 5002: }
5003: return;
5004: }
5005:
1.351 www 5006: sub get_course_adv_roles {
1.948 raeburn 5007: my ($cid,$codes) = @_;
1.620 albertel 5008: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 5009: my %coursehash=&coursedescription($cid);
1.988 raeburn 5010: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 5011: my %nothide=();
1.800 albertel 5012: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 5013: if ($user !~ /:/) {
5014: $nothide{join(':',split(/[\@]/,$user))}=1;
5015: } else {
5016: $nothide{$user}=1;
5017: }
1.470 www 5018: }
1.1219 raeburn 5019: my @possdoms = ($coursehash{'domain'});
5020: if ($coursehash{'checkforpriv'}) {
5021: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5022: }
1.351 www 5023: my %returnhash=();
5024: my %dumphash=
5025: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5026: my $now=time;
1.997 raeburn 5027: my %privileged;
1.1000 raeburn 5028: foreach my $entry (keys(%dumphash)) {
1.800 albertel 5029: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 5030: if (($tstart) && ($tstart<0)) { next; }
5031: if (($tend) && ($tend<$now)) { next; }
5032: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 5033: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 5034: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 5035: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 5036: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 5037: if ($role eq 'cr') { next; }
1.948 raeburn 5038: if ($codes) {
5039: if ($section) { $role .= ':'.$section; }
5040: if ($returnhash{$role}) {
5041: $returnhash{$role}.=','.$username.':'.$domain;
5042: } else {
5043: $returnhash{$role}=$username.':'.$domain;
5044: }
1.351 www 5045: } else {
1.988 raeburn 5046: my $key=&plaintext($role,$crstype);
1.973 bisitz 5047: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 5048: if ($returnhash{$key}) {
5049: $returnhash{$key}.=','.$username.':'.$domain;
5050: } else {
5051: $returnhash{$key}=$username.':'.$domain;
5052: }
1.351 www 5053: }
1.948 raeburn 5054: }
1.400 www 5055: return %returnhash;
5056: }
5057:
5058: sub get_my_roles {
1.937 raeburn 5059: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5060: unless (defined($uname)) { $uname=$env{'user.name'}; }
5061: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5062: my (%dumphash,%nothide);
1.1086 raeburn 5063: if ($context eq 'userroles') {
1.1166 raeburn 5064: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5065: } else {
1.1219 raeburn 5066: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5067: if ($hidepriv) {
5068: my %coursehash=&coursedescription($udom.'_'.$uname);
5069: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5070: if ($user !~ /:/) {
5071: $nothide{join(':',split(/[\@]/,$user))} = 1;
5072: } else {
5073: $nothide{$user} = 1;
5074: }
5075: }
5076: }
1.858 raeburn 5077: }
1.400 www 5078: my %returnhash=();
5079: my $now=time;
1.999 raeburn 5080: my %privileged;
1.800 albertel 5081: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5082: my ($role,$tend,$tstart);
5083: if ($context eq 'userroles') {
1.1149 raeburn 5084: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5085: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5086: } else {
5087: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5088: }
1.400 www 5089: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5090: my $status = 'active';
1.939 raeburn 5091: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5092: $status = 'previous';
5093: }
5094: if (($tstart) && ($now<$tstart)) {
5095: $status = 'future';
5096: }
5097: if (ref($types) eq 'ARRAY') {
5098: if (!grep(/^\Q$status\E$/,@{$types})) {
5099: next;
5100: }
5101: } else {
5102: if ($status ne 'active') {
5103: next;
5104: }
5105: }
1.867 raeburn 5106: my ($rolecode,$username,$domain,$section,$area);
5107: if ($context eq 'userroles') {
1.1186 raeburn 5108: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5109: (undef,$domain,$username,$section) = split(/\//,$area);
5110: } else {
5111: ($role,$username,$domain,$section) = split(/\:/,$entry);
5112: }
1.832 raeburn 5113: if (ref($roledoms) eq 'ARRAY') {
5114: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5115: next;
5116: }
5117: }
5118: if (ref($roles) eq 'ARRAY') {
5119: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5120: if ($role =~ /^cr\//) {
5121: if (!grep(/^cr$/,@{$roles})) {
5122: next;
5123: }
1.1104 raeburn 5124: } elsif ($role =~ /^gr\//) {
5125: if (!grep(/^gr$/,@{$roles})) {
5126: next;
5127: }
1.922 raeburn 5128: } else {
5129: next;
5130: }
1.832 raeburn 5131: }
1.867 raeburn 5132: }
1.937 raeburn 5133: if ($hidepriv) {
1.1219 raeburn 5134: my @privroles = ('dc','su');
1.999 raeburn 5135: if ($context eq 'userroles') {
1.1219 raeburn 5136: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5137: } else {
1.1219 raeburn 5138: my $possdoms = [$domain];
5139: if (ref($roledoms) eq 'ARRAY') {
5140: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5141: }
1.1219 raeburn 5142: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5143: if (!$nothide{$username.':'.$domain}) {
5144: next;
5145: }
5146: }
1.937 raeburn 5147: }
5148: }
1.933 raeburn 5149: if ($withsec) {
5150: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5151: $tstart.':'.$tend;
5152: } else {
5153: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5154: }
1.832 raeburn 5155: }
1.373 www 5156: return %returnhash;
1.399 www 5157: }
5158:
1.1333 raeburn 5159: sub get_all_adhocroles {
5160: my ($dom) = @_;
5161: my @roles_by_num = ();
5162: my %domdefaults = &get_domain_defaults($dom);
5163: my (%description,%access_in_dom,%access_info);
5164: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5165: my $count = 0;
5166: my %domcurrent = %{$domdefaults{'adhocroles'}};
5167: my %ordered;
5168: foreach my $role (sort(keys(%domcurrent))) {
5169: my ($order,$desc,$access_in_dom);
5170: if (ref($domcurrent{$role}) eq 'HASH') {
5171: $order = $domcurrent{$role}{'order'};
5172: $desc = $domcurrent{$role}{'desc'};
5173: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5174: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5175: }
5176: if ($order eq '') {
5177: $order = $count;
5178: }
5179: $ordered{$order} = $role;
5180: if ($desc ne '') {
5181: $description{$role} = $desc;
5182: } else {
5183: $description{$role}= $role;
5184: }
5185: $count++;
5186: }
5187: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5188: push(@roles_by_num,$ordered{$item});
5189: }
5190: }
5191: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5192: }
5193:
1.1332 raeburn 5194: sub get_my_adhocroles {
1.1333 raeburn 5195: my ($cid,$checkreg) = @_;
5196: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5197: if ($env{'request.course.id'} eq $cid) {
5198: $cdom = $env{'course.'.$cid.'.domain'};
5199: $cnum = $env{'course.'.$cid.'.num'};
5200: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5201: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5202: $cdom = $1;
5203: $cnum = $2;
5204: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5205: $cdom,$cnum);
5206: }
5207: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5208: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5209: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5210: if ($rosterhash{$user} ne '') {
5211: my $type = (split(/:/,$rosterhash{$user}))[5];
5212: return ([],{}) if ($type eq 'auto');
5213: }
5214: }
5215: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 5216: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 5217: my $then=$env{'user.login.time'};
5218: my $update=$env{'user.update.time'};
1.1335 raeburn 5219: if (!$update) {
5220: $update = $then;
5221: }
5222: my @liveroles;
1.1334 raeburn 5223: foreach my $role ('dh','da') {
5224: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 5225: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 5226: my $limit = $update;
5227: if ($env{'request.role'} eq "$role./$cdom/") {
5228: $limit = $then;
5229: }
1.1335 raeburn 5230: my $activerole = 1;
5231: if ($tstart && $tstart>$limit) { $activerole = 0; }
5232: if ($tend && $tend <$limit) { $activerole = 0; }
5233: if ($activerole) {
5234: push(@liveroles,$role);
5235: }
1.1334 raeburn 5236: }
1.1332 raeburn 5237: }
1.1335 raeburn 5238: if (@liveroles) {
1.1332 raeburn 5239: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 5240: my ($accessref,$accessinfo,%access_in_dom);
5241: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5242: if (ref($roles_by_num) eq 'ARRAY') {
5243: if (@{$roles_by_num}) {
1.1332 raeburn 5244: my %settings;
5245: if ($env{'request.course.id'} eq $cid) {
5246: foreach my $envkey (keys(%env)) {
5247: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5248: $settings{$1} = $env{$envkey};
5249: }
5250: }
5251: } else {
5252: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5253: }
5254: my %setincrs;
5255: if ($settings{'internal.adhocaccess'}) {
5256: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5257: }
5258: my @statuses;
5259: if ($env{'environment.inststatus'}) {
5260: @statuses = split(/,/,$env{'environment.inststatus'});
5261: }
5262: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 5263: if (ref($accessref) eq 'HASH') {
5264: %access_in_dom = %{$accessref};
5265: }
5266: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 5267: my ($curraccess,@okstatus,@personnel);
5268: if ($setincrs{$role}) {
5269: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5270: if ($curraccess eq 'status') {
5271: @okstatus = split(/\&/,$rest);
5272: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5273: @personnel = split(/\&/,$rest);
5274: }
5275: } else {
5276: $curraccess = $access_in_dom{$role};
1.1333 raeburn 5277: if (ref($accessinfo) eq 'HASH') {
5278: if ($curraccess eq 'status') {
5279: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5280: @okstatus = @{$accessinfo->{$role}};
5281: }
5282: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5283: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5284: @personnel = @{$accessinfo->{$role}};
5285: }
1.1332 raeburn 5286: }
5287: }
5288: }
5289: if ($curraccess eq 'none') {
5290: next;
5291: } elsif ($curraccess eq 'all') {
5292: push(@possroles,$role);
1.1336 raeburn 5293: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 5294: if (grep(/^dh$/,@liveroles)) {
5295: push(@possroles,$role);
5296: } else {
5297: next;
5298: }
1.1336 raeburn 5299: } elsif ($curraccess eq 'da') {
1.1335 raeburn 5300: if (grep(/^da$/,@liveroles)) {
5301: push(@possroles,$role);
5302: } else {
5303: next;
5304: }
1.1332 raeburn 5305: } elsif ($curraccess eq 'status') {
5306: if (@okstatus) {
5307: if (!@statuses) {
5308: if (grep(/^default$/,@okstatus)) {
5309: push(@possroles,$role);
5310: }
5311: } else {
5312: foreach my $status (@okstatus) {
5313: if (grep(/^\Q$status\E$/,@statuses)) {
5314: push(@possroles,$role);
5315: last;
5316: }
5317: }
5318: }
5319: }
5320: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5321: if (grep(/^\Q$user\E$/,@personnel)) {
5322: if ($curraccess eq 'exc') {
5323: push(@possroles,$role);
5324: }
5325: } elsif ($curraccess eq 'inc') {
5326: push(@possroles,$role);
5327: }
5328: }
5329: }
5330: }
5331: }
5332: }
5333: }
5334: }
5335: }
1.1333 raeburn 5336: unless (ref($description) eq 'HASH') {
5337: if (ref($roles_by_num) eq 'ARRAY') {
5338: my %desc;
5339: map { $desc{$_} = $_; } (@{$roles_by_num});
5340: $description = \%desc;
5341: } else {
5342: $description = {};
5343: }
5344: }
5345: return (\@possroles,$description);
1.1332 raeburn 5346: }
5347:
1.399 www 5348: # ----------------------------------------------------- Frontpage Announcements
5349: #
5350: #
5351:
5352: sub postannounce {
5353: my ($server,$text)=@_;
1.844 albertel 5354: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5355: unless ($text=~/\w/) { $text=''; }
5356: return &reply('setannounce:'.&escape($text),$server);
5357: }
5358:
5359: sub getannounce {
1.448 albertel 5360:
1.1359 raeburn 5361: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5362: my $announcement='';
1.800 albertel 5363: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5364: close($fh);
1.399 www 5365: if ($announcement=~/\w/) {
5366: return
5367: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5368: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5369: } else {
5370: return '';
5371: }
5372: } else {
5373: return '';
5374: }
1.351 www 5375: }
1.353 www 5376:
5377: # ---------------------------------------------------------- Course ID routines
5378: # Deal with domain's nohist_courseid.db files
5379: #
5380:
5381: sub courseidput {
1.921 raeburn 5382: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5383: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5384: my $outcome;
5385: if ($caller eq 'timeonly') {
5386: my $cids = '';
5387: foreach my $item (keys(%$storehash)) {
5388: $cids.=&escape($item).'&';
5389: }
5390: $cids=~s/\&$//;
5391: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5392: $coursehome);
5393: } else {
5394: my $items = '';
5395: foreach my $item (keys(%$storehash)) {
5396: $items.= &escape($item).'='.
5397: &freeze_escape($$storehash{$item}).'&';
5398: }
5399: $items=~s/\&$//;
5400: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5401: $coursehome);
1.918 raeburn 5402: }
5403: if ($outcome eq 'unknown_cmd') {
5404: my $what;
5405: foreach my $cid (keys(%$storehash)) {
5406: $what .= &escape($cid).'=';
1.921 raeburn 5407: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5408: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5409: }
5410: $what =~ s/\:$/&/;
5411: }
5412: $what =~ s/\&$//;
5413: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5414: } else {
5415: return $outcome;
5416: }
1.353 www 5417: }
5418:
5419: sub courseiddump {
1.921 raeburn 5420: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5421: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5422: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 5423: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 5424: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5425: my $as_hash = 1;
5426: my %returnhash;
5427: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5428: my %libserv = &all_library();
5429: foreach my $tryserver (keys(%libserv)) {
5430: if ( ( $hostidflag == 1
5431: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5432: || (!defined($hostidflag)) ) {
5433:
1.918 raeburn 5434: if (($domfilter eq '') ||
5435: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 5436: my $rep;
5437: if (grep { $_ eq $tryserver } current_machine_ids()) {
5438: $rep = LONCAPA::Lond::dump_course_id_handler(
5439: join(":", (&host_domain($tryserver), $sincefilter,
5440: &escape($descfilter), &escape($instcodefilter),
5441: &escape($ownerfilter), &escape($coursefilter),
5442: &escape($typefilter), &escape($regexp_ok),
5443: $as_hash, &escape($selfenrollonly),
5444: &escape($catfilter), $showhidden, $caller,
5445: &escape($cloner), &escape($cc_clone), $cloneonly,
5446: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 5447: &escape($creationcontext),$domcloner,$hasuniquecode,
5448: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 5449: } else {
5450: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5451: $sincefilter.':'.&escape($descfilter).':'.
5452: &escape($instcodefilter).':'.&escape($ownerfilter).
5453: ':'.&escape($coursefilter).':'.&escape($typefilter).
5454: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5455: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5456: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5457: &escape($cc_clone).':'.$cloneonly.':'.
5458: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 5459: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5460: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 5461: }
5462:
1.918 raeburn 5463: my @pairs=split(/\&/,$rep);
5464: foreach my $item (@pairs) {
5465: my ($key,$value)=split(/\=/,$item,2);
5466: $key = &unescape($key);
5467: next if ($key =~ /^error: 2 /);
5468: my $result = &thaw_unescape($value);
5469: if (ref($result) eq 'HASH') {
5470: $returnhash{$key}=$result;
5471: } else {
1.921 raeburn 5472: my @responses = split(/:/,$value);
5473: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5474: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5475: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5476: }
1.1008 raeburn 5477: }
1.353 www 5478: }
5479: }
5480: }
5481: }
5482: return %returnhash;
5483: }
5484:
1.1055 raeburn 5485: sub courselastaccess {
5486: my ($cdom,$cnum,$hostidref) = @_;
5487: my %returnhash;
5488: if ($cdom && $cnum) {
5489: my $chome = &homeserver($cnum,$cdom);
5490: if ($chome ne 'no_host') {
5491: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5492: &extract_lastaccess(\%returnhash,$rep);
5493: }
5494: } else {
5495: if (!$cdom) { $cdom=''; }
5496: my %libserv = &all_library();
5497: foreach my $tryserver (keys(%libserv)) {
5498: if (ref($hostidref) eq 'ARRAY') {
5499: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5500: }
5501: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5502: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5503: &extract_lastaccess(\%returnhash,$rep);
5504: }
5505: }
5506: }
5507: return %returnhash;
5508: }
5509:
5510: sub extract_lastaccess {
5511: my ($returnhash,$rep) = @_;
5512: if (ref($returnhash) eq 'HASH') {
5513: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5514: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5515: $rep eq '') {
5516: my @pairs=split(/\&/,$rep);
5517: foreach my $item (@pairs) {
5518: my ($key,$value)=split(/\=/,$item,2);
5519: $key = &unescape($key);
5520: next if ($key =~ /^error: 2 /);
5521: $returnhash->{$key} = &thaw_unescape($value);
5522: }
5523: }
5524: }
5525: return;
5526: }
5527:
1.658 raeburn 5528: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5529:
5530: sub dcmailput {
1.685 raeburn 5531: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5532: my $status = &Apache::lonnet::critical(
1.740 www 5533: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5534: &escape($message),$server);
1.662 raeburn 5535: return $status;
5536: }
5537:
1.658 raeburn 5538: sub dcmaildump {
5539: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5540: my %returnhash=();
1.846 albertel 5541:
5542: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5543: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5544: &escape($enddate).':';
5545: my @esc_senders=map { &escape($_)} @$senders;
5546: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5547: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5548: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5549: if (($key) && ($value)) {
5550: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5551: }
5552: }
5553: }
5554: return %returnhash;
5555: }
1.662 raeburn 5556: # ---------------------------------------------------------- Domain roles
5557:
5558: sub get_domain_roles {
5559: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5560: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5561: $startdate = '.';
5562: }
1.1018 raeburn 5563: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5564: $enddate = '.';
5565: }
1.922 raeburn 5566: my $rolelist;
5567: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 5568: $rolelist = join('&',@{$roles});
1.922 raeburn 5569: }
1.662 raeburn 5570: my %personnel = ();
1.841 albertel 5571:
5572: my %servers = &get_servers($dom,'library');
5573: foreach my $tryserver (keys(%servers)) {
5574: %{$personnel{$tryserver}}=();
5575: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5576: &escape($startdate).':'.
5577: &escape($enddate).':'.
5578: &escape($rolelist), $tryserver))) {
5579: my ($key,$value) = split(/\=/,$line,2);
5580: if (($key) && ($value)) {
5581: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5582: }
5583: }
1.662 raeburn 5584: }
5585: return %personnel;
5586: }
1.658 raeburn 5587:
1.1332 raeburn 5588: sub get_active_domroles {
5589: my ($dom,$roles) = @_;
5590: return () unless (ref($roles) eq 'ARRAY');
5591: my $now = time;
5592: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5593: my %domroles;
5594: foreach my $server (keys(%dompersonnel)) {
5595: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5596: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5597: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5598: }
5599: }
5600: return %domroles;
5601: }
5602:
1.1057 www 5603: # ----------------------------------------------------------- Interval timing
1.149 www 5604:
1.1153 www 5605: {
5606: # Caches needed for speedup of navmaps
5607: # We don't want to cache this for very long at all (5 seconds at most)
5608: #
5609: # The user for whom we cache
5610: my $cachedkey='';
5611: # The cached times for this user
5612: my %cachedtimes=();
5613: # When this was last done
1.1282 raeburn 5614: my $cachedtime='';
1.1153 www 5615:
5616: sub load_all_first_access {
1.1308 raeburn 5617: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5618: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 5619: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5620: (!$ignorecache)) {
1.1154 raeburn 5621: return;
5622: }
5623: $cachedtime=time;
5624: $cachedkey=$uname.':'.$udom;
5625: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5626: }
5627:
1.504 albertel 5628: sub get_first_access {
1.1308 raeburn 5629: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5630: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5631: if ($argsymb) { $symb=$argsymb; }
5632: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5633: if ($argmap) { $map = $argmap; }
1.926 albertel 5634: if ($type eq 'course') {
5635: $res='course';
5636: } elsif ($type eq 'map') {
1.588 albertel 5637: $res=&symbread($map);
5638: } else {
5639: $res=$symb;
5640: }
1.1308 raeburn 5641: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 5642: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5643: }
5644:
5645: sub set_first_access {
1.1162 raeburn 5646: my ($type,$interval)=@_;
1.790 albertel 5647: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5648: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5649: if ($type eq 'course') {
5650: $res='course';
5651: } elsif ($type eq 'map') {
1.588 albertel 5652: $res=&symbread($map);
5653: } else {
5654: $res=$symb;
5655: }
1.1153 www 5656: $cachedkey='';
1.1162 raeburn 5657: my $firstaccess=&get_first_access($type,$symb,$map);
1.1386 raeburn 5658: if ($firstaccess) {
5659: &logthis("First access time already set ($firstaccess) when attempting ".
1.1393 raeburn 5660: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5661: "in $courseid");
1.1386 raeburn 5662: return 'already_set';
5663: } else {
1.1162 raeburn 5664: my $start = time;
5665: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5666: $udom,$uname);
5667: if ($putres eq 'ok') {
5668: &put('timerinterval',{"$courseid\0$res"=>$interval},
5669: $udom,$uname);
5670: &appenv(
5671: {
5672: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5673: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5674: }
5675: );
1.1365 raeburn 5676: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5677: $cachedtimes{"$courseid\0$res"} = $start;
5678: }
1.1386 raeburn 5679: } elsif ($putres ne 'refused') {
5680: &logthis("Result: $putres when attempting to set first access time ".
5681: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5682: }
5683: return $putres;
1.505 albertel 5684: }
5685: return 'already_set';
1.504 albertel 5686: }
1.1153 www 5687: }
1.1282 raeburn 5688:
1.110 www 5689: # --------------------------------------------- Set Expire Date for Spreadsheet
5690:
5691: sub expirespread {
5692: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5693: my $cid=$env{'request.course.id'};
1.110 www 5694: if ($cid) {
5695: my $now=time;
5696: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5697: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5698: $env{'course.'.$cid.'.num'}.
1.110 www 5699: ':nohist_expirationdates:'.
5700: &escape($key).'='.$now,
1.620 albertel 5701: $env{'course.'.$cid.'.home'})
1.110 www 5702: }
5703: return 'ok';
1.14 www 5704: }
5705:
1.109 www 5706: # ----------------------------------------------------- Devalidate Spreadsheets
5707:
5708: sub devalidate {
1.325 www 5709: my ($symb,$uname,$udom)=@_;
1.620 albertel 5710: my $cid=$env{'request.course.id'};
1.109 www 5711: if ($cid) {
1.391 matthew 5712: # delete the stored spreadsheets for
5713: # - the student level sheet of this user in course's homespace
5714: # - the assessment level sheet for this resource
5715: # for this user in user's homespace
1.553 albertel 5716: # - current conditional state info
1.325 www 5717: my $key=$uname.':'.$udom.':';
1.109 www 5718: my $status=
1.299 matthew 5719: &del('nohist_calculatedsheets',
1.391 matthew 5720: [$key.'studentcalc:'],
1.620 albertel 5721: $env{'course.'.$cid.'.domain'},
5722: $env{'course.'.$cid.'.num'})
1.133 albertel 5723: .' '.
5724: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5725: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5726: unless ($status eq 'ok ok') {
5727: &logthis('Could not devalidate spreadsheet '.
1.325 www 5728: $uname.' at '.$udom.' for '.
1.109 www 5729: $symb.': '.$status);
1.133 albertel 5730: }
1.553 albertel 5731: &delenv('user.state.'.$cid);
1.109 www 5732: }
5733: }
5734:
1.265 albertel 5735: sub get_scalar {
5736: my ($string,$end) = @_;
5737: my $value;
5738: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5739: $value = $1;
5740: } elsif ($$string =~ s/^([^&]*?)&//) {
5741: $value = $1;
5742: }
5743: return &unescape($value);
5744: }
5745:
5746: sub array2str {
5747: my (@array) = @_;
5748: my $result=&arrayref2str(\@array);
5749: $result=~s/^__ARRAY_REF__//;
5750: $result=~s/__END_ARRAY_REF__$//;
5751: return $result;
5752: }
5753:
1.204 albertel 5754: sub arrayref2str {
5755: my ($arrayref) = @_;
1.265 albertel 5756: my $result='__ARRAY_REF__';
1.204 albertel 5757: foreach my $elem (@$arrayref) {
1.265 albertel 5758: if(ref($elem) eq 'ARRAY') {
5759: $result.=&arrayref2str($elem).'&';
5760: } elsif(ref($elem) eq 'HASH') {
5761: $result.=&hashref2str($elem).'&';
5762: } elsif(ref($elem)) {
5763: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5764: } else {
5765: $result.=&escape($elem).'&';
5766: }
5767: }
5768: $result=~s/\&$//;
1.265 albertel 5769: $result .= '__END_ARRAY_REF__';
1.204 albertel 5770: return $result;
5771: }
5772:
1.168 albertel 5773: sub hash2str {
1.204 albertel 5774: my (%hash) = @_;
5775: my $result=&hashref2str(\%hash);
1.265 albertel 5776: $result=~s/^__HASH_REF__//;
5777: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5778: return $result;
5779: }
5780:
5781: sub hashref2str {
5782: my ($hashref)=@_;
1.265 albertel 5783: my $result='__HASH_REF__';
1.800 albertel 5784: foreach my $key (sort(keys(%$hashref))) {
5785: if (ref($key) eq 'ARRAY') {
5786: $result.=&arrayref2str($key).'=';
5787: } elsif (ref($key) eq 'HASH') {
5788: $result.=&hashref2str($key).'=';
5789: } elsif (ref($key)) {
1.265 albertel 5790: $result.='=';
1.800 albertel 5791: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5792: } else {
1.1132 raeburn 5793: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5794: }
5795:
1.800 albertel 5796: if(ref($hashref->{$key}) eq 'ARRAY') {
5797: $result.=&arrayref2str($hashref->{$key}).'&';
5798: } elsif(ref($hashref->{$key}) eq 'HASH') {
5799: $result.=&hashref2str($hashref->{$key}).'&';
5800: } elsif(ref($hashref->{$key})) {
1.265 albertel 5801: $result.='&';
1.800 albertel 5802: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5803: } else {
1.800 albertel 5804: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5805: }
5806: }
1.168 albertel 5807: $result=~s/\&$//;
1.265 albertel 5808: $result .= '__END_HASH_REF__';
1.168 albertel 5809: return $result;
5810: }
5811:
5812: sub str2hash {
1.265 albertel 5813: my ($string)=@_;
5814: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5815: return %$hash;
5816: }
5817:
5818: sub str2hashref {
1.168 albertel 5819: my ($string) = @_;
1.265 albertel 5820:
5821: my %hash;
5822:
5823: if($string !~ /^__HASH_REF__/) {
5824: if (! ($string eq '' || !defined($string))) {
5825: $hash{'error'}='Not hash reference';
5826: }
5827: return (\%hash, $string);
5828: }
5829:
5830: $string =~ s/^__HASH_REF__//;
5831:
5832: while($string !~ /^__END_HASH_REF__/) {
5833: #key
5834: my $key='';
5835: if($string =~ /^__HASH_REF__/) {
5836: ($key, $string)=&str2hashref($string);
5837: if(defined($key->{'error'})) {
5838: $hash{'error'}='Bad data';
5839: return (\%hash, $string);
5840: }
5841: } elsif($string =~ /^__ARRAY_REF__/) {
5842: ($key, $string)=&str2arrayref($string);
5843: if($key->[0] eq 'Array reference error') {
5844: $hash{'error'}='Bad data';
5845: return (\%hash, $string);
5846: }
5847: } else {
5848: $string =~ s/^(.*?)=//;
1.267 albertel 5849: $key=&unescape($1);
1.265 albertel 5850: }
5851: $string =~ s/^=//;
5852:
5853: #value
5854: my $value='';
5855: if($string =~ /^__HASH_REF__/) {
5856: ($value, $string)=&str2hashref($string);
5857: if(defined($value->{'error'})) {
5858: $hash{'error'}='Bad data';
5859: return (\%hash, $string);
5860: }
5861: } elsif($string =~ /^__ARRAY_REF__/) {
5862: ($value, $string)=&str2arrayref($string);
5863: if($value->[0] eq 'Array reference error') {
5864: $hash{'error'}='Bad data';
5865: return (\%hash, $string);
5866: }
5867: } else {
5868: $value=&get_scalar(\$string,'__END_HASH_REF__');
5869: }
5870: $string =~ s/^&//;
5871:
5872: $hash{$key}=$value;
1.204 albertel 5873: }
1.265 albertel 5874:
5875: $string =~ s/^__END_HASH_REF__//;
5876:
5877: return (\%hash, $string);
1.204 albertel 5878: }
5879:
5880: sub str2array {
1.265 albertel 5881: my ($string)=@_;
5882: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5883: return @$array;
5884: }
5885:
5886: sub str2arrayref {
1.204 albertel 5887: my ($string) = @_;
1.265 albertel 5888: my @array;
5889:
5890: if($string !~ /^__ARRAY_REF__/) {
5891: if (! ($string eq '' || !defined($string))) {
5892: $array[0]='Array reference error';
5893: }
5894: return (\@array, $string);
5895: }
5896:
5897: $string =~ s/^__ARRAY_REF__//;
5898:
5899: while($string !~ /^__END_ARRAY_REF__/) {
5900: my $value='';
5901: if($string =~ /^__HASH_REF__/) {
5902: ($value, $string)=&str2hashref($string);
5903: if(defined($value->{'error'})) {
5904: $array[0] ='Array reference error';
5905: return (\@array, $string);
5906: }
5907: } elsif($string =~ /^__ARRAY_REF__/) {
5908: ($value, $string)=&str2arrayref($string);
5909: if($value->[0] eq 'Array reference error') {
5910: $array[0] ='Array reference error';
5911: return (\@array, $string);
5912: }
5913: } else {
5914: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5915: }
5916: $string =~ s/^&//;
5917:
5918: push(@array, $value);
1.191 harris41 5919: }
1.265 albertel 5920:
5921: $string =~ s/^__END_ARRAY_REF__//;
5922:
5923: return (\@array, $string);
1.168 albertel 5924: }
5925:
1.167 albertel 5926: # -------------------------------------------------------------------Temp Store
5927:
1.168 albertel 5928: sub tmpreset {
5929: my ($symb,$namespace,$domain,$stuname) = @_;
5930: if (!$symb) {
5931: $symb=&symbread();
1.620 albertel 5932: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5933: }
5934: $symb=escape($symb);
5935:
1.620 albertel 5936: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5937: $namespace=~s/\//\_/g;
5938: $namespace=~s/\W//g;
5939:
1.620 albertel 5940: if (!$domain) { $domain=$env{'user.domain'}; }
5941: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5942: if ($domain eq 'public' && $stuname eq 'public') {
5943: $stuname=$ENV{'REMOTE_ADDR'};
5944: }
1.1117 foxr 5945: my $path=LONCAPA::tempdir();
1.168 albertel 5946: my %hash;
5947: if (tie(%hash,'GDBM_File',
5948: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5949: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5950: foreach my $key (keys(%hash)) {
1.180 albertel 5951: if ($key=~ /:$symb/) {
1.168 albertel 5952: delete($hash{$key});
5953: }
5954: }
5955: }
5956: }
5957:
1.167 albertel 5958: sub tmpstore {
1.168 albertel 5959: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5960:
5961: if (!$symb) {
5962: $symb=&symbread();
1.620 albertel 5963: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5964: }
5965: $symb=escape($symb);
5966:
5967: if (!$namespace) {
5968: # I don't think we would ever want to store this for a course.
5969: # it seems this will only be used if we don't have a course.
1.620 albertel 5970: #$namespace=$env{'request.course.id'};
1.168 albertel 5971: #if (!$namespace) {
1.620 albertel 5972: $namespace=$env{'request.state'};
1.168 albertel 5973: #}
5974: }
5975: $namespace=~s/\//\_/g;
5976: $namespace=~s/\W//g;
1.620 albertel 5977: if (!$domain) { $domain=$env{'user.domain'}; }
5978: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5979: if ($domain eq 'public' && $stuname eq 'public') {
5980: $stuname=$ENV{'REMOTE_ADDR'};
5981: }
1.168 albertel 5982: my $now=time;
5983: my %hash;
1.1117 foxr 5984: my $path=LONCAPA::tempdir();
1.168 albertel 5985: if (tie(%hash,'GDBM_File',
5986: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5987: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5988: $hash{"version:$symb"}++;
5989: my $version=$hash{"version:$symb"};
5990: my $allkeys='';
5991: foreach my $key (keys(%$storehash)) {
5992: $allkeys.=$key.':';
1.591 albertel 5993: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5994: }
5995: $hash{"$version:$symb:timestamp"}=$now;
5996: $allkeys.='timestamp';
5997: $hash{"$version:keys:$symb"}=$allkeys;
5998: if (untie(%hash)) {
5999: return 'ok';
6000: } else {
6001: return "error:$!";
6002: }
6003: } else {
6004: return "error:$!";
6005: }
6006: }
1.167 albertel 6007:
1.168 albertel 6008: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6009:
1.168 albertel 6010: sub tmprestore {
6011: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6012:
1.168 albertel 6013: if (!$symb) {
6014: $symb=&symbread();
1.620 albertel 6015: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6016: }
6017: $symb=escape($symb);
6018:
1.620 albertel 6019: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6020:
1.620 albertel 6021: if (!$domain) { $domain=$env{'user.domain'}; }
6022: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6023: if ($domain eq 'public' && $stuname eq 'public') {
6024: $stuname=$ENV{'REMOTE_ADDR'};
6025: }
1.168 albertel 6026: my %returnhash;
6027: $namespace=~s/\//\_/g;
6028: $namespace=~s/\W//g;
6029: my %hash;
1.1117 foxr 6030: my $path=LONCAPA::tempdir();
1.168 albertel 6031: if (tie(%hash,'GDBM_File',
6032: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6033: &GDBM_READER(),0640)) {
1.168 albertel 6034: my $version=$hash{"version:$symb"};
6035: $returnhash{'version'}=$version;
6036: my $scope;
6037: for ($scope=1;$scope<=$version;$scope++) {
6038: my $vkeys=$hash{"$scope:keys:$symb"};
6039: my @keys=split(/:/,$vkeys);
6040: my $key;
6041: $returnhash{"$scope:keys"}=$vkeys;
6042: foreach $key (@keys) {
1.591 albertel 6043: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6044: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6045: }
6046: }
1.168 albertel 6047: if (!(untie(%hash))) {
6048: return "error:$!";
6049: }
6050: } else {
6051: return "error:$!";
6052: }
6053: return %returnhash;
1.167 albertel 6054: }
6055:
1.9 www 6056: # ----------------------------------------------------------------------- Store
6057:
6058: sub store {
1.1269 raeburn 6059: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6060: my $home='';
6061:
1.168 albertel 6062: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6063:
1.213 www 6064: $symb=&symbclean($symb);
1.122 albertel 6065: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6066:
1.620 albertel 6067: if (!$domain) { $domain=$env{'user.domain'}; }
6068: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6069:
6070: &devalidate($symb,$stuname,$domain);
1.109 www 6071:
6072: $symb=escape($symb);
1.187 www 6073: if (!$namespace) {
1.620 albertel 6074: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6075: return '';
6076: }
6077: }
1.620 albertel 6078: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6079:
6080: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
6081: $$storehash{'host'}=$perlvar{'lonHostID'};
6082:
1.12 www 6083: my $namevalue='';
1.800 albertel 6084: foreach my $key (keys(%$storehash)) {
6085: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6086: }
1.12 www 6087: $namevalue=~s/\&$//;
1.187 www 6088: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 6089: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6090: }
6091:
1.47 www 6092: # -------------------------------------------------------------- Critical Store
6093:
6094: sub cstore {
1.1269 raeburn 6095: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6096: my $home='';
6097:
1.168 albertel 6098: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6099:
1.213 www 6100: $symb=&symbclean($symb);
1.122 albertel 6101: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6102:
1.620 albertel 6103: if (!$domain) { $domain=$env{'user.domain'}; }
6104: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6105:
6106: &devalidate($symb,$stuname,$domain);
1.109 www 6107:
6108: $symb=escape($symb);
1.187 www 6109: if (!$namespace) {
1.620 albertel 6110: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6111: return '';
6112: }
6113: }
1.620 albertel 6114: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6115:
6116: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
6117: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6118:
1.47 www 6119: my $namevalue='';
1.800 albertel 6120: foreach my $key (keys(%$storehash)) {
6121: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6122: }
1.47 www 6123: $namevalue=~s/\&$//;
1.187 www 6124: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6125: return critical
1.1269 raeburn 6126: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6127: }
6128:
1.9 www 6129: # --------------------------------------------------------------------- Restore
6130:
6131: sub restore {
1.124 www 6132: my ($symb,$namespace,$domain,$stuname) = @_;
6133: my $home='';
6134:
1.168 albertel 6135: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6136:
1.122 albertel 6137: if (!$symb) {
1.1224 raeburn 6138: return if ($namespace eq 'courserequests');
6139: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6140: } else {
1.1224 raeburn 6141: unless ($namespace eq 'courserequests') {
6142: $symb=&escape(&symbclean($symb));
6143: }
1.122 albertel 6144: }
1.188 www 6145: if (!$namespace) {
1.620 albertel 6146: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6147: return '';
6148: }
6149: }
1.620 albertel 6150: if (!$domain) { $domain=$env{'user.domain'}; }
6151: if (!$stuname) { $stuname=$env{'user.name'}; }
6152: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6153: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6154:
1.12 www 6155: my %returnhash=();
1.800 albertel 6156: foreach my $line (split(/\&/,$answer)) {
6157: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6158: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6159: }
1.75 www 6160: my $version;
6161: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6162: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6163: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6164: }
1.75 www 6165: }
1.13 www 6166: return %returnhash;
1.34 www 6167: }
6168:
6169: # ---------------------------------------------------------- Course Description
1.1118 foxr 6170: #
6171: #
1.34 www 6172:
6173: sub coursedescription {
1.731 albertel 6174: my ($courseid,$args)=@_;
1.34 www 6175: $courseid=~s/^\///;
1.49 www 6176: $courseid=~s/\_/\//g;
1.34 www 6177: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6178: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6179: my $normalid=$cdomain.'_'.$cnum;
6180: # need to always cache even if we get errors otherwise we keep
6181: # trying and trying and trying to get the course description.
6182: my %envhash=();
6183: my %returnhash=();
1.731 albertel 6184:
6185: my $expiretime=600;
6186: if ($env{'request.course.id'} eq $normalid) {
6187: $expiretime=120;
6188: }
6189:
6190: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6191: if (!$args->{'freshen_cache'}
6192: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6193: foreach my $key (keys(%env)) {
6194: next if ($key !~ /^\Q$prefix\E(.*)/);
6195: my ($setting) = $1;
6196: $returnhash{$setting} = $env{$key};
6197: }
6198: return %returnhash;
6199: }
6200:
1.1118 foxr 6201: # get the data again
6202:
1.731 albertel 6203: if (!$args->{'one_time'}) {
6204: $envhash{'course.'.$normalid.'.last_cache'}=time;
6205: }
1.811 albertel 6206:
1.34 www 6207: if ($chome ne 'no_host') {
1.302 albertel 6208: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6209: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6210: my $username = $env{'user.name'}; # Defult username
6211: if(defined $args->{'user'}) {
6212: $username = $args->{'user'};
6213: }
1.129 albertel 6214: $returnhash{'home'}= $chome;
6215: $returnhash{'domain'} = $cdomain;
6216: $returnhash{'num'} = $cnum;
1.741 raeburn 6217: if (!defined($returnhash{'type'})) {
6218: $returnhash{'type'} = 'Course';
6219: }
1.130 albertel 6220: while (my ($name,$value) = each %returnhash) {
1.53 www 6221: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6222: }
1.270 www 6223: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6224: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6225: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6226: $envhash{'course.'.$normalid.'.home'}=$chome;
6227: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6228: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6229: }
6230: }
1.731 albertel 6231: if (!$args->{'one_time'}) {
1.949 raeburn 6232: &appenv(\%envhash);
1.731 albertel 6233: }
1.302 albertel 6234: return %returnhash;
1.461 www 6235: }
6236:
1.1080 raeburn 6237: sub update_released_required {
6238: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6239: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6240: $cid = $env{'request.course.id'};
6241: $cdom = $env{'course.'.$cid.'.domain'};
6242: $cnum = $env{'course.'.$cid.'.num'};
6243: $chome = $env{'course.'.$cid.'.home'};
6244: }
6245: if ($needsrelease) {
6246: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6247: my $needsupdate;
6248: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6249: $needsupdate = 1;
6250: } else {
6251: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6252: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6253: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6254: $needsupdate = 1;
6255: }
6256: }
6257: if ($needsupdate) {
6258: my %needshash = (
6259: 'internal.releaserequired' => $needsrelease,
6260: );
6261: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6262: if ($putresult eq 'ok') {
6263: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6264: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6265: if (ref($crsinfo{$cid}) eq 'HASH') {
6266: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6267: &courseidput($cdom,\%crsinfo,$chome,'notime');
6268: }
6269: }
6270: }
6271: }
6272: return;
6273: }
6274:
1.461 www 6275: # -------------------------------------------------See if a user is privileged
6276:
6277: sub privileged {
1.1219 raeburn 6278: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6279: my $now = time;
1.1219 raeburn 6280: my $roles;
6281: if (ref($possroles) eq 'ARRAY') {
6282: $roles = $possroles;
6283: } else {
6284: $roles = ['dc','su'];
6285: }
6286: if (ref($possdomains) eq 'ARRAY') {
6287: my %privileged = &privileged_by_domain($possdomains,$roles);
6288: foreach my $dom (@{$possdomains}) {
6289: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6290: (ref($privileged{$dom}) eq 'HASH')) {
6291: foreach my $role (@{$roles}) {
6292: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6293: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6294: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6295: return 1 unless (($end && $end < $now) ||
6296: ($start && $start > $now));
6297: }
6298: }
6299: }
6300: }
6301: }
6302: } else {
6303: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6304: my $now = time;
1.1170 droeschl 6305:
1.1275 musolffc 6306: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6307: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 6308: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 6309: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 6310: or ($tstart && $tstart > $now);
1.1170 droeschl 6311: }
1.1219 raeburn 6312: }
6313: }
6314: return 0;
6315: }
1.1170 droeschl 6316:
1.1219 raeburn 6317: sub privileged_by_domain {
6318: my ($domains,$roles) = @_;
6319: my %privileged = ();
6320: my $cachetime = 60*60*24;
6321: my $now = time;
6322: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6323: return %privileged;
6324: }
6325: foreach my $dom (@{$domains}) {
6326: next if (ref($privileged{$dom}) eq 'HASH');
6327: my $needroles;
6328: foreach my $role (@{$roles}) {
6329: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6330: if (defined($cached)) {
6331: if (ref($result) eq 'HASH') {
6332: $privileged{$dom}{$role} = $result;
6333: }
6334: } else {
6335: $needroles = 1;
6336: }
6337: }
6338: if ($needroles) {
6339: my %dompersonnel = &get_domain_roles($dom,$roles);
6340: $privileged{$dom} = {};
6341: foreach my $server (keys(%dompersonnel)) {
6342: if (ref($dompersonnel{$server}) eq 'HASH') {
6343: foreach my $item (keys(%{$dompersonnel{$server}})) {
6344: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6345: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6346: next if ($end && $end < $now);
6347: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6348: $dompersonnel{$server}{$item};
6349: }
6350: }
6351: }
6352: if (ref($privileged{$dom}) eq 'HASH') {
6353: foreach my $role (@{$roles}) {
6354: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6355: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6356: } else {
6357: my %hash = ();
6358: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6359: }
6360: }
6361: }
6362: }
6363: }
6364: return %privileged;
1.9 www 6365: }
1.1 albertel 6366:
1.103 harris41 6367: # -------------------------------------------------------- Get user privileges
1.11 www 6368:
6369: sub rolesinit {
1.1169 droeschl 6370: my ($domain, $username) = @_;
6371: my %userroles = ('user.login.time' => time);
6372: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6373:
6374: # firstaccess and timerinterval are related to timed maps/resources.
6375: # also, blocking can be triggered by an activating timer
6376: # it's saved in the user's %env.
6377: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6378: my %timerinterval = &dump('timerinterval', $domain, $username);
6379: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6380: %timerintchk, %timerintenv);
6381:
1.1162 raeburn 6382: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6383: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6384: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6385: }
1.1169 droeschl 6386:
1.1162 raeburn 6387: foreach my $key (keys(%timerinterval)) {
6388: my ($cid,$rest) = split(/\0/,$key);
6389: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6390: }
1.1169 droeschl 6391:
1.11 www 6392: my %allroles=();
1.1162 raeburn 6393: my %allgroups=();
1.11 www 6394:
1.1274 raeburn 6395: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6396: my $role = $rolesdump{$area};
6397: $area =~ s/\_\w\w$//;
6398:
6399: my ($trole, $tend, $tstart, $group_privs);
6400:
6401: if ($role =~ /^cr/) {
6402: # Custom role, defined by a user
6403: # e.g., user.role.cr/msu/smith/mynewrole
6404: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6405: $trole = $1;
6406: ($tend, $tstart) = split('_', $2);
6407: } else {
6408: $trole = $role;
6409: }
6410: } elsif ($role =~ m|^gr/|) {
6411: # Role of member in a group, defined within a course/community
6412: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6413: ($trole, $tend, $tstart) = split(/_/, $role);
6414: next if $tstart eq '-1';
6415: ($trole, $group_privs) = split(/\//, $trole);
6416: $group_privs = &unescape($group_privs);
6417: } else {
6418: # Just a normal role, defined in roles.tab
6419: ($trole, $tend, $tstart) = split(/_/,$role);
6420: }
6421:
6422: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6423: $username);
6424: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6425:
6426: # role expired or not available yet?
6427: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6428: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6429:
6430: next if $area eq '' or $trole eq '';
6431:
6432: my $spec = "$trole.$area";
6433: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6434:
6435: if ($trole =~ /^cr\//) {
6436: # Custom role, defined by a user
6437: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6438: } elsif ($trole eq 'gr') {
6439: # Role of a member in a group, defined within a course/community
6440: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6441: next;
6442: } else {
6443: # Normal role, defined in roles.tab
6444: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6445: }
6446:
6447: my $cid = $tdomain.'_'.$trest;
6448: unless ($firstaccchk{$cid}) {
6449: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6450: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6451: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6452: $coursetimerstarts{$cid}{$item};
6453: }
6454: }
6455: $firstaccchk{$cid} = 1;
6456: }
6457: unless ($timerintchk{$cid}) {
6458: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6459: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6460: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6461: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6462: }
1.12 www 6463: }
1.1169 droeschl 6464: $timerintchk{$cid} = 1;
1.191 harris41 6465: }
1.11 www 6466: }
1.1169 droeschl 6467:
1.1341 raeburn 6468: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6469: \%allroles, \%allgroups);
1.1169 droeschl 6470: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 6471: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6472:
1.1162 raeburn 6473: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6474: }
6475:
1.567 raeburn 6476: sub set_arearole {
1.1215 raeburn 6477: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6478: unless ($nolog) {
1.567 raeburn 6479: # log the associated role with the area
1.1215 raeburn 6480: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6481: }
1.743 albertel 6482: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6483: }
6484:
6485: sub custom_roleprivs {
6486: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6487: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 6488: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6489: if (&hostname($homsvr) ne '') {
1.567 raeburn 6490: my ($rdummy,$roledef)=
6491: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6492: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6493: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6494: if (defined($syspriv)) {
1.1043 raeburn 6495: if ($trest =~ /^$match_community$/) {
6496: $syspriv =~ s/bre\&S//;
6497: }
1.567 raeburn 6498: $$allroles{'cm./'}.=':'.$syspriv;
6499: $$allroles{$spec.'./'}.=':'.$syspriv;
6500: }
6501: if ($tdomain ne '') {
6502: if (defined($dompriv)) {
6503: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6504: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6505: }
6506: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 6507: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6508: my $rolename = $1;
6509: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6510: }
1.567 raeburn 6511: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6512: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6513: }
6514: }
6515: }
6516: }
6517: }
6518:
1.1332 raeburn 6519: sub course_adhocrole_privs {
6520: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6521: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6522: if ($overrides{"internal.adhocpriv.$rolename"}) {
6523: my (%currprivs,%storeprivs);
6524: foreach my $item (split(/:/,$coursepriv)) {
6525: my ($priv,$restrict) = split(/\&/,$item);
6526: $currprivs{$priv} = $restrict;
6527: }
6528: my (%possadd,%possremove,%full);
6529: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6530: my ($priv,$restrict)=split(/\&/,$item);
6531: $full{$priv} = $restrict;
6532: }
6533: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6534: next if ($item eq '');
6535: my ($rule,$rest) = split(/=/,$item);
6536: next unless (($rule eq 'off') || ($rule eq 'on'));
6537: foreach my $priv (split(/:/,$rest)) {
6538: if ($priv ne '') {
6539: if ($rule eq 'off') {
6540: $possremove{$priv} = 1;
6541: } else {
6542: $possadd{$priv} = 1;
6543: }
6544: }
6545: }
6546: }
6547: foreach my $priv (sort(keys(%full))) {
6548: if (exists($currprivs{$priv})) {
6549: unless (exists($possremove{$priv})) {
6550: $storeprivs{$priv} = $currprivs{$priv};
6551: }
6552: } elsif (exists($possadd{$priv})) {
6553: $storeprivs{$priv} = $full{$priv};
6554: }
6555: }
6556: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6557: }
6558: return $coursepriv;
6559: }
6560:
1.678 raeburn 6561: sub group_roleprivs {
6562: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6563: my $access = 1;
6564: my $now = time;
6565: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6566: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6567: if ($access) {
1.811 albertel 6568: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6569: $$allgroups{$course}{$group} .=':'.$group_privs;
6570: }
6571: }
1.567 raeburn 6572:
6573: sub standard_roleprivs {
6574: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6575: if (defined($pr{$trole.':s'})) {
6576: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6577: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6578: }
6579: if ($tdomain ne '') {
6580: if (defined($pr{$trole.':d'})) {
6581: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6582: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6583: }
6584: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6585: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6586: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6587: }
6588: }
6589: }
6590:
6591: sub set_userprivs {
1.1064 raeburn 6592: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6593: my $author=0;
6594: my $adv=0;
1.1341 raeburn 6595: my $rar=0;
1.678 raeburn 6596: my %grouproles = ();
6597: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6598: my @groupkeys;
1.1000 raeburn 6599: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6600: push(@groupkeys,$role);
6601: }
6602: if (ref($groups_roles) eq 'HASH') {
6603: foreach my $key (keys(%{$groups_roles})) {
6604: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6605: push(@groupkeys,$key);
6606: }
6607: }
6608: }
6609: if (@groupkeys > 0) {
6610: foreach my $role (@groupkeys) {
6611: my ($trole,$area,$sec,$extendedarea);
6612: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6613: $trole = $1;
6614: $area = $2;
6615: $sec = $3;
6616: $extendedarea = $area.$sec;
6617: if (exists($$allgroups{$area})) {
6618: foreach my $group (keys(%{$$allgroups{$area}})) {
6619: my $spec = $trole.'.'.$extendedarea;
6620: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6621: $$allgroups{$area}{$group};
1.1064 raeburn 6622: }
1.678 raeburn 6623: }
6624: }
6625: }
6626: }
6627: }
1.800 albertel 6628: foreach my $group (keys(%grouproles)) {
6629: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6630: }
1.800 albertel 6631: foreach my $role (keys(%{$allroles})) {
6632: my %thesepriv;
1.941 raeburn 6633: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6634: foreach my $item (split(/:/,$$allroles{$role})) {
6635: if ($item ne '') {
6636: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6637: if ($restrictions eq '') {
6638: $thesepriv{$privilege}='F';
6639: } elsif ($thesepriv{$privilege} ne 'F') {
6640: $thesepriv{$privilege}.=$restrictions;
6641: }
6642: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 6643: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6644: }
6645: }
6646: my $thesestr='';
1.1104 raeburn 6647: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6648: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6649: }
6650: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6651: }
1.1341 raeburn 6652: return ($author,$adv,$rar);
1.567 raeburn 6653: }
6654:
1.994 raeburn 6655: sub role_status {
1.1104 raeburn 6656: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6657: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 6658: my ($one,$two) = split(m{\./},$rolekey,2);
6659: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6660: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 6661: $$where = '/'.$two;
1.994 raeburn 6662: $$trolecode=$$role.'.'.$$where;
6663: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6664: $$tstatus='is';
1.1104 raeburn 6665: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6666: $$tstatus='future';
1.1034 raeburn 6667: if ($$tstart<$now) {
6668: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6669: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6670: my (%allroles,%allgroups,$group_privs,
6671: %groups_roles,@rolecodes);
1.1002 raeburn 6672: my %userroles = (
6673: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6674: );
1.1064 raeburn 6675: @rolecodes = ('cm');
1.1002 raeburn 6676: my $spec=$$role.'.'.$$where;
6677: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6678: if ($$role =~ /^cr\//) {
6679: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6680: push(@rolecodes,'cr');
1.1002 raeburn 6681: } elsif ($$role eq 'gr') {
1.1064 raeburn 6682: push(@rolecodes,$$role);
1.1002 raeburn 6683: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6684: $env{'user.name'});
1.1064 raeburn 6685: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6686: (undef,my $group_privs) = split(/\//,$trole);
6687: $group_privs = &unescape($group_privs);
6688: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6689: 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 6690: &get_groups_roles($tdomain,$trest,
6691: \%course_roles,\@rolecodes,
6692: \%groups_roles);
1.1002 raeburn 6693: } else {
1.1064 raeburn 6694: push(@rolecodes,$$role);
1.1002 raeburn 6695: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6696: }
1.1341 raeburn 6697: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6698: \%groups_roles);
1.1064 raeburn 6699: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 6700: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6701: }
6702: }
1.1034 raeburn 6703: $$tstatus = 'is';
1.1002 raeburn 6704: }
1.994 raeburn 6705: }
6706: if ($$tend) {
1.1104 raeburn 6707: if ($$tend<$update) {
1.994 raeburn 6708: $$tstatus='expired';
6709: } elsif ($$tend<$now) {
6710: $$tstatus='will_not';
6711: }
6712: }
6713: }
6714: }
6715: }
6716:
1.1104 raeburn 6717: sub get_groups_roles {
6718: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6719: return unless((ref($cdom_courseroles) eq 'HASH') &&
6720: (ref($rolecodes) eq 'ARRAY') &&
6721: (ref($groups_roles) eq 'HASH'));
6722: if (keys(%{$cdom_courseroles}) > 0) {
6723: my ($cnum) = ($rest =~ /^($match_courseid)/);
6724: if ($cdom ne '' && $cnum ne '') {
6725: foreach my $key (keys(%{$cdom_courseroles})) {
6726: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6727: my $crsrole = $1;
6728: my $crssec = $2;
6729: if ($crsrole =~ /^cr/) {
6730: unless (grep(/^cr$/,@{$rolecodes})) {
6731: push(@{$rolecodes},'cr');
6732: }
6733: } else {
6734: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6735: push(@{$rolecodes},$crsrole);
6736: }
6737: }
6738: my $rolekey = "$crsrole./$cdom/$cnum";
6739: if ($crssec ne '') {
6740: $rolekey .= "/$crssec";
6741: }
6742: $rolekey .= './';
6743: $groups_roles->{$rolekey} = $rolecodes;
6744: }
6745: }
6746: }
6747: }
6748: return;
6749: }
6750:
6751: sub delete_env_groupprivs {
6752: my ($where,$courseroles,$possroles) = @_;
6753: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6754: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6755: unless (ref($courseroles->{$udom}) eq 'HASH') {
6756: %{$courseroles->{$udom}} =
6757: &get_my_roles('','','userroles',['active'],
6758: $possroles,[$udom],1);
6759: }
6760: if (ref($courseroles->{$udom}) eq 'HASH') {
6761: foreach my $item (keys(%{$courseroles->{$udom}})) {
6762: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6763: my $area = '/'.$cdom.'/'.$cnum;
6764: my $privkey = "user.priv.$crsrole.$area";
6765: if ($crssec ne '') {
6766: $privkey .= '/'.$crssec;
6767: }
6768: $privkey .= ".$area/$group";
6769: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6770: }
6771: }
6772: return;
6773: }
6774:
1.994 raeburn 6775: sub check_adhoc_privs {
1.1329 raeburn 6776: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6777: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 6778: if ($sec) {
6779: $cckey .= '/'.$sec;
6780: }
1.1185 raeburn 6781: my $setprivs;
1.994 raeburn 6782: if ($env{$cckey}) {
6783: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6784: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6785: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 6786: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6787: $setprivs = 1;
1.994 raeburn 6788: }
6789: } else {
1.1330 raeburn 6790: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6791: $setprivs = 1;
1.994 raeburn 6792: }
1.1185 raeburn 6793: return $setprivs;
1.994 raeburn 6794: }
6795:
6796: sub set_adhoc_privileges {
1.1326 raeburn 6797: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 6798: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6799: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 6800: if ($sec ne '') {
6801: $area .= '/'.$sec;
6802: }
1.994 raeburn 6803: my $spec = $role.'.'.$area;
6804: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 6805: $env{'user.name'},1);
1.1326 raeburn 6806: my %rolehash = ();
1.1332 raeburn 6807: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6808: my $rolename = $1;
1.1326 raeburn 6809: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 6810: my %domdef = &get_domain_defaults($dcdom);
6811: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6812: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6813: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6814: }
6815: }
1.1326 raeburn 6816: } else {
6817: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6818: }
1.1341 raeburn 6819: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6820: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 6821: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402 raeburn 6822: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
6823: ($caller eq 'tiny')) {
1.1088 raeburn 6824: &appenv( {'request.role' => $spec,
6825: 'request.role.domain' => $dcdom,
1.1332 raeburn 6826: 'request.course.sec' => $sec,
1.1088 raeburn 6827: }
6828: );
6829: my $tadv=0;
6830: if (&allowed('adv') eq 'F') { $tadv=1; }
6831: &appenv({'request.role.adv' => $tadv});
6832: }
1.994 raeburn 6833: }
6834:
1.12 www 6835: # --------------------------------------------------------------- get interface
6836:
6837: sub get {
1.131 albertel 6838: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6839: my $items='';
1.800 albertel 6840: foreach my $item (@$storearr) {
6841: $items.=&escape($item).'&';
1.191 harris41 6842: }
1.12 www 6843: $items=~s/\&$//;
1.620 albertel 6844: if (!$udomain) { $udomain=$env{'user.domain'}; }
6845: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6846: my $uhome=&homeserver($uname,$udomain);
6847:
1.133 albertel 6848: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6849: my @pairs=split(/\&/,$rep);
1.273 albertel 6850: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6851: return @pairs;
6852: }
1.15 www 6853: my %returnhash=();
1.42 www 6854: my $i=0;
1.800 albertel 6855: foreach my $item (@$storearr) {
6856: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6857: $i++;
1.191 harris41 6858: }
1.15 www 6859: return %returnhash;
1.27 www 6860: }
6861:
6862: # --------------------------------------------------------------- del interface
6863:
6864: sub del {
1.133 albertel 6865: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6866: my $items='';
1.800 albertel 6867: foreach my $item (@$storearr) {
6868: $items.=&escape($item).'&';
1.191 harris41 6869: }
1.984 neumanie 6870:
1.27 www 6871: $items=~s/\&$//;
1.620 albertel 6872: if (!$udomain) { $udomain=$env{'user.domain'}; }
6873: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6874: my $uhome=&homeserver($uname,$udomain);
6875: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6876: }
6877:
6878: # -------------------------------------------------------------- dump interface
6879:
1.1180 droeschl 6880: sub unserialize {
6881: my ($rep, $escapedkeys) = @_;
6882:
6883: return {} if $rep =~ /^error/;
6884:
6885: my %returnhash=();
1.1252 raeburn 6886: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 6887: my ($key, $value) = split(/=/, $item, 2);
6888: $key = unescape($key) unless $escapedkeys;
6889: next if $key =~ /^error: 2 /;
1.1252 raeburn 6890: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 6891: }
6892: #return %returnhash;
6893: return \%returnhash;
6894: }
6895:
6896: # see Lond::dump_with_regexp
6897: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6898: sub dump {
1.1180 droeschl 6899: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6900: if (!$udomain) { $udomain=$env{'user.domain'}; }
6901: if (!$uname) { $uname=$env{'user.name'}; }
6902: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6903:
1.1266 raeburn 6904: if ($regexp) {
6905: $regexp=&escape($regexp);
6906: } else {
6907: $regexp='.';
6908: }
1.1180 droeschl 6909: if (grep { $_ eq $uhome } current_machine_ids()) {
6910: # user is hosted on this machine
1.1266 raeburn 6911: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 6912: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 6913: return %{unserialize($reply, $escapedkeys)};
6914: }
1.1166 raeburn 6915: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6916: my @pairs=split(/\&/,$rep);
6917: my %returnhash=();
1.1098 foxr 6918: if (!($rep =~ /^error/ )) {
6919: foreach my $item (@pairs) {
6920: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 6921: $key = unescape($key) unless $escapedkeys;
6922: #$key = &unescape($key);
1.1098 foxr 6923: next if ($key =~ /^error: 2 /);
6924: $returnhash{$key}=&thaw_unescape($value);
6925: }
1.755 albertel 6926: }
6927: return %returnhash;
1.407 www 6928: }
6929:
1.1098 foxr 6930:
1.717 albertel 6931: # --------------------------------------------------------- dumpstore interface
6932:
6933: sub dumpstore {
6934: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 6935: # same as dump but keys must be escaped. They may contain colon separated
6936: # lists of values that may themself contain colons (e.g. symbs).
6937: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6938: }
6939:
1.407 www 6940: # -------------------------------------------------------------- keys interface
6941:
6942: sub getkeys {
6943: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6944: if (!$udomain) { $udomain=$env{'user.domain'}; }
6945: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6946: my $uhome=&homeserver($uname,$udomain);
6947: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6948: my @keyarray=();
1.800 albertel 6949: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6950: next if ($key =~ /^error: 2 /);
1.800 albertel 6951: push(@keyarray,&unescape($key));
1.407 www 6952: }
6953: return @keyarray;
1.318 matthew 6954: }
6955:
1.319 matthew 6956: # --------------------------------------------------------------- currentdump
6957: sub currentdump {
1.328 matthew 6958: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6959: $courseid = $env{'request.course.id'} if (! defined($courseid));
6960: $sdom = $env{'user.domain'} if (! defined($sdom));
6961: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6962: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 6963: my $rep;
6964:
6965: if (grep { $_ eq $uhome } current_machine_ids()) {
6966: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6967: $courseid)));
6968: } else {
6969: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6970: }
6971:
1.318 matthew 6972: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6973: #
1.318 matthew 6974: my %returnhash=();
1.319 matthew 6975: #
1.1343 raeburn 6976: if ($rep eq 'unknown_cmd') {
1.319 matthew 6977: # an old lond will not know currentdump
6978: # Do a dump and make it look like a currentdump
1.822 albertel 6979: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6980: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6981: my %hash = @tmp;
6982: @tmp=();
1.424 matthew 6983: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6984: } else {
6985: my @pairs=split(/\&/,$rep);
1.800 albertel 6986: foreach my $pair (@pairs) {
6987: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6988: my ($symb,$param) = split(/:/,$key);
6989: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6990: &thaw_unescape($value);
1.319 matthew 6991: }
1.191 harris41 6992: }
1.12 www 6993: return %returnhash;
1.424 matthew 6994: }
6995:
6996: sub convert_dump_to_currentdump{
6997: my %hash = %{shift()};
6998: my %returnhash;
6999: # Code ripped from lond, essentially. The only difference
7000: # here is the unescaping done by lonnet::dump(). Conceivably
7001: # we might run in to problems with parameter names =~ /^v\./
7002: while (my ($key,$value) = each(%hash)) {
7003: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7004: $symb = &unescape($symb);
7005: $param = &unescape($param);
1.424 matthew 7006: next if ($v eq 'version' || $symb eq 'keys');
7007: next if (exists($returnhash{$symb}) &&
7008: exists($returnhash{$symb}->{$param}) &&
7009: $returnhash{$symb}->{'v.'.$param} > $v);
7010: $returnhash{$symb}->{$param}=$value;
7011: $returnhash{$symb}->{'v.'.$param}=$v;
7012: }
7013: #
7014: # Remove all of the keys in the hashes which keep track of
7015: # the version of the parameter.
7016: while (my ($symb,$param_hash) = each(%returnhash)) {
7017: # use a foreach because we are going to delete from the hash.
7018: foreach my $key (keys(%$param_hash)) {
7019: delete($param_hash->{$key}) if ($key =~ /^v\./);
7020: }
7021: }
7022: return \%returnhash;
1.12 www 7023: }
7024:
1.627 albertel 7025: # ------------------------------------------------------ critical inc interface
7026:
7027: sub cinc {
7028: return &inc(@_,'critical');
7029: }
7030:
1.449 matthew 7031: # --------------------------------------------------------------- inc interface
7032:
7033: sub inc {
1.627 albertel 7034: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7035: if (!$udomain) { $udomain=$env{'user.domain'}; }
7036: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7037: my $uhome=&homeserver($uname,$udomain);
7038: my $items='';
7039: if (! ref($store)) {
7040: # got a single value, so use that instead
7041: $items = &escape($store).'=&';
7042: } elsif (ref($store) eq 'SCALAR') {
7043: $items = &escape($$store).'=&';
7044: } elsif (ref($store) eq 'ARRAY') {
7045: $items = join('=&',map {&escape($_);} @{$store});
7046: } elsif (ref($store) eq 'HASH') {
7047: while (my($key,$value) = each(%{$store})) {
7048: $items.= &escape($key).'='.&escape($value).'&';
7049: }
7050: }
7051: $items=~s/\&$//;
1.627 albertel 7052: if ($critical) {
7053: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7054: } else {
7055: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7056: }
1.449 matthew 7057: }
7058:
1.12 www 7059: # --------------------------------------------------------------- put interface
7060:
7061: sub put {
1.134 albertel 7062: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7063: if (!$udomain) { $udomain=$env{'user.domain'}; }
7064: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7065: my $uhome=&homeserver($uname,$udomain);
1.12 www 7066: my $items='';
1.800 albertel 7067: foreach my $item (keys(%$storehash)) {
7068: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7069: }
1.12 www 7070: $items=~s/\&$//;
1.134 albertel 7071: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 7072: }
7073:
1.631 albertel 7074: # ------------------------------------------------------------ newput interface
7075:
7076: sub newput {
7077: my ($namespace,$storehash,$udomain,$uname)=@_;
7078: if (!$udomain) { $udomain=$env{'user.domain'}; }
7079: if (!$uname) { $uname=$env{'user.name'}; }
7080: my $uhome=&homeserver($uname,$udomain);
7081: my $items='';
7082: foreach my $key (keys(%$storehash)) {
7083: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7084: }
7085: $items=~s/\&$//;
7086: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7087: }
7088:
7089: # --------------------------------------------------------- putstore interface
7090:
1.524 raeburn 7091: sub putstore {
1.1269 raeburn 7092: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7093: if (!$udomain) { $udomain=$env{'user.domain'}; }
7094: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7095: my $uhome=&homeserver($uname,$udomain);
7096: my $items='';
1.715 albertel 7097: foreach my $key (keys(%$storehash)) {
7098: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7099: }
1.715 albertel 7100: $items=~s/\&$//;
1.716 albertel 7101: my $esc_symb=&escape($symb);
7102: my $esc_v=&escape($version);
1.715 albertel 7103: my $reply =
1.716 albertel 7104: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7105: $uhome);
1.1269 raeburn 7106: if (($tolog) && ($reply eq 'ok')) {
7107: my $namevalue='';
7108: foreach my $key (keys(%{$storehash})) {
7109: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7110: }
7111: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
7112: '&host='.&escape($perlvar{'lonHostID'}).
7113: '&version='.$esc_v.
7114: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7115: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7116: }
1.715 albertel 7117: if ($reply eq 'unknown_cmd') {
1.716 albertel 7118: # gfall back to way things use to be done
1.715 albertel 7119: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7120: $uname);
1.524 raeburn 7121: }
1.715 albertel 7122: return $reply;
7123: }
7124:
7125: sub old_putstore {
1.716 albertel 7126: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7127: if (!$udomain) { $udomain=$env{'user.domain'}; }
7128: if (!$uname) { $uname=$env{'user.name'}; }
7129: my $uhome=&homeserver($uname,$udomain);
7130: my %newstorehash;
1.800 albertel 7131: foreach my $item (keys(%$storehash)) {
7132: my $key = $version.':'.&escape($symb).':'.$item;
7133: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7134: }
7135: my $items='';
7136: my %allitems = ();
1.800 albertel 7137: foreach my $item (keys(%newstorehash)) {
7138: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7139: my $key = $1.':keys:'.$2;
7140: $allitems{$key} .= $3.':';
7141: }
1.800 albertel 7142: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7143: }
1.800 albertel 7144: foreach my $item (keys(%allitems)) {
7145: $allitems{$item} =~ s/\:$//;
7146: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7147: }
7148: $items=~s/\&$//;
7149: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7150: }
7151:
1.47 www 7152: # ------------------------------------------------------ critical put interface
7153:
7154: sub cput {
1.134 albertel 7155: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7156: if (!$udomain) { $udomain=$env{'user.domain'}; }
7157: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7158: my $uhome=&homeserver($uname,$udomain);
1.47 www 7159: my $items='';
1.800 albertel 7160: foreach my $item (keys(%$storehash)) {
7161: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7162: }
1.47 www 7163: $items=~s/\&$//;
1.134 albertel 7164: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7165: }
7166:
7167: # -------------------------------------------------------------- eget interface
7168:
7169: sub eget {
1.133 albertel 7170: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7171: my $items='';
1.800 albertel 7172: foreach my $item (@$storearr) {
7173: $items.=&escape($item).'&';
1.191 harris41 7174: }
1.12 www 7175: $items=~s/\&$//;
1.620 albertel 7176: if (!$udomain) { $udomain=$env{'user.domain'}; }
7177: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7178: my $uhome=&homeserver($uname,$udomain);
7179: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7180: my @pairs=split(/\&/,$rep);
7181: my %returnhash=();
1.42 www 7182: my $i=0;
1.800 albertel 7183: foreach my $item (@$storearr) {
7184: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7185: $i++;
1.191 harris41 7186: }
1.12 www 7187: return %returnhash;
7188: }
7189:
1.667 albertel 7190: # ------------------------------------------------------------ tmpput interface
7191: sub tmpput {
1.802 raeburn 7192: my ($storehash,$server,$context)=@_;
1.667 albertel 7193: my $items='';
1.800 albertel 7194: foreach my $item (keys(%$storehash)) {
7195: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7196: }
7197: $items=~s/\&$//;
1.802 raeburn 7198: if (defined($context)) {
7199: $items .= ':'.&escape($context);
7200: }
1.667 albertel 7201: return &reply("tmpput:$items",$server);
7202: }
7203:
7204: # ------------------------------------------------------------ tmpget interface
7205: sub tmpget {
1.688 albertel 7206: my ($token,$server)=@_;
7207: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7208: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7209: my %returnhash;
1.1328 raeburn 7210: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7211: return %returnhash;
7212: }
1.667 albertel 7213: foreach my $item (split(/\&/,$rep)) {
7214: my ($key,$value)=split(/=/,$item);
7215: $returnhash{&unescape($key)}=&thaw_unescape($value);
7216: }
7217: return %returnhash;
7218: }
7219:
1.1113 raeburn 7220: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7221: sub tmpdel {
7222: my ($token,$server)=@_;
7223: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7224: return &reply("tmpdel:$token",$server);
7225: }
7226:
1.1198 raeburn 7227: # ------------------------------------------------------------ get_timebased_id
7228:
7229: sub get_timebased_id {
7230: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7231: $maxtries) = @_;
7232: my ($newid,$error,$dellock);
7233: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7234: return ('','ok','invalid call to get suffix');
7235: }
7236:
7237: # set defaults for any optional args for which values were not supplied
7238: if ($who eq '') {
7239: $who = $env{'user.name'}.':'.$env{'user.domain'};
7240: }
7241: if (!$locktries) {
7242: $locktries = 3;
7243: }
7244: if (!$maxtries) {
7245: $maxtries = 10;
7246: }
7247:
7248: if (($cdom eq '') || ($cnum eq '')) {
7249: if ($env{'request.course.id'}) {
7250: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7251: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7252: }
7253: if (($cdom eq '') || ($cnum eq '')) {
7254: return ('','ok','call to get suffix not in course context');
7255: }
7256: }
7257:
7258: # construct locking item
7259: my $lockhash = {
7260: $prefix."\0".'locked_'.$keyid => $who,
7261: };
7262: my $tries = 0;
7263:
7264: # attempt to get lock on nohist_$namespace file
7265: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7266: while (($gotlock ne 'ok') && $tries <$locktries) {
7267: $tries ++;
7268: sleep 1;
7269: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7270: }
7271:
7272: # attempt to get unique identifier, based on current timestamp
7273: if ($gotlock eq 'ok') {
7274: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7275: my $id = time;
7276: $newid = $id;
1.1268 raeburn 7277: if ($idtype eq 'addcode') {
7278: $newid .= &sixnum_code();
7279: }
1.1198 raeburn 7280: my $idtries = 0;
7281: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7282: if ($idtype eq 'concat') {
7283: $newid = $id.$idtries;
1.1268 raeburn 7284: } elsif ($idtype eq 'addcode') {
7285: $newid = $newid.&sixnum_code();
1.1198 raeburn 7286: } else {
7287: $newid ++;
7288: }
7289: $idtries ++;
7290: }
7291: if (!exists($inuse{$prefix."\0".$newid})) {
7292: my %new_item = (
7293: $prefix."\0".$newid => $who,
7294: );
7295: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7296: $cdom,$cnum);
7297: if ($putresult ne 'ok') {
7298: undef($newid);
7299: $error = 'error saving new item: '.$putresult;
7300: }
7301: } else {
1.1268 raeburn 7302: undef($newid);
1.1198 raeburn 7303: $error = ('error: no unique suffix available for the new item ');
7304: }
7305: # remove lock
7306: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7307: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7308: } else {
7309: $error = "error: could not obtain lockfile\n";
7310: $dellock = 'ok';
1.1276 raeburn 7311: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7312: $dellock = 'nolock';
7313: }
1.1198 raeburn 7314: }
7315: return ($newid,$dellock,$error);
7316: }
7317:
1.1268 raeburn 7318: sub sixnum_code {
7319: my $code;
7320: for (0..6) {
7321: $code .= int( rand(9) );
7322: }
7323: return $code;
7324: }
7325:
1.765 albertel 7326: # -------------------------------------------------- portfolio access checking
7327:
7328: sub portfolio_access {
1.1270 raeburn 7329: my ($requrl,$clientip) = @_;
1.765 albertel 7330: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 7331: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7332: if ($result) {
7333: my %setters;
7334: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7335: my ($startblock,$endblock) =
7336: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
7337: if ($startblock && $endblock) {
7338: return 'B';
7339: }
7340: } else {
7341: my ($startblock,$endblock) =
7342: &Apache::loncommon::blockcheck(\%setters,'port');
7343: if ($startblock && $endblock) {
7344: return 'B';
7345: }
7346: }
7347: }
1.765 albertel 7348: if ($result eq 'ok') {
1.766 albertel 7349: return 'F';
1.765 albertel 7350: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7351: return 'A';
1.765 albertel 7352: }
1.766 albertel 7353: return '';
1.765 albertel 7354: }
7355:
7356: sub get_portfolio_access {
1.1270 raeburn 7357: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7358:
7359: if (!ref($access_hash)) {
7360: my $current_perms = &get_portfile_permissions($udom,$unum);
7361: my %access_controls = &get_access_controls($current_perms,$group,
7362: $file_name);
7363: $access_hash = $access_controls{$file_name};
7364: }
7365:
1.1270 raeburn 7366: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7367: my $now = time;
7368: if (ref($access_hash) eq 'HASH') {
7369: foreach my $key (keys(%{$access_hash})) {
7370: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7371: if ($start > $now) {
7372: next;
7373: }
7374: if ($end && $end<$now) {
7375: next;
7376: }
7377: if ($scope eq 'public') {
7378: $public = $key;
7379: last;
7380: } elsif ($scope eq 'guest') {
7381: $guest = $key;
7382: } elsif ($scope eq 'domains') {
7383: push(@domains,$key);
7384: } elsif ($scope eq 'users') {
7385: push(@users,$key);
7386: } elsif ($scope eq 'course') {
7387: push(@courses,$key);
7388: } elsif ($scope eq 'group') {
7389: push(@groups,$key);
1.1270 raeburn 7390: } elsif ($scope eq 'ip') {
7391: push(@ips,$key);
1.765 albertel 7392: }
7393: }
7394: if ($public) {
7395: return 'ok';
1.1270 raeburn 7396: } elsif (@ips > 0) {
7397: my $allowed;
7398: foreach my $ipkey (@ips) {
7399: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7400: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7401: $allowed = 1;
7402: last;
7403: }
7404: }
7405: }
7406: if ($allowed) {
7407: return 'ok';
7408: }
1.765 albertel 7409: }
7410: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7411: if ($guest) {
7412: return $guest;
7413: }
7414: } else {
7415: if (@domains > 0) {
7416: foreach my $domkey (@domains) {
7417: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7418: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7419: return 'ok';
7420: }
7421: }
7422: }
7423: }
7424: if (@users > 0) {
7425: foreach my $userkey (@users) {
1.865 raeburn 7426: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7427: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7428: if (ref($item) eq 'HASH') {
7429: if (($item->{'uname'} eq $env{'user.name'}) &&
7430: ($item->{'udom'} eq $env{'user.domain'})) {
7431: return 'ok';
7432: }
7433: }
7434: }
7435: }
1.765 albertel 7436: }
7437: }
7438: my %roleshash;
7439: my @courses_and_groups = @courses;
7440: push(@courses_and_groups,@groups);
7441: if (@courses_and_groups > 0) {
7442: my (%allgroups,%allroles);
7443: my ($start,$end,$role,$sec,$group);
7444: foreach my $envkey (%env) {
1.1060 raeburn 7445: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7446: my $cid = $2.'_'.$3;
7447: if ($1 eq 'gr') {
7448: $group = $4;
7449: $allgroups{$cid}{$group} = $env{$envkey};
7450: } else {
7451: if ($4 eq '') {
7452: $sec = 'none';
7453: } else {
7454: $sec = $4;
7455: }
7456: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7457: }
1.811 albertel 7458: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7459: my $cid = $2.'_'.$3;
7460: if ($4 eq '') {
7461: $sec = 'none';
7462: } else {
7463: $sec = $4;
7464: }
7465: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7466: }
7467: }
7468: if (keys(%allroles) == 0) {
7469: return;
7470: }
7471: foreach my $key (@courses_and_groups) {
7472: my %content = %{$$access_hash{$key}};
7473: my $cnum = $content{'number'};
7474: my $cdom = $content{'domain'};
7475: my $cid = $cdom.'_'.$cnum;
7476: if (!exists($allroles{$cid})) {
7477: next;
7478: }
7479: foreach my $role_id (keys(%{$content{'roles'}})) {
7480: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7481: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7482: my @status = @{$content{'roles'}{$role_id}{'access'}};
7483: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7484: foreach my $role (keys(%{$allroles{$cid}})) {
7485: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7486: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7487: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7488: if (grep/^all$/,@sections) {
7489: return 'ok';
7490: } else {
7491: if (grep/^$sec$/,@sections) {
7492: return 'ok';
7493: }
7494: }
7495: }
7496: }
7497: if (keys(%{$allgroups{$cid}}) == 0) {
7498: if (grep/^none$/,@groups) {
7499: return 'ok';
7500: }
7501: } else {
7502: if (grep/^all$/,@groups) {
7503: return 'ok';
7504: }
7505: foreach my $group (keys(%{$allgroups{$cid}})) {
7506: if (grep/^$group$/,@groups) {
7507: return 'ok';
7508: }
7509: }
7510: }
7511: }
7512: }
7513: }
7514: }
7515: }
7516: if ($guest) {
7517: return $guest;
7518: }
7519: }
7520: }
7521: return;
7522: }
7523:
7524: sub course_group_datechecker {
7525: my ($dates,$now,$status) = @_;
7526: my ($start,$end) = split(/\./,$dates);
7527: if (!$start && !$end) {
7528: return 'ok';
7529: }
7530: if (grep/^active$/,@{$status}) {
7531: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7532: return 'ok';
7533: }
7534: }
7535: if (grep/^previous$/,@{$status}) {
7536: if ($end > $now ) {
7537: return 'ok';
7538: }
7539: }
7540: if (grep/^future$/,@{$status}) {
7541: if ($start > $now) {
7542: return 'ok';
7543: }
7544: }
7545: return;
7546: }
7547:
7548: sub parse_portfolio_url {
7549: my ($url) = @_;
7550:
7551: my ($type,$udom,$unum,$group,$file_name);
7552:
1.823 albertel 7553: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7554: $type = 1;
7555: $udom = $1;
7556: $unum = $2;
7557: $file_name = $3;
1.823 albertel 7558: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7559: $type = 2;
7560: $udom = $1;
7561: $unum = $2;
7562: $group = $3;
7563: $file_name = $3.'/'.$4;
7564: }
7565: if (wantarray) {
7566: return ($type,$udom,$unum,$file_name,$group);
7567: }
7568: return $type;
7569: }
7570:
7571: sub is_portfolio_url {
7572: my ($url) = @_;
7573: return scalar(&parse_portfolio_url($url));
7574: }
7575:
1.798 raeburn 7576: sub is_portfolio_file {
7577: my ($file) = @_;
1.820 raeburn 7578: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7579: return 1;
7580: }
7581: return;
7582: }
7583:
1.976 raeburn 7584: sub usertools_access {
1.1084 raeburn 7585: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7586: my ($access,%tools);
7587: if ($context eq '') {
7588: $context = 'tools';
7589: }
7590: if ($context eq 'requestcourses') {
7591: %tools = (
7592: official => 1,
7593: unofficial => 1,
1.1006 raeburn 7594: community => 1,
1.1246 raeburn 7595: textbook => 1,
1.1305 raeburn 7596: placement => 1,
1.1368 raeburn 7597: lti => 1,
1.985 raeburn 7598: );
1.1183 raeburn 7599: } elsif ($context eq 'requestauthor') {
7600: %tools = (
7601: requestauthor => 1,
7602: );
1.985 raeburn 7603: } else {
7604: %tools = (
7605: aboutme => 1,
7606: blog => 1,
1.1177 raeburn 7607: webdav => 1,
1.985 raeburn 7608: portfolio => 1,
7609: );
7610: }
1.976 raeburn 7611: return if (!defined($tools{$tool}));
7612:
1.1242 raeburn 7613: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7614: $udom = $env{'user.domain'};
7615: $uname = $env{'user.name'};
7616: }
7617:
1.978 raeburn 7618: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7619: if ($action ne 'reload') {
1.985 raeburn 7620: if ($context eq 'requestcourses') {
7621: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 7622: } elsif ($context eq 'requestauthor') {
7623: return $env{'environment.canrequest.author'};
1.985 raeburn 7624: } else {
7625: return $env{'environment.availabletools.'.$tool};
7626: }
7627: }
1.976 raeburn 7628: }
7629:
1.1183 raeburn 7630: my ($toolstatus,$inststatus,$envkey);
7631: if ($context eq 'requestauthor') {
7632: $envkey = $context;
7633: } else {
7634: $envkey = $context.'.'.$tool;
7635: }
1.976 raeburn 7636:
1.985 raeburn 7637: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7638: ($action ne 'reload')) {
1.1183 raeburn 7639: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7640: $inststatus = $env{'environment.inststatus'};
7641: } else {
1.1084 raeburn 7642: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 7643: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7644: $inststatus = $userenvref->{'inststatus'};
7645: } else {
1.1183 raeburn 7646: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7647: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7648: $inststatus = $userenv{'inststatus'};
7649: }
1.976 raeburn 7650: }
7651:
7652: if ($toolstatus ne '') {
7653: if ($toolstatus) {
7654: $access = 1;
7655: } else {
7656: $access = 0;
7657: }
7658: return $access;
7659: }
7660:
1.1084 raeburn 7661: my ($is_adv,%domdef);
7662: if (ref($is_advref) eq 'HASH') {
7663: $is_adv = $is_advref->{'is_adv'};
7664: } else {
7665: $is_adv = &is_advanced_user($udom,$uname);
7666: }
7667: if (ref($domdefref) eq 'HASH') {
7668: %domdef = %{$domdefref};
7669: } else {
7670: %domdef = &get_domain_defaults($udom);
7671: }
1.976 raeburn 7672: if (ref($domdef{$tool}) eq 'HASH') {
7673: if ($is_adv) {
7674: if ($domdef{$tool}{'_LC_adv'} ne '') {
7675: if ($domdef{$tool}{'_LC_adv'}) {
7676: $access = 1;
7677: } else {
7678: $access = 0;
7679: }
7680: return $access;
7681: }
7682: }
7683: if ($inststatus ne '') {
7684: my ($hasaccess,$hasnoaccess);
7685: foreach my $affiliation (split(/:/,$inststatus)) {
7686: if ($domdef{$tool}{$affiliation} ne '') {
7687: if ($domdef{$tool}{$affiliation}) {
7688: $hasaccess = 1;
7689: } else {
7690: $hasnoaccess = 1;
7691: }
7692: }
7693: }
7694: if ($hasaccess || $hasnoaccess) {
7695: if ($hasaccess) {
7696: $access = 1;
7697: } elsif ($hasnoaccess) {
7698: $access = 0;
7699: }
7700: return $access;
7701: }
7702: } else {
7703: if ($domdef{$tool}{'default'} ne '') {
7704: if ($domdef{$tool}{'default'}) {
7705: $access = 1;
7706: } elsif ($domdef{$tool}{'default'} == 0) {
7707: $access = 0;
7708: }
7709: return $access;
7710: }
7711: }
7712: } else {
1.1177 raeburn 7713: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7714: $access = 1;
7715: } else {
7716: $access = 0;
7717: }
1.976 raeburn 7718: return $access;
7719: }
7720: }
7721:
1.1050 raeburn 7722: sub is_course_owner {
7723: my ($cdom,$cnum,$udom,$uname) = @_;
7724: if (($udom eq '') || ($uname eq '')) {
7725: $udom = $env{'user.domain'};
7726: $uname = $env{'user.name'};
7727: }
7728: unless (($udom eq '') || ($uname eq '')) {
7729: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7730: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7731: return 1;
7732: } else {
7733: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7734: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7735: return 1;
7736: }
7737: }
7738: }
7739: }
7740: return;
7741: }
7742:
1.976 raeburn 7743: sub is_advanced_user {
7744: my ($udom,$uname) = @_;
1.1085 raeburn 7745: if ($udom ne '' && $uname ne '') {
7746: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7747: if (wantarray) {
7748: return ($env{'user.adv'},$env{'user.author'});
7749: } else {
7750: return $env{'user.adv'};
7751: }
1.1085 raeburn 7752: }
7753: }
1.976 raeburn 7754: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7755: my %allroles;
1.1128 raeburn 7756: my ($is_adv,$is_author);
1.976 raeburn 7757: foreach my $role (keys(%roleshash)) {
7758: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7759: my $area = '/'.$tdomain.'/'.$trest;
7760: if ($sec ne '') {
7761: $area .= '/'.$sec;
7762: }
7763: if (($area ne '') && ($trole ne '')) {
7764: my $spec=$trole.'.'.$area;
7765: if ($trole =~ /^cr\//) {
7766: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7767: } elsif ($trole ne 'gr') {
7768: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7769: }
1.1128 raeburn 7770: if ($trole eq 'au') {
7771: $is_author = 1;
7772: }
1.976 raeburn 7773: }
7774: }
7775: foreach my $role (keys(%allroles)) {
7776: last if ($is_adv);
7777: foreach my $item (split(/:/,$allroles{$role})) {
7778: if ($item ne '') {
7779: my ($privilege,$restrictions)=split(/&/,$item);
7780: if ($privilege eq 'adv') {
7781: $is_adv = 1;
7782: last;
7783: }
7784: }
7785: }
7786: }
1.1128 raeburn 7787: if (wantarray) {
7788: return ($is_adv,$is_author);
7789: }
1.976 raeburn 7790: return $is_adv;
7791: }
1.798 raeburn 7792:
1.1035 raeburn 7793: sub check_can_request {
1.1368 raeburn 7794: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035 raeburn 7795: my $canreq = 0;
1.1368 raeburn 7796: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7797: $uname = $env{'user.name'};
7798: $udom = $env{'user.domain'};
7799: }
1.1035 raeburn 7800: my ($types,$typename) = &Apache::loncommon::course_types();
7801: my @options = ('approval','validate','autolimit');
7802: my $optregex = join('|',@options);
7803: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7804: foreach my $type (@{$types}) {
1.1368 raeburn 7805: if (&usertools_access($uname,$udom,$type,undef,
7806: 'requestcourses')) {
1.1035 raeburn 7807: $canreq ++;
1.1036 raeburn 7808: if (ref($request_domains) eq 'HASH') {
1.1368 raeburn 7809: push(@{$request_domains->{$type}},$udom);
1.1036 raeburn 7810: }
1.1368 raeburn 7811: if ($dom eq $udom) {
1.1035 raeburn 7812: $can_request->{$type} = 1;
7813: }
7814: }
1.1368 raeburn 7815: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
7816: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035 raeburn 7817: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7818: if (@curr > 0) {
1.1036 raeburn 7819: foreach my $item (@curr) {
7820: if (ref($request_domains) eq 'HASH') {
7821: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7822: if ($otherdom ne '') {
7823: if (ref($request_domains->{$type}) eq 'ARRAY') {
7824: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7825: push(@{$request_domains->{$type}},$otherdom);
7826: }
7827: } else {
7828: push(@{$request_domains->{$type}},$otherdom);
7829: }
7830: }
7831: }
7832: }
1.1368 raeburn 7833: unless ($dom eq $env{'user.domain'}) {
1.1036 raeburn 7834: $canreq ++;
1.1035 raeburn 7835: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7836: $can_request->{$type} = 1;
7837: }
7838: }
7839: }
7840: }
7841: }
7842: }
7843: return $canreq;
7844: }
7845:
1.341 www 7846: # ---------------------------------------------- Custom access rule evaluation
7847:
7848: sub customaccess {
7849: my ($priv,$uri)=@_;
1.807 albertel 7850: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7851: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7852: $udom = &LONCAPA::clean_domain($udom);
7853: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7854: my $access=0;
1.800 albertel 7855: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7856: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7857: if ($type eq 'user') {
7858: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7859: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7860: if ($tdom) {
7861: if ($tdom ne $env{'user.domain'}) { next; }
7862: }
1.896 albertel 7863: if ($tuname) {
7864: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7865: }
7866: $access=($effect eq 'allow');
7867: last;
7868: }
7869: } else {
7870: if ($role) {
7871: if ($role ne $urole) { next; }
7872: }
7873: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7874: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7875: if ($tdom) {
7876: if ($tdom ne $udom) { next; }
7877: }
7878: if ($tcrs) {
7879: if ($tcrs ne $ucrs) { next; }
7880: }
7881: if ($tsec) {
7882: if ($tsec ne $usec) { next; }
7883: }
7884: $access=($effect eq 'allow');
7885: last;
7886: }
7887: if ($realm eq '' && $role eq '') {
7888: $access=($effect eq 'allow');
7889: }
1.402 bowersj2 7890: }
1.341 www 7891: }
7892: return $access;
7893: }
7894:
1.103 harris41 7895: # ------------------------------------------------- Check for a user privilege
1.12 www 7896:
7897: sub allowed {
1.1281 raeburn 7898: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7899: my $ver_orguri=$uri;
1.439 www 7900: $uri=&deversion($uri);
1.152 www 7901: my $orguri=$uri;
1.52 www 7902: $uri=&declutter($uri);
1.809 raeburn 7903:
1.810 raeburn 7904: if ($priv eq 'evb') {
7905: # Evade communication block restrictions for specified role in a course
7906: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7907: return $1;
7908: } else {
7909: return;
7910: }
7911: }
7912:
1.620 albertel 7913: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7914: # Free bre access to adm and meta resources
1.1343 raeburn 7915: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$}))
1.769 albertel 7916: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7917: && ($priv eq 'bre')) {
1.14 www 7918: return 'F';
1.159 www 7919: }
7920:
1.545 banghart 7921: # Free bre access to user's own portfolio contents
1.714 raeburn 7922: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7923: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7924: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7925: my %setters;
7926: my ($startblock,$endblock) =
7927: &Apache::loncommon::blockcheck(\%setters,'port');
7928: if ($startblock && $endblock) {
7929: return 'B';
7930: } else {
7931: return 'F';
7932: }
1.545 banghart 7933: }
7934:
1.762 raeburn 7935: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7936: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7937: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7938: if (exists($env{'request.course.id'})) {
7939: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7940: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7941: if (($domain eq $cdom) && ($name eq $cnum)) {
7942: my $courseprivid=$env{'request.course.id'};
7943: $courseprivid=~s/\_/\//;
7944: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7945: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7946: return $1;
1.762 raeburn 7947: } else {
7948: if ($env{'request.course.sec'}) {
7949: $courseprivid.='/'.$env{'request.course.sec'};
7950: }
7951: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7952: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7953: return $2;
7954: }
1.714 raeburn 7955: }
7956: }
7957: }
7958: }
7959:
1.159 www 7960: # Free bre to public access
7961:
7962: if ($priv eq 'bre') {
1.1362 raeburn 7963: my $copyright;
7964: unless ($uri =~ /ext\.tool/) {
7965: $copyright=&metadata($uri,'copyright');
7966: }
1.620 albertel 7967: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7968: return 'F';
7969: }
1.238 www 7970: if ($copyright eq 'priv') {
7971: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7972: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7973: return '';
7974: }
7975: }
7976: if ($copyright eq 'domain') {
7977: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7978: unless (($env{'user.domain'} eq $1) ||
7979: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7980: return '';
7981: }
1.262 matthew 7982: }
1.620 albertel 7983: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7984: # Library role, so allow browsing of resources in this domain.
7985: return 'F';
1.238 www 7986: }
1.341 www 7987: if ($copyright eq 'custom') {
7988: unless (&customaccess($priv,$uri)) { return ''; }
7989: }
1.14 www 7990: }
1.264 matthew 7991: # Domain coordinator is trying to create a course
1.620 albertel 7992: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7993: # uri is the requested domain in this case.
7994: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7995: # a role of dc for the domain in question.
1.620 albertel 7996: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7997: }
1.29 www 7998:
1.52 www 7999: my $thisallowed='';
8000: my $statecond=0;
8001: my $courseprivid='';
8002:
1.1039 raeburn 8003: my $ownaccess;
1.1043 raeburn 8004: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8005: if (($priv eq 'bro') && ($env{'user.author'})) {
8006: if ($uri eq '') {
8007: $ownaccess = 1;
8008: } else {
8009: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8010: my $udom = $env{'user.domain'};
8011: my $uname = $env{'user.name'};
8012: if ($uri =~ m{^\Q$udom\E/?$}) {
8013: $ownaccess = 1;
1.1040 raeburn 8014: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8015: unless ($uri =~ m{\.\./}) {
8016: $ownaccess = 1;
8017: }
8018: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8019: my $now = time;
8020: if ($uri =~ m{^([^/]+)/?$}) {
8021: my $adom = $1;
8022: foreach my $key (keys(%env)) {
1.1042 raeburn 8023: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 8024: my ($start,$end) = split('.',$env{$key});
8025: if (($now >= $start) && (!$end || $end < $now)) {
8026: $ownaccess = 1;
8027: last;
8028: }
8029: }
8030: }
8031: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8032: my $adom = $1;
8033: my $aname = $2;
1.1042 raeburn 8034: foreach my $role ('ca','aa') {
8035: if ($env{"user.role.$role./$adom/$aname"}) {
8036: my ($start,$end) =
8037: split('.',$env{"user.role.$role./$adom/$aname"});
8038: if (($now >= $start) && (!$end || $end < $now)) {
8039: $ownaccess = 1;
8040: last;
8041: }
1.1039 raeburn 8042: }
8043: }
8044: }
8045: }
8046: }
8047: }
8048: }
8049:
1.52 www 8050: # Course
8051:
1.620 albertel 8052: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8053: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8054: $thisallowed.=$1;
8055: }
1.52 www 8056: }
1.29 www 8057:
1.52 www 8058: # Domain
8059:
1.620 albertel 8060: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8061: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8062: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8063: $thisallowed.=$1;
8064: }
1.12 www 8065: }
1.52 www 8066:
1.1141 raeburn 8067: # User who is not author or co-author might still be able to edit
8068: # resource of an author in the domain (e.g., if Domain Coordinator).
8069: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8070: (&allowed('mdc',$env{'request.course.id'}))) {
8071: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8072: $thisallowed.=$1;
8073: }
8074: }
8075:
1.52 www 8076: # Course: uri itself is a course
1.66 www 8077: my $courseuri=$uri;
8078: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8079: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8080:
1.620 albertel 8081: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8082: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8083: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8084: $thisallowed.=$1;
8085: }
1.12 www 8086: }
1.29 www 8087:
1.665 albertel 8088: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8089: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8090: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8091: $thisallowed='';
1.671 raeburn 8092: my ($match)=&is_on_map($uri);
8093: if ($match) {
8094: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8095: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 8096: my $value = $1;
1.1402 raeburn 8097: my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8098: if ($deeplinkblock) {
8099: $thisallowed='D';
8100: } elsif ($noblockcheck) {
1.1281 raeburn 8101: $thisallowed.=$value;
1.1162 raeburn 8102: } else {
1.1281 raeburn 8103: my @blockers = &has_comm_blocking($priv,$symb,$uri);
8104: if (@blockers > 0) {
8105: $thisallowed = 'B';
8106: } else {
8107: $thisallowed.=$value;
8108: }
1.1162 raeburn 8109: }
1.671 raeburn 8110: }
8111: } else {
1.705 albertel 8112: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8113: if ($refuri) {
8114: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8115: $thisallowed='F';
1.671 raeburn 8116: } else {
8117: $refuri=&declutter($refuri);
8118: my ($match) = &is_on_map($refuri);
8119: if ($match) {
1.1402 raeburn 8120: my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8121: if ($deeplinkblock) {
8122: $thisallowed='D';
8123: } elsif ($noblockcheck) {
1.1281 raeburn 8124: $thisallowed='F';
1.1162 raeburn 8125: } else {
1.1281 raeburn 8126: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
8127: if (@blockers > 0) {
8128: $thisallowed = 'B';
8129: } else {
8130: $thisallowed='F';
8131: }
1.1162 raeburn 8132: }
1.671 raeburn 8133: }
1.669 raeburn 8134: }
1.671 raeburn 8135: }
8136: }
1.314 www 8137: }
1.492 albertel 8138:
1.766 albertel 8139: if ($priv eq 'bre'
8140: && $thisallowed ne 'F'
8141: && $thisallowed ne '2'
8142: && &is_portfolio_url($uri)) {
1.1270 raeburn 8143: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8144: }
1.1250 raeburn 8145:
1.52 www 8146: # Full access at system, domain or course-wide level? Exit.
1.29 www 8147: if ($thisallowed=~/F/) {
8148: return 'F';
8149: }
8150:
1.52 www 8151: # If this is generating or modifying users, exit with special codes
1.29 www 8152:
1.643 www 8153: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8154: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8155: my ($audom,$auname)=split('/',$uri);
1.643 www 8156: # no author name given, so this just checks on the general right to make a co-author in this domain
8157: unless ($auname) { return $thisallowed; }
8158: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8159: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8160: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8161: ($audom ne $env{'request.role.domain'}))) { return ''; }
8162: }
1.52 www 8163: return $thisallowed;
8164: }
8165: #
1.103 harris41 8166: # Gathered so far: system, domain and course wide privileges
1.52 www 8167: #
8168: # Course: See if uri or referer is an individual resource that is part of
8169: # the course
8170:
1.620 albertel 8171: if ($env{'request.course.id'}) {
1.232 www 8172:
1.620 albertel 8173: $courseprivid=$env{'request.course.id'};
8174: if ($env{'request.course.sec'}) {
8175: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8176: }
8177: $courseprivid=~s/\_/\//;
8178: my $checkreferer=1;
1.232 www 8179: my ($match,$cond)=&is_on_map($uri);
8180: if ($match) {
8181: $statecond=$cond;
1.620 albertel 8182: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8183: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8184: my $value = $1;
8185: if ($priv eq 'bre') {
1.1281 raeburn 8186: if ($noblockcheck) {
8187: $thisallowed.=$value;
1.1162 raeburn 8188: } else {
1.1281 raeburn 8189: my @blockers = &has_comm_blocking($priv,$symb,$uri);
8190: if (@blockers > 0) {
8191: $thisallowed = 'B';
8192: } else {
8193: $thisallowed.=$value;
8194: }
1.1162 raeburn 8195: }
8196: } else {
8197: $thisallowed.=$value;
8198: }
1.52 www 8199: $checkreferer=0;
8200: }
1.29 www 8201: }
1.83 www 8202:
1.148 www 8203: if ($checkreferer) {
1.620 albertel 8204: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8205: unless ($refuri) {
1.800 albertel 8206: foreach my $key (keys(%env)) {
8207: if ($key=~/^httpref\..*\*/) {
8208: my $pattern=$key;
1.156 www 8209: $pattern=~s/^httpref\.\/res\///;
1.148 www 8210: $pattern=~s/\*/\[\^\/\]\+/g;
8211: $pattern=~s/\//\\\//g;
1.152 www 8212: if ($orguri=~/$pattern/) {
1.800 albertel 8213: $refuri=$env{$key};
1.148 www 8214: }
8215: }
1.191 harris41 8216: }
1.148 www 8217: }
1.232 www 8218:
1.148 www 8219: if ($refuri) {
1.152 www 8220: $refuri=&declutter($refuri);
1.232 www 8221: my ($match,$cond)=&is_on_map($refuri);
8222: if ($match) {
8223: my $refstatecond=$cond;
1.620 albertel 8224: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8225: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8226: my $value = $1;
8227: if ($priv eq 'bre') {
1.1402 raeburn 8228: my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8229: if ($deeplinkblock) {
8230: $thisallowed = 'D';
8231: } elsif ($noblockcheck) {
1.1281 raeburn 8232: $thisallowed.=$value;
1.1162 raeburn 8233: } else {
1.1281 raeburn 8234: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
8235: if (@blockers > 0) {
8236: $thisallowed = 'B';
8237: } else {
8238: $thisallowed.=$value;
8239: }
1.1162 raeburn 8240: }
8241: } else {
8242: $thisallowed.=$value;
8243: }
1.53 www 8244: $uri=$refuri;
8245: $statecond=$refstatecond;
1.52 www 8246: }
8247: }
1.148 www 8248: }
1.29 www 8249: }
1.52 www 8250: }
1.29 www 8251:
1.52 www 8252: #
1.103 harris41 8253: # Gathered now: all privileges that could apply, and condition number
1.52 www 8254: #
8255: #
8256: # Full or no access?
8257: #
1.29 www 8258:
1.52 www 8259: if ($thisallowed=~/F/) {
8260: return 'F';
8261: }
1.29 www 8262:
1.52 www 8263: unless ($thisallowed) {
8264: return '';
8265: }
1.29 www 8266:
1.52 www 8267: # Restrictions exist, deal with them
8268: #
8269: # C:according to course preferences
8270: # R:according to resource settings
8271: # L:unless locked
8272: # X:according to user session state
8273: #
8274:
8275: # Possibly locked functionality, check all courses
1.54 www 8276: # Locks might take effect only after 10 minutes cache expiration for other
8277: # courses, and 2 minutes for current course
1.52 www 8278:
8279: my $envkey;
8280: if ($thisallowed=~/L/) {
1.1000 raeburn 8281: foreach $envkey (keys(%env)) {
1.54 www 8282: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8283: my $courseid=$2;
8284: my $roleid=$1.'.'.$2;
1.92 www 8285: $courseid=~s/^\///;
1.54 www 8286: my $expiretime=600;
1.620 albertel 8287: if ($env{'request.role'} eq $roleid) {
1.54 www 8288: $expiretime=120;
8289: }
8290: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8291: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8292: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8293: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8294: }
1.620 albertel 8295: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8296: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8297: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8298: &log($env{'user.domain'},$env{'user.name'},
8299: $env{'user.home'},
1.57 www 8300: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8301: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8302: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8303: return '';
8304: }
8305: }
1.620 albertel 8306: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8307: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8308: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
8309: &log($env{'user.domain'},$env{'user.name'},
8310: $env{'user.home'},
1.57 www 8311: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8312: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8313: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8314: return '';
8315: }
8316: }
8317: }
1.29 www 8318: }
1.52 www 8319: }
8320:
8321: #
8322: # Rest of the restrictions depend on selected course
8323: #
8324:
1.620 albertel 8325: unless ($env{'request.course.id'}) {
1.766 albertel 8326: if ($thisallowed eq 'A') {
8327: return 'A';
1.814 raeburn 8328: } elsif ($thisallowed eq 'B') {
8329: return 'B';
1.766 albertel 8330: } else {
8331: return '1';
8332: }
1.52 www 8333: }
1.29 www 8334:
1.52 www 8335: #
8336: # Now user is definitely in a course
8337: #
1.53 www 8338:
8339:
8340: # Course preferences
8341:
8342: if ($thisallowed=~/C/) {
1.620 albertel 8343: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8344: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8345: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8346: =~/\Q$rolecode\E/) {
1.1304 raeburn 8347: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8348: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8349: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8350: $env{'request.course.id'});
8351: }
1.237 www 8352: return '';
8353: }
8354:
1.620 albertel 8355: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8356: =~/\Q$unamedom\E/) {
1.1304 raeburn 8357: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8358: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8359: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8360: $env{'request.course.id'});
8361: }
1.54 www 8362: return '';
8363: }
1.53 www 8364: }
8365:
8366: # Resource preferences
8367:
8368: if ($thisallowed=~/R/) {
1.620 albertel 8369: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8370: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8371: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8372: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8373: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8374: }
8375: return '';
1.54 www 8376: }
1.53 www 8377: }
1.30 www 8378:
1.246 www 8379: # Restricted by state or randomout?
1.30 www 8380:
1.52 www 8381: if ($thisallowed=~/X/) {
1.620 albertel 8382: if ($env{'acc.randomout'}) {
1.579 albertel 8383: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8384: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8385: return '';
8386: }
1.247 www 8387: }
8388: if (&condval($statecond)) {
1.52 www 8389: return '2';
8390: } else {
8391: return '';
8392: }
8393: }
1.30 www 8394:
1.766 albertel 8395: if ($thisallowed eq 'A') {
8396: return 'A';
1.814 raeburn 8397: } elsif ($thisallowed eq 'B') {
8398: return 'B';
1.1402 raeburn 8399: } elsif ($thisallowed eq 'D') {
8400: return 'D';
1.766 albertel 8401: }
1.52 www 8402: return 'F';
1.232 www 8403: }
1.1162 raeburn 8404:
1.1192 raeburn 8405: # ------------------------------------------- Check construction space access
8406:
8407: sub constructaccess {
8408: my ($url,$setpriv)=@_;
8409:
8410: # We do not allow editing of previous versions of files
8411: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8412:
8413: # Get username and domain from URL
8414: my ($ownername,$ownerdomain,$ownerhome);
8415:
8416: ($ownerdomain,$ownername) =
1.1325 raeburn 8417: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 8418:
8419: # The URL does not really point to any authorspace, forget it
8420: unless (($ownername) && ($ownerdomain)) { return ''; }
8421:
8422: # Now we need to see if the user has access to the authorspace of
8423: # $ownername at $ownerdomain
8424:
8425: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8426: # Real author for this?
8427: $ownerhome = $env{'user.home'};
8428: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8429: return ($ownername,$ownerdomain,$ownerhome);
8430: }
8431: } else {
8432: # Co-author for this?
8433: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8434: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8435: $ownerhome = &homeserver($ownername,$ownerdomain);
8436: return ($ownername,$ownerdomain,$ownerhome);
8437: }
1.1312 raeburn 8438: if ($env{'request.course.id'}) {
8439: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
8440: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
8441: if (&allowed('mdc',$env{'request.course.id'})) {
8442: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
8443: return ($ownername,$ownerdomain,$ownerhome);
8444: }
8445: }
8446: }
1.1192 raeburn 8447: }
8448:
8449: # We don't have any access right now. If we are not possibly going to do anything about this,
8450: # we might as well leave
8451: unless ($setpriv) { return ''; }
8452:
8453: # Backdoor access?
8454: my $allowed=&allowed('eco',$ownerdomain);
8455: # Nope
8456: unless ($allowed) { return ''; }
8457: # Looks like we may have access, but could be locked by the owner of the construction space
8458: if ($allowed eq 'U') {
8459: my %blocked=&get('environment',['domcoord.author'],
8460: $ownerdomain,$ownername);
8461: # Is blocked by owner
8462: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8463: }
8464: if (($allowed eq 'F') || ($allowed eq 'U')) {
8465: # Grant temporary access
8466: my $then=$env{'user.login.time'};
1.1209 raeburn 8467: my $update=$env{'user.update.time'};
1.1192 raeburn 8468: if (!$update) { $update = $then; }
8469: my $refresh=$env{'user.refresh.time'};
8470: if (!$refresh) { $refresh = $update; }
8471: my $now = time;
8472: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8473: $now,'ca','constructaccess');
8474: $ownerhome = &homeserver($ownername,$ownerdomain);
8475: return($ownername,$ownerdomain,$ownerhome);
8476: }
8477: # No business here
8478: return '';
8479: }
8480:
1.1282 raeburn 8481: # ----------------------------------------------------------- Content Blocking
8482:
8483: {
8484: # Caches for faster Course Contents display where content blocking
8485: # is in operation (i.e., interval param set) for timed quiz.
8486: #
8487: # User for whom data are being temporarily cached.
8488: my $cacheduser='';
8489: # Cached blockers for this user (a hash of blocking items).
8490: my %cachedblockers=();
8491: # When the data were last cached.
8492: my $cachedlast='';
8493:
8494: sub load_all_blockers {
8495: my ($uname,$udom,$blocks)=@_;
8496: if (($uname ne '') && ($udom ne '')) {
8497: if (($cacheduser eq $uname.':'.$udom) &&
8498: (abs($cachedlast-time)<5)) {
8499: return;
8500: }
8501: }
8502: $cachedlast=time;
8503: $cacheduser=$uname.':'.$udom;
8504: %cachedblockers = &get_commblock_resources($blocks);
8505: }
8506:
1.1162 raeburn 8507: sub get_comm_blocks {
8508: my ($cdom,$cnum) = @_;
8509: if ($cdom eq '' || $cnum eq '') {
8510: return unless ($env{'request.course.id'});
8511: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8512: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8513: }
8514: my %commblocks;
8515: my $hashid=$cdom.'_'.$cnum;
8516: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8517: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8518: %commblocks = %{$blocksref};
8519: } else {
8520: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8521: my $cachetime = 600;
8522: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8523: }
8524: return %commblocks;
8525: }
8526:
1.1282 raeburn 8527: sub get_commblock_resources {
8528: my ($blocks) = @_;
8529: my %blockers = ();
8530: return %blockers unless ($env{'request.course.id'});
8531: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 8532: my %commblocks;
8533: if (ref($blocks) eq 'HASH') {
8534: %commblocks = %{$blocks};
8535: } else {
8536: %commblocks = &get_comm_blocks();
8537: }
1.1282 raeburn 8538: return %blockers unless (keys(%commblocks) > 0);
8539: my $navmap = Apache::lonnavmaps::navmap->new();
8540: return %blockers unless (ref($navmap));
1.1162 raeburn 8541: my $now = time;
8542: foreach my $block (keys(%commblocks)) {
8543: if ($block =~ /^(\d+)____(\d+)$/) {
8544: my ($start,$end) = ($1,$2);
8545: if ($start <= $now && $end >= $now) {
8546: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8547: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8548: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 8549: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8550: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8551: }
8552: }
8553: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 8554: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8555: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8556: }
8557: }
8558: }
8559: }
8560: }
8561: } elsif ($block =~ /^firstaccess____(.+)$/) {
8562: my $item = $1;
1.1163 raeburn 8563: my @to_test;
1.1162 raeburn 8564: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8565: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 8566: my @interval;
8567: my $type = 'map';
8568: if ($item eq 'course') {
8569: $type = 'course';
8570: @interval=&EXT("resource.0.interval");
8571: } else {
8572: if ($item =~ /___\d+___/) {
8573: $type = 'resource';
8574: @interval=&EXT("resource.0.interval",$item);
8575: if (ref($navmap)) {
8576: my $res = $navmap->getBySymb($item);
8577: push(@to_test,$res);
8578: }
1.1162 raeburn 8579: } else {
1.1282 raeburn 8580: my $mapsymb = &symbread($item,1);
8581: if ($mapsymb) {
8582: if (ref($navmap)) {
8583: my $mapres = $navmap->getBySymb($mapsymb);
8584: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
8585: foreach my $res (@to_test) {
8586: my $symb = $res->symb();
8587: next if ($symb eq $mapsymb);
8588: if ($symb ne '') {
8589: @interval=&EXT("resource.0.interval",$symb);
8590: if ($interval[1] eq 'map') {
8591: last;
1.1162 raeburn 8592: }
8593: }
8594: }
8595: }
8596: }
8597: }
1.1282 raeburn 8598: }
1.1310 raeburn 8599: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 8600: my $timelimit = $1;
1.1282 raeburn 8601: my $first_access;
8602: if ($type eq 'resource') {
8603: $first_access=&get_first_access($interval[1],$item);
8604: } elsif ($type eq 'map') {
8605: $first_access=&get_first_access($interval[1],undef,$item);
8606: } else {
8607: $first_access=&get_first_access($interval[1]);
8608: }
8609: if ($first_access) {
1.1292 raeburn 8610: my $timesup = $first_access+$timelimit;
1.1282 raeburn 8611: if ($timesup > $now) {
8612: my $activeblock;
8613: foreach my $res (@to_test) {
1.1283 raeburn 8614: if ($res->answerable()) {
1.1282 raeburn 8615: $activeblock = 1;
8616: last;
8617: }
8618: }
8619: if ($activeblock) {
8620: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8621: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8622: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8623: }
8624: }
8625: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8626: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8627: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8628: }
1.1162 raeburn 8629: }
8630: }
8631: }
8632: }
8633: }
8634: }
8635: }
8636: }
8637: }
1.1282 raeburn 8638: return %blockers;
1.1162 raeburn 8639: }
8640:
1.1282 raeburn 8641: sub has_comm_blocking {
8642: my ($priv,$symb,$uri,$blocks) = @_;
8643: my @blockers;
8644: return unless ($env{'request.course.id'});
8645: return unless ($priv eq 'bre');
8646: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8647: return if ($env{'request.state'} eq 'construct');
8648: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
8649: return unless (keys(%cachedblockers) > 0);
8650: my (%possibles,@symbs);
8651: if (!$symb) {
8652: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 8653: }
1.1282 raeburn 8654: if ($symb) {
8655: @symbs = ($symb);
8656: } elsif (keys(%possibles)) {
8657: @symbs = keys(%possibles);
8658: }
8659: my $noblock;
8660: foreach my $symb (@symbs) {
8661: last if ($noblock);
8662: my ($map,$resid,$resurl)=&decode_symb($symb);
8663: foreach my $block (keys(%cachedblockers)) {
8664: if ($block =~ /^firstaccess____(.+)$/) {
8665: my $item = $1;
8666: if (($item eq $map) || ($item eq $symb)) {
8667: $noblock = 1;
8668: last;
8669: }
8670: }
8671: if (ref($cachedblockers{$block}) eq 'HASH') {
8672: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
8673: if ($cachedblockers{$block}{'resources'}{$symb}) {
8674: unless (grep(/^\Q$block\E$/,@blockers)) {
8675: push(@blockers,$block);
8676: }
8677: }
8678: }
1.1162 raeburn 8679: }
1.1282 raeburn 8680: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
8681: if ($cachedblockers{$block}{'maps'}{$map}) {
8682: unless (grep(/^\Q$block\E$/,@blockers)) {
8683: push(@blockers,$block);
8684: }
8685: }
1.1162 raeburn 8686: }
8687: }
8688: }
1.1282 raeburn 8689: return if ($noblock);
8690: return @blockers;
8691: }
1.1162 raeburn 8692: }
8693:
1.1402 raeburn 8694: sub deeplink_check {
8695: my ($priv,$symb,$uri) = @_;
8696: return unless ($env{'request.course.id'});
8697: return unless ($priv eq 'bre');
8698: return if ($env{'request.state'} eq 'construct');
8699: return if ($env{'request.role.adv'});
8700: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8701: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8702: my (%possibles,@symbs);
8703: if (!$symb) {
8704: $symb = &symbread($uri,1,1,1,\%possibles);
8705: }
8706: if ($symb) {
8707: @symbs = ($symb);
8708: } elsif (keys(%possibles)) {
8709: @symbs = keys(%possibles);
8710: }
8711:
8712: my ($login,$switchrole,$allow);
8713: if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
8714: my $key = $1;
8715: my $tinyurl;
8716: my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
8717: if (defined($cached)) {
8718: $tinyurl = $result;
8719: } else {
8720: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
8721: my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
8722: if ($currtiny{$key} ne '') {
8723: $tinyurl = $currtiny{$key};
8724: &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
8725: }
8726: }
8727: if ($tinyurl ne '') {
8728: my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
8729: if ($cnumreq eq $cnum) {
8730: $login = $posslogin;
8731: } else {
8732: $switchrole = 1;
8733: }
8734: }
8735: }
8736: foreach my $symb (@symbs) {
8737: last if ($allow);
8738: my $deeplink = &EXT("resource.0.deeplink",$symb);
8739: if ($deeplink eq '') {
8740: $allow = 1;
8741: } else {
8742: my ($listed,$scope,$access) = split(/,/,$deeplink);
8743: if ($access eq 'any') {
8744: $allow = 1;
8745: } elsif ($login) {
8746: if ($access eq 'only') {
8747: if ($scope eq 'res') {
8748: if ($symb eq $login) {
8749: $allow = 1;
8750: }
8751: } elsif ($scope eq 'map') {
8752: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
8753: } elsif ($scope eq 'rec') {
8754: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
8755: }
8756: } else {
8757: my ($acctype,$item) = split(/:/,$access);
8758: if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
8759: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
8760: my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
8761: if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
8762: $allow = 1;
8763: }
8764: }
8765: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
8766: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
8767: my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
8768: if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
8769: $allow = 1;
8770: }
8771: }
8772: }
8773: }
8774: }
8775: }
8776: }
8777: return if ($allow);
8778: return 1;
8779: }
8780:
1.1282 raeburn 8781: # -------------------------------- Deversion and split uri into path an filename
8782:
1.1133 foxr 8783: #
1.1282 raeburn 8784: # Removes the version from a URI and
1.1133 foxr 8785: # splits it in to its filename and path to the filename.
8786: # Seems like File::Basename could have done this more clearly.
8787: # Parameters:
8788: # $uri - input URI
8789: # Returns:
8790: # Two element list consisting of
8791: # $pathname - the URI up to and excluding the trailing /
8792: # $filename - The part of the URI following the last /
8793: # NOTE:
8794: # Another realization of this is simply:
8795: # use File::Basename;
8796: # ...
8797: # $uri = shift;
8798: # $filename = basename($uri);
8799: # $path = dirname($uri);
8800: # return ($filename, $path);
8801: #
8802: # The implementation below is probably faster however.
8803: #
1.710 albertel 8804: sub split_uri_for_cond {
8805: my $uri=&deversion(&declutter(shift));
8806: my @uriparts=split(/\//,$uri);
8807: my $filename=pop(@uriparts);
8808: my $pathname=join('/',@uriparts);
8809: return ($pathname,$filename);
8810: }
1.232 www 8811: # --------------------------------------------------- Is a resource on the map?
8812:
8813: sub is_on_map {
1.710 albertel 8814: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8815: #Trying to find the conditional for the file
1.620 albertel 8816: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8817: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8818: if ($match) {
1.289 bowersj2 8819: return (1,$1);
8820: } else {
1.434 www 8821: return (0,0);
1.289 bowersj2 8822: }
1.12 www 8823: }
8824:
1.427 www 8825: # --------------------------------------------------------- Get symb from alias
8826:
8827: sub get_symb_from_alias {
8828: my $symb=shift;
8829: my ($map,$resid,$url)=&decode_symb($symb);
8830: # Already is a symb
8831: if ($url) { return $symb; }
8832: # Must be an alias
8833: my $aliassymb='';
8834: my %bighash;
1.620 albertel 8835: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8836: &GDBM_READER(),0640)) {
8837: my $rid=$bighash{'mapalias_'.$symb};
8838: if ($rid) {
8839: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8840: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8841: $resid,$bighash{'src_'.$rid});
1.427 www 8842: }
8843: untie %bighash;
8844: }
8845: return $aliassymb;
8846: }
8847:
1.12 www 8848: # ----------------------------------------------------------------- Define Role
8849:
8850: sub definerole {
8851: if (allowed('mcr','/')) {
1.1326 raeburn 8852: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8853: foreach my $role (split(':',$sysrole)) {
8854: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8855: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8856: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8857: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8858: return "refused:s:$crole&$cqual";
8859: }
8860: }
1.191 harris41 8861: }
1.800 albertel 8862: foreach my $role (split(':',$domrole)) {
8863: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8864: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8865: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8866: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8867: return "refused:d:$crole&$cqual";
8868: }
8869: }
1.191 harris41 8870: }
1.800 albertel 8871: foreach my $role (split(':',$courole)) {
8872: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8873: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8874: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8875: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8876: return "refused:c:$crole&$cqual";
8877: }
8878: }
1.191 harris41 8879: }
1.1326 raeburn 8880: my $uhome;
8881: if (($uname ne '') && ($udom ne '')) {
8882: $uhome = &homeserver($uname,$udom);
8883: return $uhome if ($uhome eq 'no_host');
8884: } else {
8885: $uname = $env{'user.name'};
8886: $udom = $env{'user.domain'};
8887: $uhome = $env{'user.home'};
8888: }
1.620 albertel 8889: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 8890: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8891: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 8892: return reply($command,$uhome);
1.12 www 8893: } else {
8894: return 'refused';
8895: }
1.105 harris41 8896: }
8897:
8898: # ---------------- Make a metadata query against the network of library servers
8899:
8900: sub metadata_query {
1.1237 raeburn 8901: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8902: my %rhash;
1.845 albertel 8903: my %libserv = &all_library();
1.244 matthew 8904: my @server_list = (defined($server_array) ? @$server_array
8905: : keys(%libserv) );
8906: for my $server (@server_list) {
1.1237 raeburn 8907: my $domains = '';
8908: if (ref($domains_hash) eq 'HASH') {
8909: $domains = $domains_hash->{$server};
8910: }
1.118 harris41 8911: unless ($custom or $customshow) {
1.1237 raeburn 8912: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8913: $rhash{$server}=$reply;
8914: }
8915: else {
8916: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 8917: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8918: $server);
8919: $rhash{$server}=$reply;
8920: }
1.112 harris41 8921: }
1.118 harris41 8922: return \%rhash;
1.240 www 8923: }
8924:
8925: # ----------------------------------------- Send log queries and wait for reply
8926:
8927: sub log_query {
8928: my ($uname,$udom,$query,%filters)=@_;
8929: my $uhome=&homeserver($uname,$udom);
8930: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8931: my $uhost=&hostname($uhome);
1.800 albertel 8932: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8933: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8934: $uhome);
1.479 albertel 8935: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8936: return get_query_reply($queryid);
8937: }
8938:
1.818 raeburn 8939: # -------------------------- Update MySQL table for portfolio file
8940:
8941: sub update_portfolio_table {
1.821 raeburn 8942: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8943: if ($group ne '') {
8944: $file_name =~s /^\Q$group\E//;
8945: }
1.818 raeburn 8946: my $homeserver = &homeserver($uname,$udom);
8947: my $queryid=
1.821 raeburn 8948: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8949: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8950: my $reply = &get_query_reply($queryid);
8951: return $reply;
8952: }
8953:
1.899 raeburn 8954: # -------------------------- Update MySQL allusers table
8955:
8956: sub update_allusers_table {
8957: my ($uname,$udom,$names) = @_;
8958: my $homeserver = &homeserver($uname,$udom);
8959: my $queryid=
8960: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8961: 'lastname='.&escape($names->{'lastname'}).'%%'.
8962: 'firstname='.&escape($names->{'firstname'}).'%%'.
8963: 'middlename='.&escape($names->{'middlename'}).'%%'.
8964: 'generation='.&escape($names->{'generation'}).'%%'.
8965: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8966: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8967: return;
1.899 raeburn 8968: }
8969:
1.508 raeburn 8970: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8971:
8972: sub fetch_enrollment_query {
1.511 raeburn 8973: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 8974: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8975: my $maxtries = 1;
1.508 raeburn 8976: if ($context eq 'automated') {
8977: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 8978: $sleep = 2;
8979: $loopmax = 100;
1.547 raeburn 8980: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8981: } else {
8982: $homeserver = &homeserver($cnum,$dom);
8983: }
1.838 albertel 8984: my $host=&hostname($homeserver);
1.506 raeburn 8985: my $cmd = '';
1.1000 raeburn 8986: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8987: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8988: }
8989: $cmd =~ s/%%$//;
8990: $cmd = &escape($cmd);
8991: my $query = 'fetchenrollment';
1.620 albertel 8992: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8993: unless ($queryid=~/^\Q$host\E\_/) {
8994: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8995: return 'error: '.$queryid;
8996: }
1.1317 raeburn 8997: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8998: my $tries = 1;
8999: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 9000: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9001: $tries ++;
9002: }
1.526 raeburn 9003: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9004: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9005: } else {
1.901 albertel 9006: my @responses = split(/:/,$reply);
1.1322 raeburn 9007: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9008: foreach my $line (@responses) {
9009: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9010: $$replyref{$key} = $value;
9011: }
9012: } else {
1.1117 foxr 9013: my $pathname = LONCAPA::tempdir();
1.800 albertel 9014: foreach my $line (@responses) {
9015: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9016: $$replyref{$key} = $value;
9017: if ($value > 0) {
1.800 albertel 9018: foreach my $item (@{$$affiliatesref{$key}}) {
9019: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9020: my $destname = $pathname.'/'.$filename;
9021: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9022: if ($xml_classlist =~ /^error/) {
9023: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9024: } else {
1.1359 raeburn 9025: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9026: print FILE &unescape($xml_classlist);
9027: close(FILE);
1.526 raeburn 9028: } else {
9029: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9030: }
9031: }
9032: }
9033: }
9034: }
9035: }
9036: return 'ok';
9037: }
9038: return 'error';
9039: }
9040:
1.242 www 9041: sub get_query_reply {
1.1317 raeburn 9042: my ($queryid,$sleep,$loopmax) = @_;;
9043: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9044: $sleep = 0.2;
9045: }
9046: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9047: $loopmax = 100;
9048: }
1.1117 foxr 9049: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9050: my $reply='';
1.1317 raeburn 9051: for (1..$loopmax) {
9052: sleep($sleep);
1.240 www 9053: if (-e $replyfile.'.end') {
1.1359 raeburn 9054: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9055: $reply = join('',<$fh>);
9056: close($fh);
1.240 www 9057: } else { return 'error: reply_file_error'; }
1.242 www 9058: return &unescape($reply);
9059: }
1.240 www 9060: }
1.242 www 9061: return 'timeout:'.$queryid;
1.240 www 9062: }
9063:
9064: sub courselog_query {
1.241 www 9065: #
9066: # possible filters:
9067: # url: url or symb
9068: # username
9069: # domain
9070: # action: view, submit, grade
9071: # start: timestamp
9072: # end: timestamp
9073: #
1.240 www 9074: my (%filters)=@_;
1.620 albertel 9075: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9076: if ($filters{'url'}) {
9077: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9078: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9079: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9080: }
1.620 albertel 9081: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9082: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9083: return &log_query($cname,$cdom,'courselog',%filters);
9084: }
9085:
9086: sub userlog_query {
1.858 raeburn 9087: #
9088: # possible filters:
9089: # action: log check role
9090: # start: timestamp
9091: # end: timestamp
9092: #
1.240 www 9093: my ($uname,$udom,%filters)=@_;
9094: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9095: }
9096:
1.506 raeburn 9097: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9098:
9099: sub auto_run {
1.508 raeburn 9100: my ($cnum,$cdom) = @_;
1.876 raeburn 9101: my $response = 0;
9102: my $settings;
9103: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9104: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9105: $settings = $domconfig{'autoenroll'};
9106: if ($settings->{'run'} eq '1') {
9107: $response = 1;
9108: }
9109: } else {
1.934 raeburn 9110: my $homeserver;
9111: if (&is_course($cdom,$cnum)) {
9112: $homeserver = &homeserver($cnum,$cdom);
9113: } else {
9114: $homeserver = &domain($cdom,'primary');
9115: }
9116: if ($homeserver ne 'no_host') {
9117: $response = &reply('autorun:'.$cdom,$homeserver);
9118: }
1.876 raeburn 9119: }
1.506 raeburn 9120: return $response;
9121: }
1.776 albertel 9122:
1.506 raeburn 9123: sub auto_get_sections {
1.508 raeburn 9124: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9125: my $homeserver;
9126: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9127: $homeserver = &homeserver($cnum,$cdom);
9128: }
9129: if (!defined($homeserver)) {
9130: if ($cdom =~ /^$match_domain$/) {
9131: $homeserver = &domain($cdom,'primary');
9132: }
9133: }
9134: my @secs;
9135: if (defined($homeserver)) {
9136: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9137: unless ($response eq 'refused') {
9138: @secs = split(/:/,$response);
9139: }
1.506 raeburn 9140: }
9141: return @secs;
9142: }
1.776 albertel 9143:
1.506 raeburn 9144: sub auto_new_course {
1.1099 raeburn 9145: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9146: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9147: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9148: return $response;
9149: }
1.776 albertel 9150:
1.506 raeburn 9151: sub auto_validate_courseID {
1.508 raeburn 9152: my ($cnum,$cdom,$inst_course_id) = @_;
9153: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9154: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9155: return $response;
9156: }
1.776 albertel 9157:
1.1007 raeburn 9158: sub auto_validate_instcode {
1.1020 raeburn 9159: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9160: my ($homeserver,$response);
9161: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9162: $homeserver = &homeserver($cnum,$cdom);
9163: }
9164: if (!defined($homeserver)) {
9165: if ($cdom =~ /^$match_domain$/) {
9166: $homeserver = &domain($cdom,'primary');
9167: }
9168: }
1.1065 raeburn 9169: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9170: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 9171: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9172: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9173: }
9174:
1.506 raeburn 9175: sub auto_create_password {
1.873 raeburn 9176: my ($cnum,$cdom,$authparam,$udom) = @_;
9177: my ($homeserver,$response);
1.506 raeburn 9178: my $create_passwd = 0;
9179: my $authchk = '';
1.873 raeburn 9180: if ($udom =~ /^$match_domain$/) {
9181: $homeserver = &domain($udom,'primary');
9182: }
9183: if ($homeserver eq '') {
9184: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9185: $homeserver = &homeserver($cnum,$cdom);
9186: }
9187: }
9188: if ($homeserver eq '') {
9189: $authchk = 'nodomain';
1.506 raeburn 9190: } else {
1.873 raeburn 9191: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9192: if ($response eq 'refused') {
9193: $authchk = 'refused';
9194: } else {
1.901 albertel 9195: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9196: }
1.506 raeburn 9197: }
9198: return ($authparam,$create_passwd,$authchk);
9199: }
9200:
1.706 raeburn 9201: sub auto_photo_permission {
9202: my ($cnum,$cdom,$students) = @_;
9203: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9204: my ($outcome,$perm_reqd,$conditions) =
9205: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9206: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9207: return (undef,undef);
9208: }
1.706 raeburn 9209: return ($outcome,$perm_reqd,$conditions);
9210: }
9211:
9212: sub auto_checkphotos {
9213: my ($uname,$udom,$pid) = @_;
9214: my $homeserver = &homeserver($uname,$udom);
9215: my ($result,$resulttype);
9216: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9217: &escape($uname).':'.&escape($pid),
9218: $homeserver));
1.709 albertel 9219: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9220: return (undef,undef);
9221: }
1.706 raeburn 9222: if ($outcome) {
9223: ($result,$resulttype) = split(/:/,$outcome);
9224: }
9225: return ($result,$resulttype);
9226: }
9227:
9228: sub auto_photochoice {
9229: my ($cnum,$cdom) = @_;
9230: my $homeserver = &homeserver($cnum,$cdom);
9231: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9232: &escape($cdom),
9233: $homeserver)));
1.709 albertel 9234: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9235: return (undef,undef);
9236: }
1.706 raeburn 9237: return ($update,$comment);
9238: }
9239:
9240: sub auto_photoupdate {
9241: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9242: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9243: my $host=&hostname($homeserver);
1.706 raeburn 9244: my $cmd = '';
9245: my $maxtries = 1;
1.800 albertel 9246: foreach my $affiliate (keys(%{$affiliatesref})) {
9247: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9248: }
9249: $cmd =~ s/%%$//;
9250: $cmd = &escape($cmd);
9251: my $query = 'institutionalphotos';
9252: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9253: unless ($queryid=~/^\Q$host\E\_/) {
9254: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9255: return 'error: '.$queryid;
9256: }
9257: my $reply = &get_query_reply($queryid);
9258: my $tries = 1;
9259: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9260: $reply = &get_query_reply($queryid);
9261: $tries ++;
9262: }
9263: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9264: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9265: } else {
9266: my @responses = split(/:/,$reply);
9267: my $outcome = shift(@responses);
9268: foreach my $item (@responses) {
9269: my ($key,$value) = split(/=/,$item);
9270: $$photo{$key} = $value;
9271: }
9272: return $outcome;
9273: }
9274: return 'error';
9275: }
9276:
1.521 raeburn 9277: sub auto_instcode_format {
1.793 albertel 9278: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9279: $cat_order) = @_;
1.521 raeburn 9280: my $courses = '';
1.772 raeburn 9281: my @homeservers;
1.521 raeburn 9282: if ($caller eq 'global') {
1.841 albertel 9283: my %servers = &get_servers($codedom,'library');
9284: foreach my $tryserver (keys(%servers)) {
9285: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9286: push(@homeservers,$tryserver);
9287: }
1.584 raeburn 9288: }
1.1022 raeburn 9289: } elsif ($caller eq 'requests') {
9290: if ($codedom =~ /^$match_domain$/) {
9291: my $chome = &domain($codedom,'primary');
9292: unless ($chome eq 'no_host') {
9293: push(@homeservers,$chome);
9294: }
9295: }
1.521 raeburn 9296: } else {
1.772 raeburn 9297: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9298: }
1.793 albertel 9299: foreach my $code (keys(%{$instcodes})) {
9300: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9301: }
9302: chop($courses);
1.772 raeburn 9303: my $ok_response = 0;
9304: my $response;
9305: while (@homeservers > 0 && $ok_response == 0) {
9306: my $server = shift(@homeservers);
9307: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9308: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9309: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9310: split(/:/,$response);
1.772 raeburn 9311: %{$codes} = (%{$codes},&str2hash($codes_str));
9312: push(@{$codetitles},&str2array($codetitles_str));
9313: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9314: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9315: $ok_response = 1;
9316: }
9317: }
9318: if ($ok_response) {
1.521 raeburn 9319: return 'ok';
1.772 raeburn 9320: } else {
9321: return $response;
1.521 raeburn 9322: }
9323: }
9324:
1.792 raeburn 9325: sub auto_instcode_defaults {
9326: my ($domain,$returnhash,$code_order) = @_;
9327: my @homeservers;
1.841 albertel 9328:
9329: my %servers = &get_servers($domain,'library');
9330: foreach my $tryserver (keys(%servers)) {
9331: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9332: push(@homeservers,$tryserver);
9333: }
1.792 raeburn 9334: }
1.841 albertel 9335:
1.792 raeburn 9336: my $response;
1.841 albertel 9337: foreach my $server (@homeservers) {
1.792 raeburn 9338: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9339: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9340:
9341: foreach my $pair (split(/\&/,$response)) {
9342: my ($name,$value)=split(/\=/,$pair);
9343: if ($name eq 'code_order') {
9344: @{$code_order} = split(/\&/,&unescape($value));
9345: } else {
9346: $returnhash->{&unescape($name)}=&unescape($value);
9347: }
9348: }
9349: return 'ok';
1.792 raeburn 9350: }
1.841 albertel 9351:
9352: return $response;
1.1003 raeburn 9353: }
9354:
9355: sub auto_possible_instcodes {
1.1007 raeburn 9356: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9357: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9358: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9359: return;
9360: }
1.1003 raeburn 9361: my (@homeservers,$uhome);
9362: if (defined(&domain($domain,'primary'))) {
9363: $uhome=&domain($domain,'primary');
9364: push(@homeservers,&domain($domain,'primary'));
9365: } else {
9366: my %servers = &get_servers($domain,'library');
9367: foreach my $tryserver (keys(%servers)) {
9368: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9369: push(@homeservers,$tryserver);
9370: }
9371: }
9372: }
9373: my $response;
9374: foreach my $server (@homeservers) {
9375: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9376: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9377: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9378: split(':',$response);
9379: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9380: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9381: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9382: my ($name,$value)=split('=',$item);
9383: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9384: }
9385: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9386: my ($name,$value)=split('=',$item);
9387: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9388: }
9389: return 'ok';
9390: }
9391: return $response;
9392: }
1.792 raeburn 9393:
1.1010 raeburn 9394: sub auto_courserequest_checks {
9395: my ($dom) = @_;
1.1020 raeburn 9396: my ($homeserver,%validations);
9397: if ($dom =~ /^$match_domain$/) {
9398: $homeserver = &domain($dom,'primary');
9399: }
9400: unless ($homeserver eq 'no_host') {
9401: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9402: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9403: my @items = split(/&/,$response);
9404: foreach my $item (@items) {
9405: my ($key,$value) = split('=',$item);
9406: $validations{&unescape($key)} = &thaw_unescape($value);
9407: }
9408: }
9409: }
1.1010 raeburn 9410: return %validations;
9411: }
9412:
1.1020 raeburn 9413: sub auto_courserequest_validation {
1.1255 raeburn 9414: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9415: my ($homeserver,$response);
9416: if ($dom =~ /^$match_domain$/) {
9417: $homeserver = &domain($dom,'primary');
9418: }
1.1255 raeburn 9419: unless ($homeserver eq 'no_host') {
9420: my $customdata;
9421: if (ref($custominfo) eq 'HASH') {
9422: $customdata = &freeze_escape($custominfo);
9423: }
1.1020 raeburn 9424: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9425: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 9426: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9427: $customdata,$homeserver));
1.1020 raeburn 9428: }
9429: return $response;
9430: }
9431:
1.777 albertel 9432: sub auto_validate_class_sec {
1.918 raeburn 9433: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9434: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9435: my $ownerlist;
9436: if (ref($owners) eq 'ARRAY') {
9437: $ownerlist = join(',',@{$owners});
9438: } else {
9439: $ownerlist = $owners;
9440: }
1.773 raeburn 9441: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9442: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9443: return $response;
9444: }
9445:
1.1367 raeburn 9446: sub auto_validate_instclasses {
9447: my ($cdom,$cnum,$owners,$classesref) = @_;
9448: my ($homeserver,%validations);
9449: $homeserver = &homeserver($cnum,$cdom);
9450: unless ($homeserver eq 'no_host') {
9451: my $ownerlist;
9452: if (ref($owners) eq 'ARRAY') {
9453: $ownerlist = join(',',@{$owners});
9454: } else {
9455: $ownerlist = $owners;
9456: }
9457: if (ref($classesref) eq 'HASH') {
9458: my $classes = &freeze_escape($classesref);
9459: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9460: ':'.$cdom.':'.$classes,$homeserver);
9461: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9462: my @items = split(/&/,$response);
9463: foreach my $item (@items) {
9464: my ($key,$value) = split('=',$item);
9465: $validations{&unescape($key)} = &thaw_unescape($value);
9466: }
9467: }
9468: }
9469: }
9470: return %validations;
9471: }
9472:
1.1248 raeburn 9473: sub auto_crsreq_update {
9474: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 9475: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 9476: my ($homeserver,%crsreqresponse);
9477: if ($cdom =~ /^$match_domain$/) {
9478: $homeserver = &domain($cdom,'primary');
9479: }
9480: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9481: my $info;
9482: if (ref($inbound) eq 'HASH') {
9483: $info = &freeze_escape($inbound);
9484: }
9485: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9486: ':'.&escape($action).':'.&escape($ownername).':'.
9487: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 9488: &escape($title).':'.&escape($code).':'.
9489: &escape($accessstart).':'.&escape($accessend).':'.$info,
9490: $homeserver);
1.1248 raeburn 9491: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9492: my @items = split(/&/,$response);
9493: foreach my $item (@items) {
9494: my ($key,$value) = split('=',$item);
9495: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9496: }
9497: }
9498: }
9499: return \%crsreqresponse;
9500: }
9501:
1.1305 raeburn 9502: sub auto_export_grades {
1.1309 raeburn 9503: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9504: my ($homeserver,%exportresponse);
9505: if ($cdom =~ /^$match_domain$/) {
9506: $homeserver = &domain($cdom,'primary');
9507: }
9508: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9509: my $info;
9510: if (ref($inforef) eq 'HASH') {
9511: $info = &freeze_escape($inforef);
9512: }
9513: if (ref($gradesref) eq 'HASH') {
9514: my $grades = &freeze_escape($gradesref);
9515: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9516: $info.':'.$grades,$homeserver);
9517: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9518: my @items = split(/&/,$response);
9519: foreach my $item (@items) {
9520: my ($key,$value) = split('=',$item);
9521: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9522: }
9523: }
9524: }
9525: }
9526: return \%exportresponse;
1.1305 raeburn 9527: }
9528:
1.1287 raeburn 9529: sub check_instcode_cloning {
9530: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9531: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9532: return;
9533: }
9534: my $canclone;
9535: if (@{$code_order} > 0) {
9536: my $instcoderegexp ='^';
9537: my @clonecodes = split(/\&/,$cloner);
9538: foreach my $item (@{$code_order}) {
9539: if (grep(/^\Q$item\E=/,@clonecodes)) {
9540: foreach my $pair (@clonecodes) {
9541: my ($key,$val) = split(/\=/,$pair,2);
9542: $val = &unescape($val);
9543: if ($key eq $item) {
9544: $instcoderegexp .= '('.$val.')';
9545: last;
9546: }
9547: }
9548: } else {
9549: $instcoderegexp .= $codedefaults->{$item};
9550: }
9551: }
9552: $instcoderegexp .= '$';
9553: my (@from,@to);
9554: eval {
9555: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9556: (@to) = ($clonetocode =~ /$instcoderegexp/);
9557: };
9558: if ((@from > 0) && (@to > 0)) {
9559: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9560: if (!@diffs) {
9561: $canclone = 1;
9562: }
9563: }
9564: }
9565: return $canclone;
9566: }
9567:
9568: sub default_instcode_cloning {
9569: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9570: my (%codedefaults,@code_order,$canclone);
9571: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9572: %codedefaults = %{$codedefaultsref};
9573: @code_order = @{$codeorderref};
9574: } elsif ($clonedom) {
9575: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9576: }
9577: if (($domdefclone) && (@code_order)) {
9578: my @clonecodes = split(/\+/,$domdefclone);
9579: my $instcoderegexp ='^';
9580: foreach my $item (@code_order) {
9581: if (grep(/^\Q$item\E$/,@clonecodes)) {
9582: $instcoderegexp .= '('.$codedefaults{$item}.')';
9583: } else {
9584: $instcoderegexp .= $codedefaults{$item};
9585: }
9586: }
9587: $instcoderegexp .= '$';
9588: my (@from,@to);
9589: eval {
9590: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9591: (@to) = ($clonetocode =~ /$instcoderegexp/);
9592: };
9593: if ((@from > 0) && (@to > 0)) {
9594: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9595: if (!@diffs) {
9596: $canclone = 1;
9597: }
9598: }
9599: }
9600: return $canclone;
9601: }
9602:
1.679 raeburn 9603: # ------------------------------------------------------- Course Group routines
9604:
9605: sub get_coursegroups {
1.809 raeburn 9606: my ($cdom,$cnum,$group,$namespace) = @_;
9607: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9608: }
9609:
1.679 raeburn 9610: sub modify_coursegroup {
9611: my ($cdom,$cnum,$groupsettings) = @_;
9612: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9613: }
9614:
1.809 raeburn 9615: sub toggle_coursegroup_status {
9616: my ($cdom,$cnum,$group,$action) = @_;
9617: my ($from_namespace,$to_namespace);
9618: if ($action eq 'delete') {
9619: $from_namespace = 'coursegroups';
9620: $to_namespace = 'deleted_groups';
9621: } else {
9622: $from_namespace = 'deleted_groups';
9623: $to_namespace = 'coursegroups';
9624: }
9625: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9626: if (my $tmp = &error(%curr_group)) {
9627: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9628: return ('read error',$tmp);
9629: } else {
9630: my %savedsettings = %curr_group;
1.809 raeburn 9631: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9632: my $deloutcome;
9633: if ($result eq 'ok') {
1.809 raeburn 9634: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9635: } else {
9636: return ('write error',$result);
9637: }
9638: if ($deloutcome eq 'ok') {
9639: return 'ok';
9640: } else {
9641: return ('delete error',$deloutcome);
9642: }
9643: }
9644: }
9645:
1.679 raeburn 9646: sub modify_group_roles {
1.957 raeburn 9647: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9648: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9649: my $role = 'gr/'.&escape($userprivs);
9650: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9651: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9652: if ($result eq 'ok') {
9653: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9654: }
1.679 raeburn 9655: return $result;
9656: }
9657:
9658: sub modify_coursegroup_membership {
9659: my ($cdom,$cnum,$membership) = @_;
9660: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9661: return $result;
9662: }
9663:
1.682 raeburn 9664: sub get_active_groups {
9665: my ($udom,$uname,$cdom,$cnum) = @_;
9666: my $now = time;
9667: my %groups = ();
9668: foreach my $key (keys(%env)) {
1.811 albertel 9669: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9670: my ($start,$end) = split(/\./,$env{$key});
9671: if (($end!=0) && ($end<$now)) { next; }
9672: if (($start!=0) && ($start>$now)) { next; }
9673: if ($1 eq $cdom && $2 eq $cnum) {
9674: $groups{$3} = $env{$key} ;
9675: }
9676: }
9677: }
9678: return %groups;
9679: }
9680:
1.683 raeburn 9681: sub get_group_membership {
9682: my ($cdom,$cnum,$group) = @_;
9683: return(&dump('groupmembership',$cdom,$cnum,$group));
9684: }
9685:
9686: sub get_users_groups {
9687: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9688: my @usersgroups;
1.683 raeburn 9689: my $cachetime=1800;
9690:
9691: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9692: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9693: if (defined($cached)) {
1.734 albertel 9694: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9695: } else {
9696: $grouplist = '';
1.816 raeburn 9697: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9698: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9699: my $access_end = $env{'course.'.$courseid.
9700: '.default_enrollment_end_date'};
9701: my $now = time;
9702: foreach my $key (keys(%roleshash)) {
9703: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9704: my $group = $1;
9705: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9706: my $start = $2;
9707: my $end = $1;
9708: if ($start == -1) { next; } # deleted from group
9709: if (($start!=0) && ($start>$now)) { next; }
9710: if (($end!=0) && ($end<$now)) {
9711: if ($access_end && $access_end < $now) {
9712: if ($access_end - $end < 86400) {
9713: push(@usersgroups,$group);
1.733 raeburn 9714: }
9715: }
1.817 raeburn 9716: next;
1.733 raeburn 9717: }
1.817 raeburn 9718: push(@usersgroups,$group);
1.683 raeburn 9719: }
9720: }
9721: }
1.817 raeburn 9722: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9723: $grouplist = join(':',@usersgroups);
9724: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9725: }
1.733 raeburn 9726: return @usersgroups;
1.683 raeburn 9727: }
9728:
9729: sub devalidate_getgroups_cache {
9730: my ($udom,$uname,$cdom,$cnum)=@_;
9731: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9732:
1.683 raeburn 9733: my $hashid="$udom:$uname:$courseid";
9734: &devalidate_cache_new('getgroups',$hashid);
9735: }
9736:
1.12 www 9737: # ------------------------------------------------------------------ Plain Text
9738:
9739: sub plaintext {
1.988 raeburn 9740: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9741: if ($short =~ m{^cr/}) {
1.758 albertel 9742: return (split('/',$short))[-1];
9743: }
1.742 raeburn 9744: if (!defined($cid)) {
9745: $cid = $env{'request.course.id'};
9746: }
9747: my %rolenames = (
1.1008 raeburn 9748: Course => 'std',
9749: Community => 'alt1',
1.1305 raeburn 9750: Placement => 'std',
1.742 raeburn 9751: );
1.1037 raeburn 9752: if ($cid ne '') {
9753: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9754: unless ($forcedefault) {
9755: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9756: &Apache::lonlocal::mt_escape(\$roletext);
9757: return &Apache::lonlocal::mt($roletext);
9758: }
9759: }
9760: }
9761: if ((defined($type)) && (defined($rolenames{$type})) &&
9762: (defined($rolenames{$type})) &&
9763: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9764: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9765: } elsif ($cid ne '') {
9766: my $crstype = $env{'course.'.$cid.'.type'};
9767: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9768: (defined($prp{$short}{$rolenames{$crstype}}))) {
9769: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9770: }
1.742 raeburn 9771: }
1.1037 raeburn 9772: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9773: }
9774:
9775: # ----------------------------------------------------------------- Assign Role
9776:
9777: sub assignrole {
1.957 raeburn 9778: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9779: $context)=@_;
1.21 www 9780: my $mrole;
9781: if ($role =~ /^cr\//) {
1.393 www 9782: my $cwosec=$url;
1.811 albertel 9783: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9784: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9785: my $refused = 1;
9786: if ($context eq 'requestcourses') {
9787: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9788: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9789: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9790: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9791: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9792: if ($crsenv{'internal.courseowner'} eq
9793: $env{'user.name'}.':'.$env{'user.domain'}) {
9794: $refused = '';
9795: }
9796: }
9797: }
9798: }
9799: }
9800: if ($refused) {
9801: &logthis('Refused custom assignrole: '.
9802: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9803: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9804: return 'refused';
9805: }
1.104 www 9806: }
1.21 www 9807: $mrole='cr';
1.678 raeburn 9808: } elsif ($role =~ /^gr\//) {
9809: my $cwogrp=$url;
1.811 albertel 9810: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9811: unless (&allowed('mdg',$cwogrp)) {
9812: &logthis('Refused group assignrole: '.
9813: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9814: $env{'user.name'}.' at '.$env{'user.domain'});
9815: return 'refused';
9816: }
9817: $mrole='gr';
1.21 www 9818: } else {
1.82 www 9819: my $cwosec=$url;
1.811 albertel 9820: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9821: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9822: my $refused;
9823: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9824: if (!(&allowed('c'.$role,$url))) {
9825: $refused = 1;
9826: }
9827: } else {
9828: $refused = 1;
9829: }
1.947 raeburn 9830: if ($refused) {
1.1045 raeburn 9831: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377 raeburn 9832: if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045 raeburn 9833: my %crsenv;
9834: if ($role eq 'cc' || $role eq 'co') {
9835: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9836: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9837: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9838: if ($crsenv{'internal.courseowner'} eq
9839: $env{'user.name'}.':'.$env{'user.domain'}) {
9840: $refused = '';
9841: }
9842: }
9843: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9844: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9845: if ($crsenv{'internal.courseowner'} eq
9846: $env{'user.name'}.':'.$env{'user.domain'}) {
9847: $refused = '';
9848: }
9849: }
9850: }
9851: }
1.1368 raeburn 9852: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
9853: if ($role eq 'st') {
9854: $refused = '';
1.1377 raeburn 9855: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368 raeburn 9856: $refused = '';
9857: }
1.1017 raeburn 9858: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9859: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9860: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9861: my $wrongcc;
9862: if ($cnum =~ /^$match_community$/) {
9863: $wrongcc = 1 if ($role eq 'cc');
9864: } else {
9865: $wrongcc = 1 if ($role eq 'co');
9866: }
9867: unless ($wrongcc) {
9868: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9869: if ($crsenv{'internal.courseowner'} eq
9870: $env{'user.name'}.':'.$env{'user.domain'}) {
9871: $refused = '';
9872: }
1.1017 raeburn 9873: }
9874: }
1.1183 raeburn 9875: } elsif ($context eq 'requestauthor') {
9876: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9877: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9878: if ($env{'environment.requestauthor'} eq 'automatic') {
9879: $refused = '';
9880: } else {
9881: my %domdefaults = &get_domain_defaults($udom);
9882: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9883: my $checkbystatus;
9884: if ($env{'user.adv'}) {
9885: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9886: if ($disposition eq 'automatic') {
9887: $refused = '';
9888: } elsif ($disposition eq '') {
9889: $checkbystatus = 1;
9890: }
9891: } else {
9892: $checkbystatus = 1;
9893: }
9894: if ($checkbystatus) {
9895: if ($env{'environment.inststatus'}) {
9896: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9897: foreach my $type (@inststatuses) {
9898: if (($type ne '') &&
9899: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9900: $refused = '';
9901: }
9902: }
9903: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9904: $refused = '';
9905: }
9906: }
9907: }
9908: }
9909: }
1.1017 raeburn 9910: }
9911: if ($refused) {
1.947 raeburn 9912: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9913: ' '.$role.' '.$end.' '.$start.' by '.
9914: $env{'user.name'}.' at '.$env{'user.domain'});
9915: return 'refused';
9916: }
1.932 raeburn 9917: }
1.1131 raeburn 9918: } elsif ($role eq 'au') {
9919: if ($url ne '/'.$udom.'/') {
9920: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9921: ' to assign author role for '.$uname.':'.$udom.
9922: ' in domain: '.$url.' refused (wrong domain).');
9923: return 'refused';
9924: }
1.104 www 9925: }
1.21 www 9926: $mrole=$role;
9927: }
1.620 albertel 9928: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9929: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9930: if ($end) { $command.='_'.$end; }
1.21 www 9931: if ($start) {
9932: if ($end) {
1.81 www 9933: $command.='_'.$start;
1.21 www 9934: } else {
1.81 www 9935: $command.='_0_'.$start;
1.21 www 9936: }
9937: }
1.739 raeburn 9938: my $origstart = $start;
9939: my $origend = $end;
1.957 raeburn 9940: my $delflag;
1.357 www 9941: # actually delete
9942: if ($deleteflag) {
1.373 www 9943: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9944: # modify command to delete the role
1.620 albertel 9945: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9946: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9947: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9948: # set start and finish to negative values for userrolelog
9949: $start=-1;
9950: $end=-1;
1.957 raeburn 9951: $delflag = 1;
1.357 www 9952: }
9953: }
9954: # send command
1.349 www 9955: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9956: # log new user role if status is ok
1.349 www 9957: if ($answer eq 'ok') {
1.663 raeburn 9958: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 9959: if (($role eq 'cc') || ($role eq 'in') ||
9960: ($role eq 'ep') || ($role eq 'ad') ||
9961: ($role eq 'ta') || ($role eq 'st') ||
9962: ($role=~/^cr/) || ($role eq 'gr') ||
9963: ($role eq 'co')) {
1.1200 raeburn 9964: # for course roles, perform group memberships changes triggered by role change.
9965: unless ($role =~ /^gr/) {
9966: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9967: $origstart,$selfenroll,$context);
9968: }
1.1184 raeburn 9969: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9970: $selfenroll,$context);
9971: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 9972: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9973: ($role eq 'da')) {
1.1184 raeburn 9974: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9975: $context);
9976: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9977: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9978: $context);
9979: }
1.1053 raeburn 9980: if ($role eq 'cc') {
9981: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9982: }
1.349 www 9983: }
9984: return $answer;
1.169 harris41 9985: }
9986:
1.1053 raeburn 9987: sub autoupdate_coowners {
9988: my ($url,$end,$start,$uname,$udom) = @_;
9989: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9990: if (($cdom ne '') && ($cnum ne '')) {
9991: my $now = time;
9992: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9993: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9994: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9995: my $instcode = $coursehash{'internal.coursecode'};
9996: if ($instcode ne '') {
1.1056 raeburn 9997: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9998: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9999: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10000: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10001: if ($result eq 'valid') {
10002: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10003: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10004: push(@newcoowners,$coowner);
10005: }
10006: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10007: push(@newcoowners,$uname.':'.$udom);
10008: }
10009: @newcoowners = sort(@newcoowners);
10010: } else {
10011: push(@newcoowners,$uname.':'.$udom);
10012: }
10013: } else {
10014: if ($coursehash{'internal.co-owners'}) {
10015: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10016: unless ($coowner eq $uname.':'.$udom) {
10017: push(@newcoowners,$coowner);
10018: }
10019: }
10020: unless (@newcoowners > 0) {
10021: $delcoowners = 1;
10022: $coowners = '';
10023: }
10024: }
10025: }
10026: if (@newcoowners || $delcoowners) {
10027: &store_coowners($cdom,$cnum,$coursehash{'home'},
10028: $delcoowners,@newcoowners);
10029: }
10030: }
10031: }
10032: }
10033: }
10034: }
10035: }
10036:
10037: sub store_coowners {
10038: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10039: my $cid = $cdom.'_'.$cnum;
10040: my ($coowners,$delresult,$putresult);
10041: if (@newcoowners) {
10042: $coowners = join(',',@newcoowners);
10043: my %coownershash = (
10044: 'internal.co-owners' => $coowners,
10045: );
10046: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10047: if ($putresult eq 'ok') {
10048: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10049: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10050: }
10051: }
10052: }
10053: if ($delcoowners) {
10054: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10055: if ($delresult eq 'ok') {
10056: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10057: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10058: }
10059: }
10060: }
10061: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10062: my %crsinfo =
10063: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10064: if (ref($crsinfo{$cid}) eq 'HASH') {
10065: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10066: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10067: }
10068: }
10069: }
10070:
1.169 harris41 10071: # -------------------------------------------------- Modify user authentication
1.197 www 10072: # Overrides without validation
10073:
1.169 harris41 10074: sub modifyuserauth {
10075: my ($udom,$uname,$umode,$upass)=@_;
10076: my $uhome=&homeserver($uname,$udom);
1.197 www 10077: unless (&allowed('mau',$udom)) { return 'refused'; }
10078: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10079: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10080: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10081: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10082: &escape($upass),$uhome);
1.620 albertel 10083: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10084: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10085: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10086: &log($udom,,$uname,$uhome,
1.620 albertel 10087: 'Authentication changed by '.$env{'user.domain'}.', '.
10088: $env{'user.name'}.', '.$umode.
1.197 www 10089: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 10090: unless ($reply eq 'ok') {
1.197 www 10091: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10092: return 'error: '.$reply;
10093: }
1.170 harris41 10094: return 'ok';
1.80 www 10095: }
10096:
1.81 www 10097: # --------------------------------------------------------------- Modify a user
1.80 www 10098:
1.81 www 10099: sub modifyuser {
1.206 matthew 10100: my ($udom, $uname, $uid,
10101: $umode, $upass, $first,
10102: $middle, $last, $gene,
1.1058 raeburn 10103: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10104: $udom= &LONCAPA::clean_domain($udom);
10105: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10106: my $showcandelete = 'none';
10107: if (ref($candelete) eq 'ARRAY') {
10108: if (@{$candelete} > 0) {
10109: $showcandelete = join(', ',@{$candelete});
10110: }
10111: }
1.81 www 10112: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10113: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10114: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10115: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10116: ' desiredhome not specified').
1.620 albertel 10117: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10118: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10119: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10120: my $newuser;
10121: if ($uhome eq 'no_host') {
10122: $newuser = 1;
1.1368 raeburn 10123: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10124: ($umode eq 'lti')) {
10125: return 'error: more information needed to create new user';
10126: }
1.1075 raeburn 10127: }
1.80 www 10128: # ----------------------------------------------------------------- Create User
1.406 albertel 10129: if (($uhome eq 'no_host') &&
1.1368 raeburn 10130: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80 www 10131: my $unhome='';
1.844 albertel 10132: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10133: $unhome = $desiredhome;
1.620 albertel 10134: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10135: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10136: } else { # load balancing routine for determining $unhome
1.81 www 10137: my $loadm=10000000;
1.841 albertel 10138: my %servers = &get_servers($udom,'library');
10139: foreach my $tryserver (keys(%servers)) {
10140: my $answer=reply('load',$tryserver);
10141: if (($answer=~/\d+/) && ($answer<$loadm)) {
10142: $loadm=$answer;
10143: $unhome=$tryserver;
10144: }
1.80 www 10145: }
10146: }
10147: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10148: return 'error: unable to find a home server for '.$uname.
10149: ' in domain '.$udom;
1.80 www 10150: }
10151: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10152: &escape($upass),$unhome);
10153: unless ($reply eq 'ok') {
10154: return 'error: '.$reply;
10155: }
1.230 stredwic 10156: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10157: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10158: return 'error: unable verify users home machine.';
1.80 www 10159: }
1.209 matthew 10160: } # End of creation of new user
1.80 www 10161: # ---------------------------------------------------------------------- Add ID
10162: if ($uid) {
10163: $uid=~tr/A-Z/a-z/;
10164: my %uidhash=&idrget($udom,$uname);
1.196 www 10165: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10166: && (!$forceid)) {
1.80 www 10167: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10168: return 'error: user id "'.$uid.'" does not match '.
10169: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10170: }
10171: } else {
1.1300 raeburn 10172: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 10173: }
10174: }
10175: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10176: my @tmp=&get('environment',
1.899 raeburn 10177: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10178: 'permanentemail','inststatus'],
1.134 albertel 10179: $udom,$uname);
1.1075 raeburn 10180: my (%names,%oldnames);
1.313 matthew 10181: if ($tmp[0] =~ m/^error:.*/) {
10182: %names=();
10183: } else {
10184: %names = @tmp;
1.1075 raeburn 10185: %oldnames = %names;
1.313 matthew 10186: }
1.388 www 10187: #
1.1058 raeburn 10188: # If name, email and/or uid are blank (e.g., because an uploaded file
10189: # of users did not contain them), do not overwrite existing values
10190: # unless field is in $candelete array ref.
10191: #
10192:
10193: my @fields = ('firstname','middlename','lastname','generation',
10194: 'permanentemail','id');
10195: my %newvalues;
10196: if (ref($candelete) eq 'ARRAY') {
10197: foreach my $field (@fields) {
10198: if (grep(/^\Q$field\E$/,@{$candelete})) {
10199: if ($field eq 'firstname') {
10200: $names{$field} = $first;
10201: } elsif ($field eq 'middlename') {
10202: $names{$field} = $middle;
10203: } elsif ($field eq 'lastname') {
10204: $names{$field} = $last;
10205: } elsif ($field eq 'generation') {
10206: $names{$field} = $gene;
10207: } elsif ($field eq 'permanentemail') {
10208: $names{$field} = $email;
10209: } elsif ($field eq 'id') {
10210: $names{$field} = $uid;
10211: }
10212: }
10213: }
10214: }
1.388 www 10215: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10216: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10217: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10218: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10219: if ($email) {
10220: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10221: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10222: }
1.899 raeburn 10223: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10224: if (defined($inststatus)) {
10225: $names{'inststatus'} = '';
10226: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10227: if (ref($usertypes) eq 'HASH') {
10228: my @okstatuses;
10229: foreach my $item (split(/:/,$inststatus)) {
10230: if (defined($usertypes->{$item})) {
10231: push(@okstatuses,$item);
10232: }
10233: }
10234: if (@okstatuses) {
10235: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10236: }
10237: }
10238: }
1.1075 raeburn 10239: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10240: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10241: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10242: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10243: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10244: } else {
10245: $logmsg .= ' during self creation';
10246: }
1.1075 raeburn 10247: my $changed;
10248: if ($newuser) {
10249: $changed = 1;
10250: } else {
10251: foreach my $field (@fields) {
10252: if ($names{$field} ne $oldnames{$field}) {
10253: $changed = 1;
10254: last;
10255: }
10256: }
10257: }
10258: unless ($changed) {
10259: $logmsg = 'No changes in user information needed for: '.$logmsg;
10260: &logthis($logmsg);
10261: return 'ok';
10262: }
10263: my $reply = &put('environment', \%names, $udom,$uname);
10264: if ($reply ne 'ok') {
10265: return 'error: '.$reply;
10266: }
1.1087 raeburn 10267: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10268: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10269: }
1.1075 raeburn 10270: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10271: &devalidate_cache_new('namescache',$uname.':'.$udom);
10272: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10273: &logthis($logmsg);
1.134 albertel 10274: return 'ok';
1.80 www 10275: }
10276:
1.81 www 10277: # -------------------------------------------------------------- Modify student
1.80 www 10278:
1.81 www 10279: sub modifystudent {
10280: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10281: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 10282: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10283: if (!$cid) {
1.620 albertel 10284: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10285: return 'not_in_class';
10286: }
1.80 www 10287: }
10288: # --------------------------------------------------------------- Make the user
1.81 www 10289: my $reply=&modifyuser
1.209 matthew 10290: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10291: $desiredhome,$email,$inststatus);
1.80 www 10292: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10293: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 10294: # student's environment
1.297 matthew 10295: $uid = undef if (!$forceid);
1.455 albertel 10296: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 10297: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 10298: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10299: return $reply;
10300: }
10301:
10302: sub modify_student_enrollment {
1.1216 raeburn 10303: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 10304: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10305: my ($cdom,$cnum,$chome);
10306: if (!$cid) {
1.620 albertel 10307: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10308: return 'not_in_class';
10309: }
1.620 albertel 10310: $cdom=$env{'course.'.$cid.'.domain'};
10311: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10312: } else {
10313: ($cdom,$cnum)=split(/_/,$cid);
10314: }
1.620 albertel 10315: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10316: if (!$chome) {
1.457 raeburn 10317: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10318: }
1.455 albertel 10319: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10320: # Make sure the user exists
1.81 www 10321: my $uhome=&homeserver($uname,$udom);
10322: if (($uhome eq '') || ($uhome eq 'no_host')) {
10323: return 'error: no such user';
10324: }
1.297 matthew 10325: # Get student data if we were not given enough information
10326: if (!defined($first) || $first eq '' ||
10327: !defined($last) || $last eq '' ||
10328: !defined($uid) || $uid eq '' ||
10329: !defined($middle) || $middle eq '' ||
10330: !defined($gene) || $gene eq '') {
1.294 matthew 10331: # They did not supply us with enough data to enroll the student, so
10332: # we need to pick up more information.
1.297 matthew 10333: my %tmp = &get('environment',
1.294 matthew 10334: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10335: ,$udom,$uname);
10336:
1.800 albertel 10337: #foreach my $key (keys(%tmp)) {
10338: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10339: #}
1.294 matthew 10340: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10341: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10342: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10343: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10344: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10345: }
1.556 albertel 10346: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10347: my $user = "$uname:$udom";
10348: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10349: my $reply=cput('classlist',
1.1148 raeburn 10350: {$user =>
1.1314 raeburn 10351: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10352: $cdom,$cnum);
1.1148 raeburn 10353: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10354: &devalidate_getsection_cache($udom,$uname,$cid);
10355: } else {
1.81 www 10356: return 'error: '.$reply;
10357: }
1.297 matthew 10358: # Add student role to user
1.83 www 10359: my $uurl='/'.$cid;
1.81 www 10360: $uurl=~s/\_/\//g;
10361: if ($usec) {
10362: $uurl.='/'.$usec;
10363: }
1.1148 raeburn 10364: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10365: $selfenroll,$context);
10366: if ($result ne 'ok') {
10367: if ($old_entry{$user} ne '') {
10368: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10369: } else {
10370: $reply = &del('classlist',[$user],$cdom,$cnum);
10371: }
10372: }
10373: return $result;
1.21 www 10374: }
10375:
1.556 albertel 10376: sub format_name {
10377: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10378: my $name;
10379: if ($first ne 'lastname') {
10380: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10381: } else {
10382: if ($lastname=~/\S/) {
10383: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10384: $name=~s/\s+,/,/;
10385: } else {
10386: $name.= $firstname.' '.$middlename.' '.$generation;
10387: }
10388: }
10389: $name=~s/^\s+//;
10390: $name=~s/\s+$//;
10391: $name=~s/\s+/ /g;
10392: return $name;
10393: }
10394:
1.84 www 10395: # ------------------------------------------------- Write to course preferences
10396:
10397: sub writecoursepref {
10398: my ($courseid,%prefs)=@_;
10399: $courseid=~s/^\///;
10400: $courseid=~s/\_/\//g;
10401: my ($cdomain,$cnum)=split(/\//,$courseid);
10402: my $chome=homeserver($cnum,$cdomain);
10403: if (($chome eq '') || ($chome eq 'no_host')) {
10404: return 'error: no such course';
10405: }
10406: my $cstring='';
1.800 albertel 10407: foreach my $pref (keys(%prefs)) {
10408: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10409: }
1.84 www 10410: $cstring=~s/\&$//;
10411: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10412: }
10413:
10414: # ---------------------------------------------------------- Make/modify course
10415:
10416: sub createcourse {
1.741 raeburn 10417: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 10418: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 10419: $url=&declutter($url);
10420: my $cid='';
1.1028 raeburn 10421: if ($context eq 'requestcourses') {
10422: my $can_create = 0;
10423: my ($ownername,$ownerdom) = split(':',$course_owner);
10424: if ($udom eq $ownerdom) {
10425: if (&usertools_access($ownername,$ownerdom,$category,undef,
10426: $context)) {
10427: $can_create = 1;
10428: }
10429: } else {
10430: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10431: $category);
10432: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10433: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10434: if (@curr > 0) {
10435: my @options = qw(approval validate autolimit);
10436: my $optregex = join('|',@options);
10437: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10438: $can_create = 1;
10439: }
10440: }
10441: }
10442: }
10443: if ($can_create) {
10444: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10445: unless (&allowed('ccc',$udom)) {
10446: return 'refused';
10447: }
1.1017 raeburn 10448: }
10449: } else {
10450: return 'refused';
10451: }
1.1028 raeburn 10452: } elsif (!&allowed('ccc',$udom)) {
10453: return 'refused';
1.84 www 10454: }
1.1011 raeburn 10455: # --------------------------------------------------------------- Get Unique ID
10456: my $uname;
10457: if ($cnum =~ /^$match_courseid$/) {
10458: my $chome=&homeserver($cnum,$udom,'true');
10459: if (($chome eq '') || ($chome eq 'no_host')) {
10460: $uname = $cnum;
10461: } else {
1.1038 raeburn 10462: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10463: }
10464: } else {
1.1038 raeburn 10465: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10466: }
10467: return $uname if ($uname =~ /^error/);
10468: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10469: if (!defined($course_server)) {
10470: if (defined(&domain($udom,'primary'))) {
10471: $course_server = &domain($udom,'primary');
10472: } else {
10473: $course_server = $env{'user.home'};
10474: }
10475: }
10476: my %host_servers =
10477: &Apache::lonnet::get_servers($udom,'library');
10478: unless ($host_servers{$course_server}) {
10479: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10480: }
1.84 www 10481: # ------------------------------------------------------------- Make the course
10482: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10483: $course_server);
1.84 www 10484: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10485: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10486: if (($uhome eq '') || ($uhome eq 'no_host')) {
10487: return 'error: no such course';
10488: }
1.271 www 10489: # ----------------------------------------------------------------- Course made
1.516 raeburn 10490: # log existence
1.1029 raeburn 10491: my $now = time;
1.918 raeburn 10492: my $newcourse = {
10493: $udom.'_'.$uname => {
1.921 raeburn 10494: description => $description,
10495: inst_code => $inst_code,
10496: owner => $course_owner,
10497: type => $crstype,
1.1029 raeburn 10498: creator => $env{'user.name'}.':'.
10499: $env{'user.domain'},
10500: created => $now,
10501: context => $context,
1.918 raeburn 10502: },
10503: };
1.921 raeburn 10504: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10505: # set toplevel url
1.271 www 10506: my $topurl=$url;
10507: unless ($nonstandard) {
10508: # ------------------------------------------ For standard courses, make top url
10509: my $mapurl=&clutter($url);
1.278 www 10510: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10511: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10512: <map>
10513: <resource id="1" type="start"></resource>
10514: <resource id="2" src="$mapurl"></resource>
10515: <resource id="3" type="finish"></resource>
10516: <link index="1" from="1" to="2"></link>
10517: <link index="2" from="2" to="3"></link>
10518: </map>
10519: ENDINITMAP
10520: $topurl=&declutter(
1.638 albertel 10521: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10522: );
10523: }
10524: # ----------------------------------------------------------- Write preferences
1.84 www 10525: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10526: ('description' => $description,
10527: 'url' => $topurl,
10528: 'internal.creator' => $env{'user.name'}.':'.
10529: $env{'user.domain'},
10530: 'internal.created' => $now,
10531: 'internal.creationcontext' => $context)
10532: );
1.84 www 10533: return '/'.$udom.'/'.$uname;
10534: }
10535:
1.1011 raeburn 10536: # ------------------------------------------------------------------- Create ID
10537: sub generate_coursenum {
1.1038 raeburn 10538: my ($udom,$crstype) = @_;
1.1011 raeburn 10539: my $domdesc = &domain($udom);
10540: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10541: my $first;
10542: if ($crstype eq 'Community') {
10543: $first = '0';
10544: } else {
10545: $first = int(1+rand(9));
10546: }
10547: my $uname=$first.
1.1011 raeburn 10548: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10549: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10550: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10551: # ----------------------------------------------- Make sure that does not exist
10552: my $uhome=&homeserver($uname,$udom,'true');
10553: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10554: if ($crstype eq 'Community') {
10555: $first = '0';
10556: } else {
10557: $first = int(1+rand(9));
10558: }
10559: $uname=$first.
1.1011 raeburn 10560: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10561: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10562: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10563: $uhome=&homeserver($uname,$udom,'true');
10564: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10565: return 'error: unable to generate unique course-ID';
10566: }
10567: }
10568: return $uname;
10569: }
10570:
1.813 albertel 10571: sub is_course {
1.1167 droeschl 10572: my ($cdom, $cnum) = scalar(@_) == 1 ?
10573: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
10574:
1.1381 raeburn 10575: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10576: my $uhome=&homeserver($cnum,$cdom);
10577: my $iscourse;
10578: if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382 raeburn 10579: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381 raeburn 10580: } else {
10581: my $hashid = $cdom.':'.$cnum;
10582: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10583: unless (defined($cached)) {
10584: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10585: $cnum,undef,undef,'.');
10586: $iscourse = 0;
10587: if (exists($courses{$cdom.'_'.$cnum})) {
10588: $iscourse = 1;
10589: }
10590: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10591: }
10592: }
10593: return unless ($iscourse);
1.1167 droeschl 10594: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10595: }
10596:
1.1015 raeburn 10597: sub store_userdata {
10598: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10599: my $result;
1.1016 raeburn 10600: if ($datakey ne '') {
1.1013 raeburn 10601: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10602: if ($udom eq '' || $uname eq '') {
10603: $udom = $env{'user.domain'};
10604: $uname = $env{'user.name'};
10605: }
10606: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10607: if (($uhome eq '') || ($uhome eq 'no_host')) {
10608: $result = 'error: no_host';
10609: } else {
10610: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10611: $storehash->{'host'} = $perlvar{'lonHostID'};
10612:
10613: my $namevalue='';
10614: foreach my $key (keys(%{$storehash})) {
10615: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10616: }
10617: $namevalue=~s/\&$//;
1.1224 raeburn 10618: unless ($namespace eq 'courserequests') {
10619: $datakey = &escape($datakey);
10620: }
1.1105 raeburn 10621: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10622: $namevalue,$uhome);
1.1013 raeburn 10623: }
10624: } else {
10625: $result = 'error: data to store was not a hash reference';
10626: }
10627: } else {
10628: $result= 'error: invalid requestkey';
10629: }
10630: return $result;
10631: }
10632:
1.21 www 10633: # ---------------------------------------------------------- Assign Custom Role
10634:
10635: sub assigncustomrole {
1.957 raeburn 10636: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10637: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10638: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10639: }
10640:
10641: # ----------------------------------------------------------------- Revoke Role
10642:
10643: sub revokerole {
1.957 raeburn 10644: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10645: my $now=time;
1.965 raeburn 10646: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10647: }
10648:
10649: # ---------------------------------------------------------- Revoke Custom Role
10650:
10651: sub revokecustomrole {
1.957 raeburn 10652: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10653: my $now=time;
1.357 www 10654: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10655: $deleteflag,$selfenroll,$context);
1.17 www 10656: }
10657:
1.533 banghart 10658: # ------------------------------------------------------------ Disk usage
1.535 albertel 10659: sub diskusage {
1.955 raeburn 10660: my ($udom,$uname,$directorypath,$getpropath)=@_;
10661: $directorypath =~ s/\/$//;
10662: my $listing=&reply('du2:'.&escape($directorypath).':'
10663: .&escape($getpropath).':'.&escape($uname).':'
10664: .&escape($udom),homeserver($uname,$udom));
10665: if ($listing eq 'unknown_cmd') {
10666: if ($getpropath) {
10667: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10668: }
10669: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10670: }
1.514 albertel 10671: return $listing;
1.512 banghart 10672: }
10673:
1.566 banghart 10674: sub is_locked {
1.1096 raeburn 10675: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10676: my @check;
10677: my $is_locked;
1.1093 raeburn 10678: push (@check,$file_name);
1.613 albertel 10679: my %locked = &get('file_permissions',\@check,
1.620 albertel 10680: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10681: my ($tmp)=keys(%locked);
10682: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10683:
1.566 banghart 10684: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10685: $is_locked = 'false';
10686: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10687: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10688: $is_locked = 'true';
1.1096 raeburn 10689: if (ref($which) eq 'ARRAY') {
10690: push(@{$which},$entry);
10691: } else {
10692: last;
10693: }
1.745 raeburn 10694: }
10695: }
1.566 banghart 10696: } else {
10697: $is_locked = 'false';
10698: }
1.1093 raeburn 10699: return $is_locked;
1.566 banghart 10700: }
10701:
1.759 albertel 10702: sub declutter_portfile {
10703: my ($file) = @_;
1.833 albertel 10704: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10705: return $file;
10706: }
10707:
1.559 banghart 10708: # ------------------------------------------------------------- Mark as Read Only
10709:
10710: sub mark_as_readonly {
10711: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10712: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10713: my ($tmp)=keys(%current_permissions);
10714: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10715: foreach my $file (@{$files}) {
1.759 albertel 10716: $file = &declutter_portfile($file);
1.561 banghart 10717: push(@{$current_permissions{$file}},$what);
1.559 banghart 10718: }
1.613 albertel 10719: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10720: return;
10721: }
10722:
1.572 banghart 10723: # ------------------------------------------------------------Save Selected Files
10724:
10725: sub save_selected_files {
10726: my ($user, $path, @files) = @_;
10727: my $filename = $user."savedfiles";
1.573 banghart 10728: my @other_files = &files_not_in_path($user, $path);
1.1359 raeburn 10729: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10730: foreach my $file (@files) {
1.620 albertel 10731: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10732: }
10733: foreach my $file (@other_files) {
1.574 banghart 10734: print (OUT $file."\n");
1.572 banghart 10735: }
1.574 banghart 10736: close (OUT);
1.572 banghart 10737: return 'ok';
10738: }
10739:
1.574 banghart 10740: sub clear_selected_files {
10741: my ($user) = @_;
10742: my $filename = $user."savedfiles";
1.1359 raeburn 10743: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10744: print (OUT undef);
10745: close (OUT);
10746: return ("ok");
10747: }
10748:
1.572 banghart 10749: sub files_in_path {
10750: my ($user, $path) = @_;
10751: my $filename = $user."savedfiles";
10752: my %return_files;
1.1359 raeburn 10753: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10754: while (my $line_in = <IN>) {
1.574 banghart 10755: chomp ($line_in);
10756: my @paths_and_file = split (m!/!, $line_in);
10757: my $file_part = pop (@paths_and_file);
10758: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10759: $path_part.='/';
10760: my $path_and_file = $path_part.$file_part;
10761: if ($path_part eq $path) {
10762: $return_files{$file_part}= 'selected';
10763: }
10764: }
1.574 banghart 10765: close (IN);
10766: return (\%return_files);
1.572 banghart 10767: }
10768:
10769: # called in portfolio select mode, to show files selected NOT in current directory
10770: sub files_not_in_path {
10771: my ($user, $path) = @_;
10772: my $filename = $user."savedfiles";
10773: my @return_files;
10774: my $path_part;
1.1359 raeburn 10775: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 10776: while (my $line = <IN>) {
1.572 banghart 10777: #ok, I know it's clunky, but I want it to work
1.800 albertel 10778: my @paths_and_file = split(m|/|, $line);
10779: my $file_part = pop(@paths_and_file);
10780: chomp($file_part);
10781: my $path_part = join('/', @paths_and_file);
1.572 banghart 10782: $path_part .= '/';
10783: my $path_and_file = $path_part.$file_part;
10784: if ($path_part ne $path) {
1.800 albertel 10785: push(@return_files, ($path_and_file));
1.572 banghart 10786: }
10787: }
1.800 albertel 10788: close(OUT);
1.574 banghart 10789: return (@return_files);
1.572 banghart 10790: }
10791:
1.1273 raeburn 10792: #------------------------------Submitted/Handedback Portfolio Files Versioning
10793:
10794: sub portfiles_versioning {
10795: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10796: my $portfolio_root = '/userfiles/portfolio';
10797: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10798: foreach my $file (@{$portfiles}) {
10799: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10800: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10801: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10802: my $getpropath = 1;
10803: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10804: $stu_name,$getpropath);
10805: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10806: my $new_answer =
10807: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10808: if ($new_answer ne 'problem getting file') {
10809: push(@{$versioned_portfiles}, $directory.$new_answer);
10810: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10811: [$symb,$env{'request.course.id'},'graded']);
10812: }
10813: }
10814: }
10815:
10816: sub get_next_version {
10817: my ($answer_name, $answer_ext, $dir_list) = @_;
10818: my $version;
10819: if (ref($dir_list) eq 'ARRAY') {
10820: foreach my $row (@{$dir_list}) {
10821: my ($file) = split(/\&/,$row,2);
10822: my ($file_name,$file_version,$file_ext) =
10823: &file_name_version_ext($file);
10824: if (($file_name eq $answer_name) &&
10825: ($file_ext eq $answer_ext)) {
10826: # gets here if filename and extension match,
10827: # regardless of version
10828: if ($file_version ne '') {
10829: # a versioned file is found so save it for later
10830: if ($file_version > $version) {
10831: $version = $file_version;
10832: }
10833: }
10834: }
10835: }
10836: }
10837: $version ++;
10838: return($version);
10839: }
10840:
10841: sub version_selected_portfile {
10842: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10843: my ($answer_name,$answer_ver,$answer_ext) =
10844: &file_name_version_ext($file_name);
10845: my $new_answer;
10846: $env{'form.copy'} =
10847: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10848: if($env{'form.copy'} eq '-1') {
10849: $new_answer = 'problem getting file';
10850: } else {
10851: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10852: my $copy_result =
10853: &finishuserfileupload($stu_name,$domain,'copy',
10854: '/portfolio'.$directory.$new_answer);
10855: }
10856: undef($env{'form.copy'});
10857: return ($new_answer);
10858: }
10859:
10860: sub file_name_version_ext {
10861: my ($file)=@_;
10862: my @file_parts = split(/\./, $file);
10863: my ($name,$version,$ext);
10864: if (@file_parts > 1) {
10865: $ext=pop(@file_parts);
10866: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10867: $version=pop(@file_parts);
10868: }
10869: $name=join('.',@file_parts);
10870: } else {
10871: $name=join('.',@file_parts);
10872: }
10873: return($name,$version,$ext);
10874: }
10875:
1.745 raeburn 10876: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10877:
1.745 raeburn 10878: sub get_portfile_permissions {
10879: my ($domain,$user) = @_;
1.613 albertel 10880: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10881: my ($tmp)=keys(%current_permissions);
10882: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10883: return \%current_permissions;
10884: }
10885:
10886: #---------------------------------------------Get portfolio file access controls
10887:
1.749 raeburn 10888: sub get_access_controls {
1.745 raeburn 10889: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10890: my %access;
10891: my $real_file = $file;
10892: $file =~ s/\.meta$//;
1.745 raeburn 10893: if (defined($file)) {
1.749 raeburn 10894: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10895: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10896: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10897: }
10898: }
1.745 raeburn 10899: } else {
1.749 raeburn 10900: foreach my $key (keys(%{$current_permissions})) {
10901: if ($key =~ /\0accesscontrol$/) {
10902: if (defined($group)) {
10903: if ($key !~ m-^\Q$group\E/-) {
10904: next;
10905: }
10906: }
10907: my ($fullpath) = split(/\0/,$key);
10908: if (ref($$current_permissions{$key}) eq 'HASH') {
10909: foreach my $control (keys(%{$$current_permissions{$key}})) {
10910: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10911: }
10912: }
10913: }
10914: }
10915: }
10916: return %access;
10917: }
10918:
10919: sub modify_access_controls {
10920: my ($file_name,$changes,$domain,$user)=@_;
10921: my ($outcome,$deloutcome);
10922: my %store_permissions;
10923: my %new_values;
10924: my %new_control;
10925: my %translation;
10926: my @deletions = ();
10927: my $now = time;
10928: if (exists($$changes{'activate'})) {
10929: if (ref($$changes{'activate'}) eq 'HASH') {
10930: my @newitems = sort(keys(%{$$changes{'activate'}}));
10931: my $numnew = scalar(@newitems);
10932: for (my $i=0; $i<$numnew; $i++) {
10933: my $newkey = $newitems[$i];
10934: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10935: if ($newkey =~ /^\d+:/) {
10936: $newkey =~ s/^(\d+)/$newid/;
10937: $translation{$1} = $newid;
10938: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10939: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10940: $translation{$1} = $newid;
10941: }
1.749 raeburn 10942: $new_values{$file_name."\0".$newkey} =
10943: $$changes{'activate'}{$newitems[$i]};
10944: $new_control{$newkey} = $now;
10945: }
10946: }
10947: }
10948: my %todelete;
10949: my %changed_items;
10950: foreach my $action ('delete','update') {
10951: if (exists($$changes{$action})) {
10952: if (ref($$changes{$action}) eq 'HASH') {
10953: foreach my $key (keys(%{$$changes{$action}})) {
10954: my ($itemnum) = ($key =~ /^([^:]+):/);
10955: if ($action eq 'delete') {
10956: $todelete{$itemnum} = 1;
10957: } else {
10958: $changed_items{$itemnum} = $key;
10959: }
10960: }
1.745 raeburn 10961: }
10962: }
1.749 raeburn 10963: }
10964: # get lock on access controls for file.
10965: my $lockhash = {
10966: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10967: ':'.$env{'user.domain'},
10968: };
10969: my $tries = 0;
10970: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10971:
1.1288 damieng 10972: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10973: $tries ++;
1.1289 damieng 10974: sleep(0.1);
1.749 raeburn 10975: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10976: }
10977: if ($gotlock eq 'ok') {
10978: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10979: my ($tmp)=keys(%curr_permissions);
10980: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10981: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10982: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10983: if (ref($curr_controls) eq 'HASH') {
10984: foreach my $control_item (keys(%{$curr_controls})) {
10985: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10986: if (defined($todelete{$itemnum})) {
10987: push(@deletions,$file_name."\0".$control_item);
10988: } else {
10989: if (defined($changed_items{$itemnum})) {
10990: $new_control{$changed_items{$itemnum}} = $now;
10991: push(@deletions,$file_name."\0".$control_item);
10992: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10993: } else {
10994: $new_control{$control_item} = $$curr_controls{$control_item};
10995: }
10996: }
1.745 raeburn 10997: }
10998: }
10999: }
1.970 raeburn 11000: my ($group);
11001: if (&is_course($domain,$user)) {
11002: ($group,my $file) = split(/\//,$file_name,2);
11003: }
1.749 raeburn 11004: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11005: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11006: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11007: # remove lock
11008: my @del_lock = ($file_name."\0".'locked_access_records');
11009: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11010: my $sqlresult =
1.970 raeburn 11011: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11012: $group);
1.749 raeburn 11013: } else {
11014: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11015: }
1.749 raeburn 11016: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11017: }
11018:
1.827 raeburn 11019: sub make_public_indefinitely {
1.1271 raeburn 11020: my (@requrl) = @_;
11021: return &automated_portfile_access('public',\@requrl);
11022: }
11023:
11024: sub automated_portfile_access {
11025: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 11026: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11027: return 'invalid';
11028: }
1.1271 raeburn 11029: my %urls;
11030: if (ref($addsref) eq 'ARRAY') {
11031: foreach my $requrl (@{$addsref}) {
11032: if (&is_portfolio_url($requrl)) {
11033: unless (exists($urls{$requrl})) {
11034: $urls{$requrl} = 'add';
11035: }
11036: }
11037: }
11038: }
11039: if (ref($delsref) eq 'ARRAY') {
11040: foreach my $requrl (@{$delsref}) {
11041: if (&is_portfolio_url($requrl)) {
11042: unless (exists($urls{$requrl})) {
11043: $urls{$requrl} = 'delete';
11044: }
11045: }
11046: }
11047: }
11048: unless (keys(%urls)) {
11049: return 'invalid';
11050: }
11051: my $ip;
11052: if ($accesstype eq 'ip') {
11053: if (ref($info) eq 'HASH') {
11054: if ($info->{'ip'} ne '') {
11055: $ip = $info->{'ip'};
11056: }
11057: }
11058: if ($ip eq '') {
11059: return 'invalid';
11060: }
11061: }
11062: my $errors;
1.827 raeburn 11063: my $now = time;
1.1271 raeburn 11064: my %current_perms;
11065: foreach my $requrl (sort(keys(%urls))) {
11066: my $action;
11067: if ($urls{$requrl} eq 'add') {
11068: $action = 'activate';
11069: } else {
11070: $action = 'none';
11071: }
11072: my $aclnum = 0;
1.827 raeburn 11073: my (undef,$udom,$unum,$file_name,$group) =
11074: &parse_portfolio_url($requrl);
1.1271 raeburn 11075: unless (exists($current_perms{$unum.':'.$udom})) {
11076: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11077: }
11078: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 11079: $group,$file_name);
11080: foreach my $key (keys(%{$access_controls{$file_name}})) {
11081: my ($num,$scope,$end,$start) =
11082: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 11083: if ($scope eq $accesstype) {
11084: if (($start <= $now) && ($end == 0)) {
11085: if ($accesstype eq 'ip') {
11086: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11087: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11088: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11089: if ($urls{$requrl} eq 'add') {
11090: $action = 'none';
11091: last;
11092: } else {
11093: $action = 'delete';
11094: $aclnum = $num;
11095: last;
11096: }
11097: }
11098: }
11099: }
11100: } elsif ($accesstype eq 'public') {
11101: if ($urls{$requrl} eq 'add') {
11102: $action = 'none';
11103: last;
11104: } else {
11105: $action = 'delete';
11106: $aclnum = $num;
11107: last;
11108: }
11109: }
11110: } elsif ($accesstype eq 'public') {
1.827 raeburn 11111: $action = 'update';
11112: $aclnum = $num;
1.1271 raeburn 11113: last;
1.827 raeburn 11114: }
11115: }
11116: }
11117: if ($action eq 'none') {
1.1271 raeburn 11118: next;
1.827 raeburn 11119: } else {
11120: my %changes;
11121: my $newend = 0;
11122: my $newstart = $now;
1.1271 raeburn 11123: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 11124: $changes{$action}{$newkey} = {
1.1271 raeburn 11125: type => $accesstype,
1.827 raeburn 11126: time => {
11127: start => $newstart,
11128: end => $newend,
11129: },
11130: };
1.1271 raeburn 11131: if ($accesstype eq 'ip') {
11132: $changes{$action}{$newkey}{'ip'} = [$ip];
11133: }
1.827 raeburn 11134: my ($outcome,$deloutcome,$new_values,$translation) =
11135: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 11136: unless ($outcome eq 'ok') {
11137: $errors .= $outcome.' ';
11138: }
1.827 raeburn 11139: }
1.1271 raeburn 11140: }
11141: if ($errors) {
11142: $errors =~ s/\s$//;
11143: return $errors;
1.827 raeburn 11144: } else {
1.1271 raeburn 11145: return 'ok';
1.827 raeburn 11146: }
11147: }
11148:
1.745 raeburn 11149: #------------------------------------------------------Get Marked as Read Only
11150:
11151: sub get_marked_as_readonly {
11152: my ($domain,$user,$what,$group) = @_;
11153: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11154: my @readonly_files;
1.629 banghart 11155: my $cmp1=$what;
11156: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11157: while (my ($file_name,$value) = each(%{$current_permissions})) {
11158: if (defined($group)) {
11159: if ($file_name !~ m-^\Q$group\E/-) {
11160: next;
11161: }
11162: }
1.561 banghart 11163: if (ref($value) eq "ARRAY"){
11164: foreach my $stored_what (@{$value}) {
1.629 banghart 11165: my $cmp2=$stored_what;
1.759 albertel 11166: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11167: $cmp2=join('',@{$stored_what});
1.745 raeburn 11168: }
1.629 banghart 11169: if ($cmp1 eq $cmp2) {
1.561 banghart 11170: push(@readonly_files, $file_name);
1.745 raeburn 11171: last;
1.563 banghart 11172: } elsif (!defined($what)) {
11173: push(@readonly_files, $file_name);
1.745 raeburn 11174: last;
1.561 banghart 11175: }
11176: }
1.745 raeburn 11177: }
1.561 banghart 11178: }
11179: return @readonly_files;
11180: }
1.577 banghart 11181: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11182:
1.577 banghart 11183: sub get_marked_as_readonly_hash {
1.745 raeburn 11184: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11185: my %readonly_files;
1.745 raeburn 11186: while (my ($file_name,$value) = each(%{$current_permissions})) {
11187: if (defined($group)) {
11188: if ($file_name !~ m-^\Q$group\E/-) {
11189: next;
11190: }
11191: }
1.577 banghart 11192: if (ref($value) eq "ARRAY"){
11193: foreach my $stored_what (@{$value}) {
1.745 raeburn 11194: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11195: foreach my $lock_descriptor(@{$stored_what}) {
11196: if ($lock_descriptor eq 'graded') {
11197: $readonly_files{$file_name} = 'graded';
11198: } elsif ($lock_descriptor eq 'handback') {
11199: $readonly_files{$file_name} = 'handback';
11200: } else {
11201: if (!exists($readonly_files{$file_name})) {
11202: $readonly_files{$file_name} = 'locked';
11203: }
11204: }
1.745 raeburn 11205: }
1.750 banghart 11206: }
1.577 banghart 11207: }
11208: }
11209: }
11210: return %readonly_files;
11211: }
1.559 banghart 11212: # ------------------------------------------------------------ Unmark as Read Only
11213:
11214: sub unmark_as_readonly {
1.629 banghart 11215: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11216: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11217: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11218: $file_name = &declutter_portfile($file_name);
1.634 albertel 11219: my $symb_crs = $what;
11220: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11221: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11222: my ($tmp)=keys(%current_permissions);
11223: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11224: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11225: foreach my $file (@readonly_files) {
1.759 albertel 11226: my $clean_file = &declutter_portfile($file);
11227: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11228: my $current_locks = $current_permissions{$file};
1.563 banghart 11229: my @new_locks;
11230: my @del_keys;
11231: if (ref($current_locks) eq "ARRAY"){
11232: foreach my $locker (@{$current_locks}) {
1.632 albertel 11233: my $compare=$locker;
1.749 raeburn 11234: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11235: $compare=join('',@{$locker});
1.746 raeburn 11236: if ($compare ne $symb_crs) {
11237: push(@new_locks, $locker);
11238: }
1.563 banghart 11239: }
11240: }
1.650 albertel 11241: if (scalar(@new_locks) > 0) {
1.563 banghart 11242: $current_permissions{$file} = \@new_locks;
11243: } else {
11244: push(@del_keys, $file);
1.613 albertel 11245: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11246: delete($current_permissions{$file});
1.563 banghart 11247: }
11248: }
1.561 banghart 11249: }
1.613 albertel 11250: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11251: return;
11252: }
1.512 banghart 11253:
1.17 www 11254: # ------------------------------------------------------------ Directory lister
11255:
11256: sub dirlist {
1.955 raeburn 11257: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11258: $uri=~s/^\///;
11259: $uri=~s/\/$//;
1.253 stredwic 11260: my ($udom, $uname);
1.955 raeburn 11261: if ($getuserdir) {
1.253 stredwic 11262: $udom = $userdomain;
11263: $uname = $username;
1.955 raeburn 11264: } else {
11265: (undef,$udom,$uname)=split(/\//,$uri);
11266: if(defined($userdomain)) {
11267: $udom = $userdomain;
11268: }
11269: if(defined($username)) {
11270: $uname = $username;
11271: }
1.253 stredwic 11272: }
1.955 raeburn 11273: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11274:
1.955 raeburn 11275: $dirRoot = $perlvar{'lonDocRoot'};
11276: if (defined($getpropath)) {
11277: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11278: $dirRoot =~ s/\/$//;
1.955 raeburn 11279: } elsif (defined($getuserdir)) {
11280: my $subdir=$uname.'__';
11281: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11282: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11283: ."/$udom/$subdir/$uname";
11284: } elsif (defined($alternateRoot)) {
11285: $dirRoot = $alternateRoot;
1.751 banghart 11286: }
1.253 stredwic 11287:
11288: if($udom) {
11289: if($uname) {
1.1135 raeburn 11290: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11291: if ($uhome eq 'no_host') {
11292: return ([],'no_host');
11293: }
1.955 raeburn 11294: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11295: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11296: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11297: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11298: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11299: } else {
11300: @listing_results = map { &unescape($_); } split(/:/,$listing);
11301: }
1.605 matthew 11302: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11303: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11304: @listing_results = split(/:/,$listing);
11305: } else {
11306: @listing_results = map { &unescape($_); } split(/:/,$listing);
11307: }
1.1135 raeburn 11308: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11309: ($listing eq 'rejected') || ($listing eq 'refused') ||
11310: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11311: return ([],$listing);
11312: } else {
11313: return (\@listing_results);
1.1135 raeburn 11314: }
1.955 raeburn 11315: } elsif(!$alternateRoot) {
1.1136 raeburn 11316: my (%allusers,%listerror);
1.841 albertel 11317: my %servers = &get_servers($udom,'library');
1.955 raeburn 11318: foreach my $tryserver (keys(%servers)) {
11319: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11320: &escape($udom),$tryserver);
11321: if ($listing eq 'unknown_cmd') {
11322: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11323: $udom, $tryserver);
11324: } else {
11325: @listing_results = map { &unescape($_); } split(/:/,$listing);
11326: }
1.841 albertel 11327: if ($listing eq 'unknown_cmd') {
11328: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11329: $udom, $tryserver);
11330: @listing_results = split(/:/,$listing);
11331: } else {
11332: @listing_results =
11333: map { &unescape($_); } split(/:/,$listing);
11334: }
1.1136 raeburn 11335: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11336: ($listing eq 'rejected') || ($listing eq 'refused') ||
11337: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11338: $listerror{$tryserver} = $listing;
11339: } else {
1.841 albertel 11340: foreach my $line (@listing_results) {
11341: my ($entry) = split(/&/,$line,2);
11342: $allusers{$entry} = 1;
11343: }
11344: }
1.253 stredwic 11345: }
1.1136 raeburn 11346: my @alluserslist=();
1.800 albertel 11347: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11348: push(@alluserslist,$user.'&user');
1.253 stredwic 11349: }
1.1318 droeschl 11350:
11351: if (!%listerror) {
11352: # no errors
11353: return (\@alluserslist);
11354: } elsif (scalar(keys(%servers)) == 1) {
11355: # one library server, one error
11356: my ($key) = keys(%listerror);
11357: return (\@alluserslist, $listerror{$key});
11358: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11359: # con_lost indicates that we might miss data from at least one
11360: # library server
11361: return (\@alluserslist, 'con_lost');
11362: } else {
11363: # multiple library servers and no con_lost -> data should be
11364: # complete.
11365: return (\@alluserslist);
11366: }
11367:
1.253 stredwic 11368: } else {
1.1136 raeburn 11369: return ([],'missing username');
1.253 stredwic 11370: }
1.955 raeburn 11371: } elsif(!defined($getpropath)) {
1.1136 raeburn 11372: my $path = $perlvar{'lonDocRoot'}.'/res/';
11373: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11374: return (\@all_domains);
1.955 raeburn 11375: } else {
1.1136 raeburn 11376: return ([],'missing domain');
1.275 stredwic 11377: }
11378: }
11379:
11380: # --------------------------------------------- GetFileTimestamp
11381: # This function utilizes dirlist and returns the date stamp for
11382: # when it was last modified. It will also return an error of -1
11383: # if an error occurs
11384:
11385: sub GetFileTimestamp {
1.955 raeburn 11386: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11387: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11388: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11389: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11390: undef,$getuserdir);
11391: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11392: return -1;
11393: }
11394: if (ref($fileref) eq 'ARRAY') {
11395: my @stats = split('&',$fileref->[0]);
1.375 matthew 11396: # @stats contains first the filename, then the stat output
11397: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11398: } else {
11399: return -1;
1.253 stredwic 11400: }
1.26 www 11401: }
11402:
1.712 albertel 11403: sub stat_file {
11404: my ($uri) = @_;
1.787 albertel 11405: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11406:
1.955 raeburn 11407: my ($udom,$uname,$file);
1.712 albertel 11408: if ($uri =~ m-^/(uploaded|editupload)/-) {
11409: ($udom,$uname,$file) =
1.811 albertel 11410: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11411: $file = 'userfiles/'.$file;
11412: }
11413: if ($uri =~ m-^/res/-) {
11414: ($udom,$uname) =
1.807 albertel 11415: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11416: $file = $uri;
11417: }
11418:
11419: if (!$udom || !$uname || !$file) {
11420: # unable to handle the uri
11421: return ();
11422: }
1.956 raeburn 11423: my $getpropath;
11424: if ($file =~ /^userfiles\//) {
11425: $getpropath = 1;
11426: }
1.1136 raeburn 11427: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11428: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11429: return ();
11430: } else {
11431: if (ref($listref) eq 'ARRAY') {
11432: my @stats = split('&',$listref->[0]);
11433: shift(@stats); #filename is first
11434: return @stats;
11435: }
1.712 albertel 11436: }
11437: return ();
11438: }
11439:
1.1313 raeburn 11440: # --------------------------------------------------------- recursedirs
11441: # Recursive function to traverse either a specific user's Authoring Space
11442: # or corresponding Published Resource Space, and populate the hash ref:
11443: # $dirhashref with URLs of all directories, and if $filehashref hash
11444: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11445: # or .rights files in resource space, and .meta, .save, .log, and .bak
11446: # files in Authoring Space.
11447: #
11448: # Inputs:
11449: #
11450: # $is_home - true if current server is home server for user's space
11451: # $context - either: priv, or res respectively for Authoring or Resource Space.
11452: # $docroot - Document root (i.e., /home/httpd/html
11453: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11454: # $relpath - Current path (relative to top level).
11455: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11456: # $filehashref - reference to hash to populate with URLs of files (Optional)
11457: #
11458: # Returns: nothing
11459: #
11460: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11461: #
11462: # Currently used by interface/londocs.pm to create linked select boxes for
11463: # directory and filename to import a Course "Author" resource into a course, and
11464: # also to create linked select boxes for Authoring Space and Directory to choose
11465: # save location for creation of a new "standard" problem from the Course Editor.
11466: #
11467:
11468: sub recursedirs {
11469: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11470: return unless (ref($dirhashref) eq 'HASH');
11471: my $currpath = $docroot.$toppath;
11472: if ($relpath) {
11473: $currpath .= "/$relpath";
11474: }
11475: my $savefile;
11476: if (ref($filehashref)) {
11477: $savefile = 1;
11478: }
11479: if ($is_home) {
11480: if (opendir(my $dirh,$currpath)) {
11481: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11482: next if ($item eq '');
11483: if (-d "$currpath/$item") {
11484: my $newpath;
11485: if ($relpath) {
11486: $newpath = "$relpath/$item";
11487: } else {
11488: $newpath = $item;
11489: }
11490: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11491: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11492: } elsif ($savefile) {
11493: if ($context eq 'priv') {
11494: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11495: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11496: }
11497: } else {
11498: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11499: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11500: }
11501: }
11502: }
11503: }
11504: closedir($dirh);
11505: }
11506: } else {
11507: my ($dirlistref,$listerror) =
11508: &dirlist($toppath.$relpath);
11509: my @dir_lines;
11510: my $dirptr=16384;
11511: if (ref($dirlistref) eq 'ARRAY') {
11512: foreach my $dir_line (sort
11513: {
11514: my ($afile)=split('&',$a,2);
11515: my ($bfile)=split('&',$b,2);
11516: return (lc($afile) cmp lc($bfile));
11517: } (@{$dirlistref})) {
11518: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11519: split(/\&/,$dir_line,16);
11520: $item =~ s/\s+$//;
11521: next if (($item =~ /^\.\.?$/) || ($obs));
11522: if ($dirptr&$testdir) {
11523: my $newpath;
11524: if ($relpath) {
11525: $newpath = "$relpath/$item";
11526: } else {
11527: $relpath = '/';
11528: $newpath = $item;
11529: }
11530: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11531: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11532: } elsif ($savefile) {
11533: if ($context eq 'priv') {
11534: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11535: $filehashref->{$relpath}{$item} = 1;
11536: }
11537: } else {
11538: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11539: $filehashref->{$relpath}{$item} = 1;
11540: }
11541: }
11542: }
11543: }
11544: }
11545: }
11546: return;
11547: }
11548:
1.26 www 11549: # -------------------------------------------------------- Value of a Condition
11550:
1.713 albertel 11551: # gets the value of a specific preevaluated condition
11552: # stored in the string $env{user.state.<cid>}
11553: # or looks up a condition reference in the bighash and if if hasn't
11554: # already been evaluated recurses into docondval to get the value of
11555: # the condition, then memoizing it to
11556: # $env{user.state.<cid>.<condition>}
1.40 www 11557: sub directcondval {
11558: my $number=shift;
1.620 albertel 11559: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11560: &Apache::lonuserstate::evalstate();
11561: }
1.713 albertel 11562: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11563: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11564: } elsif ($number =~ /^_/) {
11565: my $sub_condition;
11566: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11567: &GDBM_READER(),0640)) {
11568: $sub_condition=$bighash{'conditions'.$number};
11569: untie(%bighash);
11570: }
11571: my $value = &docondval($sub_condition);
1.949 raeburn 11572: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11573: return $value;
11574: }
1.620 albertel 11575: if ($env{'user.state.'.$env{'request.course.id'}}) {
11576: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11577: } else {
11578: return 2;
11579: }
11580: }
11581:
1.713 albertel 11582: # get the collection of conditions for this resource
1.26 www 11583: sub condval {
11584: my $condidx=shift;
1.54 www 11585: my $allpathcond='';
1.713 albertel 11586: foreach my $cond (split(/\|/,$condidx)) {
11587: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11588: $allpathcond.=
11589: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11590: }
1.191 harris41 11591: }
1.54 www 11592: $allpathcond=~s/\|$//;
1.713 albertel 11593: return &docondval($allpathcond);
11594: }
11595:
11596: #evaluates an expression of conditions
11597: sub docondval {
11598: my ($allpathcond) = @_;
11599: my $result=0;
11600: if ($env{'request.course.id'}
11601: && defined($allpathcond)) {
11602: my $operand='|';
11603: my @stack;
11604: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11605: if ($chunk eq '(') {
11606: push @stack,($operand,$result);
11607: } elsif ($chunk eq ')') {
11608: my $before=pop @stack;
11609: if (pop @stack eq '&') {
11610: $result=$result>$before?$before:$result;
11611: } else {
11612: $result=$result>$before?$result:$before;
11613: }
11614: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11615: $operand=$chunk;
11616: } else {
11617: my $new=directcondval($chunk);
11618: if ($operand eq '&') {
11619: $result=$result>$new?$new:$result;
11620: } else {
11621: $result=$result>$new?$result:$new;
11622: }
11623: }
11624: }
1.26 www 11625: }
11626: return $result;
1.421 albertel 11627: }
11628:
11629: # ---------------------------------------------------- Devalidate courseresdata
11630:
11631: sub devalidatecourseresdata {
11632: my ($coursenum,$coursedomain)=@_;
11633: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11634: &devalidate_cache_new('courseres',$hashid);
1.28 www 11635: }
11636:
1.763 www 11637:
1.200 www 11638: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11639: #
11640: # Parameters:
11641: # $coursenum - Number of the course.
11642: # $coursedomain - Domain at which the course was created.
11643: # Returns:
11644: # A hash of the course parameters along (I think) with timestamps
11645: # and version info.
1.877 foxr 11646:
1.624 albertel 11647: sub get_courseresdata {
11648: my ($coursenum,$coursedomain)=@_;
1.200 www 11649: my $coursehom=&homeserver($coursenum,$coursedomain);
11650: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11651: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11652: my %dumpreply;
1.417 albertel 11653: unless (defined($cached)) {
1.624 albertel 11654: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11655: $result=\%dumpreply;
1.251 albertel 11656: my ($tmp) = keys(%dumpreply);
11657: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11658: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11659: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11660: return $tmp;
1.416 albertel 11661: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11662: $result=undef;
1.599 albertel 11663: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11664: }
11665: }
1.624 albertel 11666: return $result;
11667: }
11668:
1.633 albertel 11669: sub devalidateuserresdata {
11670: my ($uname,$udom)=@_;
11671: my $hashid="$udom:$uname";
11672: &devalidate_cache_new('userres',$hashid);
11673: }
11674:
1.624 albertel 11675: sub get_userresdata {
11676: my ($uname,$udom)=@_;
11677: #most student don\'t have any data set, check if there is some data
11678: if (&EXT_cache_status($udom,$uname)) { return undef; }
11679:
11680: my $hashid="$udom:$uname";
11681: my ($result,$cached)=&is_cached_new('userres',$hashid);
11682: if (!defined($cached)) {
11683: my %resourcedata=&dump('resourcedata',$udom,$uname);
11684: $result=\%resourcedata;
11685: &do_cache_new('userres',$hashid,$result,600);
11686: }
11687: my ($tmp)=keys(%$result);
11688: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11689: return $result;
11690: }
11691: #error 2 occurs when the .db doesn't exist
11692: if ($tmp!~/error: 2 /) {
1.1294 raeburn 11693: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11694: &logthis("<font color=\"blue\">WARNING:".
11695: " Trying to get resource data for ".
11696: $uname." at ".$udom.": ".
11697: $tmp."</font>");
11698: }
1.624 albertel 11699: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11700: #&EXT_cache_set($udom,$uname);
11701: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11702: undef($tmp); # not really an error so don't send it back
1.624 albertel 11703: }
11704: return $tmp;
11705: }
1.879 foxr 11706: #----------------------------------------------- resdata - return resource data
11707: # Purpose:
11708: # Return resource data for either users or for a course.
11709: # Parameters:
11710: # $name - Course/user name.
11711: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 11712: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 11713: # $mapp - decluttered URL of enclosing map
11714: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
11715: # $recurseup - Ref to array of map URLs, starting with map containing
11716: # $mapp up through hierarchy of nested maps to top level map.
11717: # $courseid - CourseID (first part of param identifier).
11718: # $modifier - Middle part of param identifier.
11719: # $what - Last part of param identifier.
1.879 foxr 11720: # @which - Array of names of resources desired.
11721: # Returns:
11722: # The value of the first reasource in @which that is found in the
11723: # resource hash.
11724: # Exceptional Conditions:
11725: # If the $type passed in is not valid (not the string 'course' or
11726: # 'user', an undefined reference is returned.
11727: # If none of the resources are found, an undef is returned
1.624 albertel 11728: sub resdata {
1.1301 raeburn 11729: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11730: $modifier,$what,@which)=@_;
1.624 albertel 11731: my $result;
11732: if ($type eq 'course') {
11733: $result=&get_courseresdata($name,$domain);
11734: } elsif ($type eq 'user') {
11735: $result=&get_userresdata($name,$domain);
11736: }
11737: if (!ref($result)) { return $result; }
1.251 albertel 11738: foreach my $item (@which) {
1.1301 raeburn 11739: if ($item->[1] eq 'course') {
11740: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11741: unless ($$recursed) {
1.1302 raeburn 11742: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 11743: $$recursed = 1;
11744: }
11745: foreach my $item (@${recurseup}) {
11746: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11747: last if (defined($result->{$norecursechk}));
11748: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11749: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11750: }
11751: }
11752: }
11753: if (defined($result->{$item->[0]})) {
1.927 albertel 11754: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11755: }
1.250 albertel 11756: }
1.291 albertel 11757: return undef;
1.200 www 11758: }
11759:
1.1360 raeburn 11760: sub get_domain_lti {
11761: my ($cdom,$context) = @_;
11762: my ($name,%lti);
11763: if ($context eq 'consumer') {
11764: $name = 'ltitools';
11765: } elsif ($context eq 'provider') {
11766: $name = 'lti';
11767: } else {
11768: return %lti;
11769: }
11770: my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298 raeburn 11771: if (defined($cached)) {
11772: if (ref($result) eq 'HASH') {
1.1360 raeburn 11773: %lti = %{$result};
1.1298 raeburn 11774: }
11775: } else {
1.1360 raeburn 11776: my %domconfig = &get_dom('configuration',[$name],$cdom);
11777: if (ref($domconfig{$name}) eq 'HASH') {
11778: %lti = %{$domconfig{$name}};
11779: my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11780: if (ref($encdomconfig{$name}) eq 'HASH') {
11781: foreach my $id (keys(%lti)) {
11782: if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344 raeburn 11783: foreach my $item ('key','secret') {
1.1360 raeburn 11784: $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344 raeburn 11785: }
11786: }
11787: }
11788: }
1.1298 raeburn 11789: }
11790: my $cachetime = 24*60*60;
1.1360 raeburn 11791: &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298 raeburn 11792: }
1.1360 raeburn 11793: return %lti;
1.1298 raeburn 11794: }
11795:
1.1236 raeburn 11796: sub get_numsuppfiles {
11797: my ($cnum,$cdom,$ignorecache)=@_;
11798: my $hashid=$cnum.':'.$cdom;
11799: my ($suppcount,$cached);
11800: unless ($ignorecache) {
11801: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11802: }
11803: unless (defined($cached)) {
11804: my $chome=&homeserver($cnum,$cdom);
11805: unless ($chome eq 'no_host') {
1.1366 raeburn 11806: ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236 raeburn 11807: my $suppmap = 'supplemental.sequence';
1.1366 raeburn 11808: ($suppcount,$supptools,$errors) =
11809: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11810: $supptools,$errors);
1.1236 raeburn 11811: }
11812: &do_cache_new('suppcount',$hashid,$suppcount,600);
11813: }
11814: return $suppcount;
11815: }
11816:
1.379 matthew 11817: #
11818: # EXT resource caching routines
11819: #
11820:
1.1302 raeburn 11821: {
11822: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11823: #
11824: # The course for which we cache
11825: my $cachedmapkey='';
11826: # The cached recursive maps for this course
11827: my %cachedmaps=();
11828: # When this was last done
11829: my $cachedmaptime='';
11830:
1.379 matthew 11831: sub clear_EXT_cache_status {
1.383 albertel 11832: &delenv('cache.EXT.');
1.379 matthew 11833: }
11834:
11835: sub EXT_cache_status {
11836: my ($target_domain,$target_user) = @_;
1.383 albertel 11837: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11838: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11839: # We know already the user has no data
11840: return 1;
11841: } else {
11842: return 0;
11843: }
11844: }
11845:
11846: sub EXT_cache_set {
11847: my ($target_domain,$target_user) = @_;
1.383 albertel 11848: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11849: #&appenv({$cachename => time});
1.379 matthew 11850: }
11851:
1.28 www 11852: # --------------------------------------------------------- Value of a Variable
1.58 www 11853: sub EXT {
1.715 albertel 11854:
1.1228 raeburn 11855: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11856: unless ($varname) { return ''; }
1.218 albertel 11857: #get real user name/domain, courseid and symb
11858: my $courseid;
1.359 albertel 11859: my $publicuser;
1.427 www 11860: if ($symbparm) {
11861: $symbparm=&get_symb_from_alias($symbparm);
11862: }
1.218 albertel 11863: if (!($uname && $udom)) {
1.790 albertel 11864: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11865: if (!$symbparm) { $symbparm=$cursymb; }
11866: } else {
1.620 albertel 11867: $courseid=$env{'request.course.id'};
1.218 albertel 11868: }
1.48 www 11869: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11870: my $rest;
1.320 albertel 11871: if (defined($therest[0])) {
1.48 www 11872: $rest=join('.',@therest);
11873: } else {
11874: $rest='';
11875: }
1.320 albertel 11876:
1.57 www 11877: my $qualifierrest=$qualifier;
11878: if ($rest) { $qualifierrest.='.'.$rest; }
11879: my $spacequalifierrest=$space;
11880: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11881: if ($realm eq 'user') {
1.48 www 11882: # --------------------------------------------------------------- user.resource
11883: if ($space eq 'resource') {
1.651 albertel 11884: if ( (defined($Apache::lonhomework::parsing_a_problem)
11885: || defined($Apache::lonhomework::parsing_a_task))
11886: &&
1.744 albertel 11887: ($symbparm eq &symbread()) ) {
11888: # if we are in the middle of processing the resource the
11889: # get the value we are planning on committing
11890: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11891: return $Apache::lonhomework::results{$qualifierrest};
11892: } else {
11893: return $Apache::lonhomework::history{$qualifierrest};
11894: }
1.335 albertel 11895: } else {
1.359 albertel 11896: my %restored;
1.620 albertel 11897: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11898: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11899: } else {
11900: %restored=&restore($symbparm,$courseid,$udom,$uname);
11901: }
1.335 albertel 11902: return $restored{$qualifierrest};
11903: }
1.48 www 11904: # ----------------------------------------------------------------- user.access
11905: } elsif ($space eq 'access') {
1.218 albertel 11906: # FIXME - not supporting calls for a specific user
1.48 www 11907: return &allowed($qualifier,$rest);
11908: # ------------------------------------------ user.preferences, user.environment
11909: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11910: if (($uname eq $env{'user.name'}) &&
11911: ($udom eq $env{'user.domain'})) {
11912: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11913: } else {
1.359 albertel 11914: my %returnhash;
11915: if (!$publicuser) {
11916: %returnhash=&userenvironment($udom,$uname,
11917: $qualifierrest);
11918: }
1.218 albertel 11919: return $returnhash{$qualifierrest};
11920: }
1.48 www 11921: # ----------------------------------------------------------------- user.course
11922: } elsif ($space eq 'course') {
1.218 albertel 11923: # FIXME - not supporting calls for a specific user
1.620 albertel 11924: return $env{join('.',('request.course',$qualifier))};
1.48 www 11925: # ------------------------------------------------------------------- user.role
11926: } elsif ($space eq 'role') {
1.218 albertel 11927: # FIXME - not supporting calls for a specific user
1.620 albertel 11928: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11929: if ($qualifier eq 'value') {
11930: return $role;
11931: } elsif ($qualifier eq 'extent') {
11932: return $where;
11933: }
11934: # ----------------------------------------------------------------- user.domain
11935: } elsif ($space eq 'domain') {
1.218 albertel 11936: return $udom;
1.48 www 11937: # ------------------------------------------------------------------- user.name
11938: } elsif ($space eq 'name') {
1.218 albertel 11939: return $uname;
1.48 www 11940: # ---------------------------------------------------- Any other user namespace
1.29 www 11941: } else {
1.359 albertel 11942: my %reply;
11943: if (!$publicuser) {
11944: %reply=&get($space,[$qualifierrest],$udom,$uname);
11945: }
11946: return $reply{$qualifierrest};
1.48 www 11947: }
1.236 www 11948: } elsif ($realm eq 'query') {
11949: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11950: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11951: [$spacequalifierrest]);
1.620 albertel 11952: return $env{'form.'.$spacequalifierrest};
1.236 www 11953: } elsif ($realm eq 'request') {
1.48 www 11954: # ------------------------------------------------------------- request.browser
11955: if ($space eq 'browser') {
1.1145 bisitz 11956: return $env{'browser.'.$qualifier};
1.57 www 11957: # ------------------------------------------------------------ request.filename
11958: } else {
1.620 albertel 11959: return $env{'request.'.$spacequalifierrest};
1.29 www 11960: }
1.28 www 11961: } elsif ($realm eq 'course') {
1.48 www 11962: # ---------------------------------------------------------- course.description
1.620 albertel 11963: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11964: } elsif ($realm eq 'resource') {
1.165 www 11965:
1.620 albertel 11966: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11967: if (!$symbparm) { $symbparm=&symbread(); }
11968: }
1.693 albertel 11969:
1.1232 raeburn 11970: if ($qualifier eq '') {
11971: if ($space eq 'title') {
11972: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11973: return &gettitle($symbparm);
11974: }
1.693 albertel 11975:
1.1232 raeburn 11976: if ($space eq 'map') {
11977: my ($map) = &decode_symb($symbparm);
11978: return &symbread($map);
11979: }
11980: if ($space eq 'maptitle') {
11981: my ($map) = &decode_symb($symbparm);
11982: return &gettitle($map);
11983: }
11984: if ($space eq 'filename') {
11985: if ($symbparm) {
11986: return &clutter((&decode_symb($symbparm))[2]);
11987: }
11988: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11989: }
1.1232 raeburn 11990:
1.1233 raeburn 11991: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11992: if ($space eq 'visibleparts') {
11993: my $navmap = Apache::lonnavmaps::navmap->new();
11994: my $item;
11995: if (ref($navmap)) {
11996: my $res = $navmap->getBySymb($symbparm);
11997: my $parts = $res->parts();
11998: if (ref($parts) eq 'ARRAY') {
11999: $item = join(',',@{$parts});
12000: }
12001: undef($navmap);
1.1232 raeburn 12002: }
1.1233 raeburn 12003: return $item;
1.1232 raeburn 12004: }
12005: }
12006: }
1.693 albertel 12007:
1.1301 raeburn 12008: my ($section, $group, @groups, @recurseup, $recursed);
12009: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 12010: if (($courseid eq '') && ($cid)) {
12011: $courseid = $cid;
12012: }
12013: if (($symbparm && $courseid) &&
12014: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 12015:
1.218 albertel 12016: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 12017:
1.60 www 12018: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 12019: my $symbp=$symbparm;
1.1301 raeburn 12020: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 12021: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 12022: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 12023: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 12024: if (($env{'user.name'} eq $uname) &&
12025: ($env{'user.domain'} eq $udom)) {
12026: $section=$env{'request.course.sec'};
1.733 raeburn 12027: @groups = split(/:/,$env{'request.course.groups'});
12028: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 12029: } else {
1.539 albertel 12030: if (! defined($usection)) {
1.551 albertel 12031: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 12032: } else {
12033: $section = $usection;
12034: }
1.733 raeburn 12035: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 12036: }
12037:
12038: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12039: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 12040: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 12041: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12042:
1.593 albertel 12043: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 12044: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 12045: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 12046: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 12047:
1.60 www 12048: # ----------------------------------------------------------- first, check user
1.624 albertel 12049:
1.1301 raeburn 12050: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12051: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 12052: ([$courselevelr,'resource'],
12053: [$courselevelm,'map' ],
1.1301 raeburn 12054: [$courseleveli,'map' ],
1.927 albertel 12055: [$courselevel, 'course' ]));
1.931 albertel 12056: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 12057:
1.594 albertel 12058: # ------------------------------------------------ second, check some of course
1.684 raeburn 12059: my $coursereply;
1.691 raeburn 12060: if (@groups > 0) {
12061: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 12062: $recurseparm,$mapparm,$spacequalifierrest,
12063: $mapp,\$recursed,\@recurseup);
12064: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 12065: }
1.96 www 12066:
1.684 raeburn 12067: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 12068: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12069: 'course',$mapp,\$recursed,\@recurseup,
12070: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 12071: ([$seclevelr, 'resource'],
12072: [$seclevelm, 'map' ],
1.1301 raeburn 12073: [$secleveli, 'map' ],
1.927 albertel 12074: [$seclevel, 'course' ],
12075: [$courselevelr,'resource']));
12076: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 12077:
1.60 www 12078: # ------------------------------------------------------ third, check map parms
1.218 albertel 12079: my %parmhash=();
12080: my $thisparm='';
12081: if (tie(%parmhash,'GDBM_File',
1.620 albertel 12082: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 12083: &GDBM_READER(),0640)) {
1.218 albertel 12084: $thisparm=$parmhash{$symbparm};
12085: untie(%parmhash);
12086: }
1.927 albertel 12087: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 12088: }
1.594 albertel 12089: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 12090:
12091: my $what = $spacequalifierrest;
12092: $what=~s/\./\_/;
1.282 albertel 12093: my $filename;
12094: if (!$symbparm) { $symbparm=&symbread(); }
12095: if ($symbparm) {
1.409 www 12096: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 12097: } else {
1.620 albertel 12098: $filename=$env{'request.filename'};
1.282 albertel 12099: }
1.1362 raeburn 12100: my $toolsymb;
12101: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12102: $toolsymb = $symbparm;
12103: }
12104: my $metadata=&metadata($filename,$what,$toolsymb);
1.927 albertel 12105: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362 raeburn 12106: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927 albertel 12107: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 12108:
1.1301 raeburn 12109: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 12110: if ($symbparm && defined($courseid) &&
1.620 albertel 12111: $courseid eq $env{'request.course.id'}) {
1.624 albertel 12112: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12113: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12114: 'course',$mapp,\$recursed,\@recurseup,
12115: $courseid,'.',$spacequalifierrest,
1.927 albertel 12116: ([$courselevelm,'map' ],
1.1301 raeburn 12117: [$courseleveli,'map' ],
1.927 albertel 12118: [$courselevel, 'course']));
12119: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 12120: }
1.145 www 12121: # ------------------------------------------------------------------ Cascade up
1.218 albertel 12122: unless ($space eq '0') {
1.336 albertel 12123: my @parts=split(/_/,$space);
12124: my $id=pop(@parts);
12125: my $part=join('_',@parts);
12126: if ($part eq '') { $part='0'; }
1.927 albertel 12127: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 12128: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 12129: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 12130: }
1.395 albertel 12131: if ($recurse) { return undef; }
1.1362 raeburn 12132: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927 albertel 12133: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 12134: # ---------------------------------------------------- Any other user namespace
12135: } elsif ($realm eq 'environment') {
12136: # ----------------------------------------------------------------- environment
1.620 albertel 12137: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12138: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 12139: } else {
1.770 albertel 12140: if ($uname eq 'anonymous' && $udom eq '') {
12141: return '';
12142: }
1.219 albertel 12143: my %returnhash=&userenvironment($udom,$uname,
12144: $spacequalifierrest);
12145: return $returnhash{$spacequalifierrest};
12146: }
1.28 www 12147: } elsif ($realm eq 'system') {
1.48 www 12148: # ----------------------------------------------------------------- system.time
12149: if ($space eq 'time') {
12150: return time;
12151: }
1.696 albertel 12152: } elsif ($realm eq 'server') {
12153: # ----------------------------------------------------------------- system.time
12154: if ($space eq 'name') {
12155: return $ENV{'SERVER_NAME'};
12156: }
1.28 www 12157: }
1.48 www 12158: return '';
1.61 www 12159: }
12160:
1.927 albertel 12161: sub get_reply {
12162: my ($reply_value) = @_;
1.940 raeburn 12163: if (ref($reply_value) eq 'ARRAY') {
12164: if (wantarray) {
12165: return @$reply_value;
12166: }
12167: return $reply_value->[0];
12168: } else {
12169: return $reply_value;
1.927 albertel 12170: }
12171: }
12172:
1.691 raeburn 12173: sub check_group_parms {
1.1301 raeburn 12174: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12175: $recursed,$recurseupref) = @_;
12176: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12177: [$what,'course']);
12178: my $coursereply;
1.691 raeburn 12179: foreach my $group (@{$groups}) {
1.1301 raeburn 12180: my @groupitems = ();
1.691 raeburn 12181: foreach my $level (@levels) {
1.927 albertel 12182: my $item = $courseid.'.['.$group.'].'.$level->[0];
12183: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 12184: }
1.1301 raeburn 12185: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12186: $env{'course.'.$courseid.'.domain'},
12187: 'course',$mapp,$recursed,$recurseupref,
12188: $courseid,'.['.$group.'].',$what,
12189: @groupitems);
12190: last if (defined($coursereply));
1.691 raeburn 12191: }
12192: return $coursereply;
12193: }
12194:
1.1301 raeburn 12195: sub get_map_hierarchy {
1.1302 raeburn 12196: my ($mapname,$courseid) = @_;
12197: my @recurseup = ();
1.1301 raeburn 12198: if ($mapname) {
1.1302 raeburn 12199: if (($cachedmapkey eq $courseid) &&
12200: (abs($cachedmaptime-time)<5)) {
12201: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12202: return @{$cachedmaps{$mapname}};
12203: }
12204: }
1.1301 raeburn 12205: my $navmap = Apache::lonnavmaps::navmap->new();
12206: if (ref($navmap)) {
12207: @recurseup = $navmap->recurseup_maps($mapname);
12208: undef($navmap);
1.1302 raeburn 12209: $cachedmaps{$mapname} = \@recurseup;
12210: $cachedmaptime=time;
12211: $cachedmapkey=$courseid;
1.1301 raeburn 12212: }
12213: }
12214: return @recurseup;
12215: }
12216:
1.1302 raeburn 12217: }
12218:
1.691 raeburn 12219: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 12220: my ($courseid,@groups) = @_;
12221: @groups = sort(@groups);
1.691 raeburn 12222: return @groups;
12223: }
12224:
1.395 albertel 12225: sub packages_tab_default {
1.1362 raeburn 12226: my ($uri,$varname,$toolsymb)=@_;
1.395 albertel 12227: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 12228:
12229: my (@extension,@specifics,$do_default);
1.1362 raeburn 12230: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395 albertel 12231: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 12232: if ($pack_type eq 'default') {
12233: $do_default=1;
12234: } elsif ($pack_type eq 'extension') {
12235: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 12236: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 12237: # only look at packages defaults for packages that this id is
1.738 albertel 12238: push(@specifics,[$package,$pack_type,$pack_part]);
12239: }
12240: }
12241: # first look for a package that matches the requested part id
12242: foreach my $package (@specifics) {
12243: my (undef,$pack_type,$pack_part)=@{$package};
12244: next if ($pack_part ne $part);
12245: if (defined($packagetab{"$pack_type&$name&default"})) {
12246: return $packagetab{"$pack_type&$name&default"};
12247: }
12248: }
12249: # look for any possible matching non extension_ package
12250: foreach my $package (@specifics) {
12251: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 12252: if (defined($packagetab{"$pack_type&$name&default"})) {
12253: return $packagetab{"$pack_type&$name&default"};
12254: }
1.585 albertel 12255: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 12256: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12257: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 12258: }
12259: }
1.738 albertel 12260: # look for any posible extension_ match
12261: foreach my $package (@extension) {
12262: my ($package,$pack_type)=@{$package};
12263: if (defined($packagetab{"$pack_type&$name&default"})) {
12264: return $packagetab{"$pack_type&$name&default"};
12265: }
12266: if (defined($packagetab{$package."&$name&default"})) {
12267: return $packagetab{$package."&$name&default"};
12268: }
12269: }
12270: # look for a global default setting
12271: if ($do_default && defined($packagetab{"default&$name&default"})) {
12272: return $packagetab{"default&$name&default"};
12273: }
1.395 albertel 12274: return undef;
12275: }
12276:
1.334 albertel 12277: sub add_prefix_and_part {
12278: my ($prefix,$part)=@_;
12279: my $keyroot;
12280: if (defined($prefix) && $prefix !~ /^__/) {
12281: # prefix that has a part already
12282: $keyroot=$prefix;
12283: } elsif (defined($prefix)) {
12284: # prefix that is missing a part
12285: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12286: } else {
12287: # no prefix at all
12288: if (defined($part)) { $keyroot='_'.$part; }
12289: }
12290: return $keyroot;
12291: }
12292:
1.71 www 12293: # ---------------------------------------------------------------- Get metadata
12294:
1.599 albertel 12295: my %metaentry;
1.1070 www 12296: my %importedpartids;
1.1369 raeburn 12297: my %importedrespids;
1.71 www 12298: sub metadata {
1.1362 raeburn 12299: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71 www 12300: $uri=&declutter($uri);
1.288 albertel 12301: # if it is a non metadata possible uri return quickly
1.529 albertel 12302: if (($uri eq '') ||
12303: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 12304: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 12305: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 12306: return undef;
12307: }
1.1261 raeburn 12308: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 12309: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 12310: return undef;
1.288 albertel 12311: }
1.73 www 12312: my $filename=$uri;
12313: $uri=~s/\.meta$//;
1.172 www 12314: #
12315: # Is the metadata already cached?
1.177 www 12316: # Look at timestamp of caching
1.172 www 12317: # Everything is cached by the main uri, libraries are never directly cached
12318: #
1.428 albertel 12319: if (!defined($liburi)) {
1.599 albertel 12320: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 12321: if (defined($cached)) { return $result->{':'.$what}; }
12322: }
1.1362 raeburn 12323:
12324: #
12325: # If the uri is for an external tool the file from
12326: # which metadata should be retrieved depends on whether
12327: # the tool had been configured to be gradable (set in the Course
12328: # Editor or Resource Editor).
12329: #
12330: # If a valid symb has been included as the third arg in the call
12331: # to &metadata() that can be used to retrieve the value of
12332: # parameter_0_gradable set for the resource, and included in the
12333: # uploaded map containing the tool. The value is retrieved via
12334: # &EXT(), if a valid symb is available. Otherwise the value of
12335: # gradable in the exttool_$marker.db file for the tool instance
1.1364 raeburn 12336: # is retrieved via &get().
12337: #
12338: # When lonuserstate::traceroute() calls lonnet::EXT() for
12339: # hiddenresource and encrypturl (during course initialization)
12340: # the map-level parameter for resource.0.gradable included in the
12341: # uploaded map containing the tool will not yet have been stored
12342: # in the user_course_parms.db file for the user's session, so in
12343: # this case fall back to retrieving gradable status from the
12344: # exttool_$marker.db file.
1.1362 raeburn 12345: #
12346: # In order to avoid an infinite loop, &metadata() will return
12347: # before a call to &EXT(), if the uri is for an external tool
12348: # and the $what for which metadata is being requested is
12349: # parameter_0_gradable or 0_gradable.
12350: #
12351:
12352: if ($uri =~ /ext\.tool$/) {
12353: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12354: return;
12355: } else {
12356: my ($checked,$use_passback);
12357: if ($toolsymb ne '') {
12358: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364 raeburn 12359: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362 raeburn 12360: $checked = 1;
12361: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12362: $use_passback = 1;
12363: }
12364: }
12365: }
12366: unless ($checked) {
12367: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12368: $marker=~s/\D//g;
1.1363 raeburn 12369: if ($marker) {
1.1362 raeburn 12370: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12371: $use_passback = $toolsettings{'gradable'};
12372: }
12373: }
12374: if ($use_passback) {
12375: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12376: } else {
12377: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12378: }
12379: }
12380: }
12381:
1.428 albertel 12382: {
1.1069 www 12383: # Imported parts would go here
1.1369 raeburn 12384: my @origfiletagids=();
1.1069 www 12385: my $importedparts=0;
1.1369 raeburn 12386:
12387: # Imported responseids would go here
12388: my $importedresponses=0;
1.172 www 12389: #
12390: # Is this a recursive call for a library?
12391: #
1.599 albertel 12392: # if (! exists($metacache{$uri})) {
12393: # $metacache{$uri}={};
12394: # }
1.924 albertel 12395: my $cachetime = 60*60;
1.171 www 12396: if ($liburi) {
12397: $liburi=&declutter($liburi);
12398: $filename=$liburi;
1.401 bowersj2 12399: } else {
1.599 albertel 12400: &devalidate_cache_new('meta',$uri);
12401: undef(%metaentry);
1.401 bowersj2 12402: }
1.140 www 12403: my %metathesekeys=();
1.73 www 12404: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 12405: my $metastring;
1.1140 www 12406: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 12407: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 12408: $metastring =
1.929 albertel 12409: &Apache::lonnet::ssi_body($which,
1.924 albertel 12410: ('grade_target' => 'meta'));
12411: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 12412: } elsif (($uri !~ m -^(editupload)/-) &&
12413: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 12414: my $file=&filelocation('',&clutter($filename));
1.599 albertel 12415: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 12416: $metastring=&getfile($file);
1.489 albertel 12417: }
1.208 albertel 12418: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 12419: my $token;
1.140 www 12420: undef %metathesekeys;
1.71 www 12421: while ($token=$parser->get_token) {
1.339 albertel 12422: if ($token->[0] eq 'S') {
12423: if (defined($token->[2]->{'package'})) {
1.172 www 12424: #
12425: # This is a package - get package info
12426: #
1.339 albertel 12427: my $package=$token->[2]->{'package'};
12428: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12429: if (defined($token->[2]->{'id'})) {
12430: $keyroot.='_'.$token->[2]->{'id'};
12431: }
1.599 albertel 12432: if ($metaentry{':packages'}) {
12433: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 12434: } else {
1.599 albertel 12435: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 12436: }
1.736 albertel 12437: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 12438: my $part=$keyroot;
12439: $part=~s/^\_//;
1.736 albertel 12440: if ($pack_entry=~/^\Q$package\E\&/ ||
12441: $pack_entry=~/^\Q$package\E_0\&/) {
12442: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 12443: # ignore package.tab specified default values
12444: # here &package_tab_default() will fetch those
12445: if ($subp eq 'default') { next; }
1.736 albertel 12446: my $value=$packagetab{$pack_entry};
1.432 albertel 12447: my $unikey;
12448: if ($pack =~ /_0$/) {
12449: $unikey='parameter_0_'.$name;
12450: $part=0;
12451: } else {
12452: $unikey='parameter'.$keyroot.'_'.$name;
12453: }
1.339 albertel 12454: if ($subp eq 'display') {
12455: $value.=' [Part: '.$part.']';
12456: }
1.599 albertel 12457: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 12458: $metathesekeys{$unikey}=1;
1.599 albertel 12459: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12460: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 12461: }
1.599 albertel 12462: if (defined($metaentry{':'.$unikey.'.default'})) {
12463: $metaentry{':'.$unikey}=
12464: $metaentry{':'.$unikey.'.default'};
1.356 albertel 12465: }
1.339 albertel 12466: }
12467: }
12468: } else {
1.172 www 12469: #
12470: # This is not a package - some other kind of start tag
1.339 albertel 12471: #
12472: my $entry=$token->[1];
1.1068 www 12473: my $unikey='';
1.175 www 12474:
1.339 albertel 12475: if ($entry eq 'import') {
1.175 www 12476: #
12477: # Importing a library here
1.339 albertel 12478: #
1.1067 www 12479: my $location=$parser->get_text('/import');
12480: my $dir=$filename;
12481: $dir=~s|[^/]*$||;
12482: $location=&filelocation($dir,$location);
1.1369 raeburn 12483:
12484: my $importid=$token->[2]->{'id'};
1.1068 www 12485: my $importmode=$token->[2]->{'importmode'};
1.1369 raeburn 12486: #
12487: # Check metadata for imported file to
12488: # see if it contained response items
12489: #
1.1372 raeburn 12490: my ($origfile,@libfilekeys);
1.1370 raeburn 12491: my %currmetaentry = %metaentry;
1.1372 raeburn 12492: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12493: $depthcount+1));
12494: if (grep(/^responseorder$/,@libfilekeys)) {
12495: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12496: undef,$depthcount+1);
12497: if ($libresponseorder ne '') {
12498: if ($#origfiletagids<0) {
12499: undef(%importedrespids);
12500: undef(%importedpartids);
12501: }
1.1373 raeburn 12502: my @respids = split(/\s*,\s*/,$libresponseorder);
12503: if (@respids) {
12504: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12505: }
12506: if ($importedrespids{$importid} ne '') {
1.1372 raeburn 12507: $importedresponses = 1;
1.1369 raeburn 12508: # We need to get the original file and the imported file to get the response order correct
12509: # Load and inspect original file
1.1372 raeburn 12510: if ($#origfiletagids<0) {
12511: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12512: $origfile=&getfile($origfilelocation);
12513: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12514: }
1.1369 raeburn 12515: }
12516: }
12517: }
1.1370 raeburn 12518: # Do not overwrite contents of %metaentry hash for resource itself with
12519: # hash populated for imported library file
12520: %metaentry = %currmetaentry;
12521: undef(%currmetaentry);
1.1374 raeburn 12522: if ($importmode eq 'part') {
1.1068 www 12523: # Import as part(s)
1.1069 www 12524: $importedparts=1;
12525: # We need to get the original file and the imported file to get the part order correct
12526: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369 raeburn 12527: # Load and inspect original file if we didn't do that already
12528: if ($#origfiletagids<0) {
12529: undef(%importedrespids);
12530: undef(%importedpartids);
12531: if ($origfile eq '') {
12532: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12533: $origfile=&getfile($origfilelocation);
12534: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12535: }
1.1070 www 12536: }
1.1372 raeburn 12537: my @impfilepartids;
12538: # If <partorder> tag is included in metadata for the imported file
12539: # get the parts in the imported file from that.
12540: if (grep(/^partorder$/,@libfilekeys)) {
12541: %currmetaentry = %metaentry;
12542: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12543: $depthcount+1);
12544: %metaentry = %currmetaentry;
12545: undef(%currmetaentry);
12546: if ($libpartorder ne '') {
12547: @impfilepartids=split(/\s*,\s*/,$libpartorder);
12548: }
12549: } else {
12550: # If no <partorder> tag available, load and inspect imported file
12551: my $impfile=&getfile($location);
12552: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12553: }
1.1069 www 12554: if ($#impfilepartids>=0) {
12555: # This problem had parts
1.1070 www 12556: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 12557: } else {
12558: # Importing by turning a single problem into a problem part
12559: # It gets the import-tags ID as part-ID
12560: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 12561: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 12562: }
1.1068 www 12563: } else {
1.1374 raeburn 12564: # Import as problem or as normal import
12565: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12566: unless ($importmode eq 'problem') {
1.1068 www 12567: # Normal import
1.1374 raeburn 12568: if (defined($token->[2]->{'id'})) {
12569: $unikey.='_'.$token->[2]->{'id'};
12570: }
12571: }
12572: # Check metadata for imported file to
12573: # see if it contained parts
12574: if (grep(/^partorder$/,@libfilekeys)) {
12575: %currmetaentry = %metaentry;
12576: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12577: $depthcount+1);
12578: %metaentry = %currmetaentry;
12579: undef(%currmetaentry);
12580: if ($libpartorder ne '') {
12581: $importedparts = 1;
12582: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12583: }
12584: }
1.1067 www 12585: }
1.339 albertel 12586: if ($depthcount<20) {
1.736 albertel 12587: my $metadata =
1.1362 raeburn 12588: &metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736 albertel 12589: $depthcount+1);
12590: foreach my $meta (split(',',$metadata)) {
12591: $metaentry{':'.$meta}=$metaentry{':'.$meta};
12592: $metathesekeys{$meta}=1;
1.339 albertel 12593: }
1.1068 www 12594: }
1.1067 www 12595: } else {
12596: #
12597: # Not importing, some other kind of non-package, non-library start tag
12598: #
12599: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12600: if (defined($token->[2]->{'id'})) {
12601: $unikey.='_'.$token->[2]->{'id'};
12602: }
1.339 albertel 12603: if (defined($token->[2]->{'name'})) {
12604: $unikey.='_'.$token->[2]->{'name'};
12605: }
12606: $metathesekeys{$unikey}=1;
1.736 albertel 12607: foreach my $param (@{$token->[3]}) {
12608: $metaentry{':'.$unikey.'.'.$param} =
12609: $token->[2]->{$param};
1.339 albertel 12610: }
12611: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 12612: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 12613: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12614: # only ws inside the tag, and not in default, so use default
12615: # as value
1.599 albertel 12616: $metaentry{':'.$unikey}=$default;
1.908 albertel 12617: } elsif ( $internaltext =~ /\S/ ) {
12618: # something interesting inside the tag
12619: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 12620: } else {
1.908 albertel 12621: # no interesting values, don't set a default
1.339 albertel 12622: }
1.172 www 12623: # end of not-a-package not-a-library import
1.339 albertel 12624: }
1.172 www 12625: # end of not-a-package start tag
1.339 albertel 12626: }
1.172 www 12627: # the next is the end of "start tag"
1.339 albertel 12628: }
12629: }
1.483 albertel 12630: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 12631: $extension = lc($extension);
12632: if ($extension eq 'htm') { $extension='html'; }
12633:
1.737 albertel 12634: foreach my $key (keys(%packagetab)) {
1.483 albertel 12635: #no specific packages #how's our extension
12636: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 12637: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 12638: \%metathesekeys);
12639: }
1.883 albertel 12640:
12641: if (!exists($metaentry{':packages'})
12642: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 12643: foreach my $key (keys(%packagetab)) {
1.483 albertel 12644: #no specific packages well let's get default then
12645: if ($key!~/^default&/) { next; }
1.488 albertel 12646: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 12647: \%metathesekeys);
12648: }
12649: }
1.338 www 12650: # are there custom rights to evaluate
1.599 albertel 12651: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 12652:
1.338 www 12653: #
12654: # Importing a rights file here
1.339 albertel 12655: #
12656: unless ($depthcount) {
1.599 albertel 12657: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 12658: my $dir=$filename;
12659: $dir=~s|[^/]*$||;
12660: $location=&filelocation($dir,$location);
1.736 albertel 12661: my $rights_metadata =
1.1362 raeburn 12662: &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736 albertel 12663: $depthcount+1);
12664: foreach my $rights (split(',',$rights_metadata)) {
12665: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12666: $metathesekeys{$rights}=1;
1.339 albertel 12667: }
12668: }
12669: }
1.737 albertel 12670: # uniqifiy package listing
12671: my %seen;
12672: my @uniq_packages =
12673: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12674: $metaentry{':packages'} = join(',',@uniq_packages);
12675:
1.1369 raeburn 12676: if (($importedresponses) || ($importedparts)) {
12677: if ($importedparts) {
1.1070 www 12678: # We had imported parts and need to rebuild partorder
1.1369 raeburn 12679: $metaentry{':partorder'}='';
12680: $metathesekeys{'partorder'}=1;
12681: }
12682: if ($importedresponses) {
12683: # We had imported responses and need to rebuil responseorder
12684: $metaentry{':responseorder'}='';
12685: $metathesekeys{'responseorder'}=1;
12686: }
12687: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12688: my $origid = $origfiletagids[$index+1];
12689: if ($origfiletagids[$index] eq 'part') {
12690: # Original part, part of the problem
12691: if ($importedparts) {
12692: $metaentry{':partorder'}.=','.$origid;
12693: }
12694: } elsif ($origfiletagids[$index] eq 'import') {
12695: if ($importedparts) {
12696: # We have imported parts at this position
1.1373 raeburn 12697: if ($importedpartids{$origid} ne '') {
12698: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12699: }
1.1369 raeburn 12700: }
12701: if ($importedresponses) {
12702: # We have imported responses at this position
1.1373 raeburn 12703: if ($importedrespids{$origid} ne '') {
12704: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369 raeburn 12705: }
12706: }
12707: } else {
12708: # Original response item, part of the problem
12709: if ($importedresponses) {
12710: $metaentry{':responseorder'}.=','.$origid;
12711: }
12712: }
12713: }
12714: if ($importedparts) {
12715: $metaentry{':partorder'}=~s/^\,//;
12716: }
12717: if ($importedresponses) {
12718: $metaentry{':responseorder'}=~s/^\,//;
12719: }
1.1070 www 12720: }
1.737 albertel 12721: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12722: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 12723: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371 raeburn 12724: unless ($liburi) {
12725: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12726: }
1.177 www 12727: # this is the end of "was not already recently cached
1.71 www 12728: }
1.599 albertel 12729: return $metaentry{':'.$what};
1.261 albertel 12730: }
12731:
1.488 albertel 12732: sub metadata_create_package_def {
1.483 albertel 12733: my ($uri,$key,$package,$metathesekeys)=@_;
12734: my ($pack,$name,$subp)=split(/\&/,$key);
12735: if ($subp eq 'default') { next; }
12736:
1.599 albertel 12737: if (defined($metaentry{':packages'})) {
12738: $metaentry{':packages'}.=','.$package;
1.483 albertel 12739: } else {
1.599 albertel 12740: $metaentry{':packages'}=$package;
1.483 albertel 12741: }
12742: my $value=$packagetab{$key};
12743: my $unikey;
12744: $unikey='parameter_0_'.$name;
1.599 albertel 12745: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12746: $$metathesekeys{$unikey}=1;
1.599 albertel 12747: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12748: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12749: }
1.599 albertel 12750: if (defined($metaentry{':'.$unikey.'.default'})) {
12751: $metaentry{':'.$unikey}=
12752: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12753: }
12754: }
12755:
1.261 albertel 12756: sub metadata_generate_part0 {
12757: my ($metadata,$metacache,$uri) = @_;
12758: my %allnames;
1.737 albertel 12759: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 12760: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 12761: my $part=$$metacache{':'.$metakey.'.part'};
12762: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 12763: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 12764: $allnames{$name}=$part;
12765: }
12766: }
12767: }
12768: foreach my $name (keys(%allnames)) {
12769: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 12770: my $key=":parameter_0_$name";
1.261 albertel 12771: $$metacache{"$key.part"}='0';
12772: $$metacache{"$key.name"}=$name;
1.428 albertel 12773: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 12774: $allnames{$name}.'_'.$name.
12775: '.type'};
1.428 albertel 12776: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 12777: '.display'};
1.644 www 12778: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 12779: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 12780: $$metacache{"$key.display"}=$olddis;
12781: }
1.71 www 12782: }
12783:
1.764 albertel 12784: # ------------------------------------------------------ Devalidate title cache
12785:
12786: sub devalidate_title_cache {
12787: my ($url)=@_;
12788: if (!$env{'request.course.id'}) { return; }
12789: my $symb=&symbread($url);
12790: if (!$symb) { return; }
12791: my $key=$env{'request.course.id'}."\0".$symb;
12792: &devalidate_cache_new('title',$key);
12793: }
12794:
1.1014 droeschl 12795: # ------------------------------------------------- Get the title of a course
12796:
12797: sub current_course_title {
12798: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12799: }
1.301 www 12800: # ------------------------------------------------- Get the title of a resource
12801:
12802: sub gettitle {
12803: my $urlsymb=shift;
12804: my $symb=&symbread($urlsymb);
1.534 albertel 12805: if ($symb) {
1.620 albertel 12806: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12807: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12808: if (defined($cached)) {
12809: return $result;
12810: }
1.534 albertel 12811: my ($map,$resid,$url)=&decode_symb($symb);
12812: my $title='';
1.907 albertel 12813: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12814: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12815: } else {
12816: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12817: &GDBM_READER(),0640)) {
12818: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12819: $title=$bighash{'title_'.$mapid.'.'.$resid};
12820: untie(%bighash);
12821: }
1.534 albertel 12822: }
12823: $title=~s/\&colon\;/\:/gs;
12824: if ($title) {
1.1159 www 12825: # Remember both $symb and $title for dynamic metadata
12826: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12827: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12828: # Cache this title and then return it
1.599 albertel 12829: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12830: }
12831: $urlsymb=$url;
12832: }
12833: my $title=&metadata($urlsymb,'title');
12834: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12835: return $title;
1.301 www 12836: }
1.613 albertel 12837:
1.614 albertel 12838: sub get_slot {
12839: my ($which,$cnum,$cdom)=@_;
12840: if (!$cnum || !$cdom) {
1.790 albertel 12841: (undef,my $courseid)=&whichuser();
1.620 albertel 12842: $cdom=$env{'course.'.$courseid.'.domain'};
12843: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 12844: }
1.703 albertel 12845: my $key=join("\0",'slots',$cdom,$cnum,$which);
12846: my %slotinfo;
12847: if (exists($remembered{$key})) {
12848: $slotinfo{$which} = $remembered{$key};
12849: } else {
12850: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12851: &Apache::lonhomework::showhash(%slotinfo);
12852: my ($tmp)=keys(%slotinfo);
12853: if ($tmp=~/^error:/) { return (); }
12854: $remembered{$key} = $slotinfo{$which};
12855: }
1.616 albertel 12856: if (ref($slotinfo{$which}) eq 'HASH') {
12857: return %{$slotinfo{$which}};
12858: }
12859: return $slotinfo{$which};
1.614 albertel 12860: }
1.1150 raeburn 12861:
12862: sub get_reservable_slots {
12863: my ($cnum,$cdom,$uname,$udom) = @_;
12864: my $now = time;
12865: my $reservable_info;
12866: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12867: if (exists($remembered{$key})) {
12868: $reservable_info = $remembered{$key};
12869: } else {
12870: my %resv;
12871: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12872: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12873: $reservable_info = \%resv;
12874: $remembered{$key} = $reservable_info;
12875: }
12876: return $reservable_info;
12877: }
12878:
12879: sub get_course_slots {
12880: my ($cnum,$cdom) = @_;
12881: my $hashid=$cnum.':'.$cdom;
12882: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12883: if (defined($cached)) {
12884: if (ref($result) eq 'HASH') {
12885: return %{$result};
12886: }
12887: } else {
12888: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12889: my ($tmp) = keys(%slots);
12890: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 12891: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 12892: return %slots;
12893: }
12894: }
12895: return;
12896: }
12897:
12898: sub devalidate_slots_cache {
12899: my ($cnum,$cdom)=@_;
12900: my $hashid=$cnum.':'.$cdom;
12901: &devalidate_cache_new('allslots',$hashid);
12902: }
12903:
1.1181 raeburn 12904: sub get_coursechange {
12905: my ($cdom,$cnum) = @_;
12906: if ($cdom eq '' || $cnum eq '') {
12907: return unless ($env{'request.course.id'});
12908: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12909: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12910: }
12911: my $hashid=$cdom.'_'.$cnum;
12912: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12913: if ((defined($cached)) && ($change ne '')) {
12914: return $change;
12915: } else {
12916: my %crshash;
12917: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12918: if ($crshash{'internal.contentchange'} eq '') {
12919: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12920: if ($change eq '') {
12921: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12922: $change = $crshash{'internal.created'};
12923: }
12924: } else {
12925: $change = $crshash{'internal.contentchange'};
12926: }
12927: my $cachetime = 600;
12928: &do_cache_new('crschange',$hashid,$change,$cachetime);
12929: }
12930: return $change;
12931: }
12932:
12933: sub devalidate_coursechange_cache {
12934: my ($cnum,$cdom)=@_;
12935: my $hashid=$cnum.':'.$cdom;
12936: &devalidate_cache_new('crschange',$hashid);
12937: }
12938:
1.31 www 12939: # ------------------------------------------------- Update symbolic store links
12940:
12941: sub symblist {
12942: my ($mapname,%newhash)=@_;
1.438 www 12943: $mapname=&deversion(&declutter($mapname));
1.31 www 12944: my %hash;
1.620 albertel 12945: if (($env{'request.course.fn'}) && (%newhash)) {
12946: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12947: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 12948: foreach my $url (keys(%newhash)) {
1.711 albertel 12949: next if ($url eq 'last_known'
12950: && $env{'form.no_update_last_known'});
12951: $hash{declutter($url)}=&encode_symb($mapname,
12952: $newhash{$url}->[1],
12953: $newhash{$url}->[0]);
1.191 harris41 12954: }
1.31 www 12955: if (untie(%hash)) {
12956: return 'ok';
12957: }
12958: }
12959: }
12960: return 'error';
1.212 www 12961: }
12962:
12963: # --------------------------------------------------------------- Verify a symb
12964:
12965: sub symbverify {
1.1190 raeburn 12966: my ($symb,$thisurl,$encstate)=@_;
1.510 www 12967: my $thisfn=$thisurl;
1.439 www 12968: $thisfn=&declutter($thisfn);
1.215 www 12969: # direct jump to resource in page or to a sequence - will construct own symbs
12970: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12971: # check URL part
1.409 www 12972: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12973:
1.431 www 12974: unless ($url eq $thisfn) { return 0; }
1.213 www 12975:
1.216 www 12976: $symb=&symbclean($symb);
1.510 www 12977: $thisurl=&deversion($thisurl);
1.439 www 12978: $thisfn=&deversion($thisfn);
1.213 www 12979:
12980: my %bighash;
12981: my $okay=0;
1.431 www 12982:
1.620 albertel 12983: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12984: &GDBM_READER(),0640)) {
1.1204 raeburn 12985: my $noclutter;
1.1032 raeburn 12986: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12987: $thisurl =~ s/\?.+$//;
1.1204 raeburn 12988: if ($map =~ m{^uploaded/.+\.page$}) {
12989: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12990: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12991: $noclutter = 1;
12992: }
12993: }
12994: my $ids;
12995: if ($noclutter) {
12996: $ids=$bighash{'ids_'.$thisurl};
12997: } else {
12998: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12999: }
1.1102 raeburn 13000: unless ($ids) {
13001: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
13002: $ids=$bighash{$idkey};
1.216 www 13003: }
13004: if ($ids) {
13005: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 13006: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 13007: $symb =~ s/\?.+$//;
1.1202 raeburn 13008: }
1.800 albertel 13009: foreach my $id (split(/\,/,$ids)) {
13010: my ($mapid,$resid)=split(/\./,$id);
1.216 www 13011: if (
13012: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 13013: eq $symb) {
13014: if (ref($encstate)) {
13015: $$encstate = $bighash{'encrypted_'.$id};
13016: }
1.620 albertel 13017: if (($env{'request.role.adv'}) ||
1.1101 raeburn 13018: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13019: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 13020: $okay=1;
1.1202 raeburn 13021: last;
1.582 albertel 13022: }
13023: }
1.216 www 13024: }
13025: }
1.213 www 13026: untie(%bighash);
13027: }
13028: return $okay;
1.31 www 13029: }
13030:
1.210 www 13031: # --------------------------------------------------------------- Clean-up symb
13032:
13033: sub symbclean {
13034: my $symb=shift;
1.568 albertel 13035: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 13036: # remove version from map
13037: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 13038:
1.210 www 13039: # remove version from URL
13040: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 13041:
1.507 www 13042: # remove wrapper
13043:
1.510 www 13044: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 13045: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 13046: return $symb;
1.409 www 13047: }
13048:
13049: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 13050:
13051: sub encode_symb {
13052: my ($map,$resid,$url)=@_;
13053: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13054: }
1.409 www 13055:
13056: sub decode_symb {
1.568 albertel 13057: my $symb=shift;
13058: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13059: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 13060: return (&fixversion($map),$resid,&fixversion($url));
13061: }
13062:
13063: sub fixversion {
13064: my $fn=shift;
1.609 banghart 13065: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 13066: my %bighash;
13067: my $uri=&clutter($fn);
1.620 albertel 13068: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 13069: # is this cached?
1.599 albertel 13070: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 13071: if (defined($cached)) { return $result; }
13072: # unfortunately not cached, or expired
1.620 albertel 13073: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 13074: &GDBM_READER(),0640)) {
13075: if ($bighash{'version_'.$uri}) {
13076: my $version=$bighash{'version_'.$uri};
1.444 www 13077: unless (($version eq 'mostrecent') ||
13078: ($version==&getversion($uri))) {
1.440 www 13079: $uri=~s/\.(\w+)$/\.$version\.$1/;
13080: }
13081: }
13082: untie %bighash;
1.413 www 13083: }
1.599 albertel 13084: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 13085: }
13086:
13087: sub deversion {
13088: my $url=shift;
13089: $url=~s/\.\d+\.(\w+)$/\.$1/;
13090: return $url;
1.210 www 13091: }
13092:
1.31 www 13093: # ------------------------------------------------------ Return symb list entry
13094:
13095: sub symbread {
1.1282 raeburn 13096: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 13097: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 13098: if (defined($env{$cache_str})) {
13099: if ($ignorecachednull) {
13100: return $env{$cache_str} unless ($env{$cache_str} eq '');
13101: } else {
13102: return $env{$cache_str};
13103: }
13104: }
1.242 www 13105: # no filename provided? try from environment
1.1265 raeburn 13106: unless ($thisfn) {
1.620 albertel 13107: if ($env{'request.symb'}) {
13108: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 13109: }
1.620 albertel 13110: $thisfn=$env{'request.filename'};
1.44 www 13111: }
1.569 albertel 13112: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 13113: # is that filename actually a symb? Verify, clean, and return
13114: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 13115: if (&symbverify($thisfn,$1)) {
1.620 albertel 13116: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 13117: }
1.242 www 13118: }
1.44 www 13119: $thisfn=declutter($thisfn);
1.31 www 13120: my %hash;
1.37 www 13121: my %bighash;
13122: my $syval='';
1.620 albertel 13123: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 13124: my $targetfn = $thisfn;
1.609 banghart 13125: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 13126: $targetfn = 'adm/wrapper/'.$thisfn;
13127: }
1.687 albertel 13128: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13129: $targetfn=$1;
13130: }
1.620 albertel 13131: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 13132: &GDBM_READER(),0640)) {
1.481 raeburn 13133: $syval=$hash{$targetfn};
1.37 www 13134: untie(%hash);
13135: }
13136: # ---------------------------------------------------------- There was an entry
13137: if ($syval) {
1.601 albertel 13138: #unless ($syval=~/\_\d+$/) {
1.620 albertel 13139: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 13140: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13141: #return $env{$cache_str}='';
1.601 albertel 13142: #}
13143: #$syval.=$1;
13144: #}
1.37 www 13145: } else {
13146: # ------------------------------------------------------- Was not in symb table
1.620 albertel 13147: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13148: &GDBM_READER(),0640)) {
1.37 www 13149: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 13150: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 13151: unless ($ids) {
13152: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 13153: }
13154: unless ($ids) {
13155: # alias?
13156: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 13157: }
1.37 www 13158: if ($ids) {
13159: # ------------------------------------------------------------------- Has ID(s)
13160: my @possibilities=split(/\,/,$ids);
1.39 www 13161: if ($#possibilities==0) {
13162: # ----------------------------------------------- There is only one possibility
1.37 www 13163: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 13164: $syval=&encode_symb($bighash{'map_id_'.$mapid},
13165: $resid,$thisfn);
1.1282 raeburn 13166: if (ref($possibles) eq 'HASH') {
13167: $possibles->{$syval} = 1;
13168: }
13169: if ($checkforblock) {
13170: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
13171: if (@blockers) {
13172: $syval = '';
13173: return;
13174: }
13175: }
13176: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 13177: # ------------------------------------------ There is more than one possibility
13178: my $realpossible=0;
1.800 albertel 13179: foreach my $id (@possibilities) {
13180: my $file=$bighash{'src_'.$id};
1.1282 raeburn 13181: my $canaccess;
13182: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13183: $canaccess = 1;
13184: } else {
13185: $canaccess = &allowed('bre',$file);
13186: }
13187: if ($canaccess) {
13188: my ($mapid,$resid)=split(/\./,$id);
13189: if ($bighash{'map_type_'.$mapid} ne 'page') {
13190: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13191: $resid,$thisfn);
13192: if (ref($possibles) eq 'HASH') {
13193: $possibles->{$syval} = 1;
13194: }
13195: if ($checkforblock) {
13196: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
13197: unless (@blockers > 0) {
13198: $syval = $poss_syval;
13199: $realpossible++;
13200: }
13201: } else {
13202: $syval = $poss_syval;
13203: $realpossible++;
13204: }
13205: }
1.39 www 13206: }
1.191 harris41 13207: }
1.39 www 13208: if ($realpossible!=1) { $syval=''; }
1.249 www 13209: } else {
13210: $syval='';
1.37 www 13211: }
13212: }
1.1282 raeburn 13213: untie(%bighash);
1.481 raeburn 13214: }
1.31 www 13215: }
1.62 www 13216: if ($syval) {
1.620 albertel 13217: return $env{$cache_str}=$syval;
1.62 www 13218: }
1.31 www 13219: }
1.949 raeburn 13220: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13221: return $env{$cache_str}='';
1.31 www 13222: }
13223:
13224: # ---------------------------------------------------------- Return random seed
13225:
1.32 www 13226: sub numval {
13227: my $txt=shift;
13228: $txt=~tr/A-J/0-9/;
13229: $txt=~tr/a-j/0-9/;
13230: $txt=~tr/K-T/0-9/;
13231: $txt=~tr/k-t/0-9/;
13232: $txt=~tr/U-Z/0-5/;
13233: $txt=~tr/u-z/0-5/;
13234: $txt=~s/\D//g;
1.564 albertel 13235: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 13236: return int($txt);
1.368 albertel 13237: }
13238:
1.484 albertel 13239: sub numval2 {
13240: my $txt=shift;
13241: $txt=~tr/A-J/0-9/;
13242: $txt=~tr/a-j/0-9/;
13243: $txt=~tr/K-T/0-9/;
13244: $txt=~tr/k-t/0-9/;
13245: $txt=~tr/U-Z/0-5/;
13246: $txt=~tr/u-z/0-5/;
13247: $txt=~s/\D//g;
13248: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13249: my $total;
13250: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 13251: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 13252: return int($total);
13253: }
13254:
1.575 albertel 13255: sub numval3 {
13256: use integer;
13257: my $txt=shift;
13258: $txt=~tr/A-J/0-9/;
13259: $txt=~tr/a-j/0-9/;
13260: $txt=~tr/K-T/0-9/;
13261: $txt=~tr/k-t/0-9/;
13262: $txt=~tr/U-Z/0-5/;
13263: $txt=~tr/u-z/0-5/;
13264: $txt=~s/\D//g;
13265: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13266: my $total;
13267: foreach my $val (@txts) { $total+=$val; }
13268: if ($_64bit) { $total=(($total<<32)>>32); }
13269: return $total;
13270: }
13271:
1.675 albertel 13272: sub digest {
13273: my ($data)=@_;
13274: my $digest=&Digest::MD5::md5($data);
13275: my ($a,$b,$c,$d)=unpack("iiii",$digest);
13276: my ($e,$f);
13277: {
13278: use integer;
13279: $e=($a+$b);
13280: $f=($c+$d);
13281: if ($_64bit) {
13282: $e=(($e<<32)>>32);
13283: $f=(($f<<32)>>32);
13284: }
13285: }
13286: if (wantarray) {
13287: return ($e,$f);
13288: } else {
13289: my $g;
13290: {
13291: use integer;
13292: $g=($e+$f);
13293: if ($_64bit) {
13294: $g=(($g<<32)>>32);
13295: }
13296: }
13297: return $g;
13298: }
13299: }
13300:
1.368 albertel 13301: sub latest_rnd_algorithm_id {
1.675 albertel 13302: return '64bit5';
1.366 albertel 13303: }
1.32 www 13304:
1.503 albertel 13305: sub get_rand_alg {
13306: my ($courseid)=@_;
1.790 albertel 13307: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 13308: if ($courseid) {
1.620 albertel 13309: return $env{"course.$courseid.rndseed"};
1.503 albertel 13310: }
13311: return &latest_rnd_algorithm_id();
13312: }
13313:
1.562 albertel 13314: sub validCODE {
13315: my ($CODE)=@_;
13316: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13317: return 0;
13318: }
13319:
1.491 albertel 13320: sub getCODE {
1.620 albertel 13321: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 13322: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13323: defined($Apache::lonhomework::parsing_a_task) ) &&
13324: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 13325: return $Apache::lonhomework::history{'resource.CODE'};
13326: }
13327: return undef;
13328: }
1.1133 foxr 13329: #
13330: # Determines the random seed for a specific context:
13331: #
13332: # parameters:
13333: # symb - in course context the symb for the seed.
13334: # course_id - The course id of the form domain_coursenum.
13335: # domain - Domain for the user.
13336: # course - Course for the user.
13337: # cenv - environment of the course.
13338: #
13339: # NOTE:
13340: # All parameters are picked out of the environment if missing
13341: # or not defined.
13342: # If a symb cannot be determined the current time is used instead.
13343: #
13344: # For a given well defined symb, courside, domain, username,
13345: # and course environment, the seed is reproducible.
13346: #
1.31 www 13347: sub rndseed {
1.1133 foxr 13348: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 13349: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 13350: if (!defined($symb)) {
1.366 albertel 13351: unless ($symb=$wsymb) { return time; }
13352: }
1.1146 foxr 13353: if (!defined $courseid) {
13354: $courseid=$wcourseid;
13355: }
13356: if (!defined $domain) { $domain=$wdomain; }
13357: if (!defined $username) { $username=$wusername }
1.1133 foxr 13358:
13359: my $which;
13360: if (defined($cenv->{'rndseed'})) {
13361: $which = $cenv->{'rndseed'};
13362: } else {
13363: $which =&get_rand_alg($courseid);
13364: }
1.491 albertel 13365: if (defined(&getCODE())) {
1.1133 foxr 13366:
1.675 albertel 13367: if ($which eq '64bit5') {
13368: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13369: } elsif ($which eq '64bit4') {
1.575 albertel 13370: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13371: } else {
13372: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13373: }
1.675 albertel 13374: } elsif ($which eq '64bit5') {
13375: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 13376: } elsif ($which eq '64bit4') {
13377: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 13378: } elsif ($which eq '64bit3') {
13379: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 13380: } elsif ($which eq '64bit2') {
13381: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 13382: } elsif ($which eq '64bit') {
13383: return &rndseed_64bit($symb,$courseid,$domain,$username);
13384: }
13385: return &rndseed_32bit($symb,$courseid,$domain,$username);
13386: }
13387:
13388: sub rndseed_32bit {
13389: my ($symb,$courseid,$domain,$username)=@_;
13390: {
13391: use integer;
13392: my $symbchck=unpack("%32C*",$symb) << 27;
13393: my $symbseed=numval($symb) << 22;
13394: my $namechck=unpack("%32C*",$username) << 17;
13395: my $nameseed=numval($username) << 12;
13396: my $domainseed=unpack("%32C*",$domain) << 7;
13397: my $courseseed=unpack("%32C*",$courseid);
13398: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 13399: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13400: #&logthis("rndseed :$num:$symb");
1.564 albertel 13401: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 13402: return $num;
13403: }
13404: }
13405:
13406: sub rndseed_64bit {
13407: my ($symb,$courseid,$domain,$username)=@_;
13408: {
13409: use integer;
13410: my $symbchck=unpack("%32S*",$symb) << 21;
13411: my $symbseed=numval($symb) << 10;
13412: my $namechck=unpack("%32S*",$username);
13413:
13414: my $nameseed=numval($username) << 21;
13415: my $domainseed=unpack("%32S*",$domain) << 10;
13416: my $courseseed=unpack("%32S*",$courseid);
13417:
13418: my $num1=$symbchck+$symbseed+$namechck;
13419: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13420: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13421: #&logthis("rndseed :$num:$symb");
1.564 albertel 13422: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 13423: return "$num1,$num2";
1.155 albertel 13424: }
1.366 albertel 13425: }
13426:
1.443 albertel 13427: sub rndseed_64bit2 {
13428: my ($symb,$courseid,$domain,$username)=@_;
13429: {
13430: use integer;
13431: # strings need to be an even # of cahracters long, it it is odd the
13432: # last characters gets thrown away
13433: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13434: my $symbseed=numval($symb) << 10;
13435: my $namechck=unpack("%32S*",$username.' ');
13436:
13437: my $nameseed=numval($username) << 21;
1.501 albertel 13438: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13439: my $courseseed=unpack("%32S*",$courseid.' ');
13440:
13441: my $num1=$symbchck+$symbseed+$namechck;
13442: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13443: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13444: #&logthis("rndseed :$num:$symb");
1.803 albertel 13445: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 13446: return "$num1,$num2";
13447: }
13448: }
13449:
13450: sub rndseed_64bit3 {
13451: my ($symb,$courseid,$domain,$username)=@_;
13452: {
13453: use integer;
13454: # strings need to be an even # of cahracters long, it it is odd the
13455: # last characters gets thrown away
13456: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13457: my $symbseed=numval2($symb) << 10;
13458: my $namechck=unpack("%32S*",$username.' ');
13459:
13460: my $nameseed=numval2($username) << 21;
1.443 albertel 13461: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13462: my $courseseed=unpack("%32S*",$courseid.' ');
13463:
13464: my $num1=$symbchck+$symbseed+$namechck;
13465: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13466: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13467: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 13468: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13469:
1.503 albertel 13470: return "$num1:$num2";
1.443 albertel 13471: }
13472: }
13473:
1.575 albertel 13474: sub rndseed_64bit4 {
13475: my ($symb,$courseid,$domain,$username)=@_;
13476: {
13477: use integer;
13478: # strings need to be an even # of cahracters long, it it is odd the
13479: # last characters gets thrown away
13480: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13481: my $symbseed=numval3($symb) << 10;
13482: my $namechck=unpack("%32S*",$username.' ');
13483:
13484: my $nameseed=numval3($username) << 21;
13485: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13486: my $courseseed=unpack("%32S*",$courseid.' ');
13487:
13488: my $num1=$symbchck+$symbseed+$namechck;
13489: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13490: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13491: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 13492: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13493:
1.575 albertel 13494: return "$num1:$num2";
13495: }
13496: }
13497:
1.675 albertel 13498: sub rndseed_64bit5 {
13499: my ($symb,$courseid,$domain,$username)=@_;
13500: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13501: return "$num1:$num2";
13502: }
13503:
1.366 albertel 13504: sub rndseed_CODE_64bit {
13505: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 13506: {
1.366 albertel 13507: use integer;
1.443 albertel 13508: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 13509: my $symbseed=numval2($symb);
1.491 albertel 13510: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13511: my $CODEseed=numval(&getCODE());
1.443 albertel 13512: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 13513: my $num1=$symbseed+$CODEchck;
13514: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13515: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13516: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 13517: if ($_64bit) { $num1=(($num1<<32)>>32); }
13518: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 13519: return "$num1:$num2";
1.366 albertel 13520: }
13521: }
13522:
1.575 albertel 13523: sub rndseed_CODE_64bit4 {
13524: my ($symb,$courseid,$domain,$username)=@_;
13525: {
13526: use integer;
13527: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13528: my $symbseed=numval3($symb);
13529: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13530: my $CODEseed=numval3(&getCODE());
13531: my $courseseed=unpack("%32S*",$courseid.' ');
13532: my $num1=$symbseed+$CODEchck;
13533: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13534: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13535: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 13536: if ($_64bit) { $num1=(($num1<<32)>>32); }
13537: if ($_64bit) { $num2=(($num2<<32)>>32); }
13538: return "$num1:$num2";
13539: }
13540: }
13541:
1.675 albertel 13542: sub rndseed_CODE_64bit5 {
13543: my ($symb,$courseid,$domain,$username)=@_;
13544: my $code = &getCODE();
13545: my ($num1,$num2)=&digest("$symb,$courseid,$code");
13546: return "$num1:$num2";
13547: }
13548:
1.366 albertel 13549: sub setup_random_from_rndseed {
13550: my ($rndseed)=@_;
1.503 albertel 13551: if ($rndseed =~/([,:])/) {
1.1262 raeburn 13552: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13553: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13554: &Math::Random::random_set_seed_from_phrase($rndseed);
13555: } else {
13556: &Math::Random::random_set_seed($num1,$num2);
13557: }
1.366 albertel 13558: } else {
13559: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 13560: }
1.36 albertel 13561: }
13562:
1.474 albertel 13563: sub latest_receipt_algorithm_id {
1.835 albertel 13564: return 'receipt3';
1.474 albertel 13565: }
13566:
1.480 www 13567: sub recunique {
13568: my $fucourseid=shift;
13569: my $unique;
1.835 albertel 13570: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13571: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13572: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 13573: } else {
13574: $unique=$perlvar{'lonReceipt'};
13575: }
13576: return unpack("%32C*",$unique);
13577: }
13578:
13579: sub recprefix {
13580: my $fucourseid=shift;
13581: my $prefix;
1.835 albertel 13582: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13583: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13584: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 13585: } else {
13586: $prefix=$perlvar{'lonHostID'};
13587: }
13588: return unpack("%32C*",$prefix);
13589: }
13590:
1.76 www 13591: sub ireceipt {
1.474 albertel 13592: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 13593:
13594: my $return =&recprefix($fucourseid).'-';
13595:
13596: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13597: $env{'request.state'} eq 'construct') {
13598: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13599: return $return;
13600: }
13601:
1.76 www 13602: my $cuname=unpack("%32C*",$funame);
13603: my $cudom=unpack("%32C*",$fudom);
13604: my $cucourseid=unpack("%32C*",$fucourseid);
13605: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 13606: my $cunique=&recunique($fucourseid);
1.474 albertel 13607: my $cpart=unpack("%32S*",$part);
1.835 albertel 13608: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13609:
1.790 albertel 13610: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 13611:
13612: $return.= ($cunique%$cuname+
13613: $cunique%$cudom+
13614: $cusymb%$cuname+
13615: $cusymb%$cudom+
13616: $cucourseid%$cuname+
13617: $cucourseid%$cudom+
13618: $cpart%$cuname+
13619: $cpart%$cudom);
13620: } else {
13621: $return.= ($cunique%$cuname+
13622: $cunique%$cudom+
13623: $cusymb%$cuname+
13624: $cusymb%$cudom+
13625: $cucourseid%$cuname+
13626: $cucourseid%$cudom);
13627: }
13628: return $return;
1.76 www 13629: }
13630:
13631: sub receipt {
1.474 albertel 13632: my ($part)=@_;
1.790 albertel 13633: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 13634: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 13635: }
1.260 ng 13636:
1.790 albertel 13637: sub whichuser {
13638: my ($passedsymb)=@_;
13639: my ($symb,$courseid,$domain,$name,$publicuser);
13640: if (defined($env{'form.grade_symb'})) {
13641: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13642: my $allowed=&allowed('vgr',$tmp_courseid);
13643: if (!$allowed &&
13644: exists($env{'request.course.sec'}) &&
13645: $env{'request.course.sec'} !~ /^\s*$/) {
13646: $allowed=&allowed('vgr',$tmp_courseid.
13647: '/'.$env{'request.course.sec'});
13648: }
13649: if ($allowed) {
13650: ($symb)=&get_env_multiple('form.grade_symb');
13651: $courseid=$tmp_courseid;
13652: ($domain)=&get_env_multiple('form.grade_domain');
13653: ($name)=&get_env_multiple('form.grade_username');
13654: return ($symb,$courseid,$domain,$name,$publicuser);
13655: }
13656: }
13657: if (!$passedsymb) {
13658: $symb=&symbread();
13659: } else {
13660: $symb=$passedsymb;
13661: }
13662: $courseid=$env{'request.course.id'};
13663: $domain=$env{'user.domain'};
13664: $name=$env{'user.name'};
13665: if ($name eq 'public' && $domain eq 'public') {
13666: if (!defined($env{'form.username'})) {
13667: $env{'form.username'}.=time.rand(10000000);
13668: }
13669: $name.=$env{'form.username'};
13670: }
13671: return ($symb,$courseid,$domain,$name,$publicuser);
13672:
13673: }
13674:
1.36 albertel 13675: # ------------------------------------------------------------ Serves up a file
1.472 albertel 13676: # returns either the contents of the file or
13677: # -1 if the file doesn't exist
1.481 raeburn 13678: #
13679: # if the target is a file that was uploaded via DOCS,
13680: # a check will be made to see if a current copy exists on the local server,
13681: # if it does this will be served, otherwise a copy will be retrieved from
13682: # the home server for the course and stored in /home/httpd/html/userfiles on
13683: # the local server.
1.472 albertel 13684:
1.36 albertel 13685: sub getfile {
1.538 albertel 13686: my ($file) = @_;
1.609 banghart 13687: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 13688: &repcopy($file);
13689: return &readfile($file);
13690: }
13691:
13692: sub repcopy_userfile {
13693: my ($file)=@_;
1.1142 raeburn 13694: my $londocroot = $perlvar{'lonDocRoot'};
13695: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 13696: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 13697: my ($cdom,$cnum,$filename) =
1.811 albertel 13698: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 13699: my $uri="/uploaded/$cdom/$cnum/$filename";
13700: if (-e "$file") {
1.828 www 13701: # we already have a local copy, check it out
1.538 albertel 13702: my @fileinfo = stat($file);
1.828 www 13703: my $rtncode;
13704: my $info;
1.538 albertel 13705: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 13706: if ($lwpresp ne 'ok') {
1.828 www 13707: # there is no such file anymore, even though we had a local copy
1.482 albertel 13708: if ($rtncode eq '404') {
1.538 albertel 13709: unlink($file);
1.482 albertel 13710: }
13711: return -1;
13712: }
13713: if ($info < $fileinfo[9]) {
1.828 www 13714: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 13715: return 'ok';
1.828 www 13716: } else {
13717: # the file is outdated, get rid of it
13718: unlink($file);
1.482 albertel 13719: }
1.828 www 13720: }
13721: # one way or the other, at this point, we don't have the file
13722: # construct the correct path for the file
13723: my @parts = ($cdom,$cnum);
13724: if ($filename =~ m|^(.+)/[^/]+$|) {
13725: push @parts, split(/\//,$1);
13726: }
13727: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13728: foreach my $part (@parts) {
13729: $path .= '/'.$part;
13730: if (!-e $path) {
13731: mkdir($path,0770);
1.482 albertel 13732: }
13733: }
1.828 www 13734: # now the path exists for sure
13735: # get a user agent
13736: my $transferfile=$file.'.in.transfer';
13737: # FIXME: this should flock
13738: if (-e $transferfile) { return 'ok'; }
13739: my $request;
13740: $uri=~s/^\///;
1.980 raeburn 13741: my $homeserver = &homeserver($cnum,$cdom);
1.1398 raeburn 13742: my $hostname = &hostname($homeserver);
1.980 raeburn 13743: my $protocol = $protocol{$homeserver};
13744: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 13745: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345 raeburn 13746: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828 www 13747: # did it work?
13748: if ($response->is_error()) {
13749: unlink($transferfile);
13750: &logthis("Userfile repcopy failed for $uri");
13751: return -1;
13752: }
13753: # worked, rename the transfer file
13754: rename($transferfile,$file);
1.607 raeburn 13755: return 'ok';
1.481 raeburn 13756: }
13757:
1.517 albertel 13758: sub tokenwrapper {
13759: my $uri=shift;
1.980 raeburn 13760: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 13761: $uri=~s|^/||;
1.620 albertel 13762: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 13763: my $token=$1;
1.552 albertel 13764: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13765: if ($udom && $uname && $file) {
13766: $file=~s|(\?\.*)*$||;
1.949 raeburn 13767: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 13768: my $homeserver = &homeserver($uname,$udom);
1.1397 raeburn 13769: my $hostname = &hostname($homeserver);
1.980 raeburn 13770: my $protocol = $protocol{$homeserver};
13771: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 13772: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 13773: (($uri=~/\?/)?'&':'?').'token='.$token.
13774: '&tokenissued='.$perlvar{'lonHostID'};
13775: } else {
13776: return '/adm/notfound.html';
13777: }
13778: }
13779:
1.828 www 13780: # call with reqtype HEAD: get last modification time
13781: # call with reqtype GET: get the file contents
13782: # Do not call this with reqtype GET for large files! It loads everything into memory
13783: #
1.481 raeburn 13784: sub getuploaded {
13785: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13786: $uri=~s/^\///;
1.980 raeburn 13787: my $homeserver = &homeserver($cnum,$cdom);
1.1397 raeburn 13788: my $hostname = &hostname($homeserver);
1.980 raeburn 13789: my $protocol = $protocol{$homeserver};
13790: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 13791: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 13792: my $request=new HTTP::Request($reqtype,$uri);
1.1345 raeburn 13793: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481 raeburn 13794: $$rtncode = $response->code;
1.482 albertel 13795: if (! $response->is_success()) {
13796: return 'failed';
13797: }
13798: if ($reqtype eq 'HEAD') {
1.486 www 13799: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13800: } elsif ($reqtype eq 'GET') {
13801: $$info = $response->content;
1.472 albertel 13802: }
1.482 albertel 13803: return 'ok';
1.36 albertel 13804: }
13805:
1.481 raeburn 13806: sub readfile {
13807: my $file = shift;
13808: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13809: my $fh;
1.1359 raeburn 13810: open($fh,"<",$file);
1.481 raeburn 13811: my $a='';
1.800 albertel 13812: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13813: return $a;
13814: }
13815:
1.36 albertel 13816: sub filelocation {
1.590 banghart 13817: my ($dir,$file) = @_;
13818: my $location;
13819: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13820:
13821: if ($file =~ m-^/adm/-) {
13822: $file=~s-^/adm/wrapper/-/-;
13823: $file=~s-^/adm/coursedocs/showdoc/-/-;
13824: }
1.882 albertel 13825:
1.1139 www 13826: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13827: $location = $file;
1.609 banghart 13828: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13829: my ($udom,$uname,$filename)=
1.811 albertel 13830: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13831: my $home=&homeserver($uname,$udom);
13832: my $is_me=0;
13833: my @ids=¤t_machine_ids();
13834: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13835: if ($is_me) {
1.1117 foxr 13836: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13837: } else {
13838: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13839: $udom.'/'.$uname.'/'.$filename;
13840: }
1.882 albertel 13841: } elsif ($file =~ m-^/adm/-) {
13842: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 13843: } else {
13844: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 13845: $file=~s:^/(res|priv)/:/:;
13846: my $space=$1;
1.590 banghart 13847: if ( !( $file =~ m:^/:) ) {
13848: $location = $dir. '/'.$file;
13849: } else {
1.1142 raeburn 13850: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 13851: }
1.59 albertel 13852: }
1.590 banghart 13853: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 13854: while ($location=~m{/\.\./}) {
13855: if ($location =~ m{/[^/]+/\.\./}) {
13856: $location=~ s{/[^/]+/\.\./}{/}g;
13857: } else {
13858: $location=~ s{/\.\./}{/}g;
13859: }
13860: } #remove dir/..
1.590 banghart 13861: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13862: return $location;
1.46 www 13863: }
1.36 albertel 13864:
1.46 www 13865: sub hreflocation {
13866: my ($dir,$file)=@_;
1.980 raeburn 13867: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 13868: $file=filelocation($dir,$file);
1.700 albertel 13869: } elsif ($file=~m-^/adm/-) {
13870: $file=~s-^/adm/wrapper/-/-;
13871: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 13872: }
13873: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13874: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13875: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 13876: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13877: {/uploaded/$1/$2/}x;
1.46 www 13878: }
1.913 albertel 13879: if ($file=~ m{^/userfiles/}) {
13880: $file =~ s{^/userfiles/}{/uploaded/};
13881: }
1.462 albertel 13882: return $file;
1.465 albertel 13883: }
13884:
1.1139 www 13885:
13886:
13887:
13888:
1.465 albertel 13889: sub current_machine_domains {
1.853 albertel 13890: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13891: }
13892:
13893: sub machine_domains {
13894: my ($hostname) = @_;
1.465 albertel 13895: my @domains;
1.838 albertel 13896: my %hostname = &all_hostnames();
1.465 albertel 13897: while( my($id, $name) = each(%hostname)) {
1.467 matthew 13898: # &logthis("-$id-$name-$hostname-");
1.465 albertel 13899: if ($hostname eq $name) {
1.844 albertel 13900: push(@domains,&host_domain($id));
1.465 albertel 13901: }
13902: }
13903: return @domains;
13904: }
13905:
13906: sub current_machine_ids {
1.853 albertel 13907: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13908: }
13909:
13910: sub machine_ids {
13911: my ($hostname) = @_;
13912: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 13913: my @ids;
1.888 albertel 13914: my %name_to_host = &all_names();
1.889 albertel 13915: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13916: return @{ $name_to_host{$hostname} };
13917: }
13918: return;
1.31 www 13919: }
13920:
1.824 raeburn 13921: sub additional_machine_domains {
13922: my @domains;
1.1359 raeburn 13923: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 13924: while( my $line = <$fh>) {
13925: $line =~ s/\s//g;
13926: push(@domains,$line);
13927: }
13928: return @domains;
13929: }
13930:
13931: sub default_login_domain {
13932: my $domain = $perlvar{'lonDefDomain'};
13933: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13934: foreach my $posdom (¤t_machine_domains(),
13935: &additional_machine_domains()) {
13936: if (lc($posdom) eq lc($testdomain)) {
13937: $domain=$posdom;
13938: last;
13939: }
13940: }
13941: return $domain;
13942: }
13943:
1.1398 raeburn 13944: sub uses_sts {
13945: my ($ignore_cache) = @_;
13946: my $lonhost = $perlvar{'lonHostID'};
13947: my $hostname = &hostname($lonhost);
13948: my $sts_on;
13949: if ($protocol{$lonhost} eq 'https') {
13950: my $cachetime = 12*3600;
13951: if (!$ignore_cache) {
13952: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13953: if (defined($cached)) {
13954: return $sts_on;
13955: }
13956: }
13957: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13958: my $request=new HTTP::Request('HEAD',$url);
13959: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
13960: if ($response->is_success) {
13961: my $has_sts = $response->header('Strict-Transport-Security');
13962: if ($has_sts eq '') {
13963: $sts_on = 0;
13964: } else {
13965: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13966: my $maxage = $1;
13967: if ($maxage) {
13968: $sts_on = 1;
13969: } else {
13970: $sts_on = 0;
13971: }
13972: } else {
13973: $sts_on = 0;
13974: }
13975: }
13976: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13977: }
13978: }
13979: return;
13980: }
13981:
1.31 www 13982: # ------------------------------------------------------------- Declutters URLs
13983:
13984: sub declutter {
13985: my $thisfn=shift;
1.569 albertel 13986: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 13987: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13988: $thisfn=~s{^/home/httpd/html}{};
13989: }
1.31 www 13990: $thisfn=~s/^\///;
1.697 albertel 13991: $thisfn=~s|^adm/wrapper/||;
13992: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 13993: $thisfn=~s/^res\///;
1.1172 bisitz 13994: $thisfn=~s/^priv\///;
1.1032 raeburn 13995: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13996: $thisfn=~s/\?.+$//;
13997: }
1.268 www 13998: return $thisfn;
13999: }
14000:
14001: # ------------------------------------------------------------- Clutter up URLs
14002:
14003: sub clutter {
14004: my $thisfn='/'.&declutter(shift);
1.887 albertel 14005: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 14006: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 14007: $thisfn='/res'.$thisfn;
14008: }
1.1031 raeburn 14009: if ($thisfn !~m|^/adm|) {
14010: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 14011: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 14012: } else {
14013: my ($ext) = ($thisfn =~ /\.(\w+)$/);
14014: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 14015: if ($embstyle eq 'ssi'
14016: || ($embstyle eq 'hdn')
14017: || ($embstyle eq 'rat')
14018: || ($embstyle eq 'prv')
14019: || ($embstyle eq 'ign')) {
14020: #do nothing with these
14021: } elsif (($embstyle eq 'img')
1.695 albertel 14022: || ($embstyle eq 'emb')
14023: || ($embstyle eq 'wrp')) {
14024: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 14025: } elsif ($embstyle eq 'unk'
14026: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 14027: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 14028: } else {
1.718 www 14029: # &logthis("Got a blank emb style");
1.695 albertel 14030: }
1.694 albertel 14031: }
1.1343 raeburn 14032: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 14033: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 14034: }
1.31 www 14035: return $thisfn;
1.12 www 14036: }
14037:
1.787 albertel 14038: sub clutter_with_no_wrapper {
14039: my $uri = &clutter(shift);
14040: if ($uri =~ m-^/adm/-) {
14041: $uri =~ s-^/adm/wrapper/-/-;
14042: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
14043: }
14044: return $uri;
14045: }
14046:
1.557 albertel 14047: sub freeze_escape {
14048: my ($value)=@_;
14049: if (ref($value)) {
14050: $value=&nfreeze($value);
14051: return '__FROZEN__'.&escape($value);
14052: }
14053: return &escape($value);
14054: }
14055:
1.11 www 14056:
1.557 albertel 14057: sub thaw_unescape {
14058: my ($value)=@_;
14059: if ($value =~ /^__FROZEN__/) {
14060: substr($value,0,10,undef);
14061: $value=&unescape($value);
14062: return &thaw($value);
14063: }
14064: return &unescape($value);
14065: }
14066:
1.436 albertel 14067: sub correct_line_ends {
14068: my ($result)=@_;
14069: $$result =~s/\r\n/\n/mg;
14070: $$result =~s/\r/\n/mg;
1.415 albertel 14071: }
1.1 albertel 14072: # ================================================================ Main Program
14073:
1.184 www 14074: sub goodbye {
1.204 albertel 14075: &logthis("Starting Shut down");
1.443 albertel 14076: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 14077: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 14078: #converted
1.599 albertel 14079: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 14080: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14081: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14082: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 14083: #1.1 only
1.870 albertel 14084: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14085: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14086: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14087: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14088: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 14089: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14090: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 14091: &flushcourselogs();
14092: &logthis("Shutting down");
14093: }
14094:
1.852 albertel 14095: sub get_dns {
1.1210 raeburn 14096: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 14097: if (!$ignore_cache) {
14098: my ($content,$cached)=
14099: &Apache::lonnet::is_cached_new('dns',$url);
14100: if ($cached) {
1.1210 raeburn 14101: &$func($content,$hashref);
1.869 albertel 14102: return;
14103: }
14104: }
14105:
14106: my %alldns;
1.1379 raeburn 14107: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14108: foreach my $dns (<$config>) {
14109: next if ($dns !~ /^\^(\S*)/x);
14110: my $line = $1;
14111: my ($host,$protocol) = split(/:/,$line);
14112: if ($protocol ne 'https') {
14113: $protocol = 'http';
14114: }
14115: $alldns{$host} = $protocol;
1.979 raeburn 14116: }
1.1379 raeburn 14117: close($config);
1.869 albertel 14118: }
14119: while (%alldns) {
1.1263 raeburn 14120: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979 raeburn 14121: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345 raeburn 14122: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979 raeburn 14123: delete($alldns{$dns});
1.852 albertel 14124: next if ($response->is_error());
1.1379 raeburn 14125: if ($url eq '/adm/dns/loncapaCRL') {
14126: return &$func($response);
14127: } else {
14128: my @content = split("\n",$response->content);
14129: unless ($nocache) {
14130: &do_cache_new('dns',$url,\@content,30*24*60*60);
14131: }
14132: &$func(\@content,$hashref);
14133: return;
14134: }
14135: }
14136: my $which = (split('/',$url,4))[3];
14137: if ($which eq 'loncapaCRL') {
14138: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14139: if (-e $diskfile) {
14140: &logthis("unable to contact DNS, on disk file $diskfile not updated");
14141: } else {
14142: &logthis("unable to contact DNS, no on disk file $diskfile available");
14143: }
14144: } else {
14145: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14146: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14147: my @content = <$config>;
14148: close($config);
14149: &$func(\@content,$hashref);
14150: }
1.852 albertel 14151: }
1.1210 raeburn 14152: return;
14153: }
14154:
14155: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 14156: sub parse_dns_checksums_tab {
1.1210 raeburn 14157: my ($lines,$hashref) = @_;
1.1264 raeburn 14158: my $lonhost = $perlvar{'lonHostID'};
14159: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 14160: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 14161: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14162: my $webconfdir = '/etc/httpd/conf';
14163: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14164: $webconfdir = '/etc/apache2';
14165: } elsif ($distro =~ /^sles(\d+)$/) {
14166: if ($1 >= 10) {
14167: $webconfdir = '/etc/apache2';
14168: }
14169: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14170: if ($1 >= 10.0) {
14171: $webconfdir = '/etc/apache2';
14172: }
14173: }
1.1210 raeburn 14174: my ($release,$timestamp) = split(/\-/,$loncaparev);
14175: my (%chksum,%revnum);
14176: if (ref($lines) eq 'ARRAY') {
14177: chomp(@{$lines});
1.1238 raeburn 14178: my $version = shift(@{$lines});
14179: if ($version eq $release) {
1.1210 raeburn 14180: foreach my $line (@{$lines}) {
1.1238 raeburn 14181: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 14182: if ($file =~ m{^/etc/httpd/conf}) {
14183: if ($webconfdir eq '/etc/apache2') {
14184: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14185: }
14186: }
1.1238 raeburn 14187: $chksum{$file} = $shasum;
14188: $revnum{$file} = $version;
1.1210 raeburn 14189: }
14190: if (ref($hashref) eq 'HASH') {
14191: %{$hashref} = (
14192: sums => \%chksum,
14193: versions => \%revnum,
14194: );
14195: }
14196: }
14197: }
1.869 albertel 14198: return;
1.852 albertel 14199: }
1.1210 raeburn 14200:
14201: sub fetch_dns_checksums {
1.1238 raeburn 14202: my %checksums;
14203: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 14204: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 14205: my ($release,$timestamp) = split(/\-/,$loncaparev);
14206: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 14207: \%checksums);
1.1210 raeburn 14208: return \%checksums;
14209: }
14210:
1.1379 raeburn 14211: sub fetch_crl_pemfile {
14212: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14213: }
14214:
14215: sub save_crl_pem {
14216: my ($response) = @_;
1.1380 raeburn 14217: my ($msg,$hadchanges);
1.1379 raeburn 14218: if (ref($response)) {
14219: my $now = time;
14220: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14221: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14222: if (open(my $fh,'>',"$tmpcrl")) {
14223: print $fh $response->content;
14224: close($fh);
14225: if (-e $lonca) {
14226: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14227: my $check = <PIPE>;
14228: close(PIPE);
14229: chomp($check);
14230: if ($check eq 'verify OK') {
14231: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380 raeburn 14232: my $backup;
1.1379 raeburn 14233: if (-e $dest) {
1.1380 raeburn 14234: if (&File::Copy::move($dest,"$dest.bak")) {
14235: $backup = 'ok';
14236: }
1.1379 raeburn 14237: }
14238: if (&File::Copy::move($tmpcrl,$dest)) {
14239: $msg = 'ok';
1.1380 raeburn 14240: if ($backup) {
14241: my (%oldnums,%newnums);
14242: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14243: while (<PIPE>) {
14244: $oldnums{(split(/:/))[1]} = 1;
14245: }
14246: close(PIPE);
14247: }
14248: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14249: while(<PIPE>) {
14250: $newnums{(split(/:/))[1]} = 1;
14251: }
14252: close(PIPE);
14253: }
14254: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14255: unless (exists($oldnums{$key})) {
14256: $hadchanges = 1;
14257: last;
14258: }
14259: }
14260: unless ($hadchanges) {
14261: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14262: unless (exists($newnums{$key})) {
14263: $hadchanges = 1;
14264: last;
14265: }
14266: }
14267: }
14268: }
1.1379 raeburn 14269: }
14270: } else {
14271: unlink($tmpcrl);
14272: }
14273: } else {
14274: unlink($tmpcrl);
14275: }
14276: } else {
14277: unlink($tmpcrl);
14278: }
14279: }
14280: }
1.1380 raeburn 14281: return ($msg,$hadchanges);
1.1379 raeburn 14282: }
14283:
1.327 albertel 14284: # ------------------------------------------------------------ Read domain file
14285: {
1.852 albertel 14286: my $loaded;
1.846 albertel 14287: my %domain;
14288:
1.852 albertel 14289: sub parse_domain_tab {
14290: my ($lines) = @_;
14291: foreach my $line (@$lines) {
14292: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 14293:
1.846 albertel 14294: chomp($line);
1.852 albertel 14295: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 14296: my %this_domain;
14297: foreach my $field ('description', 'auth_def', 'auth_arg_def',
14298: 'lang_def', 'city', 'longi', 'lati',
14299: 'primary') {
14300: $this_domain{$field} = shift(@elements);
14301: }
14302: $domain{$name} = \%this_domain;
1.852 albertel 14303: }
14304: }
1.864 albertel 14305:
14306: sub reset_domain_info {
14307: undef($loaded);
14308: undef(%domain);
14309: }
14310:
1.852 albertel 14311: sub load_domain_tab {
1.1293 raeburn 14312: my ($ignore_cache,$nocache) = @_;
14313: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 14314: my $fh;
1.1359 raeburn 14315: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 14316: my @lines = <$fh>;
14317: &parse_domain_tab(\@lines);
1.448 albertel 14318: }
1.852 albertel 14319: close($fh);
14320: $loaded = 1;
1.327 albertel 14321: }
1.846 albertel 14322:
14323: sub domain {
1.852 albertel 14324: &load_domain_tab() if (!$loaded);
14325:
1.846 albertel 14326: my ($name,$what) = @_;
14327: return if ( !exists($domain{$name}) );
14328:
14329: if (!$what) {
14330: return $domain{$name}{'description'};
14331: }
14332: return $domain{$name}{$what};
14333: }
1.974 raeburn 14334:
14335: sub domain_info {
14336: &load_domain_tab() if (!$loaded);
14337: return %domain;
14338: }
14339:
1.327 albertel 14340: }
14341:
14342:
1.1 albertel 14343: # ------------------------------------------------------------- Read hosts file
14344: {
1.838 albertel 14345: my %hostname;
1.844 albertel 14346: my %hostdom;
1.845 albertel 14347: my %libserv;
1.852 albertel 14348: my $loaded;
1.888 albertel 14349: my %name_to_host;
1.1074 raeburn 14350: my %internetdom;
1.1107 raeburn 14351: my %LC_dns_serv;
1.852 albertel 14352:
14353: sub parse_hosts_tab {
14354: my ($file) = @_;
14355: foreach my $configline (@$file) {
14356: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 14357: chomp($configline);
14358: if ($configline =~ /^\^/) {
14359: if ($configline =~ /^\^([\w.\-]+)/) {
14360: $LC_dns_serv{$1} = 1;
14361: }
14362: next;
14363: }
1.1074 raeburn 14364: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 14365: $name=~s/\s//g;
14366: if ($id && $domain && $role && $name) {
1.1351 raeburn 14367: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14368: my $curr = $hostname{$id};
14369: my $skip;
14370: if (ref($name_to_host{$curr}) eq 'ARRAY') {
14371: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14372: $skip = 1;
14373: } else {
14374: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14375: }
14376: }
14377: unless ($skip) {
14378: push(@{$name_to_host{$name}},$id);
14379: }
14380: } else {
14381: push(@{$name_to_host{$name}},$id);
14382: }
1.852 albertel 14383: $hostname{$id}=$name;
14384: $hostdom{$id}=$domain;
14385: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 14386: if (defined($protocol)) {
14387: if ($protocol eq 'https') {
14388: $protocol{$id} = $protocol;
14389: } else {
14390: $protocol{$id} = 'http';
14391: }
1.968 raeburn 14392: } else {
1.969 raeburn 14393: $protocol{$id} = 'http';
1.968 raeburn 14394: }
1.1074 raeburn 14395: if (defined($intdom)) {
14396: $internetdom{$id} = $intdom;
14397: }
1.852 albertel 14398: }
14399: }
14400: }
1.864 albertel 14401:
14402: sub reset_hosts_info {
1.897 albertel 14403: &purge_remembered();
1.864 albertel 14404: &reset_domain_info();
14405: &reset_hosts_ip_info();
1.1339 raeburn 14406: undef(%internetdom);
1.892 albertel 14407: undef(%name_to_host);
1.864 albertel 14408: undef(%hostname);
14409: undef(%hostdom);
14410: undef(%libserv);
14411: undef($loaded);
14412: }
1.1 albertel 14413:
1.852 albertel 14414: sub load_hosts_tab {
1.1293 raeburn 14415: my ($ignore_cache,$nocache) = @_;
14416: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359 raeburn 14417: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 14418: my @config = <$config>;
14419: &parse_hosts_tab(\@config);
14420: close($config);
14421: $loaded=1;
1.1 albertel 14422: }
1.852 albertel 14423:
1.838 albertel 14424: sub hostname {
1.852 albertel 14425: &load_hosts_tab() if (!$loaded);
14426:
1.838 albertel 14427: my ($lonid) = @_;
14428: return $hostname{$lonid};
14429: }
1.845 albertel 14430:
1.838 albertel 14431: sub all_hostnames {
1.852 albertel 14432: &load_hosts_tab() if (!$loaded);
14433:
1.838 albertel 14434: return %hostname;
14435: }
1.845 albertel 14436:
1.888 albertel 14437: sub all_names {
1.1293 raeburn 14438: my ($ignore_cache,$nocache) = @_;
14439: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 14440:
14441: return %name_to_host;
14442: }
14443:
1.974 raeburn 14444: sub all_host_domain {
14445: &load_hosts_tab() if (!$loaded);
14446: return %hostdom;
14447: }
14448:
1.1339 raeburn 14449: sub all_host_intdom {
14450: &load_hosts_tab() if (!$loaded);
14451: return %internetdom;
14452: }
14453:
1.845 albertel 14454: sub is_library {
1.852 albertel 14455: &load_hosts_tab() if (!$loaded);
14456:
1.845 albertel 14457: return exists($libserv{$_[0]});
14458: }
14459:
14460: sub all_library {
1.852 albertel 14461: &load_hosts_tab() if (!$loaded);
14462:
1.845 albertel 14463: return %libserv;
14464: }
14465:
1.1062 droeschl 14466: sub unique_library {
14467: #2x reverse removes all hostnames that appear more than once
14468: my %unique = reverse &all_library();
14469: return reverse %unique;
14470: }
14471:
1.841 albertel 14472: sub get_servers {
1.852 albertel 14473: &load_hosts_tab() if (!$loaded);
14474:
1.841 albertel 14475: my ($domain,$type) = @_;
14476: my %possible_hosts = ($type eq 'library') ? %libserv
14477: : %hostname;
14478: my %result;
1.842 albertel 14479: if (ref($domain) eq 'ARRAY') {
14480: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 14481: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 14482: $result{$host} = $hostname;
14483: }
14484: }
14485: } else {
14486: while ( my ($host,$hostname) = each(%possible_hosts)) {
14487: if ($hostdom{$host} eq $domain) {
14488: $result{$host} = $hostname;
14489: }
1.841 albertel 14490: }
14491: }
14492: return %result;
14493: }
1.845 albertel 14494:
1.1062 droeschl 14495: sub get_unique_servers {
14496: my %unique = reverse &get_servers(@_);
14497: return reverse %unique;
14498: }
14499:
1.844 albertel 14500: sub host_domain {
1.852 albertel 14501: &load_hosts_tab() if (!$loaded);
14502:
1.844 albertel 14503: my ($lonid) = @_;
14504: return $hostdom{$lonid};
14505: }
14506:
1.841 albertel 14507: sub all_domains {
1.852 albertel 14508: &load_hosts_tab() if (!$loaded);
14509:
1.841 albertel 14510: my %seen;
14511: my @uniq = grep(!$seen{$_}++, values(%hostdom));
14512: return @uniq;
14513: }
1.1074 raeburn 14514:
14515: sub internet_dom {
14516: &load_hosts_tab() if (!$loaded);
14517:
14518: my ($lonid) = @_;
14519: return $internetdom{$lonid};
14520: }
1.1107 raeburn 14521:
14522: sub is_LC_dns {
14523: &load_hosts_tab() if (!$loaded);
14524:
14525: my ($hostname) = @_;
14526: return exists($LC_dns_serv{$hostname});
14527: }
14528:
1.1 albertel 14529: }
14530:
1.847 albertel 14531: {
14532: my %iphost;
1.856 albertel 14533: my %name_to_ip;
14534: my %lonid_to_ip;
1.869 albertel 14535:
1.847 albertel 14536: sub get_hosts_from_ip {
14537: my ($ip) = @_;
14538: my %iphosts = &get_iphost();
14539: if (ref($iphosts{$ip})) {
14540: return @{$iphosts{$ip}};
14541: }
14542: return;
1.839 albertel 14543: }
1.864 albertel 14544:
14545: sub reset_hosts_ip_info {
14546: undef(%iphost);
14547: undef(%name_to_ip);
14548: undef(%lonid_to_ip);
14549: }
1.856 albertel 14550:
14551: sub get_host_ip {
14552: my ($lonid) = @_;
14553: if (exists($lonid_to_ip{$lonid})) {
14554: return $lonid_to_ip{$lonid};
14555: }
14556: my $name=&hostname($lonid);
14557: my $ip = gethostbyname($name);
14558: return if (!$ip || length($ip) ne 4);
14559: $ip=inet_ntoa($ip);
14560: $name_to_ip{$name} = $ip;
14561: $lonid_to_ip{$lonid} = $ip;
14562: return $ip;
14563: }
1.847 albertel 14564:
14565: sub get_iphost {
1.1293 raeburn 14566: my ($ignore_cache,$nocache) = @_;
1.894 albertel 14567:
1.869 albertel 14568: if (!$ignore_cache) {
14569: if (%iphost) {
14570: return %iphost;
14571: }
14572: my ($ip_info,$cached)=
14573: &Apache::lonnet::is_cached_new('iphost','iphost');
14574: if ($cached) {
14575: %iphost = %{$ip_info->[0]};
14576: %name_to_ip = %{$ip_info->[1]};
14577: %lonid_to_ip = %{$ip_info->[2]};
14578: return %iphost;
14579: }
14580: }
1.894 albertel 14581:
14582: # get yesterday's info for fallback
14583: my %old_name_to_ip;
14584: my ($ip_info,$cached)=
14585: &Apache::lonnet::is_cached_new('iphost','iphost');
14586: if ($cached) {
14587: %old_name_to_ip = %{$ip_info->[1]};
14588: }
14589:
1.1293 raeburn 14590: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 14591: foreach my $name (keys(%name_to_host)) {
1.847 albertel 14592: my $ip;
14593: if (!exists($name_to_ip{$name})) {
14594: $ip = gethostbyname($name);
14595: if (!$ip || length($ip) ne 4) {
1.894 albertel 14596: if (defined($old_name_to_ip{$name})) {
14597: $ip = $old_name_to_ip{$name};
14598: &logthis("Can't find $name defaulting to old $ip");
14599: } else {
14600: &logthis("Name $name no IP found");
14601: next;
14602: }
14603: } else {
14604: $ip=inet_ntoa($ip);
1.847 albertel 14605: }
14606: $name_to_ip{$name} = $ip;
14607: } else {
14608: $ip = $name_to_ip{$name};
1.653 albertel 14609: }
1.888 albertel 14610: foreach my $id (@{ $name_to_host{$name} }) {
14611: $lonid_to_ip{$id} = $ip;
14612: }
14613: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 14614: }
1.1293 raeburn 14615: unless ($nocache) {
14616: &do_cache_new('iphost','iphost',
14617: [\%iphost,\%name_to_ip,\%lonid_to_ip],
14618: 48*60*60);
14619: }
1.869 albertel 14620:
1.847 albertel 14621: return %iphost;
1.598 albertel 14622: }
14623:
1.992 raeburn 14624: #
14625: # Given a DNS returns the loncapa host name for that DNS
14626: #
14627: sub host_from_dns {
14628: my ($dns) = @_;
14629: my @hosts;
14630: my $ip;
14631:
1.993 raeburn 14632: if (exists($name_to_ip{$dns})) {
1.992 raeburn 14633: $ip = $name_to_ip{$dns};
14634: }
14635: if (!$ip) {
14636: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14637: if (length($ip) == 4) {
14638: $ip = &IO::Socket::inet_ntoa($ip);
14639: }
14640: }
14641: if ($ip) {
14642: @hosts = get_hosts_from_ip($ip);
14643: return $hosts[0];
14644: }
14645: return undef;
1.986 foxr 14646: }
1.992 raeburn 14647:
1.1074 raeburn 14648: sub get_internet_names {
14649: my ($lonid) = @_;
14650: return if ($lonid eq '');
14651: my ($idnref,$cached)=
14652: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14653: if ($cached) {
14654: return $idnref;
14655: }
14656: my $ip = &get_host_ip($lonid);
14657: my @hosts = &get_hosts_from_ip($ip);
14658: my %iphost = &get_iphost();
14659: my (@idns,%seen);
14660: foreach my $id (@hosts) {
14661: my $dom = &host_domain($id);
14662: my $prim_id = &domain($dom,'primary');
14663: my $prim_ip = &get_host_ip($prim_id);
14664: next if ($seen{$prim_ip});
14665: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14666: foreach my $id (@{$iphost{$prim_ip}}) {
14667: my $intdom = &internet_dom($id);
14668: unless (grep(/^\Q$intdom\E$/,@idns)) {
14669: push(@idns,$intdom);
14670: }
14671: }
14672: }
14673: $seen{$prim_ip} = 1;
14674: }
1.1219 raeburn 14675: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 14676: }
14677:
1.986 foxr 14678: }
14679:
1.1079 raeburn 14680: sub all_loncaparevs {
1.1249 raeburn 14681: 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 14682: }
14683:
1.1227 raeburn 14684: # ---------------------------------------------------------- Read loncaparev table
14685: {
14686: sub load_loncaparevs {
14687: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359 raeburn 14688: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227 raeburn 14689: while (my $configline=<$config>) {
14690: chomp($configline);
14691: my ($hostid,$loncaparev)=split(/:/,$configline);
14692: $loncaparevs{$hostid}=$loncaparev;
14693: }
14694: close($config);
14695: }
14696: }
14697: }
14698: }
14699:
14700: # ---------------------------------------------------------- Read serverhostID table
14701: {
14702: sub load_serverhomeIDs {
14703: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359 raeburn 14704: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227 raeburn 14705: while (my $configline=<$config>) {
14706: chomp($configline);
14707: my ($name,$id)=split(/:/,$configline);
14708: $serverhomeIDs{$name}=$id;
14709: }
14710: close($config);
14711: }
14712: }
14713: }
14714: }
14715:
14716:
1.862 albertel 14717: BEGIN {
14718:
14719: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14720: unless ($readit) {
14721: {
14722: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14723: %perlvar = (%perlvar,%{$configvars});
14724: }
14725:
14726:
1.1 albertel 14727: # ------------------------------------------------------ Read spare server file
14728: {
1.1359 raeburn 14729: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 14730:
14731: while (my $configline=<$config>) {
14732: chomp($configline);
1.284 matthew 14733: if ($configline) {
1.784 albertel 14734: my ($host,$type) = split(':',$configline,2);
1.785 albertel 14735: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 14736: push(@{ $spareid{$type} }, $host);
1.1 albertel 14737: }
14738: }
1.448 albertel 14739: close($config);
1.1 albertel 14740: }
1.11 www 14741: # ------------------------------------------------------------ Read permissions
14742: {
1.1359 raeburn 14743: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 14744:
14745: while (my $configline=<$config>) {
1.448 albertel 14746: chomp($configline);
14747: if ($configline) {
14748: my ($role,$perm)=split(/ /,$configline);
14749: if ($perm ne '') { $pr{$role}=$perm; }
14750: }
1.11 www 14751: }
1.448 albertel 14752: close($config);
1.11 www 14753: }
14754:
14755: # -------------------------------------------- Read plain texts for permissions
14756: {
1.1359 raeburn 14757: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 14758:
14759: while (my $configline=<$config>) {
1.448 albertel 14760: chomp($configline);
14761: if ($configline) {
1.742 raeburn 14762: my ($short,@plain)=split(/:/,$configline);
14763: %{$prp{$short}} = ();
14764: if (@plain > 0) {
14765: $prp{$short}{'std'} = $plain[0];
14766: for (my $i=1; $i<@plain; $i++) {
14767: $prp{$short}{'alt'.$i} = $plain[$i];
14768: }
14769: }
1.448 albertel 14770: }
1.135 www 14771: }
1.448 albertel 14772: close($config);
1.135 www 14773: }
14774:
14775: # ---------------------------------------------------------- Read package table
14776: {
1.1359 raeburn 14777: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 14778:
14779: while (my $configline=<$config>) {
1.483 albertel 14780: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 14781: chomp($configline);
14782: my ($short,$plain)=split(/:/,$configline);
14783: my ($pack,$name)=split(/\&/,$short);
14784: if ($plain ne '') {
14785: $packagetab{$pack.'&'.$name.'&name'}=$name;
14786: $packagetab{$short}=$plain;
14787: }
1.11 www 14788: }
1.448 albertel 14789: close($config);
1.329 matthew 14790: }
14791:
1.1073 raeburn 14792: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 14793:
14794: &load_loncaparevs();
1.1073 raeburn 14795:
1.1074 raeburn 14796: # ---------------------------------------------------------- Read serverhostID table
14797:
1.1227 raeburn 14798: &load_serverhomeIDs();
14799:
14800: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 14801: {
14802: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14803: if (-e $file) {
14804: my $parser = HTML::LCParser->new($file);
14805: while (my $token = $parser->get_token()) {
14806: if ($token->[0] eq 'S') {
14807: my $item = $token->[1];
14808: my $name = $token->[2]{'name'};
14809: my $value = $token->[2]{'value'};
1.1285 raeburn 14810: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 14811: my $namematch = $token->[2]{'namematch'};
14812: if ($item eq 'parameter') {
14813: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14814: my $release = $parser->get_text();
14815: $release =~ s/(^\s*|\s*$ )//gx;
14816: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14817: }
14818: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 14819: my $release = $parser->get_text();
14820: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 14821: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 14822: }
14823: }
14824: }
14825: }
1.1073 raeburn 14826: }
14827:
1.1138 raeburn 14828: # ---------------------------------------------------------- Read managers table
14829: {
14830: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359 raeburn 14831: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 14832: while (my $configline=<$config>) {
14833: chomp($configline);
14834: next if ($configline =~ /^\#/);
14835: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14836: $managerstab{$configline} = 1;
14837: }
14838: }
14839: close($config);
14840: }
14841: }
14842: }
14843:
1.329 matthew 14844: # ------------- set up temporary directory
14845: {
1.1117 foxr 14846: $tmpdir = LONCAPA::tempdir();
1.329 matthew 14847:
1.11 www 14848: }
14849:
1.1405 raeburn 14850: # ------------- set default texengine (domain default overrides this)
14851: {
14852: $deftex = LONCAPA::texengine();
14853: }
14854:
1.794 albertel 14855: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14856: 'compress_threshold'=> 20_000,
14857: });
1.185 www 14858:
1.281 www 14859: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 14860: $dumpcount=0;
1.958 www 14861: $locknum=0;
1.22 www 14862:
1.163 harris41 14863: &logtouch();
1.672 albertel 14864: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 14865: $readit=1;
1.564 albertel 14866: {
14867: use integer;
14868: my $test=(2**32)+1;
1.568 albertel 14869: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 14870: &logthis(" Detected 64bit platform ($_64bit)");
14871: }
1.195 www 14872: }
1.1 albertel 14873: }
1.179 www 14874:
1.1 albertel 14875: 1;
1.191 harris41 14876: __END__
14877:
1.243 albertel 14878: =pod
14879:
1.191 harris41 14880: =head1 NAME
14881:
1.243 albertel 14882: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 14883:
14884: =head1 SYNOPSIS
14885:
1.243 albertel 14886: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 14887:
14888: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14889:
1.243 albertel 14890: Common parameters:
14891:
14892: =over 4
14893:
14894: =item *
14895:
14896: $uname : an internal username (if $cname expecting a course Id specifically)
14897:
14898: =item *
14899:
14900: $udom : a domain (if $cdom expecting a course's domain specifically)
14901:
14902: =item *
14903:
14904: $symb : a resource instance identifier
14905:
14906: =item *
14907:
14908: $namespace : the name of a .db file that contains the data needed or
14909: being set.
14910:
14911: =back
14912:
1.394 bowersj2 14913: =head1 OVERVIEW
1.191 harris41 14914:
1.394 bowersj2 14915: lonnet provides subroutines which interact with the
14916: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14917: about classes, users, and resources.
1.243 albertel 14918:
14919: For many of these objects you can also use this to store data about
14920: them or modify them in various ways.
1.191 harris41 14921:
1.394 bowersj2 14922: =head2 Symbs
1.191 harris41 14923:
1.394 bowersj2 14924: To identify a specific instance of a resource, LON-CAPA uses symbols
14925: or "symbs"X<symb>. These identifiers are built from the URL of the
14926: map, the resource number of the resource in the map, and the URL of
14927: the resource itself. The latter is somewhat redundant, but might help
14928: if maps change.
14929:
14930: An example is
14931:
14932: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14933:
14934: The respective map entry is
14935:
14936: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14937: title="Problem 2">
14938: </resource>
14939:
14940: Symbs are used by the random number generator, as well as to store and
14941: restore data specific to a certain instance of for example a problem.
14942:
14943: =head2 Storing And Retrieving Data
14944:
14945: X<store()>X<cstore()>X<restore()>Three of the most important functions
14946: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14947: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14948: is is the non-critical message twin of cstore. These functions are for
14949: handlers to store a perl hash to a user's permanent data space in an
14950: easy manner, and to retrieve it again on another call. It is expected
14951: that a handler would use this once at the beginning to retrieve data,
14952: and then again once at the end to send only the new data back.
14953:
14954: The data is stored in the user's data directory on the user's
14955: homeserver under the ID of the course.
14956:
14957: The hash that is returned by restore will have all of the previous
14958: value for all of the elements of the hash.
14959:
14960: Example:
14961:
14962: #creating a hash
14963: my %hash;
14964: $hash{'foo'}='bar';
14965:
14966: #storing it
14967: &Apache::lonnet::cstore(\%hash);
14968:
14969: #changing a value
14970: $hash{'foo'}='notbar';
14971:
14972: #adding a new value
14973: $hash{'bar'}='foo';
14974: &Apache::lonnet::cstore(\%hash);
14975:
14976: #retrieving the hash
14977: my %history=&Apache::lonnet::restore();
14978:
14979: #print the hash
14980: foreach my $key (sort(keys(%history))) {
14981: print("\%history{$key} = $history{$key}");
14982: }
14983:
14984: Will print out:
1.191 harris41 14985:
1.394 bowersj2 14986: %history{1:foo} = bar
14987: %history{1:keys} = foo:timestamp
14988: %history{1:timestamp} = 990455579
14989: %history{2:bar} = foo
14990: %history{2:foo} = notbar
14991: %history{2:keys} = foo:bar:timestamp
14992: %history{2:timestamp} = 990455580
14993: %history{bar} = foo
14994: %history{foo} = notbar
14995: %history{timestamp} = 990455580
14996: %history{version} = 2
14997:
14998: Note that the special hash entries C<keys>, C<version> and
14999: C<timestamp> were added to the hash. C<version> will be equal to the
15000: total number of versions of the data that have been stored. The
15001: C<timestamp> attribute will be the UNIX time the hash was
15002: stored. C<keys> is available in every historical section to list which
15003: keys were added or changed at a specific historical revision of a
15004: hash.
15005:
15006: B<Warning>: do not store the hash that restore returns directly. This
15007: will cause a mess since it will restore the historical keys as if the
15008: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 15009:
1.394 bowersj2 15010: Calling convention:
1.191 harris41 15011:
1.1225 raeburn 15012: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 15013: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 15014:
1.394 bowersj2 15015: For more detailed information, see lonnet specific documentation.
1.191 harris41 15016:
1.394 bowersj2 15017: =head1 RETURN MESSAGES
1.191 harris41 15018:
1.394 bowersj2 15019: =over 4
1.191 harris41 15020:
1.394 bowersj2 15021: =item * B<con_lost>: unable to contact remote host
1.191 harris41 15022:
1.394 bowersj2 15023: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15024: when the connection is brought back up
1.191 harris41 15025:
1.394 bowersj2 15026: =item * B<con_failed>: unable to contact remote host and unable to save message
15027: for later delivery
1.191 harris41 15028:
1.967 bisitz 15029: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 15030:
1.394 bowersj2 15031: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 15032: that was requested
1.191 harris41 15033:
1.243 albertel 15034: =back
1.191 harris41 15035:
1.243 albertel 15036: =head1 PUBLIC SUBROUTINES
1.191 harris41 15037:
1.243 albertel 15038: =head2 Session Environment Functions
1.191 harris41 15039:
1.243 albertel 15040: =over 4
1.191 harris41 15041:
1.394 bowersj2 15042: =item *
15043: X<appenv()>
1.949 raeburn 15044: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 15045: the user envirnoment file, and will be restored for each access this
1.620 albertel 15046: user makes during this session, also modifies the %env for the current
1.949 raeburn 15047: process. Optional rolesarrayref - if defined contains a reference to an array
15048: of roles which are exempt from the restriction on modifying user.role entries
15049: in the user's environment.db and in %env.
1.191 harris41 15050:
15051: =item *
1.394 bowersj2 15052: X<delenv()>
1.987 raeburn 15053: B<delenv($delthis,$regexp)>: removes all items from the session
15054: environment file that begin with $delthis. If the
15055: optional second arg - $regexp - is true, $delthis is treated as a
15056: regular expression, otherwise \Q$delthis\E is used.
15057: The values are also deleted from the current processes %env.
1.191 harris41 15058:
1.795 albertel 15059: =item * get_env_multiple($name)
15060:
15061: gets $name from the %env hash, it seemlessly handles the cases where multiple
15062: values may be defined and end up as an array ref.
15063:
15064: returns an array of values
15065:
1.243 albertel 15066: =back
15067:
15068: =head2 User Information
1.191 harris41 15069:
1.243 albertel 15070: =over 4
1.191 harris41 15071:
15072: =item *
1.394 bowersj2 15073: X<queryauthenticate()>
15074: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 15075: authentication scheme
15076:
15077: =item *
1.394 bowersj2 15078: X<authenticate()>
1.1073 raeburn 15079: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 15080: authenticate user from domain's lib servers (first use the current
15081: one). C<$upass> should be the users password.
1.1073 raeburn 15082: $checkdefauth is optional (value is 1 if a check should be made to
15083: authenticate user using default authentication method, and allow
15084: account creation if username does not have account in the domain).
15085: $clientcancheckhost is optional (value is 1 if checking whether the
15086: server can host will occur on the client side in lonauth.pm).
1.191 harris41 15087:
15088: =item *
1.394 bowersj2 15089: X<homeserver()>
15090: B<homeserver($uname,$udom)>: find the server which has
15091: the user's directory and files (there must be only one), this caches
15092: the answer, and also caches if there is a borken connection.
1.191 harris41 15093:
15094: =item *
1.394 bowersj2 15095: X<idget()>
1.1300 raeburn 15096: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
15097: a list of student/employee IDs or clicker IDs
15098: (student/employee IDs are a unique resource in a domain, there must be
15099: only 1 ID per username, and only 1 username per ID in a specific domain).
15100: clickerIDs are not necessarily unique, as students might share clickers.
15101: (returns hash: id=>name,id=>name)
1.191 harris41 15102:
15103: =item *
1.394 bowersj2 15104: X<idrget()>
15105: B<idrget($udom,@unames)>: find the IDs behind a list of
15106: usernames (returns hash: name=>id,name=>id)
1.191 harris41 15107:
15108: =item *
1.394 bowersj2 15109: X<idput()>
1.1300 raeburn 15110: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
15111: names and associated student/employee IDs or clicker IDs.
15112:
15113: =item *
15114: X<iddel()>
15115: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
15116: student/employee ID or clicker ID username look-ups from domain.
15117: The homeserver ($uhome) and namespace ($namespace) are optional.
15118: If no $uhome is provided, it will be determined usig &homeserver()
15119: for each user. If no $namespace is provided, the default is ids.
15120:
15121: =item *
15122: X<updateclickers()>
15123: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
15124: clicker ID-to-username look-ups in clickers.db on library server.
15125: Permitted actions are add or del (i.e., add or delete). The
15126: clickers.db contains clickerID as keys (escaped), and each corresponding
15127: value is an escaped comma-separated list of usernames (for whom the
15128: library server is the homeserver), who registered that particular ID.
15129: If $critical is true, the update will be sent via &critical, otherwise
15130: &reply() will be used.
1.191 harris41 15131:
15132: =item *
1.394 bowersj2 15133: X<rolesinit()>
1.1169 droeschl 15134: B<rolesinit($udom,$username)>: get user privileges.
15135: returns user role, first access and timer interval hashes
1.243 albertel 15136:
15137: =item *
1.1171 droeschl 15138: X<privileged()>
15139: B<privileged($username,$domain)>: returns a true if user has a
15140: privileged and active role (i.e. su or dc), false otherwise.
15141:
15142: =item *
1.551 albertel 15143: X<getsection()>
15144: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 15145: course $cname, return section name/number or '' for "not in course"
15146: and '-1' for "no section"
15147:
15148: =item *
1.394 bowersj2 15149: X<userenvironment()>
15150: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 15151: passed in @what from the requested user's environment, returns a hash
15152:
1.858 raeburn 15153: =item *
15154: X<userlog_query()>
1.859 albertel 15155: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15156: activity.log file. %filters defines filters applied when parsing the
15157: log file. These can be start or end timestamps, or the type of action
15158: - log to look for Login or Logout events, check for Checkin or
15159: Checkout, role for role selection. The response is in the form
15160: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
15161: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 15162:
1.243 albertel 15163: =back
15164:
15165: =head2 User Roles
15166:
15167: =over 4
15168:
15169: =item *
15170:
1.1284 raeburn 15171: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
15172: returns codes for allowed actions.
15173:
15174: The first argument is required, all others are optional.
15175:
15176: $priv is the privilege being checked.
15177: $uri contains additional information about what is being checked for access (e.g.,
15178: URL, course ID etc.).
15179: $symb is the unique resource instance identifier in a course; if needed,
15180: but not provided, it will be retrieved via a call to &symbread().
15181: $role is the role for which a priv is being checked (only used if priv is evb).
15182: $clientip is the user's IP address (only used when checking for access to portfolio
15183: files).
15184: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
15185: prevents recursive calls to &allowed.
15186:
1.243 albertel 15187: F: full access
15188: U,I,K: authentication modes (cxx only)
15189: '': forbidden
15190: 1: user needs to choose course
15191: 2: browse allowed
1.766 albertel 15192: A: passphrase authentication needed
1.1284 raeburn 15193: B: access temporarily blocked because of a blocking event in a course.
1.1402 raeburn 15194: D: access blocked because access is required via session initiated via deep-link
1.243 albertel 15195:
15196: =item *
15197:
1.1192 raeburn 15198: constructaccess($url,$setpriv) : check for access to construction space URL
15199:
15200: See if the owner domain and name in the URL match those in the
15201: expected environment. If so, return three element list
15202: ($ownername,$ownerdomain,$ownerhome).
15203:
15204: Otherwise return the null string.
15205:
15206: If second argument 'setpriv' is true, it assigns the privileges,
15207: and returns the same three element list, unless the owner has
15208: blocked "ad hoc" Domain Coordinator access to the Author Space,
15209: in which case the null string is returned.
15210:
15211: =item *
15212:
1.1326 raeburn 15213: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15214: define a custom role rolename set privileges in format of lonTabs/roles.tab
15215: for system, domain, and course level. $uname and $udom are optional (current
15216: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 15217:
15218: =item *
15219:
1.988 raeburn 15220: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
15221: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 15222: $type is Course (default) or Community.
1.988 raeburn 15223: If $forcedefault evaluates to true, text returned will be default
15224: text for $type. Otherwise, if this is a course, the text returned
15225: will be a custom name for the role (if defined in the course's
15226: environment). If no custom name is defined the default is returned.
15227:
1.832 raeburn 15228: =item *
15229:
1.1219 raeburn 15230: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 15231: All arguments are optional. Returns a hash of a roles, either for
15232: co-author/assistant author roles for a user's Construction Space
1.906 albertel 15233: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 15234: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15235: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15236: For each key, value is set to colon-separated start and end times for
15237: the role. If no username and domain are specified, will default to
1.934 raeburn 15238: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 15239: of role statuses (active, future or previous), roles
15240: (e.g., cc,in, st etc.) and domains of the roles which can be used
15241: to restrict the list of roles reported. If no array ref is
15242: provided for types, will default to return only active roles.
1.834 albertel 15243:
1.1195 raeburn 15244: =item *
15245:
15246: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 15247: user: $uname:$udom has a role in the course: $cdom_$cnum.
15248:
15249: Additional optional arguments are: $type (if role checking is to be restricted
15250: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 15251: available roles) or future (roles available in the future), and
15252: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 15253: have active Domain Coordinator role in course's domain or in additional
15254: domains (specified in 'Domains to check for privileged users' in course
15255: environment -- set via: Course Settings -> Classlists and staff listing).
15256:
15257: =item *
15258:
15259: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15260: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15261: $possdomains and $possroles are optional array refs -- to domains to check and
15262: roles to check. If $possdomains is not specified, a dump will be done of the
15263: users' roles.db to check for a dc or su role in any domain. This can be
15264: time consuming if &privileged is called repeatedly (e.g., when displaying a
15265: classlist), so in such cases, supplying a $possdomains array is preferred, as
15266: this then allows &privileged_by_domain() to be used, which caches the identity
15267: of privileged users, eliminating the need for repeated calls to &dump().
15268:
15269: =item *
15270:
15271: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15272: where the outer hash keys are domains specified in the $possdomains array ref,
15273: next inner hash keys are privileged roles specified in the $roles array ref,
15274: and the innermost hash contains key = value pairs for username:domain = end:start
15275: for active or future "privileged" users with that role in that domain. To avoid
15276: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15277: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 15278:
1.243 albertel 15279: =back
15280:
15281: =head2 User Modification
15282:
15283: =over 4
15284:
15285: =item *
15286:
1.957 raeburn 15287: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 15288: user for the level given by URL. Optional start and end dates (leave empty
15289: string or zero for "no date")
1.191 harris41 15290:
15291: =item *
15292:
1.243 albertel 15293: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15294: change a users, password, possible return values are: ok,
15295: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15296: refused
1.191 harris41 15297:
15298: =item *
15299:
1.243 albertel 15300: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 15301:
15302: =item *
15303:
1.1058 raeburn 15304: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15305: $forceid,$desiredhome,$email,$inststatus,$candelete) :
15306:
15307: will update user information (firstname,middlename,lastname,generation,
15308: permanentemail), and if forceid is true, student/employee ID also.
15309: A user's institutional affiliation(s) can also be updated.
15310: User information fields will not be overwritten with empty entries
15311: unless the field is included in the $candelete array reference.
15312: This array is included when a single user is modified via "Manage Users",
15313: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 15314:
15315: =item *
15316:
1.286 matthew 15317: modifystudent
15318:
1.957 raeburn 15319: modify a student's enrollment and identification information.
1.1235 raeburn 15320: The course id is resolved based on the current user's environment.
15321: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 15322: associated with a course.
15323:
1.297 matthew 15324: This call is essentially a wrapper for lonnet::modifyuser and
15325: lonnet::modify_student_enrollment
1.286 matthew 15326:
15327: Inputs:
15328:
15329: =over 4
15330:
1.957 raeburn 15331: =item B<$udom> Student's loncapa domain
1.286 matthew 15332:
1.957 raeburn 15333: =item B<$uname> Student's loncapa login name
1.286 matthew 15334:
1.964 bisitz 15335: =item B<$uid> Student/Employee ID
1.286 matthew 15336:
1.957 raeburn 15337: =item B<$umode> Student's authentication mode
1.286 matthew 15338:
1.957 raeburn 15339: =item B<$upass> Student's password
1.286 matthew 15340:
1.957 raeburn 15341: =item B<$first> Student's first name
1.286 matthew 15342:
1.957 raeburn 15343: =item B<$middle> Student's middle name
1.286 matthew 15344:
1.957 raeburn 15345: =item B<$last> Student's last name
1.286 matthew 15346:
1.957 raeburn 15347: =item B<$gene> Student's generation
1.286 matthew 15348:
1.957 raeburn 15349: =item B<$usec> Student's section in course
1.286 matthew 15350:
15351: =item B<$end> Unix time of the roles expiration
15352:
15353: =item B<$start> Unix time of the roles start date
15354:
15355: =item B<$forceid> If defined, allow $uid to be changed
15356:
15357: =item B<$desiredhome> server to use as home server for student
15358:
1.957 raeburn 15359: =item B<$email> Student's permanent e-mail address
15360:
15361: =item B<$type> Type of enrollment (auto or manual)
15362:
1.963 raeburn 15363: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
15364:
15365: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 15366:
1.963 raeburn 15367: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 15368:
1.963 raeburn 15369: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 15370:
1.1216 raeburn 15371: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15372:
15373: =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 15374:
1.286 matthew 15375: =back
1.297 matthew 15376:
15377: =item *
15378:
15379: modify_student_enrollment
15380:
1.1235 raeburn 15381: Change a student's enrollment status in a class. The environment variable
1.297 matthew 15382: 'role.request.course' must be defined for this function to proceed.
15383:
15384: Inputs:
15385:
15386: =over 4
15387:
1.1235 raeburn 15388: =item $udom, student's domain
1.297 matthew 15389:
1.1235 raeburn 15390: =item $uname, student's name
1.297 matthew 15391:
1.1235 raeburn 15392: =item $uid, student's user id
1.297 matthew 15393:
1.1235 raeburn 15394: =item $first, student's first name
1.297 matthew 15395:
15396: =item $middle
15397:
15398: =item $last
15399:
15400: =item $gene
15401:
15402: =item $usec
15403:
15404: =item $end
15405:
15406: =item $start
15407:
1.957 raeburn 15408: =item $type
15409:
15410: =item $locktype
15411:
15412: =item $cid
15413:
15414: =item $selfenroll
15415:
15416: =item $context
15417:
1.1216 raeburn 15418: =item $credits, number of credits student will earn from this class
15419:
1.1314 raeburn 15420: =item $instsec, institutional course section code for student
15421:
1.297 matthew 15422: =back
15423:
1.191 harris41 15424:
15425: =item *
15426:
1.243 albertel 15427: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15428: custom role; give a custom role to a user for the level given by URL. Specify
15429: name and domain of role author, and role name
1.191 harris41 15430:
15431: =item *
15432:
1.243 albertel 15433: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 15434:
15435: =item *
15436:
1.243 albertel 15437: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15438:
15439: =back
15440:
15441: =head2 Course Infomation
15442:
15443: =over 4
1.191 harris41 15444:
15445: =item *
15446:
1.1118 foxr 15447: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 15448: specified course id, including all environment settings for the
15449: course, the description of the course will be in the hash under the
15450: key 'description'
1.191 harris41 15451:
1.1118 foxr 15452: $options is an optional parameter that if supplied is a hash reference that controls
15453: what how this function works. It has the following key/values:
15454:
15455: =over 4
15456:
15457: =item freshen_cache
15458:
15459: If defined, and the environment cache for the course is valid, it is
15460: returned in the returned hash.
15461:
15462: =item one_time
15463:
15464: If defined, the last cache time is set to _now_
15465:
15466: =item user
15467:
15468: If defined, the supplied username is used instead of the current user.
15469:
15470:
15471: =back
15472:
1.191 harris41 15473: =item *
15474:
1.624 albertel 15475: resdata($name,$domain,$type,@which) : request for current parameter
15476: setting for a specific $type, where $type is either 'course' or 'user',
15477: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 15478: answers for 10 minutes.
1.243 albertel 15479:
1.877 foxr 15480: =item *
15481:
15482: get_courseresdata($courseid, $domain) : dump the entire course resource
15483: data base, returning a hash that is keyed by the resource name and has
15484: values that are the resource value. I believe that the timestamps and
15485: versions are also returned.
15486:
1.1236 raeburn 15487: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15488: supplemental content area. This routine caches the number of files for
15489: 10 minutes.
15490:
1.243 albertel 15491: =back
15492:
15493: =head2 Course Modification
15494:
15495: =over 4
1.191 harris41 15496:
15497: =item *
15498:
1.243 albertel 15499: writecoursepref($courseid,%prefs) : write preferences (environment
15500: database) for a course
1.191 harris41 15501:
15502: =item *
15503:
1.1011 raeburn 15504: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15505:
15506: =item *
15507:
1.1038 raeburn 15508: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 15509:
1.1167 droeschl 15510: =item *
15511:
15512: is_course($courseid), is_course($cdom, $cnum)
15513:
15514: Accepts either a combined $courseid (in the form of domain_courseid) or the
15515: two component version $cdom, $cnum. It checks if the specified course exists.
15516:
15517: Returns:
15518: undef if the course doesn't exist, otherwise
15519: in scalar context the combined courseid.
15520: in list context the two components of the course identifier, domain and
15521: courseid.
15522:
1.243 albertel 15523: =back
15524:
1.1401 raeburn 15525: =head2 Bubblesheet Configuration
15526:
15527: =over 4
15528:
15529: =item *
15530:
15531: get_scantron_config($which)
15532:
15533: $which - the name of the configuration to parse from the file.
15534:
15535: Parses and returns the bubblesheet configuration line selected as a
15536: hash of configuration file fields.
15537:
15538:
15539: Returns:
15540: If the named configuration is not in the file, an empty
15541: hash is returned.
15542:
15543: a hash with the fields
15544: name - internal name for the this configuration setup
15545: description - text to display to operator that describes this config
15546: CODElocation - if 0 or the string 'none'
15547: - no CODE exists for this config
15548: if -1 || the string 'letter'
15549: - a CODE exists for this config and is
15550: a string of letters
15551: Unsupported value (but planned for future support)
15552: if a positive integer
15553: - The CODE exists as the first n items from
15554: the question section of the form
15555: if the string 'number'
15556: - The CODE exists for this config and is
15557: a string of numbers
15558: CODEstart - (only matter if a CODE exists) column in the line where
15559: the CODE starts
15560: CODElength - length of the CODE
15561: IDstart - column where the student/employee ID starts
15562: IDlength - length of the student/employee ID info
15563: Qstart - column where the information from the bubbled
15564: 'questions' start
15565: Qlength - number of columns comprising a single bubble line from
15566: the sheet. (usually either 1 or 10)
15567: Qon - either a single character representing the character used
15568: to signal a bubble was chosen in the positional setup, or
15569: the string 'letter' if the letter of the chosen bubble is
15570: in the final, or 'number' if a number representing the
15571: chosen bubble is in the file (1->A 0->J)
15572: Qoff - the character used to represent that a bubble was
15573: left blank
15574: PaperID - if the scanning process generates a unique number for each
15575: sheet scanned the column that this ID number starts in
15576: PaperIDlength - number of columns that comprise the unique ID number
15577: for the sheet of paper
15578: FirstName - column that the first name starts in
15579: FirstNameLength - number of columns that the first name spans
15580: LastName - column that the last name starts in
15581: LastNameLength - number of columns that the last name spans
15582: BubblesPerRow - number of bubbles available in each row used to
15583: bubble an answer. (If not specified, 10 assumed).
15584:
15585:
15586: =item *
15587:
15588: get_scantronformat_file($cdom)
15589:
15590: $cdom - the course's domain (optional); if not supplied, uses
15591: domain for current $env{'request.course.id'}.
15592:
15593: Returns an array containing lines from the scantron format file for
15594: the domain of the course.
15595:
15596: If a url for a custom.tab file is listed in domain's configuration.db,
15597: lines are from this file.
15598:
15599: Otherwise, if a default.tab has been published in RES space by the
15600: domainconfig user, lines are from this file.
15601:
15602: Otherwise, fall back to getting lines from the legacy file on the
15603: local server: /home/httpd/lonTabs/default_scantronformat.tab
15604:
15605: =back
15606:
1.243 albertel 15607: =head2 Resource Subroutines
15608:
15609: =over 4
1.191 harris41 15610:
15611: =item *
15612:
1.243 albertel 15613: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 15614:
15615: =item *
15616:
1.243 albertel 15617: repcopy($filename) : subscribes to the requested file, and attempts to
15618: replicate from the owning library server, Might return
1.607 raeburn 15619: 'unavailable', 'not_found', 'forbidden', 'ok', or
15620: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 15621: resource. Expects the local filesystem pathname
15622: (/home/httpd/html/res/....)
15623:
15624: =back
15625:
15626: =head2 Resource Information
15627:
15628: =over 4
1.191 harris41 15629:
15630: =item *
15631:
1.1228 raeburn 15632: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
15633: and returns the value of a variety of different possible values,
15634: $varname should be a request string, and the other parameters can be
15635: used to specify who and what one is asking about. Ordinarily, $cid
15636: does not need to be specified, as it is retrived from
15637: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15638: within lonuserstate::loadmap() when initializing a course, before
15639: $env{'request.course.id'} has been set, so it needs to be provided
15640: in that one case.
1.243 albertel 15641:
15642: Possible values for $varname are environment.lastname (or other item
15643: from the envirnment hash), user.name (or someother aspect about the
15644: user), resource.0.maxtries (or some other part and parameter of a
15645: resource)
1.204 albertel 15646:
15647: =item *
15648:
1.243 albertel 15649: directcondval($number) : get current value of a condition; reads from a state
15650: string
1.204 albertel 15651:
15652: =item *
15653:
1.243 albertel 15654: condval($condidx) : value of condition index based on state
1.204 albertel 15655:
15656: =item *
15657:
1.1362 raeburn 15658: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243 albertel 15659: resource's metadata, $what should be either a specific key, or either
15660: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362 raeburn 15661: packages that this resource currently uses, the last 3 arguments are
15662: only used internally for recursive metadata.
15663:
15664: the toolsymb is only used where the uri is for an external tool (for which
15665: the uri as well as the symb are guaranteed to be unique).
1.243 albertel 15666:
1.1371 raeburn 15667: this function automatically caches all requests except any made recursively
15668: to retrieve a list of metadata keys for an imported library file ($liburi is
15669: defined).
1.191 harris41 15670:
15671: =item *
15672:
1.243 albertel 15673: metadata_query($query,$custom,$customshow) : make a metadata query against the
15674: network of library servers; returns file handle of where SQL and regex results
15675: will be stored for query
1.191 harris41 15676:
15677: =item *
15678:
1.1282 raeburn 15679: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15680: return symbolic list entry (all arguments optional).
15681:
15682: Args: filename is the filename (including path) for the file for which a symb
15683: is required; donotrecurse, if true will prevent calls to allowed() being made
15684: to check access status if more than one resource was found in the bighash
15685: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15686: a randompick); ignorecachednull, if true will prevent a symb of '' being
15687: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15688: cause possible symbs to be checked to determine if they are subject to content
15689: blocking, if so they will not be included as possible symbs; possibles is a
15690: ref to a hash, which, as a side effect, will be populated with all possible
15691: symbs (content blocking not tested).
15692:
1.243 albertel 15693: returns the data handle
1.191 harris41 15694:
15695: =item *
15696:
1.1190 raeburn 15697: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15698: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 15699: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 15700: on failure, user must be in a course, as it assumes the existence of
15701: the course initial hash, and uses $env('request.course.id'}. The third
15702: arg is an optional reference to a scalar. If this arg is passed in the
15703: call to symbverify, it will be set to 1 if the symb has been set to be
15704: encrypted; otherwise it will be null.
1.191 harris41 15705:
15706: =item *
15707:
1.243 albertel 15708: symbclean($symb) : removes versions numbers from a symb, returns the
15709: cleaned symb
1.191 harris41 15710:
15711: =item *
15712:
1.243 albertel 15713: is_on_map($uri) : checks if the $uri is somewhere on the current
15714: course map, user must be in a course for it to work.
1.191 harris41 15715:
15716: =item *
15717:
1.243 albertel 15718: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 15719:
15720: =item *
15721:
1.243 albertel 15722: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15723: a random seed, all arguments are optional, if they aren't sent it uses the
15724: environment to derive them. Note: if symb isn't sent and it can't get one
15725: from &symbread it will use the current time as its return value
1.191 harris41 15726:
15727: =item *
15728:
1.243 albertel 15729: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15730: unfakeable, receipt
1.191 harris41 15731:
15732: =item *
15733:
1.620 albertel 15734: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 15735:
15736: =item *
15737:
1.243 albertel 15738: countacc($url) : count the number of accesses to a given URL
1.191 harris41 15739:
15740: =item *
15741:
1.243 albertel 15742: 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 15743:
15744: =item *
15745:
1.243 albertel 15746: 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 15747:
15748: =item *
15749:
1.243 albertel 15750: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 15751:
15752: =item *
15753:
1.243 albertel 15754: devalidate($symb) : devalidate temporary spreadsheet calculations,
15755: forcing spreadsheet to reevaluate the resource scores next time.
15756:
1.1195 raeburn 15757: =item *
15758:
1.1196 raeburn 15759: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15760: when viewing in course context.
1.1195 raeburn 15761:
1.1196 raeburn 15762: input: six args -- filename (decluttered), course number, course domain,
15763: url, symb (if registered) and group (if this is a
15764: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 15765:
1.1196 raeburn 15766: output: array of five scalars --
1.1195 raeburn 15767: $cfile -- url for file editing if editable on current server
15768: $home -- homeserver of resource (i.e., for author if published,
15769: or course if uploaded.).
15770: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 15771: $forceedit -- 1 if icon/link should be to go to edit mode
15772: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 15773:
15774: =item *
15775:
15776: is_course_upload($file,$cnum,$cdom)
15777:
15778: Used in course context to determine if current file was uploaded to
15779: the course (i.e., would be found in /userfiles/docs on the course's
15780: homeserver.
15781:
15782: input: 3 args -- filename (decluttered), course number and course domain.
15783: output: boolean -- 1 if file was uploaded.
15784:
1.243 albertel 15785: =back
15786:
15787: =head2 Storing/Retreiving Data
15788:
15789: =over 4
1.191 harris41 15790:
15791: =item *
15792:
1.1269 raeburn 15793: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15794: permanently for this url; hashref needs to be given and should be a \%hashname;
15795: the remaining args aren't required and if they aren't passed or are '' they will
15796: be derived from the env (with the exception of $laststore, which is an
15797: optional arg used when a user's submission is stored in grading).
15798: $laststore is $version=$timestamp, where $version is the most recent version
15799: number retrieved for the corresponding $symb in the $namespace db file, and
15800: $timestamp is the timestamp for that transaction (UNIX time).
15801: $laststore is currently only passed when cstore() is called by
15802: structuretags::finalize_storage().
1.191 harris41 15803:
15804: =item *
15805:
1.1269 raeburn 15806: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15807: but uses critical subroutine
1.191 harris41 15808:
15809: =item *
15810:
1.243 albertel 15811: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15812: all args are optional
1.191 harris41 15813:
15814: =item *
15815:
1.717 albertel 15816: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15817: dumps the complete (or key matching regexp) namespace into a hash
15818: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15819: normally &store()ed into
15820:
15821: $range should be either an integer '100' (give me the first 100
15822: matching records)
15823: or be two integers sperated by a - with no spaces
15824: '30-50' (give me the 30th through the 50th matching
15825: records)
15826:
15827:
15828: =item *
15829:
1.1269 raeburn 15830: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 15831: replaces a &store() version of data with a replacement set of data
15832: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 15833: reference. If $tolog is true, the transaction is logged in the courselog
15834: with an action=PUTSTORE.
1.717 albertel 15835:
15836: =item *
15837:
1.243 albertel 15838: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15839: works very similar to store/cstore, but all data is stored in a
15840: temporary location and can be reset using tmpreset, $storehash should
15841: be a hash reference, returns nothing on success
1.191 harris41 15842:
15843: =item *
15844:
1.243 albertel 15845: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15846: similar to restore, but all data is stored in a temporary location and
15847: can be reset using tmpreset. Returns a hash of values on success,
15848: error string otherwise.
1.191 harris41 15849:
15850: =item *
15851:
1.243 albertel 15852: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15853: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 15854:
15855: =item *
15856:
1.243 albertel 15857: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15858: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 15859:
15860: =item *
15861:
1.243 albertel 15862: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15863: namesp ($udom and $uname are optional)
1.191 harris41 15864:
15865: =item *
15866:
1.702 albertel 15867: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 15868: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 15869: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 15870:
1.702 albertel 15871: $range should be either an integer '100' (give me the first 100
15872: matching records)
15873: or be two integers sperated by a - with no spaces
15874: '30-50' (give me the 30th through the 50th matching
15875: records)
1.449 matthew 15876: =item *
15877:
15878: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15879: $store can be a scalar, an array reference, or if the amount to be
15880: incremented is > 1, a hash reference.
15881:
15882: ($udom and $uname are optional)
1.191 harris41 15883:
15884: =item *
15885:
1.243 albertel 15886: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15887: ($udom and $uname are optional)
1.191 harris41 15888:
15889: =item *
15890:
1.243 albertel 15891: cput($namespace,$storehash,$udom,$uname) : critical put
15892: ($udom and $uname are optional)
1.191 harris41 15893:
15894: =item *
15895:
1.748 albertel 15896: newput($namespace,$storehash,$udom,$uname) :
15897:
15898: Attempts to store the items in the $storehash, but only if they don't
15899: currently exist, if this succeeds you can be certain that you have
15900: successfully created a new key value pair in the $namespace db.
15901:
15902:
15903: Args:
15904: $namespace: name of database to store values to
15905: $storehash: hashref to store to the db
15906: $udom: (optional) domain of user containing the db
15907: $uname: (optional) name of user caontaining the db
15908:
15909: Returns:
15910: 'ok' -> succeeded in storing all keys of $storehash
15911: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15912: least <key> already existed in the db (other
15913: requested keys may also already exist)
1.967 bisitz 15914: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 15915: 'con_lost' -> unable to contact request server
15916: 'refused' -> action was not allowed by remote machine
15917:
15918:
15919: =item *
15920:
1.243 albertel 15921: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15922: reference filled in from namesp (encrypts the return communication)
15923: ($udom and $uname are optional)
1.191 harris41 15924:
15925: =item *
15926:
1.243 albertel 15927: log($udom,$name,$home,$message) : write to permanent log for user; use
15928: critical subroutine
15929:
1.806 raeburn 15930: =item *
15931:
1.860 raeburn 15932: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15933: array reference filled in from namespace found in domain level on either
15934: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 15935:
15936: =item *
15937:
1.860 raeburn 15938: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15939: domain level either on specified domain server ($uhome) or primary domain
15940: server ($udom and $uhome are optional)
1.806 raeburn 15941:
1.943 raeburn 15942: =item *
15943:
1.1240 raeburn 15944: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15945: for: authentication, language, quotas, timezone, date locale, and portal URL in
15946: the target domain.
15947:
15948: May also include additional key => value pairs for the following groups:
15949:
15950: =over
15951:
15952: =item
15953: disk quotas (MB allocated by default to portfolios and authoring spaces).
15954:
15955: =over
15956:
15957: =item defaultquota, authorquota
15958:
15959: =back
15960:
15961: =item
15962: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15963: portfolio for users).
15964:
15965: =over
15966:
15967: =item
15968: aboutme, blog, webdav, portfolio
15969:
15970: =back
15971:
15972: =item
15973: requestcourses: ability to request courses, and how requests are processed.
15974:
15975: =over
15976:
15977: =item
1.1305 raeburn 15978: official, unofficial, community, textbook, placement
1.1240 raeburn 15979:
15980: =back
15981:
15982: =item
15983: inststatus: types of institutional affiliation, and order in which they are displayed.
15984:
15985: =over
15986:
15987: =item
1.1256 raeburn 15988: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 15989:
15990: =back
15991:
15992: =item
15993: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15994: for course's uploaded content.
15995:
15996: =over
15997:
15998: =item
1.1246 raeburn 15999: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 16000: communityquota, textbookquota, placementquota
1.1240 raeburn 16001:
16002: =back
16003:
16004: =item
16005: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16006: on your servers.
16007:
16008: =over
16009:
16010: =item
16011: remotesessions, hostedsessions
16012:
16013: =back
16014:
16015: =back
16016:
16017: In cases where a domain coordinator has never used the "Set Domain Configuration"
16018: utility to create a configuration.db file on a domain's primary library server
16019: only the following domain defaults: auth_def, auth_arg_def, lang_def
16020: -- corresponding values are authentication type (internal, krb4, krb5,
16021: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
16022: will be available. Values are retrieved from cache (if current), unless the
16023: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16024: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16025:
16026: Typical usage:
1.943 raeburn 16027:
1.1240 raeburn 16028: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 16029:
1.243 albertel 16030: =back
16031:
16032: =head2 Network Status Functions
16033:
16034: =over 4
1.191 harris41 16035:
16036: =item *
16037:
1.1137 raeburn 16038: dirlist() : return directory list based on URI (first arg).
16039:
16040: Inputs: 1 required, 5 optional.
16041:
16042: =over
16043:
16044: =item
16045: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16046:
16047: =item
16048: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
16049:
16050: =item
16051: $username - username of user/course to be listed. Extracted from $uri if absent.
16052:
16053: =item
16054: $getpropath - boolean: 1 if prepend path using &propath().
16055:
16056: =item
16057: $getuserdir - boolean: 1 if prepend path for "userfiles".
16058:
16059: =item
16060: $alternateRoot - path to prepend in place of path from $uri.
16061:
16062: =back
16063:
16064: Returns: Array of up to two items.
16065:
16066: =over
16067:
16068: a reference to an array of files/subdirectories
16069:
16070: =over
16071:
16072: Each element in the array of files/subdirectories is a & separated list of
16073: item name and the result of running stat on the item. If dirlist was requested
16074: for a file instead of a directory, the item name will be ''. For a directory
16075: listing, if the item is a metadata file, the element will end &N&M
16076: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16077: default copyright set (1).
16078:
16079: =back
16080:
16081: a scalar containing error condition (if encountered).
16082:
16083: =over
16084:
16085: =item
16086: no_host (no homeserver identified for $username:$domain).
16087:
16088: =item
16089: no_such_host (server contacted for listing not identified as valid host).
16090:
16091: =item
16092: con_lost (connection to remote server failed).
16093:
16094: =item
16095: refused (invalid $username:$domain received on lond side).
16096:
16097: =item
16098: no_such_dir (directory at specified path on lond side does not exist).
16099:
16100: =item
16101: empty (directory at specified path on lond side is empty).
16102:
16103: =over
16104:
16105: This is currently not encountered because the &ls3, &ls2,
16106: &ls (_handler) routines on the lond side do not filter out
16107: . and .. from a directory listing.
16108:
16109: =back
16110:
16111: =back
16112:
16113: =back
1.191 harris41 16114:
16115: =item *
16116:
1.243 albertel 16117: spareserver() : find server with least workload from spare.tab
16118:
1.986 foxr 16119:
16120: =item *
16121:
16122: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16123: if there is no corresponding loncapa host.
16124:
1.243 albertel 16125: =back
16126:
1.986 foxr 16127:
1.243 albertel 16128: =head2 Apache Request
16129:
16130: =over 4
1.191 harris41 16131:
16132: =item *
16133:
1.243 albertel 16134: ssi($url,%hash) : server side include, does a complete request cycle on url to
16135: localhost, posts hash
16136:
16137: =back
16138:
16139: =head2 Data to String to Data
16140:
16141: =over 4
1.191 harris41 16142:
16143: =item *
16144:
1.243 albertel 16145: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16146: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 16147:
16148: =item *
16149:
1.243 albertel 16150: hashref2str($hashref) : convert a hashref into a string complete with
16151: escaping and '=' and '&' separators, supports elements that are
16152: arrayrefs and hashrefs
1.191 harris41 16153:
16154: =item *
16155:
1.243 albertel 16156: arrayref2str($arrayref) : convert an arrayref into a string complete
16157: with escaping and '&' separators, supports elements that are arrayrefs
16158: and hashrefs
1.191 harris41 16159:
16160: =item *
16161:
1.243 albertel 16162: str2hash($string) : convert string to hash using unescaping and
16163: splitting on '=' and '&', supports elements that are arrayrefs and
16164: hashrefs
1.191 harris41 16165:
16166: =item *
16167:
1.243 albertel 16168: str2array($string) : convert string to hash using unescaping and
16169: splitting on '&', supports elements that are arrayrefs and hashrefs
16170:
16171: =back
16172:
16173: =head2 Logging Routines
16174:
16175:
16176: These routines allow one to make log messages in the lonnet.log and
16177: lonnet.perm logfiles.
1.191 harris41 16178:
1.1119 foxr 16179: =over 4
16180:
1.191 harris41 16181: =item *
16182:
1.243 albertel 16183: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 16184:
16185: =item *
16186:
1.243 albertel 16187: logthis() : append message to the normal lonnet.log file, it gets
16188: preiodically rolled over and deleted.
1.191 harris41 16189:
16190: =item *
16191:
1.243 albertel 16192: logperm() : append a permanent message to lonnet.perm.log, this log
16193: file never gets deleted by any automated portion of the system, only
16194: messages of critical importance should go in here.
16195:
1.1119 foxr 16196:
1.243 albertel 16197: =back
16198:
16199: =head2 General File Helper Routines
16200:
16201: =over 4
1.191 harris41 16202:
16203: =item *
16204:
1.481 raeburn 16205: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16206: (a) files in /uploaded
16207: (i) If a local copy of the file exists -
16208: compares modification date of local copy with last-modified date for
16209: definitive version stored on home server for course. If local copy is
16210: stale, requests a new version from the home server and stores it.
16211: If the original has been removed from the home server, then local copy
16212: is unlinked.
16213: (ii) If local copy does not exist -
16214: requests the file from the home server and stores it.
16215:
16216: If $caller is 'uploadrep':
16217: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16218: for request for files originally uploaded via DOCS.
16219: - returns 'ok' if fresh local copy now available, -1 otherwise.
16220:
16221: Otherwise:
16222: This indicates a call from the content generation phase of the request.
16223: - returns the entire contents of the file or -1.
16224:
16225: (b) files in /res
16226: - returns the entire contents of a file or -1;
16227: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 16228:
1.712 albertel 16229:
16230: =item *
16231:
16232: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16233: reference
16234:
16235: returns either a stat() list of data about the file or an empty list
16236: if the file doesn't exist or couldn't find out about it (connection
16237: problems or user unknown)
16238:
1.191 harris41 16239: =item *
16240:
1.243 albertel 16241: filelocation($dir,$file) : returns file system location of a file
16242: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16243: directory that relative $file lookups are to looked in ($dir of /a/dir
16244: and a file of ../bob will become /a/bob)
1.191 harris41 16245:
16246: =item *
16247:
16248: hreflocation($dir,$file) : returns file system location or a URL; same as
16249: filelocation except for hrefs
16250:
16251: =item *
16252:
1.1261 raeburn 16253: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16254: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 16255:
1.243 albertel 16256: =back
16257:
1.608 albertel 16258: =head2 Usererfile file routines (/uploaded*)
16259:
16260: =over 4
16261:
16262: =item *
16263:
16264: userfileupload(): main rotine for putting a file in a user or course's
16265: filespace, arguments are,
16266:
1.620 albertel 16267: formname - required - this is the name of the element in $env where the
1.608 albertel 16268: filename, and the contents of the file to create/modifed exist
1.620 albertel 16269: the filename is in $env{'form.'.$formname.'.filename'} and the
16270: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 16271: context - if coursedoc, store the file in the course of the active role
16272: of the current user;
16273: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16274: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 16275: subdir - required - subdirectory to put the file in under ../userfiles/
16276: if undefined, it will be placed in "unknown"
16277:
16278: (This routine calls clean_filename() to remove any dangerous
16279: characters from the filename, and then calls finuserfileupload() to
16280: complete the transaction)
16281:
16282: returns either the url of the uploaded file (/uploaded/....) if successful
16283: and /adm/notfound.html if unsuccessful
16284:
16285: =item *
16286:
16287: clean_filename(): routine for cleaing a filename up for storage in
16288: userfile space, argument is:
16289:
16290: filename - proposed filename
16291:
16292: returns: the new clean filename
16293:
16294: =item *
16295:
1.1090 raeburn 16296: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 16297: userspace, probably shouldn't be called directly
16298:
16299: docuname: username or courseid of destination for the file
16300: docudom: domain of user/course of destination for the file
16301: formname: same as for userfileupload()
1.1090 raeburn 16302: fname: filename (including subdirectories) for the file
16303: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401 raeburn 16304: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 16305: allfiles: reference to hash used to store objects found by parser
16306: codebase: reference to hash used for codebases of java objects found by parser
16307: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16308: thumbheight: height (pixels) of thumbnail to be created for uploaded image
16309: resizewidth: width to be used to resize image using resizeImage from ImageMagick
16310: resizeheight: height to be used to resize image using resizeImage from ImageMagick
16311: context: if 'overwrite', will move the uploaded file from its temporary location to
16312: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 16313: mimetype: reference to scalar to accommodate mime type determined
16314: from File::MMagic if $parser = parse.
1.608 albertel 16315:
16316: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 16317: and /adm/notfound.html if unsuccessful (or an error message if context
16318: was 'overwrite').
16319:
1.608 albertel 16320:
16321: =item *
16322:
16323: renameuserfile(): renames an existing userfile to a new name
16324:
16325: Args:
16326: docuname: username or courseid of destination for the file
16327: docudom: domain of user/course of destination for the file
16328: old: current file name (including any subdirs under userfiles)
16329: new: desired file name (including any subdirs under userfiles)
16330:
16331: =item *
16332:
16333: mkdiruserfile(): creates a directory is a userfiles dir
16334:
16335: Args:
16336: docuname: username or courseid of destination for the file
16337: docudom: domain of user/course of destination for the file
16338: dir: dir to create (including any subdirs under userfiles)
16339:
16340: =item *
16341:
16342: removeuserfile(): removes a file that exists in userfiles
16343:
16344: Args:
16345: docuname: username or courseid of destination for the file
16346: docudom: domain of user/course of destination for the file
16347: fname: filname to delete (including any subdirs under userfiles)
16348:
16349: =item *
16350:
16351: removeuploadedurl(): convience function for removeuserfile()
16352:
16353: Args:
16354: url: a full /uploaded/... url to delete
16355:
1.747 albertel 16356: =item *
16357:
16358: get_portfile_permissions():
16359: Args:
16360: domain: domain of user or course contain the portfolio files
16361: user: name of user or num of course contain the portfolio files
16362: Returns:
16363: hashref of a dump of the proper file_permissions.db
16364:
16365:
16366: =item *
16367:
16368: get_access_controls():
16369:
16370: Args:
16371: current_permissions: the hash ref returned from get_portfile_permissions()
16372: group: (optional) the group you want the files associated with
16373: file: (optional) the file you want access info on
16374:
16375: Returns:
1.749 raeburn 16376: a hash (keys are file names) of hashes containing
16377: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16378: values are XML containing access control settings (see below)
1.747 albertel 16379:
16380: Internal notes:
16381:
1.749 raeburn 16382: access controls are stored in file_permissions.db as key=value pairs.
16383: key -> path to file/file_name\0uniqueID:scope_end_start
16384: where scope -> public,guest,course,group,domains or users.
16385: end -> UNIX time for end of access (0 -> no end date)
16386: start -> UNIX time for start of access
16387:
16388: value -> XML description of access control
16389: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16390: <start></start>
16391: <end></end>
16392:
16393: <password></password> for scope type = guest
16394:
16395: <domain></domain> for scope type = course or group
16396: <number></number>
16397: <roles id="">
16398: <role></role>
16399: <access></access>
16400: <section></section>
16401: <group></group>
16402: </roles>
16403:
16404: <dom></dom> for scope type = domains
16405:
16406: <users> for scope type = users
16407: <user>
16408: <uname></uname>
16409: <udom></udom>
16410: </user>
16411: </users>
16412: </scope>
16413:
16414: Access data is also aggregated for each file in an additional key=value pair:
16415: key -> path to file/file_name\0accesscontrol
16416: value -> reference to hash
16417: hash contains key = value pairs
16418: where key = uniqueID:scope_end_start
16419: value = UNIX time record was last updated
16420:
16421: Used to improve speed of look-ups of access controls for each file.
16422:
16423: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16424:
1.1198 raeburn 16425: =item *
16426:
1.749 raeburn 16427: modify_access_controls():
16428:
16429: Modifies access controls for a portfolio file
16430: Args
16431: 1. file name
16432: 2. reference to hash of required changes,
16433: 3. domain
16434: 4. username
16435: where domain,username are the domain of the portfolio owner
16436: (either a user or a course)
16437:
16438: Returns:
16439: 1. result of additions or updates ('ok' or 'error', with error message).
16440: 2. result of deletions ('ok' or 'error', with error message).
16441: 3. reference to hash of any new or updated access controls.
16442: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16443: key = integer (inbound ID)
1.1198 raeburn 16444: value = uniqueID
16445:
16446: =item *
16447:
16448: get_timebased_id():
16449:
16450: Attempts to get a unique timestamp-based suffix for use with items added to a
16451: course via the Course Editor (e.g., folders, composite pages,
16452: group bulletin boards).
16453:
16454: Args: (first three required; six others optional)
16455:
16456: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16457: docssequence, or name of group
16458:
16459: 2. keyid (alphanumeric): name of temporary locking key in hash,
16460: e.g., num, boardids
16461:
16462: 3. namespace: name of gdbm file used to store suffixes already assigned;
16463: file will be named nohist_namespace.db
16464:
16465: 4. cdom: domain of course; default is current course domain from %env
16466:
16467: 5. cnum: course number; default is current course number from %env
16468:
16469: 6. idtype: set to concat if an additional digit is to be appended to the
16470: unix timestamp to form the suffix, if the plain timestamp is already
16471: in use. Default is to not do this, but simply increment the unix
16472: timestamp by 1 until a unique key is obtained.
16473:
16474: 7. who: holder of locking key; defaults to user:domain for user.
16475:
16476: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
16477: retrying); default is 3.
16478:
16479: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
16480:
16481: Returns:
16482:
16483: 1. suffix obtained (numeric)
16484:
16485: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16486:
16487: 3. error: contains (localized) error message if an error occurred.
16488:
1.747 albertel 16489:
1.608 albertel 16490: =back
16491:
1.243 albertel 16492: =head2 HTTP Helper Routines
16493:
16494: =over 4
16495:
1.191 harris41 16496: =item *
16497:
16498: escape() : unpack non-word characters into CGI-compatible hex codes
16499:
16500: =item *
16501:
16502: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16503:
1.243 albertel 16504: =back
16505:
16506: =head1 PRIVATE SUBROUTINES
16507:
16508: =head2 Underlying communication routines (Shouldn't call)
16509:
16510: =over 4
16511:
16512: =item *
16513:
16514: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16515:
16516: =item *
16517:
16518: reply() : uses subreply to send a message to remote machine, logs all failures
16519:
16520: =item *
16521:
16522: critical() : passes a critical message to another server; if cannot
16523: get through then place message in connection buffer directory and
16524: returns con_delayed, if incapable of saving message, returns
16525: con_failed
16526:
16527: =item *
16528:
16529: reconlonc() : tries to reconnect lonc client processes.
16530:
16531: =back
16532:
16533: =head2 Resource Access Logging
16534:
16535: =over 4
16536:
16537: =item *
16538:
16539: flushcourselogs() : flush (save) buffer logs and access logs
16540:
16541: =item *
16542:
16543: courselog($what) : save message for course in hash
16544:
16545: =item *
16546:
16547: courseacclog($what) : save message for course using &courselog(). Perform
16548: special processing for specific resource types (problems, exams, quizzes, etc).
16549:
1.191 harris41 16550: =item *
16551:
16552: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16553: as a PerlChildExitHandler
1.243 albertel 16554:
16555: =back
16556:
16557: =head2 Other
16558:
16559: =over 4
16560:
16561: =item *
16562:
16563: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 16564:
16565: =back
16566:
16567: =cut
1.877 foxr 16568:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>