Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1506
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1506 ! raeburn 4: # $Id: lonnet.pm,v 1.1505 2023/03/27 18:41:07 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
1.1416 raeburn 82: %managerstab $passwdmin);
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.1434 raeburn 99: use Net::CIDR;
1.1456 raeburn 100: use Sys::Hostname::FQDN();
1.807 albertel 101: use LONCAPA qw(:DEFAULT :match);
1.740 www 102: use LONCAPA::Configuration;
1.1160 www 103: use LONCAPA::lonmetadata;
1.1167 droeschl 104: use LONCAPA::Lond;
1.1345 raeburn 105: use LONCAPA::LWPReq;
1.1406 raeburn 106: use LONCAPA::transliterate;
1.1117 foxr 107:
1.1090 raeburn 108: use File::Copy;
1.676 albertel 109:
1.195 www 110: my $readit;
1.1288 damieng 111: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 112:
1.619 albertel 113: require Exporter;
114:
115: our @ISA = qw (Exporter);
116: our @EXPORT = qw(%env);
117:
1.449 matthew 118:
1.1187 raeburn 119: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 120: {
121: my $logid;
1.1187 raeburn 122: sub write_log {
1.1188 raeburn 123: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 124: if ($context eq 'course') {
125: if (($cnum eq '') || ($cdom eq '')) {
126: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
127: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
128: }
1.957 raeburn 129: }
1.1184 raeburn 130: $logid ++;
1.957 raeburn 131: my $now = time();
132: my $id=$now.'00000'.$$.'00000'.$logid;
1.1434 raeburn 133: my $ip = &get_requestor_ip();
1.1184 raeburn 134: my $logentry = {
135: $id => {
136: 'exe_uname' => $env{'user.name'},
137: 'exe_udom' => $env{'user.domain'},
138: 'exe_time' => $now,
1.1434 raeburn 139: 'exe_ip' => $ip,
1.1184 raeburn 140: 'delflag' => $delflag,
141: 'logentry' => $storehash,
142: 'uname' => $uname,
143: 'udom' => $udom,
144: }
145: };
146: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 147: }
148: }
1.1 albertel 149:
1.163 harris41 150: sub logtouch {
151: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 152: unless (-e "$execdir/logs/lonnet.log") {
1.1359 raeburn 153: open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 154: close $fh;
155: }
156: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
157: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
158: }
159:
1.1 albertel 160: sub logthis {
161: my $message=shift;
162: my $execdir=$perlvar{'lonDaemons'};
163: my $now=time;
164: my $local=localtime($now);
1.1359 raeburn 165: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 166: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
167: print $fh $logstring;
1.448 albertel 168: close($fh);
169: }
1.1 albertel 170: return 1;
171: }
172:
173: sub logperm {
174: my $message=shift;
175: my $execdir=$perlvar{'lonDaemons'};
176: my $now=time;
177: my $local=localtime($now);
1.1359 raeburn 178: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 179: print $fh "$now:$message:$local\n";
180: close($fh);
181: }
1.1 albertel 182: return 1;
183: }
184:
1.850 albertel 185: sub create_connection {
1.853 albertel 186: my ($hostname,$lonid) = @_;
1.851 albertel 187: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 188: Type => SOCK_STREAM,
189: Timeout => 10);
190: return 0 if (!$client);
1.1399 raeburn 191: print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
1.850 albertel 192: my $result = <$client>;
193: chomp($result);
194: return 1 if ($result eq 'done');
195: return 0;
196: }
197:
1.983 raeburn 198: sub get_server_timezone {
199: my ($cnum,$cdom) = @_;
200: my $home=&homeserver($cnum,$cdom);
201: if ($home ne 'no_host') {
202: my $cachetime = 24*3600;
203: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
204: if (defined($cached)) {
205: return $timezone;
206: } else {
207: my $timezone = &reply('servertimezone',$home);
208: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
209: }
210: }
211: }
1.850 albertel 212:
1.1106 raeburn 213: sub get_server_distarch {
214: my ($lonhost,$ignore_cache) = @_;
215: if (defined($lonhost)) {
216: if (!defined(&hostname($lonhost))) {
217: return;
218: }
219: my $cachetime = 12*3600;
220: if (!$ignore_cache) {
221: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
222: if (defined($cached)) {
223: return $distarch;
224: }
225: }
226: my $rep = &reply('serverdistarch',$lonhost);
227: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
228: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
229: $rep eq '') {
230: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
231: }
232: }
233: return;
234: }
235:
1.1315 raeburn 236: sub get_servercerts_info {
1.1383 raeburn 237: my ($lonhost,$hostname,$context) = @_;
238: return if ($lonhost eq '');
239: if ($hostname eq '') {
240: $hostname = &hostname($lonhost);
241: }
242: return if ($hostname eq '');
1.1315 raeburn 243: my ($rep,$uselocal);
1.1388 raeburn 244: if ($context eq 'install') {
1.1387 raeburn 245: $uselocal = 1;
246: } elsif (grep { $_ eq $lonhost } ¤t_machine_ids()) {
1.1315 raeburn 247: $uselocal = 1;
248: }
1.1387 raeburn 249: if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315 raeburn 250: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323 raeburn 251: if ($distro eq '') {
252: $uselocal = 0;
253: } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315 raeburn 254: if ($1 < 6) {
255: $uselocal = 0;
256: }
1.1346 raeburn 257: } elsif ($distro =~ /^(?:sles)(\d+)$/) {
258: if ($1 < 12) {
259: $uselocal = 0;
260: }
1.1315 raeburn 261: }
262: }
263: if ($uselocal) {
1.1383 raeburn 264: $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315 raeburn 265: } else {
266: $rep=&reply('servercerts',$lonhost);
267: }
268: my ($result,%returnhash);
269: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
270: ($rep eq 'unknown_cmd')) {
271: $result = $rep;
272: } else {
273: $result = 'ok';
274: my @pairs=split(/\&/,$rep);
275: foreach my $item (@pairs) {
276: my ($key,$value)=split(/=/,$item,2);
277: my $what = &unescape($key);
278: $returnhash{$what}=&thaw_unescape($value);
279: }
280: }
281: return ($result,\%returnhash);
282: }
283:
1.993 raeburn 284: sub get_server_loncaparev {
1.1073 raeburn 285: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 286: if (defined($lonhost)) {
287: if (!defined(&hostname($lonhost))) {
288: undef($lonhost);
289: }
290: }
291: if (!defined($lonhost)) {
292: if (defined(&domain($dom,'primary'))) {
293: $lonhost=&domain($dom,'primary');
294: if ($lonhost eq 'no_host') {
295: undef($lonhost);
296: }
297: }
298: }
299: if (defined($lonhost)) {
1.1073 raeburn 300: my $cachetime = 12*3600;
301: if (!$ignore_cache) {
302: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
303: if (defined($cached)) {
304: return $loncaparev;
305: }
306: }
307: my ($answer,$loncaparev);
308: my @ids=¤t_machine_ids();
309: if (grep(/^\Q$lonhost\E$/,@ids)) {
310: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 311: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 312: $loncaparev = $1;
313: }
314: } else {
315: $answer = &reply('serverloncaparev',$lonhost);
316: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
317: if ($caller eq 'loncron') {
1.1397 raeburn 318: my $hostname = &hostname($lonhost);
1.1073 raeburn 319: my $protocol = $protocol{$lonhost};
320: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 321: my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073 raeburn 322: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 323: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073 raeburn 324: unless ($response->is_error()) {
325: my $content = $response->content;
1.1081 raeburn 326: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 327: $loncaparev = $1;
328: }
329: }
330: } else {
331: $loncaparev = $loncaparevs{$lonhost};
332: }
1.1081 raeburn 333: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 334: $loncaparev = $1;
335: }
1.993 raeburn 336: }
1.1073 raeburn 337: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 338: }
339: }
340:
1.1074 raeburn 341: sub get_server_homeID {
342: my ($hostname,$ignore_cache,$caller) = @_;
343: unless ($ignore_cache) {
344: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
345: if (defined($cached)) {
346: return $serverhomeID;
347: }
348: }
349: my $cachetime = 12*3600;
350: my $serverhomeID;
351: if ($caller eq 'loncron') {
352: my @machine_ids = &machine_ids($hostname);
353: foreach my $id (@machine_ids) {
354: my $response = &reply('serverhomeID',$id);
355: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
356: $serverhomeID = $response;
357: last;
358: }
359: }
360: if ($serverhomeID eq '') {
361: $serverhomeID = $machine_ids[-1];
362: }
363: } else {
364: $serverhomeID = $serverhomeIDs{$hostname};
365: }
366: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
367: }
368:
1.1121 raeburn 369: sub get_remote_globals {
370: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 371: my ($result,%returnhash,%whatneeded);
372: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 373: foreach my $what (sort(keys(%{$whathash}))) {
374: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 375: my ($response,$cached);
1.1121 raeburn 376: unless ($ignore_cache) {
1.1125 raeburn 377: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 378: }
379: if (defined($cached)) {
1.1125 raeburn 380: $returnhash{$what} = $response;
1.1121 raeburn 381: } else {
1.1125 raeburn 382: $whatneeded{$what} = 1;
1.1121 raeburn 383: }
384: }
1.1125 raeburn 385: if (keys(%whatneeded) == 0) {
386: $result = 'ok';
387: } else {
1.1121 raeburn 388: my $requested = &freeze_escape(\%whatneeded);
389: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 390: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
391: ($rep eq 'unknown_cmd')) {
392: $result = $rep;
393: } else {
394: $result = 'ok';
1.1121 raeburn 395: my @pairs=split(/\&/,$rep);
1.1125 raeburn 396: foreach my $item (@pairs) {
397: my ($key,$value)=split(/=/,$item,2);
398: my $what = &unescape($key);
399: my $hashid = $lonhost.'-'.$what;
400: $returnhash{$what}=&thaw_unescape($value);
401: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 402: }
403: }
404: }
405: }
1.1125 raeburn 406: return ($result,\%returnhash);
1.1121 raeburn 407: }
408:
1.1124 raeburn 409: sub remote_devalidate_cache {
1.1241 raeburn 410: my ($lonhost,$cachekeys) = @_;
411: my $items;
412: return unless (ref($cachekeys) eq 'ARRAY');
413: my $cachestr = join('&',@{$cachekeys});
414: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 415: return $response;
416: }
417:
1.1 albertel 418: # -------------------------------------------------- Non-critical communication
419: sub subreply {
420: my ($cmd,$server)=@_;
1.838 albertel 421: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 422: #
423: # With loncnew process trimming, there's a timing hole between lonc server
424: # process exit and the master server picking up the listen on the AF_UNIX
425: # socket. In that time interval, a lock file will exist:
426:
427: my $lockfile=$peerfile.".lock";
428: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1289 damieng 429: sleep(0.1);
1.549 foxr 430: }
431: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 432: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 433: #
1.550 foxr 434: # We'll give the connection a few tries before abandoning it. If
435: # connection is not possible, we'll con_lost back to the client.
436: #
437: my $client;
438: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
439: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
440: Type => SOCK_STREAM,
441: Timeout => 10);
1.869 albertel 442: if ($client) {
1.550 foxr 443: last; # Connected!
1.850 albertel 444: } else {
1.853 albertel 445: &create_connection(&hostname($server),$server);
1.550 foxr 446: }
1.1289 damieng 447: sleep(0.1); # Try again later if failed connection.
1.550 foxr 448: }
449: my $answer;
450: if ($client) {
1.704 albertel 451: print $client "sethost:$server:$cmd\n";
1.550 foxr 452: $answer=<$client>;
453: if (!$answer) { $answer="con_lost"; }
454: chomp($answer);
455: } else {
456: $answer = 'con_lost'; # Failed connection.
457: }
1.1 albertel 458: return $answer;
459: }
460:
461: sub reply {
462: my ($cmd,$server)=@_;
1.838 albertel 463: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 464: my $answer=subreply($cmd,$server);
1.65 www 465: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396 raeburn 466: my $logged = $cmd;
467: if ($cmd =~ /^encrypt:([^:]+):/) {
468: my $subcmd = $1;
469: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
470: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462 raeburn 471: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
472: ($subcmd eq 'put')) {
1.1396 raeburn 473: (undef,undef,my @rest) = split(/:/,$cmd);
474: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
475: splice(@rest,2,1,'Hidden');
476: } elsif ($subcmd eq 'passwd') {
477: splice(@rest,2,2,('Hidden','Hidden'));
478: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462 raeburn 479: ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
1.1396 raeburn 480: splice(@rest,3,1,'Hidden');
481: }
482: $logged = join(':',('encrypt:'.$subcmd,@rest));
483: }
484: }
485: &logthis("<font color=\"blue\">WARNING:".
486: " $logged to $server returned $answer</font>");
1.12 www 487: }
1.1 albertel 488: return $answer;
489: }
490:
491: # ----------------------------------------------------------- Send USR1 to lonc
492:
493: sub reconlonc {
1.891 albertel 494: my ($lonid) = @_;
495: if ($lonid) {
1.1295 raeburn 496: my $hostname = &hostname($lonid);
1.891 albertel 497: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
498: if ($hostname && -e $peerfile) {
499: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
500: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
501: Type => SOCK_STREAM,
502: Timeout => 10);
503: if ($client) {
504: print $client ("reset_retries\n");
505: my $answer=<$client>;
506: #reset just this one.
507: }
508: }
509: return;
510: }
511:
1.836 www 512: &logthis("Trying to reconnect lonc");
1.1 albertel 513: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359 raeburn 514: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 515: my $loncpid=<$fh>;
516: chomp($loncpid);
517: if (kill 0 => $loncpid) {
518: &logthis("lonc at pid $loncpid responding, sending USR1");
519: kill USR1 => $loncpid;
520: sleep 1;
1.1295 raeburn 521: } else {
1.12 www 522: &logthis(
1.672 albertel 523: "<font color=\"blue\">WARNING:".
1.12 www 524: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 525: }
526: } else {
1.836 www 527: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 528: }
529: }
530:
531: # ------------------------------------------------------ Critical communication
1.12 www 532:
1.1 albertel 533: sub critical {
534: my ($cmd,$server)=@_;
1.838 albertel 535: unless (&hostname($server)) {
1.672 albertel 536: &logthis("<font color=\"blue\">WARNING:".
1.89 www 537: " Critical message to unknown server ($server)</font>");
538: return 'no_such_host';
539: }
1.1 albertel 540: my $answer=reply($cmd,$server);
541: if ($answer eq 'con_lost') {
1.1295 raeburn 542: &reconlonc($server);
1.589 albertel 543: my $answer=reply($cmd,$server);
1.1 albertel 544: if ($answer eq 'con_lost') {
545: my $now=time;
546: my $middlename=$cmd;
1.5 www 547: $middlename=substr($middlename,0,16);
1.1 albertel 548: $middlename=~s/\W//g;
549: my $dfilename=
1.305 www 550: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
551: $dumpcount++;
1.1 albertel 552: {
1.448 albertel 553: my $dfh;
1.1359 raeburn 554: if (open($dfh,">",$dfilename)) {
1.448 albertel 555: print $dfh "$cmd\n";
556: close($dfh);
557: }
1.1 albertel 558: }
1.1288 damieng 559: sleep 1;
1.1 albertel 560: my $wcmd='';
561: {
1.448 albertel 562: my $dfh;
1.1359 raeburn 563: if (open($dfh,"<",$dfilename)) {
1.448 albertel 564: $wcmd=<$dfh>;
565: close($dfh);
566: }
1.1 albertel 567: }
568: chomp($wcmd);
1.7 www 569: if ($wcmd eq $cmd) {
1.672 albertel 570: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 571: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 572: &logperm("D:$server:$cmd");
573: return 'con_delayed';
574: } else {
1.672 albertel 575: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 576: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 577: &logperm("F:$server:$cmd");
578: return 'con_failed';
579: }
580: }
581: }
582: return $answer;
1.405 albertel 583: }
584:
1.755 albertel 585: # ------------------------------------------- check if return value is an error
586:
587: sub error {
588: my ($result) = @_;
1.756 albertel 589: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 590: if ($2 == 2) { return undef; }
591: return $1;
592: }
593: return undef;
594: }
595:
1.783 albertel 596: sub convert_and_load_session_env {
597: my ($lonidsdir,$handle)=@_;
598: my @profile;
599: {
1.917 albertel 600: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
601: if (!$opened) {
1.915 albertel 602: return 0;
603: }
1.783 albertel 604: flock($idf,LOCK_SH);
605: @profile=<$idf>;
606: close($idf);
607: }
608: my %temp_env;
609: foreach my $line (@profile) {
1.786 albertel 610: if ($line !~ m/=/) {
611: return 0;
612: }
1.783 albertel 613: chomp($line);
614: my ($envname,$envvalue)=split(/=/,$line,2);
615: $temp_env{&unescape($envname)} = &unescape($envvalue);
616: }
617: unlink("$lonidsdir/$handle.id");
618: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
619: 0640)) {
620: %disk_env = %temp_env;
621: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
622: untie(%disk_env);
623: }
1.786 albertel 624: return 1;
1.783 albertel 625: }
626:
1.374 www 627: # ------------------------------------------- Transfer profile into environment
1.780 albertel 628: my $env_loaded;
629: sub transfer_profile_to_env {
1.788 albertel 630: my ($lonidsdir,$handle,$force_transfer) = @_;
631: if (!$force_transfer && $env_loaded) { return; }
1.374 www 632:
1.720 albertel 633: if (!defined($lonidsdir)) {
634: $lonidsdir = $perlvar{'lonIDsDir'};
635: }
636: if (!defined($handle)) {
637: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
638: }
639:
1.786 albertel 640: my $convert;
641: {
1.917 albertel 642: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
643: if (!$opened) {
1.915 albertel 644: return;
645: }
1.786 albertel 646: flock($idf,LOCK_SH);
647: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
648: &GDBM_READER(),0640)) {
649: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
650: untie(%disk_env);
651: } else {
652: $convert = 1;
653: }
654: }
655: if ($convert) {
656: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
657: &logthis("Failed to load session, or convert session.");
658: }
1.374 www 659: }
1.783 albertel 660:
1.786 albertel 661: my %remove;
1.783 albertel 662: while ( my $envname = each(%env) ) {
1.433 matthew 663: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
664: if ($time < time-300) {
1.783 albertel 665: $remove{$key}++;
1.433 matthew 666: }
667: }
668: }
1.783 albertel 669:
1.619 albertel 670: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 671: $env_loaded=1;
1.783 albertel 672: foreach my $expired_key (keys(%remove)) {
1.433 matthew 673: &delenv($expired_key);
1.374 www 674: }
1.1 albertel 675: }
676:
1.916 albertel 677: # ---------------------------------------------------- Check for valid session
678: sub check_for_valid_session {
1.1355 raeburn 679: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 680: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378 raeburn 681: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
682: if ($name eq 'lonDAV') {
683: $lonidsdir=$r->dir_config('lonDAVsessDir');
684: } else {
685: $lonidsdir=$r->dir_config('lonIDsDir');
686: if ($name eq '') {
687: $name = 'lonID';
688: }
689: }
690: if ($name eq 'lonID') {
691: $secure = 'lonSID';
1.1337 raeburn 692: $linkname = 'lonLinkID';
693: $pubname = 'lonPubID';
1.1378 raeburn 694: if (exists($cookies{$secure})) {
695: $lonid=$cookies{$secure};
696: } elsif (exists($cookies{$name})) {
697: $lonid=$cookies{$name};
1.1400 raeburn 698: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337 raeburn 699: $lonid=$cookies{$linkname};
1.1378 raeburn 700: } elsif (exists($cookies{$pubname})) {
701: $lonid=$cookies{$pubname};
1.1337 raeburn 702: }
1.1378 raeburn 703: } else {
704: $lonid=$cookies{$name};
1.1337 raeburn 705: }
1.916 albertel 706: return undef if (!$lonid);
707:
708: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378 raeburn 709: if (-l "$lonidsdir/$handle.id") {
710: my $link = readlink("$lonidsdir/$handle.id");
711: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
712: $handle = $1;
713: }
1.1155 raeburn 714: }
1.1355 raeburn 715: if (!-e "$lonidsdir/$handle.id") {
716: if ((ref($domref)) && ($name eq 'lonID') &&
717: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
718: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
719: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
720: $$domref = $possudom;
721: }
722: }
723: return undef;
724: }
1.916 albertel 725:
1.917 albertel 726: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
727: return undef if (!$opened);
1.916 albertel 728:
729: flock($idf,LOCK_SH);
730: my %disk_env;
731: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
732: &GDBM_READER(),0640)) {
733: return undef;
734: }
735:
736: if (!defined($disk_env{'user.name'})
737: || !defined($disk_env{'user.domain'})) {
1.1394 raeburn 738: untie(%disk_env);
1.916 albertel 739: return undef;
740: }
1.1245 raeburn 741:
742: if (ref($userhashref) eq 'HASH') {
743: $userhashref->{'name'} = $disk_env{'user.name'};
744: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1448 raeburn 745: if ($disk_env{'request.role'}) {
746: $userhashref->{'role'} = $disk_env{'request.role'};
747: }
1.1361 raeburn 748: $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375 raeburn 749: if ($userhashref->{'lti'}) {
750: $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
751: $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
752: }
1.1212 raeburn 753: }
1.1394 raeburn 754: untie(%disk_env);
1.1245 raeburn 755:
1.916 albertel 756: return $handle;
757: }
758:
1.830 albertel 759: sub timed_flock {
760: my ($file,$lock_type) = @_;
761: my $failed=0;
762: eval {
763: local $SIG{__DIE__}='DEFAULT';
764: local $SIG{ALRM}=sub {
765: $failed=1;
766: die("failed lock");
767: };
768: alarm(13);
769: flock($file,$lock_type);
770: alarm(0);
771: };
772: if ($failed) {
773: return undef;
774: } else {
775: return 1;
776: }
777: }
778:
1.1392 raeburn 779: sub get_sessionfile_vars {
780: my ($handle,$lonidsdir,$storearr) = @_;
781: my %returnhash;
782: unless (ref($storearr) eq 'ARRAY') {
783: return %returnhash;
784: }
785: if (-l "$lonidsdir/$handle.id") {
786: my $link = readlink("$lonidsdir/$handle.id");
787: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
788: $handle = $1;
789: }
790: }
791: if ((-e "$lonidsdir/$handle.id") &&
792: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
793: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
794: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
795: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
796: flock($idf,LOCK_SH);
797: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
798: &GDBM_READER(),0640)) {
799: foreach my $item (@{$storearr}) {
800: $returnhash{$item} = $disk_env{$item};
801: }
802: untie(%disk_env);
803: }
804: }
805: }
806: }
807: return %returnhash;
808: }
809:
1.5 www 810: # ---------------------------------------------------------- Append Environment
811:
812: sub appenv {
1.949 raeburn 813: my ($newenv,$roles) = @_;
814: if (ref($newenv) eq 'HASH') {
815: foreach my $key (keys(%{$newenv})) {
816: my $refused = 0;
817: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
818: $refused = 1;
819: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 820: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 821: if (grep(/^\Q$role\E$/,@{$roles})) {
822: $refused = 0;
823: }
824: }
825: }
826: if ($refused) {
827: &logthis("<font color=\"blue\">WARNING: ".
828: "Attempt to modify environment ".$key." to ".$newenv->{$key}
829: .'</font>');
830: delete($newenv->{$key});
831: } else {
832: $env{$key}=$newenv->{$key};
833: }
834: }
1.1376 raeburn 835: my $lonids = $perlvar{'lonIDsDir'};
836: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
837: my $opened = open(my $env_file,'+<',$env{'user.environment'});
838: if ($opened
839: && &timed_flock($env_file,LOCK_EX)
840: &&
841: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
842: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
843: while (my ($key,$value) = each(%{$newenv})) {
844: $disk_env{$key} = $value;
845: }
846: untie(%disk_env);
847: }
1.35 www 848: }
1.191 harris41 849: }
1.56 www 850: return 'ok';
851: }
852: # ----------------------------------------------------- Delete from Environment
853:
854: sub delenv {
1.1104 raeburn 855: my ($delthis,$regexp,$roles) = @_;
856: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
857: my $refused = 1;
858: if (ref($roles) eq 'ARRAY') {
859: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
860: if (grep(/^\Q$role\E$/,@{$roles})) {
861: $refused = 0;
862: }
863: }
864: if ($refused) {
865: &logthis("<font color=\"blue\">WARNING: ".
866: "Attempt to delete from environment ".$delthis);
867: return 'error';
868: }
1.56 www 869: }
1.917 albertel 870: my $opened = open(my $env_file,'+<',$env{'user.environment'});
871: if ($opened
1.915 albertel 872: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 873: &&
874: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
875: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 876: foreach my $key (keys(%disk_env)) {
1.987 raeburn 877: if ($regexp) {
878: if ($key=~/^$delthis/) {
879: delete($env{$key});
880: delete($disk_env{$key});
881: }
882: } else {
883: if ($key=~/^\Q$delthis\E/) {
884: delete($env{$key});
885: delete($disk_env{$key});
886: }
887: }
1.448 albertel 888: }
1.783 albertel 889: untie(%disk_env);
1.5 www 890: }
891: return 'ok';
1.369 albertel 892: }
893:
1.790 albertel 894: sub get_env_multiple {
895: my ($name) = @_;
896: my @values;
897: if (defined($env{$name})) {
898: # exists is it an array
899: if (ref($env{$name})) {
900: @values=@{ $env{$name} };
901: } else {
902: $values[0]=$env{$name};
903: }
904: }
905: return(@values);
906: }
907:
1.958 www 908: # ------------------------------------------------------------------- Locking
909:
910: sub set_lock {
911: my ($text)=@_;
912: $locknum++;
913: my $id=$$.'-'.$locknum;
914: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
915: 'session.lock.'.$id => $text});
916: return $id;
917: }
918:
919: sub get_locks {
920: my $num=0;
921: my %texts=();
922: foreach my $lock (split(/\,/,$env{'session.locks'})) {
923: if ($lock=~/\w/) {
924: $num++;
925: $texts{$lock}=$env{'session.lock.'.$lock};
926: }
927: }
928: return ($num,%texts);
929: }
930:
931: sub remove_lock {
932: my ($id)=@_;
933: my $newlocks='';
934: foreach my $lock (split(/\,/,$env{'session.locks'})) {
935: if (($lock=~/\w/) && ($lock ne $id)) {
936: $newlocks.=','.$lock;
937: }
938: }
939: &appenv({'session.locks' => $newlocks});
940: &delenv('session.lock.'.$id);
941: }
942:
943: sub remove_all_locks {
944: my $activelocks=$env{'session.locks'};
945: foreach my $lock (split(/\,/,$env{'session.locks'})) {
946: if ($lock=~/\w/) {
947: &remove_lock($lock);
948: }
949: }
950: }
951:
952:
1.369 albertel 953: # ------------------------------------------ Find out current server userload
954: sub userload {
955: my $numusers=0;
956: {
957: opendir(LONIDS,$perlvar{'lonIDsDir'});
958: my $filename;
959: my $curtime=time;
960: while ($filename=readdir(LONIDS)) {
1.925 albertel 961: next if ($filename eq '.' || $filename eq '..');
962: next if ($filename =~ /publicuser_\d+\.id/);
1.1390 raeburn 963: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 964: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 965: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 966: }
967: closedir(LONIDS);
968: }
969: my $userloadpercent=0;
970: my $maxuserload=$perlvar{'lonUserLoadLim'};
971: if ($maxuserload) {
1.371 albertel 972: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 973: }
1.372 albertel 974: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 975: return $userloadpercent;
1.283 www 976: }
977:
1.1 albertel 978: # ------------------------------ Find server with least workload from spare.tab
1.11 www 979:
1.1 albertel 980: sub spareserver {
1.1451 raeburn 981: my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 982: my $spare_server;
1.370 albertel 983: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 984: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
985: : $userloadpercent;
1.1083 raeburn 986: my ($uint_dom,$remotesessions);
987: if (($udom ne '') && (&domain($udom) ne '')) {
1.1494 raeburn 988: my $uprimary_id = &domain($udom,'primary');
989: $uint_dom = &internet_dom($uprimary_id);
990: my %udomdefaults = &get_domain_defaults($udom);
1.1083 raeburn 991: $remotesessions = $udomdefaults{'remotesessions'};
992: }
1.1123 raeburn 993: my $spareshash = &this_host_spares($udom);
994: if (ref($spareshash) eq 'HASH') {
995: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
996: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 997: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
998: $try_server));
1.1123 raeburn 999: ($spare_server, $lowest_load) =
1000: &compare_server_load($try_server, $spare_server, $lowest_load);
1001: }
1.1083 raeburn 1002: }
1.784 albertel 1003:
1.1123 raeburn 1004: my $found_server = ($spare_server ne '' && $lowest_load < 100);
1005:
1006: if (!$found_server) {
1007: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1008: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 1009: next unless (&spare_can_host($udom,$uint_dom,
1010: $remotesessions,$try_server));
1.1123 raeburn 1011: ($spare_server, $lowest_load) =
1012: &compare_server_load($try_server, $spare_server, $lowest_load);
1013: }
1014: }
1015: }
1.784 albertel 1016: }
1017:
1018: if (!$want_server_name) {
1.1001 raeburn 1019: if (defined($spare_server)) {
1020: my $hostname = &hostname($spare_server);
1.1083 raeburn 1021: if (defined($hostname)) {
1.1397 raeburn 1022: my $protocol = 'http';
1023: if ($protocol{$spare_server} eq 'https') {
1024: $protocol = $protocol{$spare_server};
1025: }
1.1494 raeburn 1026: my $alias = &use_proxy_alias($r,$spare_server);
1.1451 raeburn 1027: $hostname = $alias if ($alias ne '');
1.1001 raeburn 1028: $spare_server = $protocol.'://'.$hostname;
1029: }
1030: }
1.784 albertel 1031: }
1032: return $spare_server;
1033: }
1034:
1035: sub compare_server_load {
1.1253 raeburn 1036: my ($try_server, $spare_server, $lowest_load, $required) = @_;
1037:
1038: if ($required) {
1039: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
1040: my $remoterev = &get_server_loncaparev(undef,$try_server);
1041: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
1042: if (($major eq '' && $minor eq '') ||
1043: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
1044: return ($spare_server,$lowest_load);
1045: }
1046: }
1.784 albertel 1047:
1048: my $loadans = &reply('load', $try_server);
1049: my $userloadans = &reply('userload',$try_server);
1050:
1051: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 1052: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 1053: }
1054:
1055: my $load;
1056: if ($loadans =~ /\d/) {
1057: if ($userloadans =~ /\d/) {
1058: #both are numbers, pick the bigger one
1059: $load = ($loadans > $userloadans) ? $loadans
1060: : $userloadans;
1.411 albertel 1061: } else {
1.784 albertel 1062: $load = $loadans;
1.411 albertel 1063: }
1.784 albertel 1064: } else {
1065: $load = $userloadans;
1066: }
1067:
1068: if (($load =~ /\d/) && ($load < $lowest_load)) {
1069: $spare_server = $try_server;
1070: $lowest_load = $load;
1.370 albertel 1071: }
1.784 albertel 1072: return ($spare_server,$lowest_load);
1.202 matthew 1073: }
1.914 albertel 1074:
1075: # --------------------------- ask offload servers if user already has a session
1076: sub find_existing_session {
1077: my ($udom,$uname) = @_;
1.1123 raeburn 1078: my $spareshash = &this_host_spares($udom);
1079: if (ref($spareshash) eq 'HASH') {
1080: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1081: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1082: return $try_server if (&has_user_session($try_server, $udom, $uname));
1083: }
1084: }
1085: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1086: foreach my $try_server (@{ $spareshash->{'default'} }) {
1087: return $try_server if (&has_user_session($try_server, $udom, $uname));
1088: }
1089: }
1.914 albertel 1090: }
1091: return;
1092: }
1093:
1.1411 raeburn 1094: sub delusersession {
1095: my ($lonid,$udom,$uname) = @_;
1096: my $uprimary_id = &domain($udom,'primary');
1097: my $uintdom = &internet_dom($uprimary_id);
1098: my $intdom = &internet_dom($lonid);
1099: my $serverhomedom = &host_domain($lonid);
1100: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1101: return &reply(join(':','delusersession',
1102: map {&escape($_)} ($udom,$uname)),$lonid);
1103: }
1104: return;
1105: }
1106:
1.1389 raeburn 1107: # check if user's browser sent load balancer cookie and server still has session
1108: # and is not overloaded.
1109: sub check_for_balancer_cookie {
1110: my ($r,$update_mtime) = @_;
1111: my ($otherserver,$cookie);
1112: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1113: if (exists($cookies{'balanceID'})) {
1114: my $balid = $cookies{'balanceID'};
1115: $cookie=&LONCAPA::clean_handle($balid->value);
1116: my $balancedir=$r->dir_config('lonBalanceDir');
1117: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1118: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1119: my ($possudom,$possuname) = ($1,$2);
1120: my $has_session = 0;
1121: if ((&domain($possudom) ne '') &&
1122: (&homeserver($possuname,$possudom) ne 'no_host')) {
1123: my $try_server;
1124: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1125: if ($opened) {
1126: flock($idf,LOCK_SH);
1127: while (my $line = <$idf>) {
1128: chomp($line);
1129: if (&hostname($line) ne '') {
1130: $try_server = $line;
1131: last;
1132: }
1133: }
1134: close($idf);
1135: if (($try_server) &&
1136: (&has_user_session($try_server,$possudom,$possuname))) {
1137: my $lowest_load = 30000;
1138: ($otherserver,$lowest_load) =
1139: &compare_server_load($try_server,undef,$lowest_load);
1140: if ($otherserver ne '' && $lowest_load < 100) {
1141: $has_session = 1;
1142: } else {
1143: undef($otherserver);
1144: }
1145: }
1146: }
1147: }
1148: if ($has_session) {
1149: if ($update_mtime) {
1150: my $atime = my $mtime = time;
1151: utime($atime,$mtime,"$balancedir/$cookie.id");
1152: }
1153: } else {
1154: unlink("$balancedir/$cookie.id");
1155: }
1156: }
1157: }
1158: }
1159: return ($otherserver,$cookie);
1160: }
1161:
1.1431 raeburn 1162: sub updatebalcookie {
1163: my ($cookie,$balancer,$lastentry)=@_;
1164: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1165: my ($udom,$uname) = ($1,$2);
1166: my $uprimary_id = &domain($udom,'primary');
1167: my $uintdom = &internet_dom($uprimary_id);
1168: my $intdom = &internet_dom($balancer);
1169: my $serverhomedom = &host_domain($balancer);
1170: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1171: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1172: }
1173: }
1174: return;
1175: }
1176:
1.1389 raeburn 1177: sub delbalcookie {
1178: my ($cookie,$balancer) =@_;
1179: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1180: my ($udom,$uname) = ($1,$2);
1181: my $uprimary_id = &domain($udom,'primary');
1182: my $uintdom = &internet_dom($uprimary_id);
1183: my $intdom = &internet_dom($balancer);
1184: my $serverhomedom = &host_domain($balancer);
1185: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1431 raeburn 1186: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1389 raeburn 1187: }
1188: }
1189: }
1190:
1.914 albertel 1191: # -------------------------------- ask if server already has a session for user
1192: sub has_user_session {
1193: my ($lonid,$udom,$uname) = @_;
1194: my $result = &reply(join(':','userhassession',
1195: map {&escape($_)} ($udom,$uname)),$lonid);
1196: return 1 if ($result eq 'ok');
1197:
1198: return 0;
1199: }
1200:
1.1076 raeburn 1201: # --------- determine least loaded server in a user's domain which allows login
1202:
1203: sub choose_server {
1.1259 raeburn 1204: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1205: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1206: my %servers = &get_servers($udom);
1.1076 raeburn 1207: my $lowest_load = 30000;
1.1259 raeburn 1208: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1209: if ($skiploadbal) {
1210: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1211: unless (defined($cached)) {
1212: my $cachetime = 60*60*24;
1213: my %domconfig =
1.1494 raeburn 1214: &get_dom('configuration',['loadbalancing'],$udom);
1.1259 raeburn 1215: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1216: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1217: $cachetime);
1218: }
1219: }
1220: }
1.1076 raeburn 1221: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1222: if ($skiploadbal) {
1223: if (ref($balancers) eq 'HASH') {
1224: next if (exists($balancers->{$lonhost}));
1225: }
1.1389 raeburn 1226: }
1.1115 raeburn 1227: my $loginvia;
1228: if ($checkloginvia) {
1229: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1230: if ($loginvia) {
1231: my ($server,$path) = split(/:/,$loginvia);
1232: ($login_host, $lowest_load) =
1.1253 raeburn 1233: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1234: if ($login_host eq $server) {
1235: $portal_path = $path;
1.1151 raeburn 1236: $isredirect = 1;
1.1116 raeburn 1237: }
1238: } else {
1239: ($login_host, $lowest_load) =
1.1253 raeburn 1240: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1241: if ($login_host eq $lonhost) {
1242: $portal_path = '';
1.1151 raeburn 1243: $isredirect = '';
1.1116 raeburn 1244: }
1245: }
1246: } else {
1.1076 raeburn 1247: ($login_host, $lowest_load) =
1.1253 raeburn 1248: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1249: }
1250: }
1251: if ($login_host ne '') {
1.1116 raeburn 1252: $hostname = &hostname($login_host);
1.1076 raeburn 1253: }
1.1331 raeburn 1254: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1255: }
1256:
1.1420 raeburn 1257: sub get_course_sessions {
1258: my ($cnum,$cdom,$lastactivity) = @_;
1259: my %servers = &internet_dom_servers($cdom);
1260: my %returnhash;
1261: foreach my $server (sort(keys(%servers))) {
1262: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1263: my @pairs=split(/\&/,$rep);
1264: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1265: foreach my $item (@pairs) {
1266: my ($key,$value)=split(/=/,$item,2);
1267: $key = &unescape($key);
1268: next if ($key =~ /^error: 2 /);
1269: if (exists($returnhash{$key})) {
1270: next if ($value < $returnhash{$key});
1271: }
1272: $returnhash{$key}=$value;
1273: }
1274: }
1275: }
1276: return %returnhash;
1277: }
1278:
1.202 matthew 1279: # --------------------------------------------- Try to change a user's password
1280:
1281: sub changepass {
1.799 raeburn 1282: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1283: $currentpass = &escape($currentpass);
1284: $newpass = &escape($newpass);
1.1030 raeburn 1285: my $lonhost = $perlvar{'lonHostID'};
1286: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1287: $server);
1288: if (! $answer) {
1289: &logthis("No reply on password change request to $server ".
1290: "by $uname in domain $udom.");
1291: } elsif ($answer =~ "^ok") {
1292: &logthis("$uname in $udom successfully changed their password ".
1293: "on $server.");
1294: } elsif ($answer =~ "^pwchange_failure") {
1295: &logthis("$uname in $udom was unable to change their password ".
1296: "on $server. The action was blocked by either lcpasswd ".
1297: "or pwchange");
1298: } elsif ($answer =~ "^non_authorized") {
1299: &logthis("$uname in $udom did not get their password correct when ".
1300: "attempting to change it on $server.");
1301: } elsif ($answer =~ "^auth_mode_error") {
1302: &logthis("$uname in $udom attempted to change their password despite ".
1303: "not being locally or internally authenticated on $server.");
1304: } elsif ($answer =~ "^unknown_user") {
1305: &logthis("$uname in $udom attempted to change their password ".
1306: "on $server but were unable to because $server is not ".
1307: "their home server.");
1308: } elsif ($answer =~ "^refused") {
1309: &logthis("$server refused to change $uname in $udom password because ".
1310: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1311: } elsif ($answer =~ "invalid_client") {
1312: &logthis("$server refused to change $uname in $udom password because ".
1313: "it was a reset by e-mail originating from an invalid server.");
1.1408 raeburn 1314: } elsif ($answer =~ "^prioruse") {
1315: &logthis("$server refused to change $uname in $udom password because ".
1316: "the password had been used before");
1.202 matthew 1317: }
1318: return $answer;
1.1 albertel 1319: }
1320:
1.169 harris41 1321: # ----------------------- Try to determine user's current authentication scheme
1322:
1323: sub queryauthenticate {
1324: my ($uname,$udom)=@_;
1.456 albertel 1325: my $uhome=&homeserver($uname,$udom);
1.1484 raeburn 1326: if ((!$uhome) || ($uhome eq 'no_host')) {
1.456 albertel 1327: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1328: return 'no_host';
1329: }
1330: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1331: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1332: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1333: }
1.456 albertel 1334: return $answer;
1.169 harris41 1335: }
1336:
1.1 albertel 1337: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1338:
1.1 albertel 1339: sub authenticate {
1.1073 raeburn 1340: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1341: $upass=&escape($upass);
1342: $uname= &LONCAPA::clean_username($uname);
1.836 www 1343: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1344: my $newhome;
1.836 www 1345: if ((!$uhome) || ($uhome eq 'no_host')) {
1346: # Maybe the machine was offline and only re-appeared again recently?
1347: &reconlonc();
1348: # One more
1.952 raeburn 1349: $uhome=&homeserver($uname,$udom,1);
1350: if (($uhome eq 'no_host') && $checkdefauth) {
1351: if (defined(&domain($udom,'primary'))) {
1352: $newhome=&domain($udom,'primary');
1353: }
1354: if ($newhome ne '') {
1355: $uhome = $newhome;
1356: }
1357: }
1.836 www 1358: if ((!$uhome) || ($uhome eq 'no_host')) {
1359: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1360: return 'no_host';
1361: }
1.1 albertel 1362: }
1.1073 raeburn 1363: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1364: if ($answer eq 'authorized') {
1.952 raeburn 1365: if ($newhome) {
1366: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1367: return 'no_account_on_host';
1368: } else {
1369: &logthis("User $uname at $udom authorized by $uhome");
1370: return $uhome;
1371: }
1.471 albertel 1372: }
1373: if ($answer eq 'non_authorized') {
1374: &logthis("User $uname at $udom rejected by $uhome");
1.1484 raeburn 1375: return 'no_host';
1.9 www 1376: }
1.471 albertel 1377: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1378: return 'no_host';
1379: }
1380:
1.1491 raeburn 1381: sub can_switchserver {
1382: my ($udom,$home) = @_;
1383: my ($canswitch,@intdoms);
1384: my $internet_names = &get_internet_names($home);
1385: if (ref($internet_names) eq 'ARRAY') {
1386: @intdoms = @{$internet_names};
1387: }
1388: my $uint_dom = &internet_dom(&domain($udom,'primary'));
1389: if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1390: $canswitch = 1;
1391: } else {
1392: my $serverhomeID = &get_server_homeID(&hostname($home));
1393: my $serverhomedom = &host_domain($serverhomeID);
1394: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1395: my %udomdefaults = &get_domain_defaults($udom);
1396: my $remoterev = &get_server_loncaparev('',$home);
1397: $canswitch = &can_host_session($udom,$home,$remoterev,
1398: $udomdefaults{'remotesessions'},
1399: $defdomdefaults{'hostedsessions'});
1400: }
1401: return $canswitch;
1402: }
1403:
1.1073 raeburn 1404: sub can_host_session {
1.1074 raeburn 1405: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1406: my $canhost = 1;
1.1494 raeburn 1407: my $host_idn = &internet_dom($lonhost);
1.1073 raeburn 1408: if (ref($remotesessions) eq 'HASH') {
1409: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1410: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1411: $canhost = 0;
1412: } else {
1413: $canhost = 1;
1414: }
1415: }
1416: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1417: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1418: $canhost = 1;
1419: } else {
1420: $canhost = 0;
1421: }
1422: }
1423: if ($canhost) {
1424: if ($remotesessions->{'version'} ne '') {
1425: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1426: if ($reqmajor ne '' && $reqminor ne '') {
1427: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1428: my $major = $1;
1429: my $minor = $2;
1430: if (($major < $reqmajor ) ||
1431: (($major == $reqmajor) && ($minor < $reqminor))) {
1432: $canhost = 0;
1433: }
1434: } else {
1435: $canhost = 0;
1436: }
1437: }
1438: }
1439: }
1440: }
1441: if ($canhost) {
1442: if (ref($hostedsessions) eq 'HASH') {
1.1494 raeburn 1443: my $uprimary_id = &domain($udom,'primary');
1444: my $uint_dom = &internet_dom($uprimary_id);
1.1073 raeburn 1445: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1446: if (($uint_dom ne '') &&
1447: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1448: $canhost = 0;
1449: } else {
1450: $canhost = 1;
1451: }
1452: }
1453: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1454: if (($uint_dom ne '') &&
1455: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1456: $canhost = 1;
1457: } else {
1458: $canhost = 0;
1459: }
1460: }
1461: }
1462: }
1463: return $canhost;
1464: }
1465:
1.1083 raeburn 1466: sub spare_can_host {
1467: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1468: my $canhost=1;
1.1279 raeburn 1469: my $try_server_hostname = &hostname($try_server);
1470: my $serverhomeID = &get_server_homeID($try_server_hostname);
1471: my $serverhomedom = &host_domain($serverhomeID);
1472: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1473: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1474: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1475: $canhost = 0;
1476: }
1477: }
1.1439 raeburn 1478: if ($canhost) {
1479: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1480: if ($defdomdefaults{'offloadoth'}{$try_server}) {
1481: unless (&shared_institution($udom,$try_server)) {
1482: $canhost = 0;
1483: }
1484: }
1485: }
1486: }
1.1279 raeburn 1487: if (($canhost) && ($uint_dom)) {
1488: my @intdoms;
1489: my $internet_names = &get_internet_names($try_server);
1490: if (ref($internet_names) eq 'ARRAY') {
1491: @intdoms = @{$internet_names};
1492: }
1493: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1494: my $remoterev = &get_server_loncaparev(undef,$try_server);
1495: $canhost = &can_host_session($udom,$try_server,$remoterev,
1496: $remotesessions,
1497: $defdomdefaults{'hostedsessions'});
1498: }
1.1083 raeburn 1499: }
1500: return $canhost;
1501: }
1502:
1.1123 raeburn 1503: sub this_host_spares {
1504: my ($dom) = @_;
1.1126 raeburn 1505: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1506: my @hosts = ¤t_machine_ids();
1507: foreach my $lonhost (@hosts) {
1508: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1509: $dom_in_use = $dom;
1510: $lonhost_in_use = $lonhost;
1.1123 raeburn 1511: last;
1512: }
1513: }
1.1126 raeburn 1514: if ($dom_in_use ne '') {
1515: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1516: }
1517: if (ref($result) ne 'HASH') {
1518: $lonhost_in_use = $perlvar{'lonHostID'};
1519: $dom_in_use = &host_domain($lonhost_in_use);
1520: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1521: if (ref($result) ne 'HASH') {
1522: $result = \%spareid;
1523: }
1524: }
1525: return $result;
1526: }
1527:
1528: sub spares_for_offload {
1529: my ($dom_in_use,$lonhost_in_use) = @_;
1530: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1531: if (defined($cached)) {
1532: return $result;
1533: } else {
1.1126 raeburn 1534: my $cachetime = 60*60*24;
1535: my %domconfig =
1.1494 raeburn 1536: &get_dom('configuration',['usersessions'],$dom_in_use);
1.1126 raeburn 1537: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1538: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1539: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1540: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1541: }
1542: }
1543: }
1544: }
1.1126 raeburn 1545: return;
1.1123 raeburn 1546: }
1547:
1.1129 raeburn 1548: sub get_lonbalancer_config {
1549: my ($servers) = @_;
1550: my ($currbalancer,$currtargets);
1551: if (ref($servers) eq 'HASH') {
1552: foreach my $server (keys(%{$servers})) {
1553: my %what = (
1554: spareid => 1,
1555: perlvar => 1,
1556: );
1557: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1558: if ($result eq 'ok') {
1559: if (ref($returnhash) eq 'HASH') {
1560: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1561: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1562: $currbalancer = $server;
1563: $currtargets = {};
1564: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1565: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1566: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1567: }
1568: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1569: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1570: }
1571: }
1572: last;
1573: }
1574: }
1575: }
1576: }
1577: }
1578: }
1579: return ($currbalancer,$currtargets);
1580: }
1581:
1582: sub check_loadbalancing {
1.1331 raeburn 1583: my ($uname,$udom,$caller) = @_;
1.1191 raeburn 1584: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391 raeburn 1585: $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129 raeburn 1586: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1587: my @hosts = ¤t_machine_ids();
1.1494 raeburn 1588: my $uprimary_id = &domain($udom,'primary');
1589: my $uintdom = &internet_dom($uprimary_id);
1590: my $intdom = &internet_dom($lonhost);
1.1129 raeburn 1591: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1592: my $domneedscache;
1.1129 raeburn 1593: my $cachetime = 60*60*24;
1594:
1595: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1596: $dom_in_use = $udom;
1597: $homeintdom = 1;
1598: } else {
1599: $dom_in_use = $serverhomedom;
1600: }
1601: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1602: unless (defined($cached)) {
1603: my %domconfig =
1.1494 raeburn 1604: &get_dom('configuration',['loadbalancing'],$dom_in_use);
1.1129 raeburn 1605: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1606: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1607: } else {
1608: $domneedscache = $dom_in_use;
1.1129 raeburn 1609: }
1610: }
1611: if (ref($result) eq 'HASH') {
1.1391 raeburn 1612: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1613: &check_balancer_result($result,@hosts);
1.1129 raeburn 1614: if ($is_balancer) {
1615: if (ref($currrules) eq 'HASH') {
1616: if ($homeintdom) {
1617: if ($uname ne '') {
1618: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1619: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1620: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1621: $rule_in_effect = $currrules->{'_LC_author'};
1622: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1623: $rule_in_effect = $currrules->{'_LC_adv'}
1624: }
1625: }
1626: if ($rule_in_effect eq '') {
1627: my %userenv = &userenvironment($udom,$uname,'inststatus');
1628: if ($userenv{'inststatus'} ne '') {
1629: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1630: my ($othertitle,$usertypes,$types) =
1631: &Apache::loncommon::sorted_inst_types($udom);
1632: if (ref($types) eq 'ARRAY') {
1633: foreach my $type (@{$types}) {
1634: if (grep(/^\Q$type\E$/,@statuses)) {
1635: if (exists($currrules->{$type})) {
1636: $rule_in_effect = $currrules->{$type};
1637: }
1638: }
1639: }
1640: }
1641: } else {
1642: if (exists($currrules->{'default'})) {
1643: $rule_in_effect = $currrules->{'default'};
1644: }
1645: }
1646: }
1647: } else {
1648: if (exists($currrules->{'default'})) {
1649: $rule_in_effect = $currrules->{'default'};
1650: }
1651: }
1652: } else {
1653: if ($currrules->{'_LC_external'} ne '') {
1654: $rule_in_effect = $currrules->{'_LC_external'};
1655: }
1656: }
1657: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1658: $uname,$udom);
1659: }
1660: }
1661: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1662: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1663: unless (defined($cached)) {
1664: my %domconfig =
1.1494 raeburn 1665: &get_dom('configuration',['loadbalancing'],$serverhomedom);
1.1129 raeburn 1666: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1667: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1668: } else {
1669: $domneedscache = $serverhomedom;
1.1129 raeburn 1670: }
1671: }
1672: if (ref($result) eq 'HASH') {
1.1391 raeburn 1673: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1674: &check_balancer_result($result,@hosts);
1675: if ($is_balancer) {
1.1129 raeburn 1676: if (ref($currrules) eq 'HASH') {
1677: if ($currrules->{'_LC_internetdom'} ne '') {
1678: $rule_in_effect = $currrules->{'_LC_internetdom'};
1679: }
1680: }
1681: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1682: $uname,$udom);
1683: }
1684: } else {
1685: if ($perlvar{'lonBalancer'} eq 'yes') {
1686: $is_balancer = 1;
1687: $offloadto = &this_host_spares($dom_in_use);
1688: }
1.1307 raeburn 1689: unless (defined($cached)) {
1690: $domneedscache = $serverhomedom;
1691: }
1.1129 raeburn 1692: }
1693: } else {
1694: if ($perlvar{'lonBalancer'} eq 'yes') {
1695: $is_balancer = 1;
1696: $offloadto = &this_host_spares($dom_in_use);
1697: }
1.1307 raeburn 1698: unless (defined($cached)) {
1699: $domneedscache = $serverhomedom;
1700: }
1701: }
1702: if ($domneedscache) {
1703: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1704: }
1.1430 raeburn 1705: if (($is_balancer) && ($caller ne 'switchserver')) {
1.1176 raeburn 1706: my $lowest_load = 30000;
1707: if (ref($offloadto) eq 'HASH') {
1708: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1709: foreach my $try_server (@{$offloadto->{'primary'}}) {
1710: ($otherserver,$lowest_load) =
1711: &compare_server_load($try_server,$otherserver,$lowest_load);
1712: }
1.1129 raeburn 1713: }
1.1176 raeburn 1714: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1715:
1.1176 raeburn 1716: if (!$found_server) {
1717: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1718: foreach my $try_server (@{$offloadto->{'default'}}) {
1719: ($otherserver,$lowest_load) =
1720: &compare_server_load($try_server,$otherserver,$lowest_load);
1721: }
1722: }
1723: }
1724: } elsif (ref($offloadto) eq 'ARRAY') {
1725: if (@{$offloadto} == 1) {
1726: $otherserver = $offloadto->[0];
1727: } elsif (@{$offloadto} > 1) {
1728: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1729: ($otherserver,$lowest_load) =
1730: &compare_server_load($try_server,$otherserver,$lowest_load);
1731: }
1732: }
1733: }
1.1331 raeburn 1734: unless ($caller eq 'login') {
1735: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1736: $is_balancer = 0;
1737: if ($uname ne '' && $udom ne '') {
1738: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389 raeburn 1739: &appenv({'user.loadbalexempt' => $lonhost,
1.1331 raeburn 1740: 'user.loadbalcheck.time' => time});
1741: }
1.1176 raeburn 1742: }
1.1129 raeburn 1743: }
1744: }
1.1430 raeburn 1745: }
1746: if (($is_balancer) && (!$homeintdom)) {
1747: undef($setcookie);
1.1129 raeburn 1748: }
1.1391 raeburn 1749: return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129 raeburn 1750: }
1751:
1.1191 raeburn 1752: sub check_balancer_result {
1753: my ($result,@hosts) = @_;
1.1391 raeburn 1754: my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1755: if (ref($result) eq 'HASH') {
1756: if ($result->{'lonhost'} ne '') {
1757: my $currbalancer = $result->{'lonhost'};
1758: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1759: $is_balancer = 1;
1760: $currtargets = $result->{'targets'};
1761: $currrules = $result->{'rules'};
1762: }
1.1391 raeburn 1763: $dom_balancers = $currbalancer;
1.1191 raeburn 1764: } else {
1.1391 raeburn 1765: if (keys(%{$result})) {
1766: foreach my $key (keys(%{$result})) {
1767: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1768: (ref($result->{$key}) eq 'HASH')) {
1769: $is_balancer = 1;
1770: $currrules = $result->{$key}{'rules'};
1771: $currtargets = $result->{$key}{'targets'};
1772: $setcookie = $result->{$key}{'cookie'};
1773: last;
1774: }
1.1191 raeburn 1775: }
1.1391 raeburn 1776: $dom_balancers = join(',',sort(keys(%{$result})));
1.1191 raeburn 1777: }
1778: }
1779: }
1.1391 raeburn 1780: return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1781: }
1782:
1.1129 raeburn 1783: sub get_loadbalancer_targets {
1784: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1785: my $offloadto;
1.1175 raeburn 1786: if ($rule_in_effect eq 'none') {
1787: return [$perlvar{'lonHostID'}];
1788: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1789: $offloadto = $currtargets;
1790: } else {
1791: if ($rule_in_effect eq 'homeserver') {
1792: my $homeserver = &homeserver($uname,$udom);
1793: if ($homeserver ne 'no_host') {
1794: $offloadto = [$homeserver];
1795: }
1796: } elsif ($rule_in_effect eq 'externalbalancer') {
1797: my %domconfig =
1.1494 raeburn 1798: &get_dom('configuration',['loadbalancing'],$udom);
1.1129 raeburn 1799: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1800: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1801: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1802: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1803: }
1804: }
1805: } else {
1.1178 raeburn 1806: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1807: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1808: if (&hostname($remotebalancer) ne '') {
1809: $offloadto = [$remotebalancer];
1810: }
1811: }
1812: } elsif (&hostname($rule_in_effect) ne '') {
1813: $offloadto = [$rule_in_effect];
1814: }
1815: }
1816: return $offloadto;
1817: }
1818:
1.1127 raeburn 1819: sub internet_dom_servers {
1820: my ($dom) = @_;
1821: my (%uniqservers,%servers);
1822: my $primaryserver = &hostname(&domain($dom,'primary'));
1823: my @machinedoms = &machine_domains($primaryserver);
1824: foreach my $mdom (@machinedoms) {
1825: my %currservers = %servers;
1826: my %server = &get_servers($mdom);
1827: %servers = (%currservers,%server);
1828: }
1829: my %by_hostname;
1830: foreach my $id (keys(%servers)) {
1831: push(@{$by_hostname{$servers{$id}}},$id);
1832: }
1833: foreach my $hostname (sort(keys(%by_hostname))) {
1834: if (@{$by_hostname{$hostname}} > 1) {
1835: my $match = 0;
1836: foreach my $id (@{$by_hostname{$hostname}}) {
1837: if (&host_domain($id) eq $dom) {
1838: $uniqservers{$id} = $hostname;
1839: $match = 1;
1840: }
1841: }
1842: unless ($match) {
1843: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1844: }
1845: } else {
1846: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1847: }
1848: }
1849: return %uniqservers;
1850: }
1851:
1.1347 raeburn 1852: sub trusted_domains {
1853: my ($cmdtype,$calldom) = @_;
1.1349 raeburn 1854: my ($trusted,$untrusted);
1.1347 raeburn 1855: if (&domain($calldom) eq '') {
1.1349 raeburn 1856: return ($trusted,$untrusted);
1.1347 raeburn 1857: }
1.1395 raeburn 1858: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349 raeburn 1859: return ($trusted,$untrusted);
1.1347 raeburn 1860: }
1861: my $callprimary = &domain($calldom,'primary');
1.1494 raeburn 1862: my $intcalldom = &internet_dom($callprimary);
1.1347 raeburn 1863: if ($intcalldom eq '') {
1.1349 raeburn 1864: return ($trusted,$untrusted);
1.1347 raeburn 1865: }
1866:
1.1494 raeburn 1867: my ($trustconfig,$cached)=&is_cached_new('trust',$calldom);
1.1347 raeburn 1868: unless (defined($cached)) {
1.1494 raeburn 1869: my %domconfig = &get_dom('configuration',['trust'],$calldom);
1870: &do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1.1347 raeburn 1871: $trustconfig = $domconfig{'trust'};
1872: }
1873: if (ref($trustconfig)) {
1874: my (%possexc,%possinc,@allexc,@allinc);
1875: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1876: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1877: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1878: }
1879: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395 raeburn 1880: $possinc{$intcalldom} = 1;
1.1347 raeburn 1881: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1882: }
1883: }
1884: if (keys(%possexc)) {
1885: if (keys(%possinc)) {
1886: foreach my $key (sort(keys(%possexc))) {
1887: next if ($key eq $intcalldom);
1888: unless ($possinc{$key}) {
1889: push(@allexc,$key);
1890: }
1891: }
1892: } else {
1893: @allexc = sort(keys(%possexc));
1894: }
1895: }
1896: if (keys(%possinc)) {
1897: $possinc{$intcalldom} = 1;
1898: @allinc = sort(keys(%possinc));
1899: }
1900: if ((@allexc > 0) || (@allinc > 0)) {
1901: my %doms_by_intdom;
1902: my %allintdoms = &all_host_intdom();
1903: my %alldoms = &all_host_domain();
1904: foreach my $key (%allintdoms) {
1905: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1906: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1907: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1908: }
1909: } else {
1910: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1911: }
1912: }
1913: foreach my $exc (@allexc) {
1914: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395 raeburn 1915: push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347 raeburn 1916: }
1917: }
1918: foreach my $inc (@allinc) {
1919: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395 raeburn 1920: push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347 raeburn 1921: }
1922: }
1923: }
1924: }
1.1349 raeburn 1925: return ($trusted,$untrusted);
1.1347 raeburn 1926: }
1927:
1928: sub will_trust {
1929: my ($cmdtype,$domain,$possdom) = @_;
1930: return 1 if ($domain eq $possdom);
1931: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1932: my $willtrust;
1933: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1934: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1935: $willtrust = 1;
1936: }
1937: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1938: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1939: $willtrust = 1;
1940: }
1941: } else {
1942: $willtrust = 1;
1943: }
1944: return $willtrust;
1945: }
1946:
1.1 albertel 1947: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1948:
1.599 albertel 1949: my %homecache;
1.1 albertel 1950: sub homeserver {
1.230 stredwic 1951: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1952: my $index="$uname:$udom";
1.426 albertel 1953:
1.599 albertel 1954: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1955:
1956: my %servers = &get_servers($udom,'library');
1957: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1958: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1959: exists($badServerCache{$tryserver}));
1.841 albertel 1960:
1961: my $answer=reply("home:$udom:$uname",$tryserver);
1962: if ($answer eq 'found') {
1963: delete($badServerCache{$tryserver});
1964: return $homecache{$index}=$tryserver;
1965: } elsif ($answer eq 'no_host') {
1966: $badServerCache{$tryserver}=1;
1967: }
1.1 albertel 1968: }
1969: return 'no_host';
1.70 www 1970: }
1971:
1.1300 raeburn 1972: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1973:
1974: sub idget {
1.1300 raeburn 1975: my ($udom,$idsref,$namespace)=@_;
1.70 www 1976: my %returnhash=();
1.1300 raeburn 1977: my @ids=();
1978: if (ref($idsref) eq 'ARRAY') {
1979: @ids = @{$idsref};
1980: } else {
1981: return %returnhash;
1982: }
1983: if ($namespace eq '') {
1984: $namespace = 'ids';
1985: }
1.70 www 1986:
1.841 albertel 1987: my %servers = &get_servers($udom,'library');
1988: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1989: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1990: if ($namespace eq 'ids') {
1991: $idlist=~tr/A-Z/a-z/;
1992: }
1993: my $reply;
1994: if ($namespace eq 'ids') {
1995: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1996: } else {
1997: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1998: }
1.841 albertel 1999: my @answer=();
2000: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
2001: @answer=split(/\&/,$reply);
2002: } ;
2003: my $i;
2004: for ($i=0;$i<=$#ids;$i++) {
2005: if ($answer[$i]) {
1.1299 raeburn 2006: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 2007: }
1.841 albertel 2008: }
1.1300 raeburn 2009: }
1.70 www 2010: return %returnhash;
2011: }
2012:
2013: # ------------------------------------- Find the IDs behind a list of usernames
2014:
2015: sub idrget {
2016: my ($udom,@unames)=@_;
2017: my %returnhash=();
1.800 albertel 2018: foreach my $uname (@unames) {
2019: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 2020: }
1.70 www 2021: return %returnhash;
2022: }
2023:
1.1300 raeburn 2024: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 2025:
2026: sub idput {
1.1300 raeburn 2027: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 2028: my %servers=();
1.1300 raeburn 2029: my %ids=();
2030: my %byid = ();
2031: if (ref($idsref) eq 'HASH') {
2032: %ids=%{$idsref};
2033: }
2034: if ($namespace eq '') {
2035: $namespace = 'ids';
2036: }
1.800 albertel 2037: foreach my $uname (keys(%ids)) {
2038: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 2039: if ($uhom eq '') {
2040: $uhom=&homeserver($uname,$udom);
2041: }
1.70 www 2042: if ($uhom ne 'no_host') {
1.800 albertel 2043: my $esc_unam=&escape($uname);
1.1300 raeburn 2044: if ($namespace eq 'ids') {
2045: my $id=&escape($ids{$uname});
2046: $id=~tr/A-Z/a-z/;
2047: my $esc_unam=&escape($uname);
2048: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 2049: } else {
1.1300 raeburn 2050: my @currids = split(/,/,$ids{$uname});
2051: foreach my $id (@currids) {
2052: $byid{$uhom}{$id} .= $uname.',';
2053: }
2054: }
2055: }
2056: }
2057: if ($namespace eq 'clickers') {
2058: foreach my $server (keys(%byid)) {
2059: if (ref($byid{$server}) eq 'HASH') {
2060: foreach my $id (keys(%{$byid{$server}})) {
2061: $byid{$server} =~ s/,$//;
2062: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
2063: }
1.70 www 2064: }
2065: }
1.191 harris41 2066: }
1.800 albertel 2067: foreach my $server (keys(%servers)) {
1.1300 raeburn 2068: $servers{$server} =~ s/\&$//;
2069: if ($namespace eq 'ids') {
2070: &critical('idput:'.$udom.':'.$servers{$server},$server);
2071: } else {
2072: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
2073: }
1.191 harris41 2074: }
1.344 www 2075: }
2076:
1.1300 raeburn 2077: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 2078:
2079: sub iddel {
1.1300 raeburn 2080: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 2081: my %result=();
1.1300 raeburn 2082: my %ids=();
2083: my %byid = ();
2084: if (ref($idshashref) eq 'HASH') {
2085: %ids=%{$idshashref};
2086: } else {
1.1231 raeburn 2087: return %result;
2088: }
1.1300 raeburn 2089: if ($namespace eq '') {
2090: $namespace = 'ids';
2091: }
1.1231 raeburn 2092: my %servers=();
1.1300 raeburn 2093: while (my ($id,$unamestr) = each(%ids)) {
2094: if ($namespace eq 'ids') {
2095: my $uhom = $uhome;
2096: if ($uhom eq '') {
2097: $uhom=&homeserver($unamestr,$udom);
2098: }
2099: if ($uhom ne 'no_host') {
2100: $servers{$uhom}.='&'.&escape($id);
2101: }
2102: } else {
2103: my @curritems = split(/,/,$ids{$id});
2104: foreach my $uname (@curritems) {
2105: my $uhom = $uhome;
2106: if ($uhom eq '') {
2107: $uhom=&homeserver($uname,$udom);
2108: }
2109: if ($uhom ne 'no_host') {
2110: $byid{$uhom}{$id} .= $uname.',';
2111: }
2112: }
1.1231 raeburn 2113: }
1.1300 raeburn 2114: }
2115: if ($namespace eq 'clickers') {
2116: foreach my $server (keys(%byid)) {
2117: if (ref($byid{$server}) eq 'HASH') {
2118: foreach my $id (keys(%{$byid{$server}})) {
2119: $byid{$server}{$id} =~ s/,$//;
2120: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
2121: }
1.1231 raeburn 2122: }
2123: }
2124: }
2125: foreach my $server (keys(%servers)) {
1.1300 raeburn 2126: $servers{$server} =~ s/\&$//;
2127: if ($namespace eq 'ids') {
2128: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
2129: } elsif ($namespace eq 'clickers') {
2130: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
2131: }
1.1231 raeburn 2132: }
2133: return %result;
2134: }
2135:
1.1300 raeburn 2136: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
2137:
2138: sub updateclickers {
2139: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
2140: my %clickers;
2141: if (ref($idshashref) eq 'HASH') {
2142: %clickers=%{$idshashref};
2143: } else {
2144: return;
2145: }
2146: my $items='';
2147: foreach my $item (keys(%clickers)) {
2148: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
2149: }
2150: $items=~s/\&$//;
2151: my $request = "updateclickers:$udom:$action:$items";
2152: if ($critical) {
2153: return &critical($request,$uhome);
2154: } else {
2155: return &reply($request,$uhome);
2156: }
2157: }
2158:
1.1023 raeburn 2159: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 2160: sub dump_dom {
1.1165 droeschl 2161: my ($namespace, $udom, $regexp) = @_;
2162:
2163: $udom ||= $env{'user.domain'};
2164:
2165: return () unless $udom;
2166:
2167: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 2168: }
2169:
1.1023 raeburn 2170: # ------------------------------------------ get items from domain db files
1.806 raeburn 2171:
2172: sub get_dom {
1.1462 raeburn 2173: my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1267 raeburn 2174: return if ($udom eq 'public');
1.806 raeburn 2175: my $items='';
2176: foreach my $item (@$storearr) {
2177: $items.=&escape($item).'&';
2178: }
2179: $items=~s/\&$//;
1.860 raeburn 2180: if (!$udom) {
2181: $udom=$env{'user.domain'};
1.1267 raeburn 2182: return if ($udom eq 'public');
1.860 raeburn 2183: if (defined(&domain($udom,'primary'))) {
2184: $uhome=&domain($udom,'primary');
2185: } else {
1.874 albertel 2186: undef($uhome);
1.860 raeburn 2187: }
2188: } else {
2189: if (!$uhome) {
2190: if (defined(&domain($udom,'primary'))) {
2191: $uhome=&domain($udom,'primary');
2192: }
2193: }
2194: }
2195: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344 raeburn 2196: my $rep;
1.1442 raeburn 2197: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
2198: # domain information is hosted on this machine
1.1462 raeburn 2199: $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1344 raeburn 2200: } else {
1.1462 raeburn 2201: if ($encrypt) {
1.1442 raeburn 2202: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
2203: } else {
2204: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
2205: }
1.1344 raeburn 2206: }
1.866 raeburn 2207: my %returnhash;
1.875 albertel 2208: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 2209: return %returnhash;
2210: }
1.806 raeburn 2211: my @pairs=split(/\&/,$rep);
2212: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2213: return @pairs;
2214: }
2215: my $i=0;
2216: foreach my $item (@$storearr) {
2217: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2218: $i++;
2219: }
2220: return %returnhash;
2221: } else {
1.880 banghart 2222: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 2223: }
2224: }
2225:
2226: # -------------------------------------------- put items in domain db files
2227:
2228: sub put_dom {
1.1462 raeburn 2229: my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860 raeburn 2230: if (!$udom) {
2231: $udom=$env{'user.domain'};
2232: if (defined(&domain($udom,'primary'))) {
2233: $uhome=&domain($udom,'primary');
2234: } else {
1.874 albertel 2235: undef($uhome);
1.860 raeburn 2236: }
2237: } else {
2238: if (!$uhome) {
2239: if (defined(&domain($udom,'primary'))) {
2240: $uhome=&domain($udom,'primary');
2241: }
2242: }
2243: }
2244: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 2245: my $items='';
2246: foreach my $item (keys(%$storehash)) {
2247: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2248: }
2249: $items=~s/\&$//;
1.1462 raeburn 2250: if ($encrypt) {
1.1344 raeburn 2251: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2252: } else {
2253: return &reply("putdom:$udom:$namespace:$items",$uhome);
2254: }
1.806 raeburn 2255: } else {
1.860 raeburn 2256: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 2257: }
2258: }
2259:
1.1023 raeburn 2260: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 2261: sub newput_dom {
1.1023 raeburn 2262: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 2263: my $result;
2264: if (!$udom) {
2265: $udom=$env{'user.domain'};
2266: }
1.1023 raeburn 2267: if ($udom) {
2268: my $uname = &get_domainconfiguser($udom);
2269: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 2270: }
2271: return $result;
2272: }
2273:
1.1023 raeburn 2274: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 2275: sub del_dom {
1.1023 raeburn 2276: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 2277: if (ref($storearr) eq 'ARRAY') {
2278: if (!$udom) {
2279: $udom=$env{'user.domain'};
2280: }
1.1023 raeburn 2281: if ($udom) {
2282: my $uname = &get_domainconfiguser($udom);
2283: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 2284: }
2285: }
2286: }
2287:
1.1481 raeburn 2288: sub store_dom {
1.1482 raeburn 2289: my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
1.1481 raeburn 2290: $$storehash{'ip'}=&get_requestor_ip();
2291: $$storehash{'host'}=$perlvar{'lonHostID'};
2292: my $namevalue='';
2293: foreach my $key (keys(%{$storehash})) {
2294: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2295: }
2296: $namevalue=~s/\&$//;
2297: if (grep { $_ eq $home } current_machine_ids()) {
2298: return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
2299: } else {
2300: if ($namespace eq 'private') {
2301: return 'refused';
1.1482 raeburn 2302: } elsif ($encrypt) {
2303: return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481 raeburn 2304: } else {
1.1482 raeburn 2305: return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481 raeburn 2306: }
2307: }
2308: }
2309:
1.1482 raeburn 2310: sub restore_dom {
2311: my ($id,$namespace,$dom,$home,$encrypt) = @_;
2312: my $answer;
2313: if (grep { $_ eq $home } current_machine_ids()) {
2314: $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
2315: } elsif ($namespace ne 'private') {
2316: if ($encrypt) {
2317: $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
2318: } else {
2319: $answer=&reply("restoredom:$dom:$namespace:$id",$home);
2320: }
2321: }
2322: my %returnhash=();
2323: unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') ||
2324: ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
2325: foreach my $line (split(/\&/,$answer)) {
2326: my ($name,$value)=split(/\=/,$line);
2327: $returnhash{&unescape($name)}=&thaw_unescape($value);
2328: }
2329: my $version;
2330: for ($version=1;$version<=$returnhash{'version'};$version++) {
2331: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2332: $returnhash{$item}=$returnhash{$version.':'.$item};
2333: }
2334: }
2335: }
2336: return %returnhash;
2337: }
2338:
1.1023 raeburn 2339: # ----------------------------------construct domainconfig user for a domain
2340: sub get_domainconfiguser {
2341: my ($udom) = @_;
2342: return $udom.'-domainconfig';
2343: }
2344:
1.837 raeburn 2345: sub retrieve_inst_usertypes {
2346: my ($udom) = @_;
2347: my (%returnhash,@order);
1.1494 raeburn 2348: my %domdefs = &get_domain_defaults($udom);
1.989 raeburn 2349: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2350: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 2351: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2352: } else {
2353: if (defined(&domain($udom,'primary'))) {
2354: my $uhome=&domain($udom,'primary');
2355: my $rep=&reply("inst_usertypes:$udom",$uhome);
2356: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 2357: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2358: return (\%returnhash,\@order);
2359: }
2360: my ($hashitems,$orderitems) = split(/:/,$rep);
2361: my @pairs=split(/\&/,$hashitems);
2362: foreach my $item (@pairs) {
2363: my ($key,$value)=split(/=/,$item,2);
2364: $key = &unescape($key);
2365: next if ($key =~ /^error: 2 /);
2366: $returnhash{$key}=&thaw_unescape($value);
2367: }
2368: my @esc_order = split(/\&/,$orderitems);
2369: foreach my $item (@esc_order) {
2370: push(@order,&unescape($item));
2371: }
2372: } else {
1.1256 raeburn 2373: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2374: }
1.1256 raeburn 2375: return (\%returnhash,\@order);
1.837 raeburn 2376: }
2377: }
2378:
1.868 raeburn 2379: sub is_domainimage {
2380: my ($url) = @_;
1.1468 raeburn 2381: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868 raeburn 2382: if (&domain($1) ne '') {
2383: return '1';
2384: }
2385: }
2386: return;
2387: }
2388:
1.899 raeburn 2389: sub inst_directory_query {
2390: my ($srch) = @_;
2391: my $udom = $srch->{'srchdomain'};
2392: my %results;
2393: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2394: my $outcome;
1.899 raeburn 2395: if ($homeserver ne '') {
1.1357 raeburn 2396: unless ($homeserver eq $perlvar{'lonHostID'}) {
2397: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2398: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357 raeburn 2399: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2400: if (($major eq '' && $minor eq '') || ($major < 2) ||
2401: (($major == 2) && ($minor < 12))) {
2402: return;
2403: }
2404: }
2405: }
1.904 albertel 2406: my $queryid=&reply("querysend:instdirsearch:".
2407: &escape($srch->{'srchby'}).':'.
2408: &escape($srch->{'srchterm'}).':'.
2409: &escape($srch->{'srchtype'}),$homeserver);
2410: my $host=&hostname($homeserver);
2411: if ($queryid !~/^\Q$host\E\_/) {
1.1343 raeburn 2412: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2413: return;
2414: }
2415: my $response = &get_query_reply($queryid);
2416: my $maxtries = 5;
2417: my $tries = 1;
2418: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2419: $response = &get_query_reply($queryid);
2420: $tries ++;
2421: }
2422:
2423: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2424: if ($response eq 'unavailable') {
2425: $outcome = $response;
2426: } else {
2427: $outcome = 'ok';
2428: my @matches = split(/\n/,$response);
2429: foreach my $match (@matches) {
2430: my ($key,$value) = split(/=/,$match);
2431: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2432: }
1.899 raeburn 2433: }
2434: }
2435: }
1.909 raeburn 2436: return ($outcome,%results);
1.899 raeburn 2437: }
2438:
2439: sub usersearch {
2440: my ($srch) = @_;
2441: my $dom = $srch->{'srchdomain'};
2442: my %results;
2443: my %libserv = &all_library();
2444: my $query = 'usersearch';
2445: foreach my $tryserver (keys(%libserv)) {
2446: if (&host_domain($tryserver) eq $dom) {
1.1357 raeburn 2447: unless ($tryserver eq $perlvar{'lonHostID'}) {
2448: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2449: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357 raeburn 2450: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2451: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2452: (($major == 2) && ($minor < 12)));
2453: }
2454: }
1.899 raeburn 2455: my $host=&hostname($tryserver);
2456: my $queryid=
1.911 raeburn 2457: &reply("querysend:".&escape($query).':'.
2458: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2459: &escape($srch->{'srchtype'}).':'.
2460: &escape($srch->{'srchterm'}),$tryserver);
2461: if ($queryid !~/^\Q$host\E\_/) {
2462: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2463: next;
1.899 raeburn 2464: }
2465: my $reply = &get_query_reply($queryid);
2466: my $maxtries = 1;
2467: my $tries = 1;
2468: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2469: $reply = &get_query_reply($queryid);
2470: $tries ++;
2471: }
2472: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2473: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2474: } else {
1.911 raeburn 2475: my @matches;
2476: if ($reply =~ /\n/) {
2477: @matches = split(/\n/,$reply);
2478: } else {
2479: @matches = split(/\&/,$reply);
2480: }
1.899 raeburn 2481: foreach my $match (@matches) {
2482: my ($uname,$udom,%userhash);
1.911 raeburn 2483: foreach my $entry (split(/:/,$match)) {
2484: my ($key,$value) =
2485: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2486: $userhash{$key} = $value;
2487: if ($key eq 'username') {
2488: $uname = $value;
2489: } elsif ($key eq 'domain') {
2490: $udom = $value;
1.911 raeburn 2491: }
1.899 raeburn 2492: }
2493: $results{$uname.':'.$udom} = \%userhash;
2494: }
2495: }
2496: }
2497: }
2498: return %results;
2499: }
2500:
1.912 raeburn 2501: sub get_instuser {
2502: my ($udom,$uname,$id) = @_;
2503: my $homeserver = &domain($udom,'primary');
2504: my ($outcome,%results);
2505: if ($homeserver ne '') {
2506: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2507: &escape($id).':'.&escape($udom),$homeserver);
2508: my $host=&hostname($homeserver);
2509: if ($queryid !~/^\Q$host\E\_/) {
2510: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2511: return;
2512: }
2513: my $response = &get_query_reply($queryid);
2514: my $maxtries = 5;
2515: my $tries = 1;
2516: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2517: $response = &get_query_reply($queryid);
2518: $tries ++;
2519: }
2520: if (!&error($response) && $response ne 'refused') {
2521: if ($response eq 'unavailable') {
2522: $outcome = $response;
2523: } else {
2524: $outcome = 'ok';
2525: my @matches = split(/\n/,$response);
2526: foreach my $match (@matches) {
2527: my ($key,$value) = split(/=/,$match);
2528: $results{&unescape($key)} = &thaw_unescape($value);
2529: }
2530: }
2531: }
2532: }
2533: my %userinfo;
2534: if (ref($results{$uname}) eq 'HASH') {
2535: %userinfo = %{$results{$uname}};
2536: }
2537: return ($outcome,%userinfo);
2538: }
2539:
1.1290 raeburn 2540: sub get_multiple_instusers {
2541: my ($udom,$users,$caller) = @_;
2542: my ($outcome,$results);
2543: if (ref($users) eq 'HASH') {
2544: my $count = keys(%{$users});
2545: my $requested = &freeze_escape($users);
2546: my $homeserver = &domain($udom,'primary');
2547: if ($homeserver ne '') {
2548: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2549: my $host=&hostname($homeserver);
2550: if ($queryid !~/^\Q$host\E\_/) {
2551: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2552: ' for host: '.$homeserver.'in domain '.$udom);
2553: return ($outcome,$results);
2554: }
2555: my $response = &get_query_reply($queryid);
2556: my $maxtries = 5;
2557: if ($count > 100) {
2558: $maxtries = 1+int($count/20);
2559: }
2560: my $tries = 1;
2561: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2562: $response = &get_query_reply($queryid);
2563: $tries ++;
2564: }
2565: if ($response eq '') {
2566: $results = {};
2567: foreach my $key (keys(%{$users})) {
2568: my ($uname,$id);
2569: if ($caller eq 'id') {
2570: $id = $key;
2571: } else {
2572: $uname = $key;
2573: }
2574: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2575: $outcome = $resp;
1.1290 raeburn 2576: if ($resp eq 'ok') {
2577: %{$results} = (%{$results}, %info);
2578: } else {
2579: last;
2580: }
2581: }
2582: } elsif(!&error($response) && ($response ne 'refused')) {
2583: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2584: $outcome = $response;
2585: } else {
1.1291 raeburn 2586: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2587: if ($outcome eq 'ok') {
2588: $results = &thaw_unescape($userdata);
2589: }
2590: }
2591: }
2592: }
2593: }
2594: return ($outcome,$results);
2595: }
2596:
1.912 raeburn 2597: sub inst_rulecheck {
1.923 raeburn 2598: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2599: my %returnhash;
2600: if ($udom ne '') {
2601: if (ref($rules) eq 'ARRAY') {
2602: @{$rules} = map {&escape($_);} (@{$rules});
2603: my $rulestr = join(':',@{$rules});
2604: my $homeserver=&domain($udom,'primary');
2605: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2606: my $response;
2607: if ($item eq 'username') {
2608: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2609: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2610: $homeserver));
1.923 raeburn 2611: } elsif ($item eq 'id') {
2612: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2613: ':'.&escape($id).':'.$rulestr,
2614: $homeserver));
1.945 raeburn 2615: } elsif ($item eq 'selfcreate') {
2616: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2617: &escape($udom).':'.&escape($uname).
2618: ':'.$rulestr,$homeserver));
1.1484 raeburn 2619: } elsif ($item eq 'unamemap') {
2620: $response=&unescape(&reply('instunamemapcheck:'.
2621: &escape($udom).':'.&escape($uname).
2622: ':'.$rulestr,$homeserver));
1.923 raeburn 2623: }
1.912 raeburn 2624: if ($response ne 'refused') {
2625: my @pairs=split(/\&/,$response);
2626: foreach my $item (@pairs) {
2627: my ($key,$value)=split(/=/,$item,2);
2628: $key = &unescape($key);
2629: next if ($key =~ /^error: 2 /);
2630: $returnhash{$key}=&thaw_unescape($value);
2631: }
2632: }
2633: }
2634: }
2635: }
2636: return %returnhash;
2637: }
2638:
2639: sub inst_userrules {
1.923 raeburn 2640: my ($udom,$check) = @_;
1.912 raeburn 2641: my (%ruleshash,@ruleorder);
2642: if ($udom ne '') {
2643: my $homeserver=&domain($udom,'primary');
2644: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2645: my $response;
2646: if ($check eq 'id') {
2647: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2648: $homeserver);
1.943 raeburn 2649: } elsif ($check eq 'email') {
2650: $response=&reply('instemailrules:'.&escape($udom),
2651: $homeserver);
1.1484 raeburn 2652: } elsif ($check eq 'unamemap') {
2653: $response=&reply('unamemaprules:'.&escape($udom),
2654: $homeserver);
1.923 raeburn 2655: } else {
2656: $response=&reply('instuserrules:'.&escape($udom),
2657: $homeserver);
2658: }
1.912 raeburn 2659: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2660: ($response ne 'unknown_cmd') &&
1.912 raeburn 2661: ($response ne 'no_such_host')) {
2662: my ($hashitems,$orderitems) = split(/:/,$response);
2663: my @pairs=split(/\&/,$hashitems);
2664: foreach my $item (@pairs) {
2665: my ($key,$value)=split(/=/,$item,2);
2666: $key = &unescape($key);
2667: next if ($key =~ /^error: 2 /);
2668: $ruleshash{$key}=&thaw_unescape($value);
2669: }
2670: my @esc_order = split(/\&/,$orderitems);
2671: foreach my $item (@esc_order) {
2672: push(@ruleorder,&unescape($item));
2673: }
2674: }
2675: }
2676: }
2677: return (\%ruleshash,\@ruleorder);
2678: }
2679:
1.976 raeburn 2680: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2681:
2682: sub get_domain_defaults {
1.1240 raeburn 2683: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2684: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2685: my $cachetime = 60*60*24;
1.1240 raeburn 2686: unless ($ignore_cache) {
2687: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2688: if (defined($cached)) {
2689: if (ref($result) eq 'HASH') {
2690: return %{$result};
2691: }
1.943 raeburn 2692: }
2693: }
2694: my %domdefaults;
2695: my %domconfig =
1.1494 raeburn 2696: &get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2697: 'requestcourses','inststatus',
1.1183 raeburn 2698: 'coursedefaults','usersessions',
1.1258 raeburn 2699: 'requestauthor','selfenrollment',
1.1320 raeburn 2700: 'coursecategories','ssl','autoenroll',
1.1504 raeburn 2701: 'trust','helpsettings','wafproxy',
2702: 'ltisec','toolsec'],$domain);
1.1305 raeburn 2703: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2704: if (ref($domconfig{'defaults'}) eq 'HASH') {
2705: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2706: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2707: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2708: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2709: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2710: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1492 raeburn 2711: $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
2712: $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
1.1340 raeburn 2713: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2714: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2715: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1484 raeburn 2716: $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943 raeburn 2717: } else {
2718: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2719: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2720: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2721: }
1.976 raeburn 2722: if (ref($domconfig{'quotas'}) eq 'HASH') {
2723: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2724: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2725: } else {
2726: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2727: }
1.1177 raeburn 2728: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2729: foreach my $item (@usertools) {
2730: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2731: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2732: }
2733: }
1.1229 raeburn 2734: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2735: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2736: }
1.976 raeburn 2737: }
1.985 raeburn 2738: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2739: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2740: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2741: }
2742: }
1.1183 raeburn 2743: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2744: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2745: }
1.989 raeburn 2746: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2747: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2748: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2749: }
2750: }
1.1047 raeburn 2751: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2752: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2753: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1476 raeburn 2754: $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1277 raeburn 2755: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2756: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2757: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2758: }
1.1254 raeburn 2759: foreach my $type (@coursetypes) {
2760: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2761: unless ($type eq 'community') {
2762: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2763: }
2764: }
2765: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2766: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2767: }
1.1277 raeburn 2768: if ($domdefaults{'postsubmit'} eq 'on') {
2769: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2770: $domdefaults{$type.'postsubtimeout'} =
2771: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2772: }
2773: }
1.1230 raeburn 2774: }
1.1286 raeburn 2775: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2776: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2777: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2778: if (@clonecodes) {
2779: $domdefaults{'canclone'} = join('+',@clonecodes);
2780: }
2781: }
2782: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2783: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2784: }
1.1356 raeburn 2785: if ($domconfig{'coursedefaults'}{'texengine'}) {
2786: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
1.1480 raeburn 2787: }
2788: if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
2789: $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
2790: }
1.1047 raeburn 2791: }
1.1073 raeburn 2792: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2793: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2794: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2795: }
2796: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2797: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2798: }
1.1279 raeburn 2799: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2800: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2801: }
1.1440 raeburn 2802: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439 raeburn 2803: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2804: }
1.1073 raeburn 2805: }
1.1254 raeburn 2806: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2807: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2808: my @settings = ('types','registered','enroll_dates','access_dates','section',
2809: 'approval','limit');
2810: foreach my $type (@coursetypes) {
2811: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2812: my @mgrdc = ();
2813: foreach my $item (@settings) {
2814: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2815: push(@mgrdc,$item);
2816: }
2817: }
2818: if (@mgrdc) {
2819: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2820: }
2821: }
2822: }
2823: }
2824: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2825: foreach my $type (@coursetypes) {
2826: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2827: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2828: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2829: }
2830: }
2831: }
2832: }
2833: }
1.1258 raeburn 2834: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2835: $domdefaults{'catauth'} = 'std';
2836: $domdefaults{'catunauth'} = 'std';
1.1413 raeburn 2837: if ($domconfig{'coursecategories'}{'auth'}) {
1.1258 raeburn 2838: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2839: }
2840: if ($domconfig{'coursecategories'}{'unauth'}) {
2841: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2842: }
2843: }
1.1315 raeburn 2844: if (ref($domconfig{'ssl'}) eq 'HASH') {
2845: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2846: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2847: }
1.1338 raeburn 2848: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2849: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2850: }
2851: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2852: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315 raeburn 2853: }
2854: }
1.1320 raeburn 2855: if (ref($domconfig{'trust'}) eq 'HASH') {
2856: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2857: foreach my $prefix (@prefixes) {
2858: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2859: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2860: }
2861: }
2862: }
1.1314 raeburn 2863: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2864: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1477 raeburn 2865: $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1314 raeburn 2866: }
1.1332 raeburn 2867: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2868: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2869: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2870: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2871: }
2872: }
1.1434 raeburn 2873: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1449 raeburn 2874: foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
1.1434 raeburn 2875: if ($domconfig{'wafproxy'}{$item}) {
2876: $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
2877: }
2878: }
1.1482 raeburn 2879: }
2880: if (ref($domconfig{'ltisec'}) eq 'HASH') {
2881: if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
2882: $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
2883: $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
2884: $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
2885: }
2886: if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
2887: if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
1.1504 raeburn 2888: $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
2889: }
2890: }
2891: }
2892: if (ref($domconfig{'toolsec'}) eq 'HASH') {
2893: if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
2894: $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
2895: $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
2896: }
2897: if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
2898: if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
2899: $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
1.1482 raeburn 2900: }
2901: }
2902: }
1.1219 raeburn 2903: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2904: return %domdefaults;
2905: }
2906:
1.1412 raeburn 2907: sub get_dom_cats {
2908: my ($dom) = @_;
2909: return unless (&domain($dom));
2910: my ($cats,$cached)=&is_cached_new('cats',$dom);
2911: unless (defined($cached)) {
2912: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2913: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2914: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2915: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2916: } else {
2917: $cats = {};
2918: }
2919: } else {
2920: $cats = {};
2921: }
1.1494 raeburn 2922: &do_cache_new('cats',$dom,$cats,3600);
1.1412 raeburn 2923: }
1.1413 raeburn 2924: return $cats;
2925: }
2926:
2927: sub get_dom_instcats {
2928: my ($dom) = @_;
2929: return unless (&domain($dom));
2930: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2931: unless (defined($cached)) {
2932: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2933: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2934: if ($totcodes > 0) {
2935: my $caller = 'global';
2936: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2937: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2938: $instcats = {
1.1503 raeburn 2939: totcodes => $totcodes,
1.1413 raeburn 2940: codes => \%codes,
2941: codetitles => \@codetitles,
2942: cat_titles => \%cat_titles,
2943: cat_order => \%cat_order,
2944: };
2945: &do_cache_new('instcats',$dom,$instcats,3600);
2946: }
2947: }
2948: }
2949: return $instcats;
2950: }
2951:
2952: sub retrieve_instcodes {
2953: my ($coursecodes,$dom) = @_;
2954: my $totcodes;
2955: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2956: foreach my $course (keys(%courses)) {
2957: if (ref($courses{$course}) eq 'HASH') {
2958: if ($courses{$course}{'inst_code'} ne '') {
2959: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2960: $totcodes ++;
2961: }
2962: }
2963: }
2964: return $totcodes;
1.1412 raeburn 2965: }
2966:
1.1311 raeburn 2967: sub course_portal_url {
1.1451 raeburn 2968: my ($cnum,$cdom,$r) = @_;
1.1311 raeburn 2969: my $chome = &homeserver($cnum,$cdom);
2970: my $hostname = &hostname($chome);
2971: my $protocol = $protocol{$chome};
2972: $protocol = 'http' if ($protocol ne 'https');
2973: my %domdefaults = &get_domain_defaults($cdom);
2974: my $firsturl;
2975: if ($domdefaults{'portal_def'}) {
2976: $firsturl = $domdefaults{'portal_def'};
2977: } else {
1.1494 raeburn 2978: my $alias = &use_proxy_alias($r,$chome);
1.1451 raeburn 2979: $hostname = $alias if ($alias ne '');
1.1311 raeburn 2980: $firsturl = $protocol.'://'.$hostname;
2981: }
2982: return $firsturl;
2983: }
2984:
1.1492 raeburn 2985: sub url_prefix {
2986: my ($r,$dom,$home,$context) = @_;
2987: my $prefix;
2988: my %domdefs = &get_domain_defaults($dom);
2989: if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
2990: if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
2991: $prefix = $1;
2992: }
2993: }
2994: if ($prefix eq '') {
2995: my $hostname = &hostname($home);
2996: my $protocol = $protocol{$home};
2997: $protocol = 'http' if ($protocol{$home} ne 'https');
2998: my $alias = &use_proxy_alias($r,$home);
2999: $hostname = $alias if ($alias ne '');
3000: $prefix = $protocol.'://'.$hostname;
3001: }
3002: return $prefix;
3003: }
3004:
1.1407 raeburn 3005: # --------------------------------------------- Get domain config for passwords
3006:
3007: sub get_passwdconf {
3008: my ($dom) = @_;
3009: my (%passwdconf,$gotconf,$lookup);
3010: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
3011: if (defined($cached)) {
3012: if (ref($result) eq 'HASH') {
3013: %passwdconf = %{$result};
3014: $gotconf = 1;
3015: }
3016: }
3017: unless ($gotconf) {
3018: my %domconfig = &get_dom('configuration',['passwords'],$dom);
3019: if (ref($domconfig{'passwords'}) eq 'HASH') {
3020: %passwdconf = %{$domconfig{'passwords'}};
3021: }
3022: my $cachetime = 24*60*60;
3023: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
3024: }
3025: return %passwdconf;
3026: }
3027:
1.344 www 3028: # --------------------------------------------------- Assign a key to a student
3029:
3030: sub assign_access_key {
1.364 www 3031: #
3032: # a valid key looks like uname:udom#comments
3033: # comments are being appended
3034: #
1.498 www 3035: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
3036: $kdom=
1.620 albertel 3037: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 3038: $knum=
1.620 albertel 3039: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 3040: $cdom=
1.620 albertel 3041: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3042: $cnum=
1.620 albertel 3043: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3044: $udom=$env{'user.name'} unless (defined($udom));
3045: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 3046: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 3047: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 3048: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 3049: # assigned to this person
3050: # - this should not happen,
1.345 www 3051: # unless something went wrong
3052: # the first time around
3053: # ready to assign
1.364 www 3054: $logentry=$1.'; '.$logentry;
1.496 www 3055: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 3056: $kdom,$knum) eq 'ok') {
1.345 www 3057: # key now belongs to user
1.346 www 3058: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 3059: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 3060: &appenv({'environment.'.$envkey => $ckey});
1.345 www 3061: return 'ok';
3062: } else {
3063: return
3064: 'error: Count not permanently assign key, will need to be re-entered later.';
3065: }
3066: } else {
3067: return 'error: Could not assign key, try again later.';
3068: }
1.364 www 3069: } elsif (!$existing{$ckey}) {
1.345 www 3070: # the key does not exist
3071: return 'error: The key does not exist';
3072: } else {
3073: # the key is somebody else's
3074: return 'error: The key is already in use';
3075: }
1.344 www 3076: }
3077:
1.364 www 3078: # ------------------------------------------ put an additional comment on a key
3079:
3080: sub comment_access_key {
3081: #
3082: # a valid key looks like uname:udom#comments
3083: # comments are being appended
3084: #
3085: my ($ckey,$cdom,$cnum,$logentry)=@_;
3086: $cdom=
1.620 albertel 3087: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 3088: $cnum=
1.620 albertel 3089: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 3090: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
3091: if ($existing{$ckey}) {
3092: $existing{$ckey}.='; '.$logentry;
3093: # ready to assign
1.367 www 3094: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 3095: $cdom,$cnum) eq 'ok') {
3096: return 'ok';
3097: } else {
3098: return 'error: Count not store comment.';
3099: }
3100: } else {
3101: # the key does not exist
3102: return 'error: The key does not exist';
3103: }
3104: }
3105:
1.344 www 3106: # ------------------------------------------------------ Generate a set of keys
3107:
3108: sub generate_access_keys {
1.364 www 3109: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 3110: $cdom=
1.620 albertel 3111: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3112: $cnum=
1.620 albertel 3113: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 3114: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 3115: unless (($cdom) && ($cnum)) { return 0; }
3116: if ($number>10000) { return 0; }
3117: sleep(2); # make sure don't get same seed twice
3118: srand(time()^($$+($$<<15))); # from "Programming Perl"
3119: my $total=0;
3120: for (my $i=1;$i<=$number;$i++) {
3121: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
3122: sprintf("%lx",int(100000*rand)).'-'.
3123: sprintf("%lx",int(100000*rand));
3124: $newkey=~s/1/g/g; # folks mix up 1 and l
3125: $newkey=~s/0/h/g; # and also 0 and O
3126: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
3127: if ($existing{$newkey}) {
3128: $i--;
3129: } else {
1.364 www 3130: if (&put('accesskeys',
3131: { $newkey => '# generated '.localtime().
1.620 albertel 3132: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 3133: '; '.$logentry },
3134: $cdom,$cnum) eq 'ok') {
1.344 www 3135: $total++;
3136: }
3137: }
3138: }
1.620 albertel 3139: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 3140: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
3141: return $total;
3142: }
3143:
3144: # ------------------------------------------------------- Validate an accesskey
3145:
3146: sub validate_access_key {
3147: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
3148: $cdom=
1.620 albertel 3149: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3150: $cnum=
1.620 albertel 3151: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3152: $udom=$env{'user.domain'} unless (defined($udom));
3153: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 3154: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 3155: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 3156: }
3157:
3158: # ------------------------------------- Find the section of student in a course
1.652 albertel 3159: sub devalidate_getsection_cache {
3160: my ($udom,$unam,$courseid)=@_;
3161: my $hashid="$udom:$unam:$courseid";
3162: &devalidate_cache_new('getsection',$hashid);
3163: }
1.298 matthew 3164:
1.815 albertel 3165: sub courseid_to_courseurl {
3166: my ($courseid) = @_;
3167: #already url style courseid
3168: return $courseid if ($courseid =~ m{^/});
3169:
3170: if (exists($env{'course.'.$courseid.'.num'})) {
3171: my $cnum = $env{'course.'.$courseid.'.num'};
3172: my $cdom = $env{'course.'.$courseid.'.domain'};
3173: return "/$cdom/$cnum";
3174: }
3175:
1.1494 raeburn 3176: my %courseinfo=&coursedescription($courseid);
1.815 albertel 3177: if (exists($courseinfo{'num'})) {
3178: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
3179: }
3180:
3181: return undef;
3182: }
3183:
1.298 matthew 3184: sub getsection {
3185: my ($udom,$unam,$courseid)=@_;
1.599 albertel 3186: my $cachetime=1800;
1.551 albertel 3187:
3188: my $hashid="$udom:$unam:$courseid";
1.599 albertel 3189: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 3190: if (defined($cached)) { return $result; }
3191:
1.298 matthew 3192: my %Pending;
3193: my %Expired;
3194: #
3195: # Each role can either have not started yet (pending), be active,
3196: # or have expired.
3197: #
3198: # If there is an active role, we are done.
3199: #
3200: # If there is more than one role which has not started yet,
3201: # choose the one which will start sooner
3202: # If there is one role which has not started yet, return it.
3203: #
3204: # If there is more than one expired role, choose the one which ended last.
3205: # If there is a role which has expired, return it.
3206: #
1.815 albertel 3207: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 3208: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 3209: foreach my $key (keys(%roleshash)) {
1.479 albertel 3210: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 3211: my $section=$1;
3212: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 3213: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 3214: my $now=time;
1.548 albertel 3215: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 3216: $Expired{$end}=$section;
3217: next;
3218: }
1.548 albertel 3219: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 3220: $Pending{$start}=$section;
3221: next;
3222: }
1.599 albertel 3223: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 3224: }
3225: #
3226: # Presumedly there will be few matching roles from the above
3227: # loop and the sorting time will be negligible.
3228: if (scalar(keys(%Pending))) {
3229: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 3230: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 3231: }
3232: if (scalar(keys(%Expired))) {
3233: my @sorted = sort {$a <=> $b} keys(%Expired);
3234: my $time = pop(@sorted);
1.599 albertel 3235: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 3236: }
1.599 albertel 3237: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 3238: }
1.70 www 3239:
1.599 albertel 3240: sub save_cache {
3241: &purge_remembered();
1.722 albertel 3242: #&Apache::loncommon::validate_page();
1.620 albertel 3243: undef(%env);
1.780 albertel 3244: undef($env_loaded);
1.599 albertel 3245: }
1.452 albertel 3246:
1.599 albertel 3247: my $to_remember=-1;
3248: my %remembered;
3249: my %accessed;
3250: my $kicks=0;
3251: my $hits=0;
1.849 albertel 3252: sub make_key {
3253: my ($name,$id) = @_;
1.872 albertel 3254: if (length($id) > 65
3255: && length(&escape($id)) > 200) {
3256: $id=length($id).':'.&Digest::MD5::md5_hex($id);
3257: }
1.849 albertel 3258: return &escape($name.':'.$id);
3259: }
3260:
1.599 albertel 3261: sub devalidate_cache_new {
3262: my ($name,$id,$debug) = @_;
3263: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 3264: my $remembered_id=$name.':'.$id;
1.849 albertel 3265: $id=&make_key($name,$id);
1.599 albertel 3266: $memcache->delete($id);
1.1319 damieng 3267: delete($remembered{$remembered_id});
3268: delete($accessed{$remembered_id});
1.599 albertel 3269: }
3270:
3271: sub is_cached_new {
3272: my ($name,$id,$debug) = @_;
1.1319 damieng 3273: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
3274: if (exists($remembered{$remembered_id})) {
3275: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
3276: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3277: $hits++;
1.1319 damieng 3278: return ($remembered{$remembered_id},1);
1.599 albertel 3279: }
1.1319 damieng 3280: $id=&make_key($name,$id);
1.599 albertel 3281: my $value = $memcache->get($id);
3282: if (!(defined($value))) {
3283: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 3284: return (undef,undef);
1.416 albertel 3285: }
1.599 albertel 3286: if ($value eq '__undef__') {
3287: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3288: $value=undef;
3289: }
1.1319 damieng 3290: &make_room($remembered_id,$value,$debug);
1.599 albertel 3291: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3292: return ($value,1);
3293: }
3294:
3295: sub do_cache_new {
3296: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 3297: my $remembered_id=$name.':'.$id;
1.849 albertel 3298: $id=&make_key($name,$id);
1.599 albertel 3299: my $setvalue=$value;
3300: if (!defined($setvalue)) {
3301: $setvalue='__undef__';
3302: }
1.623 albertel 3303: if (!defined($time) ) {
3304: $time=600;
3305: }
1.599 albertel 3306: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 3307: my $result = $memcache->set($id,$setvalue,$time);
3308: if (! $result) {
1.872 albertel 3309: &logthis("caching of id -> $id failed");
1.910 albertel 3310: $memcache->disconnect_all();
1.872 albertel 3311: }
1.600 albertel 3312: # need to make a copy of $value
1.1319 damieng 3313: &make_room($remembered_id,$value,$debug);
1.599 albertel 3314: return $value;
3315: }
3316:
3317: sub make_room {
1.1319 damieng 3318: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 3319:
1.1319 damieng 3320: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 3321: : $value;
1.599 albertel 3322: if ($to_remember<0) { return; }
1.1319 damieng 3323: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3324: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3325: my $to_kick;
3326: my $max_time=0;
3327: foreach my $other (keys(%accessed)) {
3328: if (&tv_interval($accessed{$other}) > $max_time) {
3329: $to_kick=$other;
3330: $max_time=&tv_interval($accessed{$other});
3331: }
3332: }
3333: delete($remembered{$to_kick});
3334: delete($accessed{$to_kick});
3335: $kicks++;
3336: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 3337: return;
3338: }
3339:
1.599 albertel 3340: sub purge_remembered {
1.604 albertel 3341: #&logthis("Tossing ".scalar(keys(%remembered)));
3342: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 3343: undef(%remembered);
3344: undef(%accessed);
1.428 albertel 3345: }
1.70 www 3346: # ------------------------------------- Read an entry from a user's environment
3347:
3348: sub userenvironment {
3349: my ($udom,$unam,@what)=@_;
1.976 raeburn 3350: my $items;
3351: foreach my $item (@what) {
3352: $items.=&escape($item).'&';
3353: }
3354: $items=~s/\&$//;
1.70 www 3355: my %returnhash=();
1.1009 raeburn 3356: my $uhome = &homeserver($unam,$udom);
3357: unless ($uhome eq 'no_host') {
3358: my @answer=split(/\&/,
3359: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 3360: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3361: return %returnhash;
3362: }
1.1009 raeburn 3363: my $i;
3364: for ($i=0;$i<=$#what;$i++) {
3365: $returnhash{$what[$i]}=&unescape($answer[$i]);
3366: }
1.70 www 3367: }
3368: return %returnhash;
1.1 albertel 3369: }
3370:
1.617 albertel 3371: # ---------------------------------------------------------- Get a studentphoto
3372: sub studentphoto {
3373: my ($udom,$unam,$ext) = @_;
1.1494 raeburn 3374: my $home=&homeserver($unam,$udom);
1.706 raeburn 3375: if (defined($env{'request.course.id'})) {
1.708 raeburn 3376: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 3377: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3378: return(&retrievestudentphoto($udom,$unam,$ext));
3379: } else {
3380: my ($result,$perm_reqd)=
1.1494 raeburn 3381: &auto_photo_permission($unam,$udom);
1.706 raeburn 3382: if ($result eq 'ok') {
3383: if (!($perm_reqd eq 'yes')) {
3384: return(&retrievestudentphoto($udom,$unam,$ext));
3385: }
3386: }
3387: }
3388: }
3389: } else {
3390: my ($result,$perm_reqd) =
1.1494 raeburn 3391: &auto_photo_permission($unam,$udom);
1.706 raeburn 3392: if ($result eq 'ok') {
3393: if (!($perm_reqd eq 'yes')) {
3394: return(&retrievestudentphoto($udom,$unam,$ext));
3395: }
3396: }
3397: }
3398: return '/adm/lonKaputt/lonlogo_broken.gif';
3399: }
3400:
3401: sub retrievestudentphoto {
3402: my ($udom,$unam,$ext,$type) = @_;
1.1494 raeburn 3403: my $home=&homeserver($unam,$udom);
3404: my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
1.706 raeburn 3405: if ($ret eq 'ok') {
3406: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3407: if ($type eq 'thumbnail') {
3408: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3409: }
1.1494 raeburn 3410: my $tokenurl=&tokenwrapper($url);
1.706 raeburn 3411: return $tokenurl;
3412: } else {
3413: if ($type eq 'thumbnail') {
3414: return '/adm/lonKaputt/genericstudent_tn.gif';
3415: } else {
3416: return '/adm/lonKaputt/lonlogo_broken.gif';
3417: }
1.617 albertel 3418: }
3419: }
3420:
1.263 www 3421: # -------------------------------------------------------------------- New chat
3422:
3423: sub chatsend {
1.724 raeburn 3424: my ($newentry,$anon,$group)=@_;
1.620 albertel 3425: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3426: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3427: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 3428: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 3429: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 3430: &escape($newentry)).':'.$group,$chome);
1.292 www 3431: }
3432:
3433: # ------------------------------------------ Find current version of a resource
3434:
3435: sub getversion {
3436: my $fname=&clutter(shift);
1.1189 raeburn 3437: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3438: return ¤tversion(&filelocation('',$fname));
3439: }
3440:
3441: sub currentversion {
3442: my $fname=shift;
3443: my $author=$fname;
3444: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3445: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3446: my $home=&homeserver($uname,$udom);
1.292 www 3447: if ($home eq 'no_host') {
3448: return -1;
3449: }
1.1112 www 3450: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3451: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3452: return -1;
3453: }
1.1112 www 3454: return $answer;
1.263 www 3455: }
3456:
1.1111 www 3457: #
3458: # Return special version number of resource if set by override, empty otherwise
3459: #
3460: sub usedversion {
3461: my $fname=shift;
3462: unless ($fname) { $fname=$env{'request.uri'}; }
3463: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3464: if ($urlversion) { return $urlversion; }
3465: return '';
3466: }
3467:
1.1 albertel 3468: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3469:
1.1 albertel 3470: sub subscribe {
3471: my $fname=shift;
1.761 raeburn 3472: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3473: $fname=~s/[\n\r]//g;
1.1 albertel 3474: my $author=$fname;
3475: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3476: my ($udom,$uname)=split(/\//,$author);
3477: my $home=homeserver($uname,$udom);
1.335 albertel 3478: if ($home eq 'no_host') {
3479: return 'not_found';
1.1 albertel 3480: }
3481: my $answer=reply("sub:$fname",$home);
1.64 www 3482: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3483: $answer.=' by '.$home;
3484: }
1.1 albertel 3485: return $answer;
3486: }
3487:
1.8 www 3488: # -------------------------------------------------------------- Replicate file
3489:
3490: sub repcopy {
3491: my $filename=shift;
1.23 www 3492: $filename=~s/\/+/\//g;
1.1142 raeburn 3493: my $londocroot = $perlvar{'lonDocRoot'};
3494: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3495: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3496: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3497: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3498: return &repcopy_userfile($filename);
3499: }
1.532 albertel 3500: $filename=~s/[\n\r]//g;
1.8 www 3501: my $transname="$filename.in.transfer";
1.828 www 3502: # FIXME: this should flock
1.607 raeburn 3503: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3504: my $remoteurl=subscribe($filename);
1.64 www 3505: if ($remoteurl =~ /^con_lost by/) {
3506: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3507: return 'unavailable';
1.8 www 3508: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3509: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3510: return 'not_found';
1.64 www 3511: } elsif ($remoteurl =~ /^rejected by/) {
3512: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3513: return 'forbidden';
1.20 www 3514: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3515: return 'ok';
1.8 www 3516: } else {
1.290 www 3517: my $author=$filename;
3518: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3519: my ($udom,$uname)=split(/\//,$author);
3520: my $home=homeserver($uname,$udom);
3521: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3522: my @parts=split(/\//,$filename);
3523: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3524: if ($path ne "$londocroot/res") {
1.8 www 3525: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3526: return 'bad_request';
1.8 www 3527: }
3528: my $count;
3529: for ($count=5;$count<$#parts;$count++) {
3530: $path.="/$parts[$count]";
3531: if ((-e $path)!=1) {
3532: mkdir($path,0777);
3533: }
3534: }
3535: my $request=new HTTP::Request('GET',"$remoteurl");
1.1345 raeburn 3536: my $response;
3537: if ($remoteurl =~ m{/raw/}) {
3538: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3539: } else {
3540: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3541: }
1.8 www 3542: if ($response->is_error()) {
3543: unlink($transname);
3544: my $message=$response->status_line;
1.672 albertel 3545: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3546: ." LWP get: $message: $filename</font>");
1.607 raeburn 3547: return 'unavailable';
1.8 www 3548: } else {
1.16 www 3549: if ($remoteurl!~/\.meta$/) {
3550: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345 raeburn 3551: my $mresponse;
3552: if ($remoteurl =~ m{/raw/}) {
3553: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3554: } else {
3555: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3556: }
1.16 www 3557: if ($mresponse->is_error()) {
3558: unlink($filename.'.meta');
3559: &logthis(
1.672 albertel 3560: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3561: }
3562: }
1.8 www 3563: rename($transname,$filename);
1.607 raeburn 3564: return 'ok';
1.8 www 3565: }
1.290 www 3566: }
1.8 www 3567: }
1.330 www 3568: }
3569:
1.1422 raeburn 3570: # ------------------------------------------------- Unsubscribe from a resource
3571:
3572: sub unsubscribe {
3573: my ($fname) = @_;
3574: my $answer;
3575: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3576: $fname=~s/[\n\r]//g;
3577: my $author=$fname;
3578: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3579: my ($udom,$uname)=split(/\//,$author);
3580: my $home=homeserver($uname,$udom);
3581: if ($home eq 'no_host') {
3582: $answer = 'no_host';
3583: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3584: $answer = 'home';
3585: } else {
3586: my $defdom = $perlvar{'lonDefDomain'};
3587: if (&will_trust('content',$defdom,$udom)) {
3588: $answer = reply("unsub:$fname",$home);
3589: } else {
3590: $answer = 'untrusted';
3591: }
3592: }
3593: return $answer;
3594: }
3595:
1.330 www 3596: # ------------------------------------------------ Get server side include body
3597: sub ssi_body {
1.381 albertel 3598: my ($filelink,%form)=@_;
1.606 matthew 3599: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3600: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3601: }
1.953 www 3602: my $output='';
3603: my $response;
1.980 raeburn 3604: if ($filelink=~/^https?\:/) {
1.954 raeburn 3605: ($output,$response)=&externalssi($filelink);
1.953 www 3606: } else {
1.1004 droeschl 3607: $filelink .= $filelink=~/\?/ ? '&' : '?';
3608: $filelink .= 'inhibitmenu=yes';
1.953 www 3609: ($output,$response)=&ssi($filelink,%form);
3610: }
1.778 albertel 3611: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3612: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3613: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3614: if (wantarray) {
3615: return ($output, $response);
3616: } else {
3617: return $output;
3618: }
1.8 www 3619: }
3620:
1.15 www 3621: # --------------------------------------------------------- Server Side Include
3622:
1.782 albertel 3623: sub absolute_url {
1.1447 raeburn 3624: my ($host_name,$unalias,$keep_proto) = @_;
1.782 albertel 3625: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3626: if ($host_name eq '') {
3627: $host_name = $ENV{'SERVER_NAME'};
3628: }
1.1447 raeburn 3629: if ($unalias) {
3630: my $alias = &get_proxy_alias();
3631: if ($alias eq $host_name) {
3632: my $lonhost = $perlvar{'lonHostID'};
3633: my $hostname = &hostname($lonhost);
3634: my $lcproto;
3635: if (($keep_proto) || ($hostname eq '')) {
3636: $lcproto = $protocol;
3637: } else {
3638: $lcproto = $protocol{$lonhost};
3639: $lcproto = 'http' if ($lcproto ne 'https');
3640: $lcproto .= '://';
3641: }
3642: unless ($hostname eq '') {
3643: return $lcproto.$hostname;
3644: }
3645: }
3646: }
1.782 albertel 3647: return $protocol.$host_name;
3648: }
3649:
1.942 foxr 3650: #
3651: # Server side include.
3652: # Parameters:
3653: # fn Possibly encrypted resource name/id.
3654: # form Hash that describes how the rendering should be done
3655: # and other things.
1.944 foxr 3656: # Returns:
1.950 raeburn 3657: # Scalar context: The content of the response.
3658: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3659: #
1.15 www 3660: sub ssi {
3661:
1.944 foxr 3662: my ($fn,%form)=@_;
1.1447 raeburn 3663: my ($host,$request,$response);
3664: $host = &absolute_url('',1);
1.711 albertel 3665:
3666: $form{'no_update_last_known'}=1;
1.895 albertel 3667: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3668: if (%form) {
1.1447 raeburn 3669: $request=new HTTP::Request('POST',$host.$fn);
1.1272 droeschl 3670: $request->content(join('&',map {
3671: my $name = escape($_);
3672: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3673: ? join("&$name=", map {escape($_) } @{$form{$_}})
3674: : &escape($form{$_}) );
3675: } keys(%form)));
1.23 www 3676: } else {
1.1447 raeburn 3677: $request=new HTTP::Request('GET',$host.$fn);
1.23 www 3678: }
3679:
1.15 www 3680: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345 raeburn 3681: my $lonhost = $perlvar{'lonHostID'};
1.1385 raeburn 3682: my $islocal;
3683: if (($env{'request.course.id'}) &&
3684: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3685: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3686: ($form{'grade_symb'} ne '') &&
1.1494 raeburn 3687: (&allowed('mgr',$env{'request.course.id'}.
3688: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1385 raeburn 3689: $islocal = 1;
3690: }
1.1447 raeburn 3691: $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
3692: '','','',$islocal);
1.1182 foxr 3693:
1.944 foxr 3694: if (wantarray) {
1.1345 raeburn 3695: return ($response->content, $response);
1.944 foxr 3696: } else {
1.1345 raeburn 3697: return $response->content;
1.942 foxr 3698: }
1.324 www 3699: }
3700:
3701: sub externalssi {
3702: my ($url)=@_;
3703: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 3704: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954 raeburn 3705: if (wantarray) {
3706: return ($response->content, $response);
3707: } else {
3708: return $response->content;
3709: }
1.15 www 3710: }
1.254 www 3711:
1.1354 raeburn 3712:
3713: # If the local copy of a replicated resource is outdated, trigger a
3714: # connection from the homeserver to flush the delayed queue. If no update
3715: # happens, remove local copies of outdated resource (and corresponding
3716: # metadata file).
3717:
1.1352 raeburn 3718: sub remove_stale_resfile {
3719: my ($url) = @_;
1.1354 raeburn 3720: my $removed;
1.1352 raeburn 3721: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3722: my $audom = $1;
3723: my $auname = $2;
1.1353 raeburn 3724: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352 raeburn 3725: my $homeserver = &homeserver($auname,$audom);
3726: unless (($homeserver eq 'no_host') ||
3727: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3728: my $fname = &filelocation('',$url);
3729: if (-e $fname) {
3730: my $hostname = &hostname($homeserver);
3731: if ($hostname) {
1.1397 raeburn 3732: my $protocol = $protocol{$homeserver};
3733: $protocol = 'http' if ($protocol ne 'https');
1.1352 raeburn 3734: my $uri = &declutter($url);
3735: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3736: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3737: if ($response->is_success()) {
3738: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3739: my $locmodtime = (stat($fname))[9];
3740: if ($locmodtime < $remmodtime) {
1.1354 raeburn 3741: my $stale;
3742: my $answer = &reply('pong',$homeserver);
3743: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3744: sleep(0.2);
3745: $locmodtime = (stat($fname))[9];
3746: if ($locmodtime < $remmodtime) {
3747: my $posstransfer = $fname.'.in.transfer';
3748: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3749: $removed = 1;
3750: } else {
3751: $stale = 1;
3752: }
3753: } else {
3754: $removed = 1;
3755: }
3756: } else {
3757: $stale = 1;
3758: }
3759: if ($stale) {
1.1421 raeburn 3760: if (unlink($fname)) {
3761: if ($uri!~/\.meta$/) {
3762: if (-e $fname.'.meta') {
3763: unlink($fname.'.meta');
3764: }
3765: }
1.1422 raeburn 3766: my $unsubresult = &unsubscribe($fname);
3767: unless ($unsubresult eq 'ok') {
3768: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3769: }
1.1421 raeburn 3770: $removed = 1;
1.1354 raeburn 3771: }
1.1352 raeburn 3772: }
3773: }
3774: }
3775: }
3776: }
3777: }
3778: }
3779: }
1.1354 raeburn 3780: return $removed;
1.1352 raeburn 3781: }
3782:
1.492 albertel 3783: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3784:
3785: sub allowuploaded {
3786: my ($srcurl,$url)=@_;
3787: $url=&clutter(&declutter($url));
3788: my $dir=$url;
3789: $dir=~s/\/[^\/]+$//;
3790: my %httpref=();
3791: my $httpurl=&hreflocation('',$url);
3792: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3793: &Apache::lonnet::appenv(\%httpref);
1.254 www 3794: }
1.477 raeburn 3795:
1.1193 raeburn 3796: #
3797: # Determine if the current user should be able to edit a particular resource,
3798: # when viewing in course context.
3799: # (a) When viewing resource used to determine if "Edit" item is included in
3800: # Functions.
3801: # (b) When displaying folder contents in course editor, used to determine if
3802: # "Edit" link will be displayed alongside resource.
3803: #
1.1196 raeburn 3804: # input: six args -- filename (decluttered), course number, course domain,
3805: # url, symb (if registered) and group (if this is a group
3806: # item -- e.g., bulletin board, group page etc.).
3807: # output: array of five scalars --
1.1193 raeburn 3808: # $cfile -- url for file editing if editable on current server
3809: # $home -- homeserver of resource (i.e., for author if published,
3810: # or course if uploaded.).
3811: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3812: # $forceedit -- 1 if icon/link should be to go to edit mode
3813: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3814: #
3815:
3816: sub can_edit_resource {
1.1194 raeburn 3817: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3818: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3819: #
3820: # For aboutme pages user can only edit his/her own.
3821: #
1.1199 raeburn 3822: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3823: my ($sdom,$sname) = ($1,$2);
3824: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3825: $home = $env{'user.home'};
3826: $cfile = $resurl;
3827: if ($env{'form.forceedit'}) {
3828: $forceview = 1;
3829: } else {
3830: $forceedit = 1;
3831: }
3832: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3833: } else {
3834: return;
3835: }
3836: }
3837:
3838: if ($env{'request.course.id'}) {
1.1494 raeburn 3839: my $crsedit = &allowed('mdc',$env{'request.course.id'});
1.1194 raeburn 3840: if ($group ne '') {
3841: # if this is a group homepage or group bulletin board, check group privs
3842: my $allowed = 0;
1.1197 raeburn 3843: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3844: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3845: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3846: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3847: $allowed = 1;
3848: }
1.1197 raeburn 3849: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3850: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3851: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3852: $allowed = 1;
3853: }
3854: }
3855: if ($allowed) {
3856: $home=&homeserver($cnum,$cdom);
3857: if ($env{'form.forceedit'}) {
3858: $forceview = 1;
3859: } else {
3860: $forceedit = 1;
3861: }
3862: $cfile = $resurl;
3863: } else {
3864: return;
3865: }
3866: } else {
1.1208 raeburn 3867: if ($resurl =~ m{^/?adm/viewclasslist$}) {
1.1494 raeburn 3868: unless (&allowed('opa',$env{'request.course.id'})) {
1.1208 raeburn 3869: return;
3870: }
3871: } elsif (!$crsedit) {
1.1194 raeburn 3872: #
3873: # No edit allowed where CC has switched to student role.
3874: #
3875: return;
3876: }
3877: }
3878: }
3879:
1.1193 raeburn 3880: if ($file ne '') {
3881: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3882: if (&is_course_upload($file,$cnum,$cdom)) {
3883: $uploaded = 1;
3884: $incourse = 1;
1.1193 raeburn 3885: if ($file =~/\.(htm|html|css|js|txt)$/) {
3886: $cfile = &hreflocation('',$file);
1.1201 raeburn 3887: if ($env{'form.forceedit'}) {
3888: $forceview = 1;
3889: } else {
3890: $forceedit = 1;
3891: }
1.1194 raeburn 3892: }
3893: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3894: $incourse = 1;
3895: if ($env{'form.forceedit'}) {
3896: $forceview = 1;
3897: } else {
3898: $forceedit = 1;
3899: }
3900: $cfile = $resurl;
3901: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3902: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3903: $incourse = 1;
3904: if ($env{'form.forceedit'}) {
3905: $forceview = 1;
3906: } else {
3907: $forceedit = 1;
3908: }
3909: $cfile = $resurl;
1.1199 raeburn 3910: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3911: $incourse = 1;
3912: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3913: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3914: $incourse = 1;
1.1199 raeburn 3915: if ($env{'form.forceedit'}) {
3916: $forceview = 1;
3917: } else {
3918: $forceedit = 1;
3919: }
3920: $cfile = $resurl;
1.1419 raeburn 3921: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3922: my ($map,$id,$res) = &decode_symb($symb);
3923: if ($map =~ /\.page$/) {
3924: $incourse = 1;
3925: if ($env{'form.forceedit'}) {
3926: $forceview = 1;
3927: $cfile = $map;
3928: } else {
3929: $forceedit = 1;
3930: $cfile = '/adm/wrapper'.$resurl;
3931: }
3932: }
1.1343 raeburn 3933: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3934: $incourse = 1;
3935: if ($env{'form.forceedit'}) {
3936: $forceview = 1;
3937: } else {
3938: $forceedit = 1;
3939: }
3940: $cfile = $resurl;
1.1208 raeburn 3941: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3942: $incourse = 1;
3943: if ($env{'form.forceedit'}) {
3944: $forceview = 1;
3945: } else {
3946: $forceedit = 1;
3947: }
3948: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3949: }
3950: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3951: my $template = '/res/lib/templates/simpleproblem.problem';
3952: if (&is_on_map($template)) {
3953: $incourse = 1;
3954: $forceview = 1;
3955: $cfile = $template;
1.1193 raeburn 3956: }
1.1199 raeburn 3957: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418 raeburn 3958: $incourse = 1;
3959: if ($env{'form.forceedit'}) {
3960: $forceview = 1;
3961: } else {
3962: $forceedit = 1;
3963: }
3964: $cfile = $resurl;
1.1343 raeburn 3965: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298 raeburn 3966: $incourse = 1;
3967: if ($env{'form.forceedit'}) {
3968: $forceview = 1;
3969: } else {
3970: $forceedit = 1;
3971: }
3972: $cfile = $resurl;
1.1199 raeburn 3973: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3974: $incourse = 1;
3975: $forceview = 1;
3976: if ($symb) {
3977: my ($map,$id,$res)=&decode_symb($symb);
3978: $env{'request.symb'} = $symb;
3979: $cfile = &clutter($res);
3980: } else {
3981: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3982: my $escfile = &unescape($cfile);
1.1343 raeburn 3983: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3984: $cfile = '/adm/wrapper'.$escfile;
3985: } else {
3986: $escfile =~ s{^http://}{};
3987: $cfile = &escape("/adm/wrapper/ext/$escfile");
3988: }
1.1199 raeburn 3989: }
1.1234 raeburn 3990: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3991: if ($env{'form.forceedit'}) {
3992: $forceview = 1;
3993: } else {
3994: $forceedit = 1;
3995: }
3996: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3997: }
3998: }
1.1194 raeburn 3999: if ($uploaded || $incourse) {
4000: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 4001: } elsif ($file !~ m{/$}) {
1.1193 raeburn 4002: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
4003: $file=~s{^($match_domain/$match_username)}{/priv/$1};
4004: # Check that the user has permission to edit this resource
4005: my $setpriv = 1;
4006: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
4007: if (defined($cfudom)) {
4008: $home=&homeserver($cfuname,$cfudom);
4009: $cfile=$file;
4010: }
4011: }
1.1194 raeburn 4012: if (($cfile ne '') && (!$incourse || $uploaded) &&
4013: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 4014: my @ids=¤t_machine_ids();
4015: unless (grep(/^\Q$home\E$/,@ids)) {
4016: $switchserver=1;
4017: }
4018: }
4019: }
1.1194 raeburn 4020: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 4021: }
4022:
4023: sub is_course_upload {
4024: my ($file,$cnum,$cdom) = @_;
4025: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
4026: $uploadpath =~ s{^\/}{};
1.1201 raeburn 4027: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
4028: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 4029: return 1;
4030: }
4031: return;
4032: }
4033:
1.1194 raeburn 4034: sub in_course {
1.1195 raeburn 4035: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
4036: if ($hideprivileged) {
4037: my $skipuser;
1.1219 raeburn 4038: my %coursehash = &coursedescription($cdom.'_'.$cnum);
4039: my @possdoms = ($cdom);
4040: if ($coursehash{'checkforpriv'}) {
4041: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4042: }
4043: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 4044: $skipuser = 1;
4045: if ($coursehash{'nothideprivileged'}) {
4046: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4047: my $user;
4048: if ($item =~ /:/) {
4049: $user = $item;
4050: } else {
4051: $user = join(':',split(/[\@]/,$item));
4052: }
4053: if ($user eq $uname.':'.$udom) {
4054: undef($skipuser);
4055: last;
4056: }
4057: }
4058: }
4059: if ($skipuser) {
4060: return 0;
4061: }
4062: }
4063: }
1.1194 raeburn 4064: $type ||= 'any';
4065: if (!defined($cdom) || !defined($cnum)) {
4066: my $cid = $env{'request.course.id'};
4067: $cdom = $env{'course.'.$cid.'.domain'};
4068: $cnum = $env{'course.'.$cid.'.num'};
4069: }
4070: my $typesref;
1.1195 raeburn 4071: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 4072: $typesref = ['active','previous','future'];
4073: } elsif ($type eq 'previous' || $type eq 'future') {
4074: $typesref = [$type];
4075: }
4076: my %roles = &get_my_roles($uname,$udom,'userroles',
4077: $typesref,undef,[$cdom]);
4078: my ($tmp) = keys(%roles);
4079: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
4080: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
4081: if (@course_roles > 0) {
4082: return 1;
4083: }
4084: return 0;
4085: }
4086:
1.478 albertel 4087: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 4088: # input: action, courseID, current domain, intended
1.637 raeburn 4089: # path to file, source of file, instruction to parse file for objects,
4090: # ref to hash for embedded objects,
4091: # ref to hash for codebase of java objects.
1.1095 raeburn 4092: # reference to scalar to accommodate mime type determined
4093: # from File::MMagic if $parser = parse.
1.637 raeburn 4094: #
1.485 raeburn 4095: # output: url to file (if action was uploaddoc),
4096: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 4097: #
1.478 albertel 4098: # Allows directory structure to be used within lonUsers/../userfiles/ for a
4099: # course.
1.477 raeburn 4100: #
1.478 albertel 4101: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4102: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
4103: # course's home server.
1.477 raeburn 4104: #
1.478 albertel 4105: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
4106: # be copied from $source (current location) to
4107: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4108: # and will then be copied to
4109: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
4110: # course's home server.
1.485 raeburn 4111: #
1.481 raeburn 4112: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 4113: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 4114: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4115: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
4116: # in course's home server.
1.637 raeburn 4117: #
1.477 raeburn 4118:
4119: sub process_coursefile {
1.1095 raeburn 4120: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
4121: $mimetype)=@_;
1.477 raeburn 4122: my $fetchresult;
1.638 albertel 4123: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 4124: if ($action eq 'propagate') {
1.638 albertel 4125: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4126: $home);
1.481 raeburn 4127: } else {
1.477 raeburn 4128: my $fpath = '';
4129: my $fname = $file;
1.478 albertel 4130: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 4131: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 4132: my $filepath = &build_filepath($fpath);
1.481 raeburn 4133: if ($action eq 'copy') {
4134: if ($source eq '') {
4135: $fetchresult = 'no source file';
4136: return $fetchresult;
4137: } else {
4138: my $destination = $filepath.'/'.$fname;
4139: rename($source,$destination);
4140: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4141: $home);
1.481 raeburn 4142: }
4143: } elsif ($action eq 'uploaddoc') {
1.1359 raeburn 4144: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 4145: print $fh $env{'form.'.$source};
1.481 raeburn 4146: close($fh);
1.637 raeburn 4147: if ($parser eq 'parse') {
1.1024 raeburn 4148: my $mm = new File::MMagic;
1.1095 raeburn 4149: my $type = $mm->checktype_filename($filepath.'/'.$fname);
4150: if ($type eq 'text/html') {
1.1024 raeburn 4151: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
4152: unless ($parse_result eq 'ok') {
4153: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
4154: }
1.637 raeburn 4155: }
1.1095 raeburn 4156: if (ref($mimetype)) {
4157: $$mimetype = $type;
4158: }
1.637 raeburn 4159: }
1.477 raeburn 4160: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4161: $home);
1.481 raeburn 4162: if ($fetchresult eq 'ok') {
4163: return '/uploaded/'.$fpath.'/'.$fname;
4164: } else {
4165: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4166: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 4167: return '/adm/notfound.html';
4168: }
1.477 raeburn 4169: }
4170: }
1.485 raeburn 4171: unless ( $fetchresult eq 'ok') {
1.477 raeburn 4172: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4173: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 4174: }
4175: return $fetchresult;
4176: }
4177:
1.637 raeburn 4178: sub build_filepath {
4179: my ($fpath) = @_;
4180: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
4181: unless ($fpath eq '') {
4182: my @parts=split('/',$fpath);
4183: foreach my $part (@parts) {
4184: $filepath.= '/'.$part;
4185: if ((-e $filepath)!=1) {
4186: mkdir($filepath,0777);
4187: }
4188: }
4189: }
4190: return $filepath;
4191: }
4192:
4193: sub store_edited_file {
1.638 albertel 4194: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 4195: my $file = $primary_url;
4196: $file =~ s#^/uploaded/$docudom/$docuname/##;
4197: my $fpath = '';
4198: my $fname = $file;
4199: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
4200: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
4201: my $filepath = &build_filepath($fpath);
1.1359 raeburn 4202: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 4203: print $fh $content;
4204: close($fh);
1.638 albertel 4205: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 4206: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4207: $home);
1.637 raeburn 4208: if ($$fetchresult eq 'ok') {
4209: return '/uploaded/'.$fpath.'/'.$fname;
4210: } else {
1.638 albertel 4211: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4212: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 4213: return '/adm/notfound.html';
4214: }
4215: }
4216:
1.531 albertel 4217: sub clean_filename {
1.831 albertel 4218: my ($fname,$args)=@_;
1.315 www 4219: # Replace Windows backslashes by forward slashes
1.257 www 4220: $fname=~s/\\/\//g;
1.831 albertel 4221: if (!$args->{'keep_path'}) {
4222: # Get rid of everything but the actual filename
4223: $fname=~s/^.*\/([^\/]+)$/$1/;
4224: }
1.315 www 4225: # Replace spaces by underscores
4226: $fname=~s/\s+/\_/g;
1.1406 raeburn 4227: # Transliterate non-ascii text to ascii
4228: my $lang = &Apache::lonlocal::current_language();
4229: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 4230: # Replace all other weird characters by nothing
1.831 albertel 4231: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 4232: # Replace all .\d. sequences with _\d. so they no longer look like version
4233: # numbers
4234: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443 raeburn 4235: # Replace three or more adjacent underscores with one for consistency
4236: # with loncfile::filename_check() so complete url can be extracted by
4237: # lonnet::decode_symb()
4238: $fname=~s/_{3,}/_/g;
1.531 albertel 4239: return $fname;
4240: }
1.1406 raeburn 4241:
1.1051 raeburn 4242: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4243: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4244: # image with the same aspect ratio as the original, but with dimensions which do
4245: # not exceed $resizewidth and $resizeheight.
4246:
1.984 neumanie 4247: sub resizeImage {
1.1051 raeburn 4248: my ($img_path,$resizewidth,$resizeheight) = @_;
4249: my $ima = Image::Magick->new;
4250: my $resized;
4251: if (-e $img_path) {
4252: $ima->Read($img_path);
4253: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4254: my $width = $ima->Get('width');
4255: my $height = $ima->Get('height');
4256: if ($width > $resizewidth) {
4257: my $factor = $width/$resizewidth;
4258: my $newheight = $height/$factor;
4259: $ima->Scale(width=>$resizewidth,height=>$newheight);
4260: $resized = 1;
4261: }
4262: }
4263: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4264: my $width = $ima->Get('width');
4265: my $height = $ima->Get('height');
4266: if ($height > $resizeheight) {
4267: my $factor = $height/$resizeheight;
4268: my $newwidth = $width/$factor;
4269: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4270: $resized = 1;
4271: }
4272: }
4273: if ($resized) {
4274: $ima->Write($img_path);
4275: }
4276: }
4277: return;
1.977 amueller 4278: }
4279:
1.608 albertel 4280: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 4281: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 4282: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 4283: # $context - possible values: coursedoc, existingfile, overwrite,
1.1504 raeburn 4284: # canceloverwrite, scantron, toollogo or ''.
1.1090 raeburn 4285: # if 'coursedoc': upload to the current course
4286: # if 'existingfile': write file to tmp/overwrites directory
4287: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4288: # $context is passed as argument to &finishuserfileupload
1.686 albertel 4289: # $subdir - directory in userfile to store the file into
1.1401 raeburn 4290: # $parser - instruction to parse file for objects ($parser = parse) or
4291: # if context is 'scantron', $parser is hashref of csv column mapping
4292: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4293: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 4294: # $allfiles - reference to hash for embedded objects
4295: # $codebase - reference to hash for codebase of java objects
1.1504 raeburn 4296: # $destuname - username for permanent storage of uploaded file
4297: # $destudom - domain for permanaent storage of uploaded file
1.860 raeburn 4298: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4299: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 4300: # $resizewidth - width (pixels) to which to resize uploaded image
4301: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 4302: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 4303: # from File::MMagic.
1.858 raeburn 4304: #
1.686 albertel 4305: # output: url of file in userspace, or error: <message>
4306: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 4307:
1.531 albertel 4308: sub userfileupload {
1.1090 raeburn 4309: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 4310: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 4311: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 4312: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 4313: $fname=&clean_filename($fname);
1.1090 raeburn 4314: # See if there is anything left
1.257 www 4315: unless ($fname) { return 'error: no uploaded file'; }
1.1406 raeburn 4316: # If filename now begins with a . prepend unix timestamp _ milliseconds
4317: if ($fname =~ /^\./) {
4318: my ($s,$usec) = &gettimeofday();
4319: while (length($usec) < 6) {
4320: $usec = '0'.$usec;
4321: }
4322: $fname = $s.'_'.substr($usec,0,3).$fname;
4323: }
1.1090 raeburn 4324: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4325: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4326: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4327: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 4328: my $now = time;
1.1090 raeburn 4329: my $filepath;
1.1095 raeburn 4330: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 4331: $filepath = 'tmp/helprequests/'.$now;
4332: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4333: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4334: '_'.$env{'user.domain'}.'/pending';
4335: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4336: my ($docuname,$docudom);
1.1350 raeburn 4337: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 4338: $docudom = $destudom;
4339: } else {
4340: $docudom = $env{'user.domain'};
4341: }
1.1350 raeburn 4342: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 4343: $docuname = $destuname;
4344: } else {
4345: $docuname = $env{'user.name'};
4346: }
4347: if (exists($env{'form.group'})) {
4348: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4349: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4350: }
4351: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4352: if ($context eq 'canceloverwrite') {
4353: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4354: if (-e $tempfile) {
4355: my @info = stat($tempfile);
4356: if ($info[9] eq $env{'form.timestamp'}) {
4357: unlink($tempfile);
4358: }
4359: }
4360: return;
1.523 raeburn 4361: }
4362: }
1.1090 raeburn 4363: # Create the directory if not present
1.741 raeburn 4364: my @parts=split(/\//,$filepath);
4365: my $fullpath = $perlvar{'lonDaemons'};
4366: for (my $i=0;$i<@parts;$i++) {
4367: $fullpath .= '/'.$parts[$i];
4368: if ((-e $fullpath)!=1) {
4369: mkdir($fullpath,0777);
4370: }
4371: }
1.1359 raeburn 4372: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 4373: print $fh $env{'form.'.$formname};
4374: close($fh);
1.1090 raeburn 4375: if ($context eq 'existingfile') {
4376: my @info = stat($fullpath.'/'.$fname);
4377: return ($fullpath.'/'.$fname,$info[9]);
4378: } else {
4379: return $fullpath.'/'.$fname;
4380: }
1.523 raeburn 4381: }
1.995 raeburn 4382: if ($subdir eq 'scantron') {
4383: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 4384: } else {
1.995 raeburn 4385: $fname="$subdir/$fname";
4386: }
1.1090 raeburn 4387: if ($context eq 'coursedoc') {
1.638 albertel 4388: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4389: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 4390: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 4391: return &finishuserfileupload($docuname,$docudom,
4392: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 4393: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 4394: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 4395: } else {
1.1218 raeburn 4396: if ($env{'form.folder'}) {
4397: $fname=$env{'form.folder'}.'/'.$fname;
4398: }
1.638 albertel 4399: return &process_coursefile('uploaddoc',$docuname,$docudom,
4400: $fname,$formname,$parser,
1.1095 raeburn 4401: $allfiles,$codebase,$mimetype);
1.481 raeburn 4402: }
1.719 banghart 4403: } elsif (defined($destuname)) {
4404: my $docuname=$destuname;
4405: my $docudom=$destudom;
1.860 raeburn 4406: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4407: $parser,$allfiles,$codebase,
1.1051 raeburn 4408: $thumbwidth,$thumbheight,
1.1095 raeburn 4409: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4410: } else {
1.638 albertel 4411: my $docuname=$env{'user.name'};
4412: my $docudom=$env{'user.domain'};
1.1220 raeburn 4413: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 4414: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4415: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4416: }
1.860 raeburn 4417: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4418: $parser,$allfiles,$codebase,
1.1051 raeburn 4419: $thumbwidth,$thumbheight,
1.1095 raeburn 4420: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4421: }
1.271 www 4422: }
4423:
4424: sub finishuserfileupload {
1.860 raeburn 4425: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4426: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4427: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4428: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4429:
1.860 raeburn 4430: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4431: $file=$fname;
4432: if ($fname=~m|/|) {
4433: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4434: $path.=$fnamepath.'/';
4435: }
1.259 www 4436: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4437: my $count;
4438: for ($count=4;$count<=$#parts;$count++) {
4439: $filepath.="/$parts[$count]";
4440: if ((-e $filepath)!=1) {
4441: mkdir($filepath,0777);
4442: }
4443: }
1.984 neumanie 4444:
1.258 www 4445: # Save the file
4446: {
1.1359 raeburn 4447: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4448: &logthis('Failed to create '.$filepath.'/'.$file);
4449: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4450: return '/adm/notfound.html';
4451: }
1.1090 raeburn 4452: if ($context eq 'overwrite') {
1.1117 foxr 4453: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4454: my $target = $filepath.'/'.$file;
4455: if (-e $source) {
4456: my @info = stat($source);
4457: if ($info[9] eq $env{'form.timestamp'}) {
4458: unless (&File::Copy::move($source,$target)) {
4459: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4460: return "Moving from $source failed";
4461: }
4462: } else {
4463: return "Temporary file: $source had unexpected date/time for last modification";
4464: }
4465: } else {
4466: return "Temporary file: $source missing";
4467: }
4468: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4469: &logthis('Failed to write to '.$filepath.'/'.$file);
4470: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4471: return '/adm/notfound.html';
4472: }
1.570 albertel 4473: close(FH);
1.1051 raeburn 4474: if ($resizewidth && $resizeheight) {
4475: my $mm = new File::MMagic;
4476: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4477: if ($mime_type =~ m{^image/}) {
4478: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4479: }
1.977 amueller 4480: }
1.258 www 4481: }
1.1152 raeburn 4482: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4483: if (ref($mimetype)) {
4484: if ($$mimetype eq '') {
4485: my $mm = new File::MMagic;
4486: my $type = $mm->checktype_filename($filepath.'/'.$file);
4487: $$mimetype = $type;
4488: }
4489: }
4490: }
1.1401 raeburn 4491: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4492: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4493: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4494: $allfiles,$codebase);
4495: unless ($parse_result eq 'ok') {
4496: &logthis('Failed to parse '.$filepath.$file.
4497: ' for embedded media: '.$parse_result);
4498: }
1.637 raeburn 4499: }
1.1401 raeburn 4500: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4501: my $format = $env{'form.scantron_format'};
4502: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4503: }
1.860 raeburn 4504: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4505: my $input = $filepath.'/'.$file;
4506: my $output = $filepath.'/'.'tn-'.$file;
1.1504 raeburn 4507: my $makethumb;
1.860 raeburn 4508: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1504 raeburn 4509: if ($context eq 'toollogo') {
4510: my ($fullwidth,$fullheight) = &check_dimensions($input);
4511: if ($fullwidth ne '' && $fullheight ne '') {
4512: if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
4513: $makethumb = 1;
4514: }
4515: }
4516: } else {
4517: $makethumb = 1;
4518: }
4519: if ($makethumb) {
4520: my @args = ('convert','-sample',$thumbsize,$input,$output);
4521: system({$args[0]} @args);
4522: if (-e $filepath.'/'.'tn-'.$file) {
4523: $fetchthumb = 1;
4524: }
1.860 raeburn 4525: }
4526: }
1.858 raeburn 4527:
1.259 www 4528: # Notify homeserver to grep it
4529: #
1.984 neumanie 4530: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4531: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4532: if ($fetchresult eq 'ok') {
1.860 raeburn 4533: if ($fetchthumb) {
4534: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4535: if ($thumbresult ne 'ok') {
4536: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4537: $docuhome.': '.$thumbresult);
4538: }
4539: }
1.259 www 4540: #
1.258 www 4541: # Return the URL to it
1.494 albertel 4542: return '/uploaded/'.$path.$file;
1.263 www 4543: } else {
1.494 albertel 4544: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4545: ': '.$fetchresult);
1.263 www 4546: return '/adm/notfound.html';
1.858 raeburn 4547: }
1.493 albertel 4548: }
4549:
1.637 raeburn 4550: sub extract_embedded_items {
1.961 raeburn 4551: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4552: my @state = ();
1.1164 raeburn 4553: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4554: my %javafiles = (
4555: codebase => '',
4556: code => '',
4557: archive => ''
4558: );
4559: my %mediafiles = (
4560: src => '',
4561: movie => '',
4562: );
1.648 raeburn 4563: my $p;
4564: if ($content) {
4565: $p = HTML::LCParser->new($content);
4566: } else {
1.961 raeburn 4567: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4568: }
1.641 albertel 4569: while (my $t=$p->get_token()) {
1.640 albertel 4570: if ($t->[0] eq 'S') {
4571: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4572: push(@state, $tagname);
1.648 raeburn 4573: if (lc($tagname) eq 'allow') {
4574: &add_filetype($allfiles,$attr->{'src'},'src');
4575: }
1.640 albertel 4576: if (lc($tagname) eq 'img') {
4577: &add_filetype($allfiles,$attr->{'src'},'src');
4578: }
1.886 albertel 4579: if (lc($tagname) eq 'a') {
1.1222 raeburn 4580: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 4581: &add_filetype($allfiles,$attr->{'href'},'href');
4582: }
1.886 albertel 4583: }
1.645 raeburn 4584: if (lc($tagname) eq 'script') {
1.1164 raeburn 4585: my $src;
1.645 raeburn 4586: if ($attr->{'archive'} =~ /\.jar$/i) {
4587: &add_filetype($allfiles,$attr->{'archive'},'archive');
4588: } else {
1.1164 raeburn 4589: if ($attr->{'src'} ne '') {
4590: $src = $attr->{'src'};
4591: &add_filetype($allfiles,$src,'src');
4592: }
4593: }
4594: my $text = $p->get_trimmed_text();
4595: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4596: my @swfargs = split(/,/,$1);
4597: foreach my $item (@swfargs) {
4598: $item =~ s/["']//g;
4599: $item =~ s/^\s+//;
4600: $item =~ s/\s+$//;
4601: }
4602: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4603: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4604: push(@{$related{$swfargs[0]}},$swfargs[2]);
4605: } else {
4606: $related{$swfargs[0]} = [$swfargs[2]];
4607: }
4608: }
1.645 raeburn 4609: }
4610: }
4611: if (lc($tagname) eq 'link') {
4612: if (lc($attr->{'rel'}) eq 'stylesheet') {
4613: &add_filetype($allfiles,$attr->{'href'},'href');
4614: }
4615: }
1.640 albertel 4616: if (lc($tagname) eq 'object' ||
4617: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4618: foreach my $item (keys(%javafiles)) {
4619: $javafiles{$item} = '';
4620: }
1.1164 raeburn 4621: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4622: $lastids{lc($tagname)} = $attr->{'id'};
4623: }
1.640 albertel 4624: }
4625: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4626: my $name = lc($attr->{'name'});
4627: foreach my $item (keys(%javafiles)) {
4628: if ($name eq $item) {
4629: $javafiles{$item} = $attr->{'value'};
4630: last;
4631: }
4632: }
1.1164 raeburn 4633: my $pathfrom;
1.640 albertel 4634: foreach my $item (keys(%mediafiles)) {
4635: if ($name eq $item) {
1.1164 raeburn 4636: $pathfrom = $attr->{'value'};
4637: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4638: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4639: last;
4640: }
4641: }
1.1164 raeburn 4642: if ($name eq 'flashvars') {
4643: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4644: }
4645: if ($pathfrom ne '') {
4646: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4647: $pathfrom);
4648: }
1.640 albertel 4649: }
4650: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4651: foreach my $item (keys(%javafiles)) {
4652: if ($attr->{$item}) {
4653: $javafiles{$item} = $attr->{$item};
4654: last;
4655: }
4656: }
4657: foreach my $item (keys(%mediafiles)) {
4658: if ($attr->{$item}) {
4659: &add_filetype($allfiles,$attr->{$item},$item);
4660: last;
4661: }
4662: }
1.1164 raeburn 4663: if (lc($tagname) eq 'embed') {
4664: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4665: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4666: $attr->{'src'});
4667: }
4668: }
1.640 albertel 4669: }
1.1243 raeburn 4670: if (lc($tagname) eq 'iframe') {
4671: my $src = $attr->{'src'} ;
4672: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4673: &add_filetype($allfiles,$src,'src');
4674: } elsif ($src =~ m{^/}) {
4675: if ($env{'request.course.id'}) {
4676: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4677: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4678: my $url = &hreflocation('',$fullpath);
4679: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4680: my $relpath = $1;
4681: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4682: &add_filetype($allfiles,$1,'src');
4683: }
4684: }
4685: }
4686: }
4687: }
1.1164 raeburn 4688: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 4689: pop(@state);
1.1164 raeburn 4690: }
1.640 albertel 4691: } elsif ($t->[0] eq 'E') {
4692: my ($tagname) = ($t->[1]);
4693: if ($javafiles{'codebase'} ne '') {
4694: $javafiles{'codebase'} .= '/';
4695: }
4696: if (lc($tagname) eq 'applet' ||
4697: lc($tagname) eq 'object' ||
4698: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4699: ) {
4700: foreach my $item (keys(%javafiles)) {
4701: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4702: my $file=$javafiles{'codebase'}.$javafiles{$item};
4703: &add_filetype($allfiles,$file,$item);
4704: }
4705: }
4706: }
4707: pop @state;
4708: }
4709: }
1.1164 raeburn 4710: foreach my $id (sort(keys(%flashvars))) {
4711: if ($shockwave{$id} ne '') {
4712: my @pairs = split(/\&/,$flashvars{$id});
4713: foreach my $pair (@pairs) {
4714: my ($key,$value) = split(/\=/,$pair);
4715: if ($key eq 'thumb') {
4716: &add_filetype($allfiles,$value,$key);
4717: } elsif ($key eq 'content') {
4718: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4719: my ($ext) = ($value =~ /\.([^.]+)$/);
4720: if ($ext ne '') {
4721: &add_filetype($allfiles,$path.$value,$ext);
4722: }
4723: }
4724: }
4725: }
4726: }
1.637 raeburn 4727: return 'ok';
4728: }
4729:
1.639 albertel 4730: sub add_filetype {
4731: my ($allfiles,$file,$type)=@_;
4732: if (exists($allfiles->{$file})) {
4733: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4734: push(@{$allfiles->{$file}}, &escape($type));
4735: }
4736: } else {
4737: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4738: }
4739: }
4740:
1.1164 raeburn 4741: sub embedded_dependency {
4742: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4743: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4744: if (($identifier ne '') &&
4745: (ref($related->{$identifier}) eq 'ARRAY') &&
4746: ($pathfrom ne '')) {
4747: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4748: foreach my $dep (@{$related->{$identifier}}) {
4749: &add_filetype($allfiles,$path.$dep,'object');
4750: }
4751: }
4752: }
4753: return;
4754: }
4755:
1.1504 raeburn 4756: sub check_dimensions {
4757: my ($inputfile) = @_;
4758: my ($fullwidth,$fullheight);
4759: if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
4760: my $mm = new File::MMagic;
4761: my $mime_type = $mm->checktype_filename($inputfile);
4762: if ($mime_type =~ m{^image/}) {
4763: if (open(PIPE,"identify $inputfile 2>&1 |")) {
4764: my $imageinfo = <PIPE>;
4765: if (!close(PIPE)) {
4766: &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
4767: }
4768: chomp($imageinfo);
4769: my ($fullsize) =
4770: ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
4771: if ($fullsize) {
4772: ($fullwidth,$fullheight) = split(/x/,$fullsize);
4773: }
4774: }
4775: }
4776: }
4777: return ($fullwidth,$fullheight);
4778: }
4779:
1.1401 raeburn 4780: sub bubblesheet_converter {
4781: my ($cdom,$fullpath,$config,$format) = @_;
4782: if ((&domain($cdom) ne '') &&
1.1403 raeburn 4783: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401 raeburn 4784: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404 raeburn 4785: my (%csvcols,%csvoptions);
4786: if (ref($config->{'fields'}) eq 'HASH') {
4787: %csvcols = %{$config->{'fields'}};
4788: }
4789: if (ref($config->{'options'}) eq 'HASH') {
4790: %csvoptions = %{$config->{'options'}};
4791: }
1.1401 raeburn 4792: my %csvbynum = reverse(%csvcols);
4793: my %scantronconf = &get_scantron_config($format,$cdom);
4794: if (keys(%scantronconf)) {
4795: my %bynum = (
4796: $scantronconf{CODEstart} => 'CODEstart',
4797: $scantronconf{IDstart} => 'IDstart',
4798: $scantronconf{PaperID} => 'PaperID',
4799: $scantronconf{FirstName} => 'FirstName',
4800: $scantronconf{LastName} => 'LastName',
4801: $scantronconf{Qstart} => 'Qstart',
4802: );
4803: my @ordered;
4804: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403 raeburn 4805: push(@ordered,$bynum{$item});
1.1401 raeburn 4806: }
4807: my %mapstart = (
4808: CODEstart => 'CODE',
4809: IDstart => 'ID',
4810: PaperID => 'PaperID',
4811: FirstName => 'FirstName',
4812: LastName => 'LastName',
4813: Qstart => 'FirstQuestion',
4814: );
4815: my %maplength = (
4816: CODEstart => 'CODElength',
4817: IDstart => 'IDlength',
4818: PaperID => 'PaperIDlength',
4819: FirstName => 'FirstNamelength',
4820: LastName => 'LastNamelength',
4821: );
4822: if (open(my $fh,'<',$fullpath)) {
4823: my $output;
1.1403 raeburn 4824: my %lettdig = &letter_to_digits();
4825: my %diglett = reverse(%lettdig);
4826: my $numletts = scalar(keys(%lettdig));
1.1404 raeburn 4827: my $num = 0;
1.1401 raeburn 4828: while (my $line=<$fh>) {
1.1404 raeburn 4829: $num ++;
4830: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401 raeburn 4831: $line =~ s{[\r\n]+$}{};
4832: my %found;
1.1475 raeburn 4833: my @values = split(/,/,$line,-1);
1.1401 raeburn 4834: my ($qstart,$record);
4835: for (my $i=0; $i<@values; $i++) {
1.1403 raeburn 4836: if ((($qstart ne '') && ($i > $qstart)) ||
4837: ($csvbynum{$i} eq 'FirstQuestion')) {
4838: if ($values[$i] eq '') {
4839: $values[$i] = $scantronconf{'Qoff'};
4840: } elsif ($scantronconf{'Qon'} eq 'number') {
4841: if ($values[$i] =~ /^[A-Ja-j]$/) {
4842: $values[$i] = $lettdig{uc($values[$i])};
4843: }
4844: } elsif ($scantronconf{'Qon'} eq 'letter') {
4845: if ($values[$i] =~ /^[0-9]$/) {
4846: $values[$i] = $diglett{$values[$i]};
4847: }
4848: } else {
4849: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4850: my $digit;
4851: if ($values[$i] =~ /^[A-Ja-j]$/) {
4852: $digit = $lettdig{uc($values[$i])}-1;
4853: if ($values[$i] eq 'J') {
4854: $digit += $numletts;
4855: }
4856: } elsif ($values[$i] =~ /^[0-9]$/) {
4857: $digit = $values[$i]-1;
4858: if ($values[$i] eq '0') {
4859: $digit += $numletts;
4860: }
4861: }
4862: my $qval='';
4863: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4864: if ($j == $digit) {
4865: $qval .= $scantronconf{'Qon'};
4866: } else {
4867: $qval .= $scantronconf{'Qoff'};
4868: }
4869: }
4870: $values[$i] = $qval;
4871: }
4872: }
4873: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4874: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4875: }
4876: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4877: if ($numblank > 0) {
4878: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4879: }
1.1401 raeburn 4880: if ($csvbynum{$i} eq 'FirstQuestion') {
4881: $qstart = $i;
1.1403 raeburn 4882: $found{$csvbynum{$i}} = $values[$i];
1.1401 raeburn 4883: } else {
1.1403 raeburn 4884: $found{'FirstQuestion'} .= $values[$i];
4885: }
4886: } elsif (exists($csvbynum{$i})) {
1.1404 raeburn 4887: if ($csvoptions{'rem'}) {
4888: $values[$i] =~ s/^\s+//;
4889: }
4890: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403 raeburn 4891: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4892: $values[$i] = '0'.$values[$i];
1.1401 raeburn 4893: }
4894: }
4895: $found{$csvbynum{$i}} = $values[$i];
4896: }
4897: }
4898: foreach my $item (@ordered) {
4899: my $currlength = 1+length($record);
4900: my $numspaces = $scantronconf{$item} - $currlength;
4901: if ($numspaces > 0) {
4902: $record .= (' ' x $numspaces);
4903: }
4904: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4905: unless ($item eq 'Qstart') {
4906: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4907: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4908: }
4909: }
4910: $record .= $found{$mapstart{$item}};
4911: }
4912: }
4913: $output .= "$record\n";
4914: }
4915: close($fh);
4916: if ($output) {
4917: if (open(my $fh,'>',$fullpath)) {
4918: print $fh $output;
4919: close($fh);
4920: }
4921: }
4922: }
4923: }
4924: return;
4925: }
4926: }
4927:
1.1403 raeburn 4928: sub letter_to_digits {
4929: my %lettdig = (
4930: A => 1,
4931: B => 2,
4932: C => 3,
4933: D => 4,
4934: E => 5,
4935: F => 6,
4936: G => 7,
4937: H => 8,
4938: I => 9,
4939: J => 0,
4940: );
4941: return %lettdig;
4942: }
4943:
1.1401 raeburn 4944: sub get_scantron_config {
4945: my ($which,$cdom) = @_;
4946: my @lines = &get_scantronformat_file($cdom);
4947: my %config;
4948: #FIXME probably should move to XML it has already gotten a bit much now
4949: foreach my $line (@lines) {
4950: my ($name,$descrip)=split(/:/,$line);
4951: if ($name ne $which ) { next; }
4952: chomp($line);
4953: my @config=split(/:/,$line);
4954: $config{'name'}=$config[0];
4955: $config{'description'}=$config[1];
4956: $config{'CODElocation'}=$config[2];
4957: $config{'CODEstart'}=$config[3];
4958: $config{'CODElength'}=$config[4];
4959: $config{'IDstart'}=$config[5];
4960: $config{'IDlength'}=$config[6];
4961: $config{'Qstart'}=$config[7];
4962: $config{'Qlength'}=$config[8];
4963: $config{'Qoff'}=$config[9];
4964: $config{'Qon'}=$config[10];
4965: $config{'PaperID'}=$config[11];
4966: $config{'PaperIDlength'}=$config[12];
4967: $config{'FirstName'}=$config[13];
4968: $config{'FirstNamelength'}=$config[14];
4969: $config{'LastName'}=$config[15];
4970: $config{'LastNamelength'}=$config[16];
4971: $config{'BubblesPerRow'}=$config[17];
4972: last;
4973: }
4974: return %config;
4975: }
4976:
4977: sub get_scantronformat_file {
4978: my ($cdom) = @_;
4979: if ($cdom eq '') {
4980: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4981: }
4982: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4983: my $gottab = 0;
4984: my @lines;
4985: if (ref($domconfig{'scantron'}) eq 'HASH') {
4986: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4987: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4988: if ($formatfile ne '-1') {
4989: @lines = split("\n",$formatfile,-1);
4990: $gottab = 1;
4991: }
4992: }
4993: }
4994: if (!$gottab) {
4995: my $confname = $cdom.'-domainconfig';
4996: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4997: my $formatfile = &getfile($default);
4998: if ($formatfile ne '-1') {
4999: @lines = split("\n",$formatfile,-1);
5000: $gottab = 1;
5001: }
5002: }
5003: if (!$gottab) {
5004: my @domains = ¤t_machine_domains();
5005: if (grep(/^\Q$cdom\E$/,@domains)) {
5006: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
5007: @lines = <$fh>;
5008: close($fh);
1.1403 raeburn 5009: }
1.1401 raeburn 5010: } else {
5011: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
5012: @lines = <$fh>;
5013: close($fh);
5014: }
5015: }
1.1488 raeburn 5016: chomp(@lines);
1.1401 raeburn 5017: }
5018: return @lines;
5019: }
5020:
1.493 albertel 5021: sub removeuploadedurl {
1.984 neumanie 5022: my ($url)=@_;
5023: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 5024: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 5025: }
5026:
5027: sub removeuserfile {
5028: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 5029: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 5030: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 5031: if ($result eq 'ok') {
1.798 raeburn 5032: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
5033: my $metafile = $fname.'.meta';
5034: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 5035: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 5036: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 5037: my $sqlresult =
1.823 albertel 5038: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 5039: 'portfolio_metadata',$group,
5040: 'delete');
1.798 raeburn 5041: }
5042: }
5043: return $result;
1.257 www 5044: }
1.15 www 5045:
1.530 albertel 5046: sub mkdiruserfile {
5047: my ($docuname,$docudom,$dir)=@_;
5048: my $home=&homeserver($docuname,$docudom);
5049: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
5050: }
5051:
1.531 albertel 5052: sub renameuserfile {
5053: my ($docuname,$docudom,$old,$new)=@_;
5054: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 5055: my $result = &reply("renameuserfile:$docudom:$docuname:".
5056: &escape("$old").':'.&escape("$new"),$home);
5057: if ($result eq 'ok') {
5058: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
5059: my $oldmeta = $old.'.meta';
5060: my $newmeta = $new.'.meta';
5061: my $metaresult =
5062: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 5063: my $url = "/uploaded/$docudom/$docuname/$old";
5064: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 5065: my $sqlresult =
1.823 albertel 5066: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 5067: 'portfolio_metadata',$group,
5068: 'delete');
1.798 raeburn 5069: }
5070: }
5071: return $result;
1.531 albertel 5072: }
5073:
1.14 www 5074: # ------------------------------------------------------------------------- Log
5075:
5076: sub log {
5077: my ($dom,$nam,$hom,$what)=@_;
1.47 www 5078: return critical("log:$dom:$nam:$what",$hom);
1.157 www 5079: }
5080:
5081: # ------------------------------------------------------------------ Course Log
1.352 www 5082: #
5083: # This routine flushes several buffers of non-mission-critical nature
5084: #
1.157 www 5085:
5086: sub flushcourselogs {
1.352 www 5087: &logthis('Flushing log buffers');
5088: #
5089: # course logs
5090: # This is a log of all transactions in a course, which can be used
5091: # for data mining purposes
5092: #
5093: # It also collects the courseid database, which lists last transaction
5094: # times and course titles for all courseids
5095: #
5096: my %courseidbuffer=();
1.921 raeburn 5097: foreach my $crsid (keys(%courselogs)) {
1.352 www 5098: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 5099: &escape($courselogs{$crsid}),
5100: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 5101: delete $courselogs{$crsid};
5102: } else {
5103: &logthis('Failed to flush log buffer for '.$crsid);
5104: if (length($courselogs{$crsid})>40000) {
1.672 albertel 5105: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 5106: " exceeded maximum size, deleting.</font>");
5107: delete $courselogs{$crsid};
5108: }
1.352 www 5109: }
1.920 raeburn 5110: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 5111: 'description' => $coursedescrbuf{$crsid},
5112: 'inst_code' => $courseinstcodebuf{$crsid},
5113: 'type' => $coursetypebuf{$crsid},
5114: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 5115: };
1.191 harris41 5116: }
1.352 www 5117: #
5118: # Write course id database (reverse lookup) to homeserver of courses
5119: # Is used in pickcourse
5120: #
1.840 albertel 5121: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 5122: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 5123: $courseidbuffer{$crs_home},
5124: $crs_home,'timeonly');
1.352 www 5125: }
5126: #
5127: # File accesses
5128: # Writes to the dynamic metadata of resources to get hit counts, etc.
5129: #
1.449 matthew 5130: foreach my $entry (keys(%accesshash)) {
1.458 matthew 5131: if ($entry =~ /___count$/) {
5132: my ($dom,$name);
1.807 albertel 5133: ($dom,$name,undef)=
1.811 albertel 5134: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 5135: if (! defined($dom) || $dom eq '' ||
5136: ! defined($name) || $name eq '') {
1.620 albertel 5137: my $cid = $env{'request.course.id'};
1.1472 raeburn 5138: #
5139: # FIXME 11/29/2021
5140: # Typo in rev. 1.458 (2003/12/09)??
5141: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
5142: #
5143: # While these ramain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
5144: # $dom and $name will always be null, so the &inc() call will default to storing this data
5145: # in a nohist_accesscount.db file for the user rather than the course.
5146: #
5147: # That said there is a lot of noise in the data being stored.
5148: # So counts for prtspool/ and adm/ etc. are recorded.
5149: #
5150: # A review of which items ending '___count' are written to %accesshash should likely be
5151: # made before deciding whether to set these to 'course.' instead of 'request.'
5152: #
5153: # Under the current scheme each user receives a nohist_accesscount.db file listing
5154: # accesses for things which are not published resources, regardless of course, and
5155: # there is not a nohist_accesscount.db file in a course, which might log accesses from
5156: # anyone in the course for things which are not published resources.
5157: #
5158: # For an author, nohist_accesscount.db ends up having records for other items
5159: # mixed up with the legitimate access counts for the author's published resources.
5160: #
1.620 albertel 5161: $dom = $env{'request.'.$cid.'.domain'};
5162: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 5163: }
1.450 matthew 5164: my $value = $accesshash{$entry};
5165: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
5166: my %temphash=($url => $value);
1.449 matthew 5167: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
5168: if ($result eq 'ok') {
5169: delete $accesshash{$entry};
5170: }
5171: } else {
1.811 albertel 5172: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 5173: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 5174: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 5175: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
5176: delete $accesshash{$entry};
5177: }
1.185 www 5178: }
1.191 harris41 5179: }
1.352 www 5180: #
5181: # Roles
5182: # Reverse lookup of user roles for course faculty/staff and co-authorship
5183: #
1.800 albertel 5184: foreach my $entry (keys(%userrolehash)) {
1.351 www 5185: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 5186: split(/\:/,$entry);
1.1494 raeburn 5187: if (&put('nohist_userroles',
1.351 www 5188: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 5189: $rudom,$runame) eq 'ok') {
5190: delete $userrolehash{$entry};
5191: }
5192: }
1.662 raeburn 5193: #
1.1334 raeburn 5194: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 5195: #
5196: my %domrolebuffer = ();
1.1000 raeburn 5197: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 5198: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 5199: if ($domrolebuffer{$rudom}) {
5200: $domrolebuffer{$rudom}.='&'.&escape($entry).
5201: '='.&escape($domainrolehash{$entry});
5202: } else {
5203: $domrolebuffer{$rudom}.=&escape($entry).
5204: '='.&escape($domainrolehash{$entry});
5205: }
5206: delete $domainrolehash{$entry};
5207: }
5208: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 5209: my %servers;
5210: if (defined(&domain($dom,'primary'))) {
5211: my $primary=&domain($dom,'primary');
5212: my $hostname=&hostname($primary);
5213: $servers{$primary} = $hostname;
5214: } else {
5215: %servers = &get_servers($dom,'library');
5216: }
1.841 albertel 5217: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 5218: if (&reply('domroleput:'.$dom.':'.
5219: $domrolebuffer{$dom},$tryserver) eq 'ok') {
5220: last;
5221: } else {
1.841 albertel 5222: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
5223: }
1.662 raeburn 5224: }
5225: }
1.186 www 5226: $dumpcount++;
1.157 www 5227: }
5228:
5229: sub courselog {
5230: my $what=shift;
1.158 www 5231: $what=time.':'.$what;
1.620 albertel 5232: unless ($env{'request.course.id'}) { return ''; }
5233: $coursedombuf{$env{'request.course.id'}}=
5234: $env{'course.'.$env{'request.course.id'}.'.domain'};
5235: $coursenumbuf{$env{'request.course.id'}}=
5236: $env{'course.'.$env{'request.course.id'}.'.num'};
5237: $coursehombuf{$env{'request.course.id'}}=
5238: $env{'course.'.$env{'request.course.id'}.'.home'};
5239: $coursedescrbuf{$env{'request.course.id'}}=
5240: $env{'course.'.$env{'request.course.id'}.'.description'};
5241: $courseinstcodebuf{$env{'request.course.id'}}=
5242: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
5243: $courseownerbuf{$env{'request.course.id'}}=
5244: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 5245: $coursetypebuf{$env{'request.course.id'}}=
5246: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 5247: if (defined $courselogs{$env{'request.course.id'}}) {
5248: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 5249: } else {
1.620 albertel 5250: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 5251: }
1.620 albertel 5252: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 5253: &flushcourselogs();
5254: }
1.158 www 5255: }
5256:
5257: sub courseacclog {
5258: my $fnsymb=shift;
1.620 albertel 5259: unless ($env{'request.course.id'}) { return ''; }
5260: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 5261: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 5262: $what.=':POST';
1.583 matthew 5263: # FIXME: Probably ought to escape things....
1.800 albertel 5264: foreach my $key (keys(%env)) {
5265: if ($key=~/^form\.(.*)/) {
1.975 raeburn 5266: my $formitem = $1;
5267: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
5268: $what.=':'.$formitem.'='.$env{$key};
5269: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432 raeburn 5270: if ($formitem eq 'proctorpassword') {
1.1433 raeburn 5271: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432 raeburn 5272: } else {
5273: $what.=':'.$formitem.'='.$env{$key};
5274: }
1.975 raeburn 5275: }
1.158 www 5276: }
1.191 harris41 5277: }
1.583 matthew 5278: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
5279: # FIXME: We should not be depending on a form parameter that someone
5280: # editing lonsearchcat.pm might change in the future.
1.620 albertel 5281: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 5282: $what.= ':POST';
5283: # FIXME: Probably ought to escape things....
5284: foreach my $element ('courseexp','crsfulltext','crsrelated',
5285: 'crsdiscuss') {
1.620 albertel 5286: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 5287: }
5288: }
1.158 www 5289: }
5290: &courselog($what);
1.149 www 5291: }
5292:
1.185 www 5293: sub countacc {
5294: my $url=&declutter(shift);
1.458 matthew 5295: return if (! defined($url) || $url eq '');
1.620 albertel 5296: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 5297: #
5298: # Mark that this url was used in this course
5299: #
1.620 albertel 5300: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 5301: #
5302: # Increase the access count for this resource in this child process
5303: #
1.281 www 5304: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 5305: $accesshash{$key}++;
1.185 www 5306: }
1.349 www 5307:
1.361 www 5308: sub linklog {
5309: my ($from,$to)=@_;
5310: $from=&declutter($from);
5311: $to=&declutter($to);
5312: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5313: $accesshash{$to.'___'.$from.'___goto'}=1;
5314: }
1.1160 www 5315:
5316: sub statslog {
5317: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5318: if ($users<2) { return; }
5319: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5320: 'course' => $env{'request.course.id'},
5321: 'sections' => '"all"',
5322: 'num_students' => $users,
5323: 'part' => $part,
5324: 'symb' => $symb,
5325: 'mean_tries' => $av_attempts,
5326: 'deg_of_diff' => $degdiff});
5327: foreach my $key (keys(%dynstore)) {
5328: $accesshash{$key}=$dynstore{$key};
5329: }
5330: }
1.361 www 5331:
1.349 www 5332: sub userrolelog {
5333: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 5334: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 5335: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5336: $userrolehash
5337: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 5338: =$tend.':'.$tstart;
1.662 raeburn 5339: }
1.1169 droeschl 5340: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 5341: $userrolehash
5342: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5343: =$tend.':'.$tstart;
5344: }
1.1334 raeburn 5345: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 5346: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5347: $domainrolehash
5348: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5349: = $tend.':'.$tstart;
5350: }
1.351 www 5351: }
5352:
1.957 raeburn 5353: sub courserolelog {
5354: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 5355: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5356: my $cdom = $1;
5357: my $cnum = $2;
5358: my $sec = $3;
5359: my $namespace = 'rolelog';
5360: my %storehash = (
5361: role => $trole,
5362: start => $tstart,
5363: end => $tend,
5364: selfenroll => $selfenroll,
5365: context => $context,
5366: );
5367: if ($trole eq 'gr') {
5368: $namespace = 'groupslog';
5369: $storehash{'group'} = $sec;
5370: } else {
5371: $storehash{'section'} = $sec;
5372: }
1.1188 raeburn 5373: &write_log('course',$namespace,\%storehash,$delflag,$username,
5374: $domain,$cnum,$cdom);
1.1184 raeburn 5375: if (($trole ne 'st') || ($sec ne '')) {
5376: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 5377: }
5378: }
5379: return;
5380: }
5381:
1.1184 raeburn 5382: sub domainrolelog {
5383: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5384: if ($area =~ m{^/($match_domain)/$}) {
5385: my $cdom = $1;
1.1494 raeburn 5386: my $domconfiguser = &get_domainconfiguser($cdom);
1.1184 raeburn 5387: my $namespace = 'rolelog';
5388: my %storehash = (
5389: role => $trole,
5390: start => $tstart,
5391: end => $tend,
5392: context => $context,
5393: );
1.1188 raeburn 5394: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5395: $domain,$domconfiguser,$cdom);
1.1184 raeburn 5396: }
5397: return;
5398:
5399: }
5400:
5401: sub coauthorrolelog {
5402: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5403: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5404: my $audom = $1;
5405: my $auname = $2;
5406: my $namespace = 'rolelog';
5407: my %storehash = (
5408: role => $trole,
5409: start => $tstart,
5410: end => $tend,
5411: context => $context,
5412: );
1.1188 raeburn 5413: &write_log('author',$namespace,\%storehash,$delflag,$username,
5414: $domain,$auname,$audom);
1.1184 raeburn 5415: }
5416: return;
5417: }
5418:
1.351 www 5419: sub get_course_adv_roles {
1.948 raeburn 5420: my ($cid,$codes) = @_;
1.620 albertel 5421: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 5422: my %coursehash=&coursedescription($cid);
1.988 raeburn 5423: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 5424: my %nothide=();
1.800 albertel 5425: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 5426: if ($user !~ /:/) {
5427: $nothide{join(':',split(/[\@]/,$user))}=1;
5428: } else {
5429: $nothide{$user}=1;
5430: }
1.470 www 5431: }
1.1219 raeburn 5432: my @possdoms = ($coursehash{'domain'});
5433: if ($coursehash{'checkforpriv'}) {
5434: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5435: }
1.351 www 5436: my %returnhash=();
5437: my %dumphash=
5438: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5439: my $now=time;
1.997 raeburn 5440: my %privileged;
1.1000 raeburn 5441: foreach my $entry (keys(%dumphash)) {
1.800 albertel 5442: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 5443: if (($tstart) && ($tstart<0)) { next; }
5444: if (($tend) && ($tend<$now)) { next; }
5445: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 5446: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 5447: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 5448: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 5449: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 5450: if ($role eq 'cr') { next; }
1.948 raeburn 5451: if ($codes) {
5452: if ($section) { $role .= ':'.$section; }
5453: if ($returnhash{$role}) {
5454: $returnhash{$role}.=','.$username.':'.$domain;
5455: } else {
5456: $returnhash{$role}=$username.':'.$domain;
5457: }
1.351 www 5458: } else {
1.988 raeburn 5459: my $key=&plaintext($role,$crstype);
1.973 bisitz 5460: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 5461: if ($returnhash{$key}) {
5462: $returnhash{$key}.=','.$username.':'.$domain;
5463: } else {
5464: $returnhash{$key}=$username.':'.$domain;
5465: }
1.351 www 5466: }
1.948 raeburn 5467: }
1.400 www 5468: return %returnhash;
5469: }
5470:
5471: sub get_my_roles {
1.937 raeburn 5472: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5473: unless (defined($uname)) { $uname=$env{'user.name'}; }
5474: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5475: my (%dumphash,%nothide);
1.1086 raeburn 5476: if ($context eq 'userroles') {
1.1166 raeburn 5477: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5478: } else {
1.1219 raeburn 5479: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5480: if ($hidepriv) {
5481: my %coursehash=&coursedescription($udom.'_'.$uname);
5482: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5483: if ($user !~ /:/) {
5484: $nothide{join(':',split(/[\@]/,$user))} = 1;
5485: } else {
5486: $nothide{$user} = 1;
5487: }
5488: }
5489: }
1.858 raeburn 5490: }
1.400 www 5491: my %returnhash=();
5492: my $now=time;
1.999 raeburn 5493: my %privileged;
1.800 albertel 5494: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5495: my ($role,$tend,$tstart);
5496: if ($context eq 'userroles') {
1.1149 raeburn 5497: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5498: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5499: } else {
5500: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5501: }
1.400 www 5502: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5503: my $status = 'active';
1.939 raeburn 5504: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5505: $status = 'previous';
5506: }
5507: if (($tstart) && ($now<$tstart)) {
5508: $status = 'future';
5509: }
5510: if (ref($types) eq 'ARRAY') {
5511: if (!grep(/^\Q$status\E$/,@{$types})) {
5512: next;
5513: }
5514: } else {
5515: if ($status ne 'active') {
5516: next;
5517: }
5518: }
1.867 raeburn 5519: my ($rolecode,$username,$domain,$section,$area);
5520: if ($context eq 'userroles') {
1.1186 raeburn 5521: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5522: (undef,$domain,$username,$section) = split(/\//,$area);
5523: } else {
5524: ($role,$username,$domain,$section) = split(/\:/,$entry);
5525: }
1.832 raeburn 5526: if (ref($roledoms) eq 'ARRAY') {
5527: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5528: next;
5529: }
5530: }
5531: if (ref($roles) eq 'ARRAY') {
5532: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5533: if ($role =~ /^cr\//) {
5534: if (!grep(/^cr$/,@{$roles})) {
5535: next;
5536: }
1.1104 raeburn 5537: } elsif ($role =~ /^gr\//) {
5538: if (!grep(/^gr$/,@{$roles})) {
5539: next;
5540: }
1.922 raeburn 5541: } else {
5542: next;
5543: }
1.832 raeburn 5544: }
1.867 raeburn 5545: }
1.937 raeburn 5546: if ($hidepriv) {
1.1219 raeburn 5547: my @privroles = ('dc','su');
1.999 raeburn 5548: if ($context eq 'userroles') {
1.1219 raeburn 5549: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5550: } else {
1.1219 raeburn 5551: my $possdoms = [$domain];
5552: if (ref($roledoms) eq 'ARRAY') {
5553: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5554: }
1.1219 raeburn 5555: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5556: if (!$nothide{$username.':'.$domain}) {
5557: next;
5558: }
5559: }
1.937 raeburn 5560: }
5561: }
1.933 raeburn 5562: if ($withsec) {
5563: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5564: $tstart.':'.$tend;
5565: } else {
5566: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5567: }
1.832 raeburn 5568: }
1.373 www 5569: return %returnhash;
1.399 www 5570: }
5571:
1.1333 raeburn 5572: sub get_all_adhocroles {
5573: my ($dom) = @_;
5574: my @roles_by_num = ();
5575: my %domdefaults = &get_domain_defaults($dom);
5576: my (%description,%access_in_dom,%access_info);
5577: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5578: my $count = 0;
5579: my %domcurrent = %{$domdefaults{'adhocroles'}};
5580: my %ordered;
5581: foreach my $role (sort(keys(%domcurrent))) {
5582: my ($order,$desc,$access_in_dom);
5583: if (ref($domcurrent{$role}) eq 'HASH') {
5584: $order = $domcurrent{$role}{'order'};
5585: $desc = $domcurrent{$role}{'desc'};
5586: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5587: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5588: }
5589: if ($order eq '') {
5590: $order = $count;
5591: }
5592: $ordered{$order} = $role;
5593: if ($desc ne '') {
5594: $description{$role} = $desc;
5595: } else {
5596: $description{$role}= $role;
5597: }
5598: $count++;
5599: }
5600: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5601: push(@roles_by_num,$ordered{$item});
5602: }
5603: }
5604: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5605: }
5606:
1.1332 raeburn 5607: sub get_my_adhocroles {
1.1333 raeburn 5608: my ($cid,$checkreg) = @_;
5609: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5610: if ($env{'request.course.id'} eq $cid) {
5611: $cdom = $env{'course.'.$cid.'.domain'};
5612: $cnum = $env{'course.'.$cid.'.num'};
5613: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5614: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5615: $cdom = $1;
5616: $cnum = $2;
1.1494 raeburn 5617: %info = &get('environment',['internal.coursecode'],
5618: $cdom,$cnum);
1.1333 raeburn 5619: }
5620: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5621: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5622: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5623: if ($rosterhash{$user} ne '') {
5624: my $type = (split(/:/,$rosterhash{$user}))[5];
5625: return ([],{}) if ($type eq 'auto');
5626: }
5627: }
5628: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 5629: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 5630: my $then=$env{'user.login.time'};
5631: my $update=$env{'user.update.time'};
1.1335 raeburn 5632: if (!$update) {
5633: $update = $then;
5634: }
5635: my @liveroles;
1.1334 raeburn 5636: foreach my $role ('dh','da') {
5637: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 5638: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 5639: my $limit = $update;
5640: if ($env{'request.role'} eq "$role./$cdom/") {
5641: $limit = $then;
5642: }
1.1335 raeburn 5643: my $activerole = 1;
5644: if ($tstart && $tstart>$limit) { $activerole = 0; }
5645: if ($tend && $tend <$limit) { $activerole = 0; }
5646: if ($activerole) {
5647: push(@liveroles,$role);
5648: }
1.1334 raeburn 5649: }
1.1332 raeburn 5650: }
1.1335 raeburn 5651: if (@liveroles) {
1.1332 raeburn 5652: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 5653: my ($accessref,$accessinfo,%access_in_dom);
5654: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5655: if (ref($roles_by_num) eq 'ARRAY') {
5656: if (@{$roles_by_num}) {
1.1332 raeburn 5657: my %settings;
5658: if ($env{'request.course.id'} eq $cid) {
5659: foreach my $envkey (keys(%env)) {
5660: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5661: $settings{$1} = $env{$envkey};
5662: }
5663: }
5664: } else {
5665: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5666: }
5667: my %setincrs;
5668: if ($settings{'internal.adhocaccess'}) {
5669: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5670: }
5671: my @statuses;
5672: if ($env{'environment.inststatus'}) {
5673: @statuses = split(/,/,$env{'environment.inststatus'});
5674: }
5675: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 5676: if (ref($accessref) eq 'HASH') {
5677: %access_in_dom = %{$accessref};
5678: }
5679: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 5680: my ($curraccess,@okstatus,@personnel);
5681: if ($setincrs{$role}) {
5682: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5683: if ($curraccess eq 'status') {
5684: @okstatus = split(/\&/,$rest);
5685: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5686: @personnel = split(/\&/,$rest);
5687: }
5688: } else {
5689: $curraccess = $access_in_dom{$role};
1.1333 raeburn 5690: if (ref($accessinfo) eq 'HASH') {
5691: if ($curraccess eq 'status') {
5692: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5693: @okstatus = @{$accessinfo->{$role}};
5694: }
5695: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5696: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5697: @personnel = @{$accessinfo->{$role}};
5698: }
1.1332 raeburn 5699: }
5700: }
5701: }
5702: if ($curraccess eq 'none') {
5703: next;
5704: } elsif ($curraccess eq 'all') {
5705: push(@possroles,$role);
1.1336 raeburn 5706: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 5707: if (grep(/^dh$/,@liveroles)) {
5708: push(@possroles,$role);
5709: } else {
5710: next;
5711: }
1.1336 raeburn 5712: } elsif ($curraccess eq 'da') {
1.1335 raeburn 5713: if (grep(/^da$/,@liveroles)) {
5714: push(@possroles,$role);
5715: } else {
5716: next;
5717: }
1.1332 raeburn 5718: } elsif ($curraccess eq 'status') {
5719: if (@okstatus) {
5720: if (!@statuses) {
5721: if (grep(/^default$/,@okstatus)) {
5722: push(@possroles,$role);
5723: }
5724: } else {
5725: foreach my $status (@okstatus) {
5726: if (grep(/^\Q$status\E$/,@statuses)) {
5727: push(@possroles,$role);
5728: last;
5729: }
5730: }
5731: }
5732: }
5733: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5734: if (grep(/^\Q$user\E$/,@personnel)) {
5735: if ($curraccess eq 'exc') {
5736: push(@possroles,$role);
5737: }
5738: } elsif ($curraccess eq 'inc') {
5739: push(@possroles,$role);
5740: }
5741: }
5742: }
5743: }
5744: }
5745: }
5746: }
5747: }
5748: }
1.1333 raeburn 5749: unless (ref($description) eq 'HASH') {
5750: if (ref($roles_by_num) eq 'ARRAY') {
5751: my %desc;
5752: map { $desc{$_} = $_; } (@{$roles_by_num});
5753: $description = \%desc;
5754: } else {
5755: $description = {};
5756: }
5757: }
5758: return (\@possroles,$description);
1.1332 raeburn 5759: }
5760:
1.399 www 5761: # ----------------------------------------------------- Frontpage Announcements
5762: #
5763: #
5764:
5765: sub postannounce {
5766: my ($server,$text)=@_;
1.844 albertel 5767: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5768: unless ($text=~/\w/) { $text=''; }
5769: return &reply('setannounce:'.&escape($text),$server);
5770: }
5771:
5772: sub getannounce {
1.448 albertel 5773:
1.1359 raeburn 5774: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5775: my $announcement='';
1.800 albertel 5776: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5777: close($fh);
1.399 www 5778: if ($announcement=~/\w/) {
5779: return
5780: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5781: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5782: } else {
5783: return '';
5784: }
5785: } else {
5786: return '';
5787: }
1.351 www 5788: }
1.353 www 5789:
5790: # ---------------------------------------------------------- Course ID routines
5791: # Deal with domain's nohist_courseid.db files
5792: #
5793:
5794: sub courseidput {
1.921 raeburn 5795: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5796: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5797: my $outcome;
5798: if ($caller eq 'timeonly') {
5799: my $cids = '';
5800: foreach my $item (keys(%$storehash)) {
5801: $cids.=&escape($item).'&';
5802: }
5803: $cids=~s/\&$//;
5804: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5805: $coursehome);
5806: } else {
5807: my $items = '';
5808: foreach my $item (keys(%$storehash)) {
5809: $items.= &escape($item).'='.
5810: &freeze_escape($$storehash{$item}).'&';
5811: }
5812: $items=~s/\&$//;
5813: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5814: $coursehome);
1.918 raeburn 5815: }
5816: if ($outcome eq 'unknown_cmd') {
5817: my $what;
5818: foreach my $cid (keys(%$storehash)) {
5819: $what .= &escape($cid).'=';
1.921 raeburn 5820: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5821: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5822: }
5823: $what =~ s/\:$/&/;
5824: }
5825: $what =~ s/\&$//;
5826: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5827: } else {
5828: return $outcome;
5829: }
1.353 www 5830: }
5831:
5832: sub courseiddump {
1.921 raeburn 5833: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5834: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5835: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 5836: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 5837: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5838: my $as_hash = 1;
5839: my %returnhash;
5840: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5841: my %libserv = &all_library();
5842: foreach my $tryserver (keys(%libserv)) {
5843: if ( ( $hostidflag == 1
5844: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5845: || (!defined($hostidflag)) ) {
5846:
1.918 raeburn 5847: if (($domfilter eq '') ||
5848: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 5849: my $rep;
5850: if (grep { $_ eq $tryserver } current_machine_ids()) {
5851: $rep = LONCAPA::Lond::dump_course_id_handler(
5852: join(":", (&host_domain($tryserver), $sincefilter,
5853: &escape($descfilter), &escape($instcodefilter),
5854: &escape($ownerfilter), &escape($coursefilter),
5855: &escape($typefilter), &escape($regexp_ok),
5856: $as_hash, &escape($selfenrollonly),
5857: &escape($catfilter), $showhidden, $caller,
5858: &escape($cloner), &escape($cc_clone), $cloneonly,
5859: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 5860: &escape($creationcontext),$domcloner,$hasuniquecode,
5861: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 5862: } else {
5863: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5864: $sincefilter.':'.&escape($descfilter).':'.
5865: &escape($instcodefilter).':'.&escape($ownerfilter).
5866: ':'.&escape($coursefilter).':'.&escape($typefilter).
5867: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5868: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5869: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5870: &escape($cc_clone).':'.$cloneonly.':'.
5871: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 5872: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5873: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 5874: }
5875:
1.918 raeburn 5876: my @pairs=split(/\&/,$rep);
5877: foreach my $item (@pairs) {
5878: my ($key,$value)=split(/\=/,$item,2);
5879: $key = &unescape($key);
5880: next if ($key =~ /^error: 2 /);
5881: my $result = &thaw_unescape($value);
5882: if (ref($result) eq 'HASH') {
5883: $returnhash{$key}=$result;
5884: } else {
1.921 raeburn 5885: my @responses = split(/:/,$value);
5886: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5887: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5888: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5889: }
1.1008 raeburn 5890: }
1.353 www 5891: }
5892: }
5893: }
5894: }
5895: return %returnhash;
5896: }
5897:
1.1055 raeburn 5898: sub courselastaccess {
5899: my ($cdom,$cnum,$hostidref) = @_;
5900: my %returnhash;
5901: if ($cdom && $cnum) {
5902: my $chome = &homeserver($cnum,$cdom);
5903: if ($chome ne 'no_host') {
5904: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5905: &extract_lastaccess(\%returnhash,$rep);
5906: }
5907: } else {
5908: if (!$cdom) { $cdom=''; }
5909: my %libserv = &all_library();
5910: foreach my $tryserver (keys(%libserv)) {
5911: if (ref($hostidref) eq 'ARRAY') {
5912: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5913: }
5914: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5915: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5916: &extract_lastaccess(\%returnhash,$rep);
5917: }
5918: }
5919: }
5920: return %returnhash;
5921: }
5922:
5923: sub extract_lastaccess {
5924: my ($returnhash,$rep) = @_;
5925: if (ref($returnhash) eq 'HASH') {
5926: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5927: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5928: $rep eq '') {
5929: my @pairs=split(/\&/,$rep);
5930: foreach my $item (@pairs) {
5931: my ($key,$value)=split(/\=/,$item,2);
5932: $key = &unescape($key);
5933: next if ($key =~ /^error: 2 /);
5934: $returnhash->{$key} = &thaw_unescape($value);
5935: }
5936: }
5937: }
5938: return;
5939: }
5940:
1.658 raeburn 5941: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5942:
5943: sub dcmailput {
1.685 raeburn 5944: my ($domain,$msgid,$message,$server)=@_;
1.1494 raeburn 5945: my $status = &critical(
1.740 www 5946: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5947: &escape($message),$server);
1.662 raeburn 5948: return $status;
5949: }
5950:
1.658 raeburn 5951: sub dcmaildump {
5952: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5953: my %returnhash=();
1.846 albertel 5954:
5955: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5956: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5957: &escape($enddate).':';
5958: my @esc_senders=map { &escape($_)} @$senders;
5959: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5960: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5961: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5962: if (($key) && ($value)) {
5963: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5964: }
5965: }
5966: }
5967: return %returnhash;
5968: }
1.662 raeburn 5969: # ---------------------------------------------------------- Domain roles
5970:
5971: sub get_domain_roles {
5972: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5973: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5974: $startdate = '.';
5975: }
1.1018 raeburn 5976: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5977: $enddate = '.';
5978: }
1.922 raeburn 5979: my $rolelist;
5980: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 5981: $rolelist = join('&',@{$roles});
1.922 raeburn 5982: }
1.662 raeburn 5983: my %personnel = ();
1.841 albertel 5984:
5985: my %servers = &get_servers($dom,'library');
5986: foreach my $tryserver (keys(%servers)) {
5987: %{$personnel{$tryserver}}=();
5988: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5989: &escape($startdate).':'.
5990: &escape($enddate).':'.
5991: &escape($rolelist), $tryserver))) {
5992: my ($key,$value) = split(/\=/,$line,2);
5993: if (($key) && ($value)) {
5994: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5995: }
5996: }
1.662 raeburn 5997: }
5998: return %personnel;
5999: }
1.658 raeburn 6000:
1.1332 raeburn 6001: sub get_active_domroles {
6002: my ($dom,$roles) = @_;
6003: return () unless (ref($roles) eq 'ARRAY');
6004: my $now = time;
6005: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
6006: my %domroles;
6007: foreach my $server (keys(%dompersonnel)) {
6008: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
6009: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
6010: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
6011: }
6012: }
6013: return %domroles;
6014: }
6015:
1.1057 www 6016: # ----------------------------------------------------------- Interval timing
1.149 www 6017:
1.1153 www 6018: {
6019: # Caches needed for speedup of navmaps
6020: # We don't want to cache this for very long at all (5 seconds at most)
6021: #
6022: # The user for whom we cache
6023: my $cachedkey='';
6024: # The cached times for this user
6025: my %cachedtimes=();
6026: # When this was last done
1.1282 raeburn 6027: my $cachedtime='';
1.1153 www 6028:
6029: sub load_all_first_access {
1.1308 raeburn 6030: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 6031: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 6032: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
6033: (!$ignorecache)) {
1.1154 raeburn 6034: return;
6035: }
6036: $cachedtime=time;
6037: $cachedkey=$uname.':'.$udom;
6038: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 6039: }
6040:
1.504 albertel 6041: sub get_first_access {
1.1308 raeburn 6042: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 6043: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 6044: if ($argsymb) { $symb=$argsymb; }
6045: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 6046: if ($argmap) { $map = $argmap; }
1.926 albertel 6047: if ($type eq 'course') {
6048: $res='course';
6049: } elsif ($type eq 'map') {
1.588 albertel 6050: $res=&symbread($map);
6051: } else {
6052: $res=$symb;
6053: }
1.1308 raeburn 6054: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 6055: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 6056: }
6057:
6058: sub set_first_access {
1.1162 raeburn 6059: my ($type,$interval)=@_;
1.790 albertel 6060: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 6061: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 6062: if ($type eq 'course') {
6063: $res='course';
6064: } elsif ($type eq 'map') {
1.588 albertel 6065: $res=&symbread($map);
6066: } else {
6067: $res=$symb;
6068: }
1.1153 www 6069: $cachedkey='';
1.1162 raeburn 6070: my $firstaccess=&get_first_access($type,$symb,$map);
1.1386 raeburn 6071: if ($firstaccess) {
6072: &logthis("First access time already set ($firstaccess) when attempting ".
1.1393 raeburn 6073: "to set new value (type: $type, extent: $res) for $uname:$udom ".
6074: "in $courseid");
1.1386 raeburn 6075: return 'already_set';
6076: } else {
1.1162 raeburn 6077: my $start = time;
6078: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
6079: $udom,$uname);
6080: if ($putres eq 'ok') {
6081: &put('timerinterval',{"$courseid\0$res"=>$interval},
6082: $udom,$uname);
6083: &appenv(
6084: {
6085: 'course.'.$courseid.'.firstaccess.'.$res => $start,
6086: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
6087: }
6088: );
1.1365 raeburn 6089: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
6090: $cachedtimes{"$courseid\0$res"} = $start;
6091: }
1.1386 raeburn 6092: } elsif ($putres ne 'refused') {
6093: &logthis("Result: $putres when attempting to set first access time ".
6094: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 6095: }
6096: return $putres;
1.505 albertel 6097: }
6098: return 'already_set';
1.504 albertel 6099: }
1.1153 www 6100: }
1.1282 raeburn 6101:
1.110 www 6102: # --------------------------------------------- Set Expire Date for Spreadsheet
6103:
6104: sub expirespread {
6105: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 6106: my $cid=$env{'request.course.id'};
1.110 www 6107: if ($cid) {
6108: my $now=time;
6109: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 6110: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
6111: $env{'course.'.$cid.'.num'}.
1.110 www 6112: ':nohist_expirationdates:'.
6113: &escape($key).'='.$now,
1.620 albertel 6114: $env{'course.'.$cid.'.home'})
1.110 www 6115: }
6116: return 'ok';
1.14 www 6117: }
6118:
1.109 www 6119: # ----------------------------------------------------- Devalidate Spreadsheets
6120:
6121: sub devalidate {
1.325 www 6122: my ($symb,$uname,$udom)=@_;
1.620 albertel 6123: my $cid=$env{'request.course.id'};
1.109 www 6124: if ($cid) {
1.391 matthew 6125: # delete the stored spreadsheets for
6126: # - the student level sheet of this user in course's homespace
6127: # - the assessment level sheet for this resource
6128: # for this user in user's homespace
1.553 albertel 6129: # - current conditional state info
1.325 www 6130: my $key=$uname.':'.$udom.':';
1.109 www 6131: my $status=
1.299 matthew 6132: &del('nohist_calculatedsheets',
1.391 matthew 6133: [$key.'studentcalc:'],
1.620 albertel 6134: $env{'course.'.$cid.'.domain'},
6135: $env{'course.'.$cid.'.num'})
1.133 albertel 6136: .' '.
6137: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 6138: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 6139: unless ($status eq 'ok ok') {
6140: &logthis('Could not devalidate spreadsheet '.
1.325 www 6141: $uname.' at '.$udom.' for '.
1.109 www 6142: $symb.': '.$status);
1.133 albertel 6143: }
1.553 albertel 6144: &delenv('user.state.'.$cid);
1.109 www 6145: }
6146: }
6147:
1.265 albertel 6148: sub get_scalar {
6149: my ($string,$end) = @_;
6150: my $value;
6151: if ($$string =~ s/^([^&]*?)($end)/$2/) {
6152: $value = $1;
6153: } elsif ($$string =~ s/^([^&]*?)&//) {
6154: $value = $1;
6155: }
6156: return &unescape($value);
6157: }
6158:
6159: sub array2str {
6160: my (@array) = @_;
6161: my $result=&arrayref2str(\@array);
6162: $result=~s/^__ARRAY_REF__//;
6163: $result=~s/__END_ARRAY_REF__$//;
6164: return $result;
6165: }
6166:
1.204 albertel 6167: sub arrayref2str {
6168: my ($arrayref) = @_;
1.265 albertel 6169: my $result='__ARRAY_REF__';
1.204 albertel 6170: foreach my $elem (@$arrayref) {
1.265 albertel 6171: if(ref($elem) eq 'ARRAY') {
6172: $result.=&arrayref2str($elem).'&';
6173: } elsif(ref($elem) eq 'HASH') {
6174: $result.=&hashref2str($elem).'&';
6175: } elsif(ref($elem)) {
6176: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 6177: } else {
6178: $result.=&escape($elem).'&';
6179: }
6180: }
6181: $result=~s/\&$//;
1.265 albertel 6182: $result .= '__END_ARRAY_REF__';
1.204 albertel 6183: return $result;
6184: }
6185:
1.168 albertel 6186: sub hash2str {
1.204 albertel 6187: my (%hash) = @_;
6188: my $result=&hashref2str(\%hash);
1.265 albertel 6189: $result=~s/^__HASH_REF__//;
6190: $result=~s/__END_HASH_REF__$//;
1.204 albertel 6191: return $result;
6192: }
6193:
6194: sub hashref2str {
6195: my ($hashref)=@_;
1.265 albertel 6196: my $result='__HASH_REF__';
1.800 albertel 6197: foreach my $key (sort(keys(%$hashref))) {
6198: if (ref($key) eq 'ARRAY') {
6199: $result.=&arrayref2str($key).'=';
6200: } elsif (ref($key) eq 'HASH') {
6201: $result.=&hashref2str($key).'=';
6202: } elsif (ref($key)) {
1.265 albertel 6203: $result.='=';
1.800 albertel 6204: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 6205: } else {
1.1132 raeburn 6206: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 6207: }
6208:
1.800 albertel 6209: if(ref($hashref->{$key}) eq 'ARRAY') {
6210: $result.=&arrayref2str($hashref->{$key}).'&';
6211: } elsif(ref($hashref->{$key}) eq 'HASH') {
6212: $result.=&hashref2str($hashref->{$key}).'&';
6213: } elsif(ref($hashref->{$key})) {
1.265 albertel 6214: $result.='&';
1.800 albertel 6215: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 6216: } else {
1.800 albertel 6217: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 6218: }
6219: }
1.168 albertel 6220: $result=~s/\&$//;
1.265 albertel 6221: $result .= '__END_HASH_REF__';
1.168 albertel 6222: return $result;
6223: }
6224:
6225: sub str2hash {
1.265 albertel 6226: my ($string)=@_;
6227: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
6228: return %$hash;
6229: }
6230:
6231: sub str2hashref {
1.168 albertel 6232: my ($string) = @_;
1.265 albertel 6233:
6234: my %hash;
6235:
6236: if($string !~ /^__HASH_REF__/) {
6237: if (! ($string eq '' || !defined($string))) {
6238: $hash{'error'}='Not hash reference';
6239: }
6240: return (\%hash, $string);
6241: }
6242:
6243: $string =~ s/^__HASH_REF__//;
6244:
6245: while($string !~ /^__END_HASH_REF__/) {
6246: #key
6247: my $key='';
6248: if($string =~ /^__HASH_REF__/) {
6249: ($key, $string)=&str2hashref($string);
6250: if(defined($key->{'error'})) {
6251: $hash{'error'}='Bad data';
6252: return (\%hash, $string);
6253: }
6254: } elsif($string =~ /^__ARRAY_REF__/) {
6255: ($key, $string)=&str2arrayref($string);
6256: if($key->[0] eq 'Array reference error') {
6257: $hash{'error'}='Bad data';
6258: return (\%hash, $string);
6259: }
6260: } else {
6261: $string =~ s/^(.*?)=//;
1.267 albertel 6262: $key=&unescape($1);
1.265 albertel 6263: }
6264: $string =~ s/^=//;
6265:
6266: #value
6267: my $value='';
6268: if($string =~ /^__HASH_REF__/) {
6269: ($value, $string)=&str2hashref($string);
6270: if(defined($value->{'error'})) {
6271: $hash{'error'}='Bad data';
6272: return (\%hash, $string);
6273: }
6274: } elsif($string =~ /^__ARRAY_REF__/) {
6275: ($value, $string)=&str2arrayref($string);
6276: if($value->[0] eq 'Array reference error') {
6277: $hash{'error'}='Bad data';
6278: return (\%hash, $string);
6279: }
6280: } else {
6281: $value=&get_scalar(\$string,'__END_HASH_REF__');
6282: }
6283: $string =~ s/^&//;
6284:
6285: $hash{$key}=$value;
1.204 albertel 6286: }
1.265 albertel 6287:
6288: $string =~ s/^__END_HASH_REF__//;
6289:
6290: return (\%hash, $string);
1.204 albertel 6291: }
6292:
6293: sub str2array {
1.265 albertel 6294: my ($string)=@_;
6295: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
6296: return @$array;
6297: }
6298:
6299: sub str2arrayref {
1.204 albertel 6300: my ($string) = @_;
1.265 albertel 6301: my @array;
6302:
6303: if($string !~ /^__ARRAY_REF__/) {
6304: if (! ($string eq '' || !defined($string))) {
6305: $array[0]='Array reference error';
6306: }
6307: return (\@array, $string);
6308: }
6309:
6310: $string =~ s/^__ARRAY_REF__//;
6311:
6312: while($string !~ /^__END_ARRAY_REF__/) {
6313: my $value='';
6314: if($string =~ /^__HASH_REF__/) {
6315: ($value, $string)=&str2hashref($string);
6316: if(defined($value->{'error'})) {
6317: $array[0] ='Array reference error';
6318: return (\@array, $string);
6319: }
6320: } elsif($string =~ /^__ARRAY_REF__/) {
6321: ($value, $string)=&str2arrayref($string);
6322: if($value->[0] eq 'Array reference error') {
6323: $array[0] ='Array reference error';
6324: return (\@array, $string);
6325: }
6326: } else {
6327: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6328: }
6329: $string =~ s/^&//;
6330:
6331: push(@array, $value);
1.191 harris41 6332: }
1.265 albertel 6333:
6334: $string =~ s/^__END_ARRAY_REF__//;
6335:
6336: return (\@array, $string);
1.168 albertel 6337: }
6338:
1.167 albertel 6339: # -------------------------------------------------------------------Temp Store
6340:
1.168 albertel 6341: sub tmpreset {
6342: my ($symb,$namespace,$domain,$stuname) = @_;
6343: if (!$symb) {
6344: $symb=&symbread();
1.620 albertel 6345: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6346: }
6347: $symb=escape($symb);
6348:
1.620 albertel 6349: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 6350: $namespace=~s/\//\_/g;
6351: $namespace=~s/\W//g;
6352:
1.620 albertel 6353: if (!$domain) { $domain=$env{'user.domain'}; }
6354: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6355: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6356: $stuname=&get_requestor_ip();
1.591 albertel 6357: }
1.1117 foxr 6358: my $path=LONCAPA::tempdir();
1.168 albertel 6359: my %hash;
6360: if (tie(%hash,'GDBM_File',
6361: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6362: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 6363: foreach my $key (keys(%hash)) {
1.180 albertel 6364: if ($key=~ /:$symb/) {
1.168 albertel 6365: delete($hash{$key});
6366: }
6367: }
6368: }
6369: }
6370:
1.167 albertel 6371: sub tmpstore {
1.168 albertel 6372: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6373:
6374: if (!$symb) {
6375: $symb=&symbread();
1.620 albertel 6376: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6377: }
6378: $symb=escape($symb);
6379:
6380: if (!$namespace) {
6381: # I don't think we would ever want to store this for a course.
6382: # it seems this will only be used if we don't have a course.
1.620 albertel 6383: #$namespace=$env{'request.course.id'};
1.168 albertel 6384: #if (!$namespace) {
1.620 albertel 6385: $namespace=$env{'request.state'};
1.168 albertel 6386: #}
6387: }
6388: $namespace=~s/\//\_/g;
6389: $namespace=~s/\W//g;
1.620 albertel 6390: if (!$domain) { $domain=$env{'user.domain'}; }
6391: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6392: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6393: $stuname=&get_requestor_ip();
1.591 albertel 6394: }
1.168 albertel 6395: my $now=time;
6396: my %hash;
1.1117 foxr 6397: my $path=LONCAPA::tempdir();
1.168 albertel 6398: if (tie(%hash,'GDBM_File',
6399: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6400: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6401: $hash{"version:$symb"}++;
6402: my $version=$hash{"version:$symb"};
6403: my $allkeys='';
6404: foreach my $key (keys(%$storehash)) {
6405: $allkeys.=$key.':';
1.591 albertel 6406: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6407: }
6408: $hash{"$version:$symb:timestamp"}=$now;
6409: $allkeys.='timestamp';
6410: $hash{"$version:keys:$symb"}=$allkeys;
6411: if (untie(%hash)) {
6412: return 'ok';
6413: } else {
6414: return "error:$!";
6415: }
6416: } else {
6417: return "error:$!";
6418: }
6419: }
1.167 albertel 6420:
1.168 albertel 6421: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6422:
1.168 albertel 6423: sub tmprestore {
6424: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6425:
1.168 albertel 6426: if (!$symb) {
6427: $symb=&symbread();
1.620 albertel 6428: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6429: }
6430: $symb=escape($symb);
6431:
1.620 albertel 6432: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6433:
1.620 albertel 6434: if (!$domain) { $domain=$env{'user.domain'}; }
6435: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6436: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6437: $stuname=&get_requestor_ip();
1.591 albertel 6438: }
1.168 albertel 6439: my %returnhash;
6440: $namespace=~s/\//\_/g;
6441: $namespace=~s/\W//g;
6442: my %hash;
1.1117 foxr 6443: my $path=LONCAPA::tempdir();
1.168 albertel 6444: if (tie(%hash,'GDBM_File',
6445: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6446: &GDBM_READER(),0640)) {
1.168 albertel 6447: my $version=$hash{"version:$symb"};
6448: $returnhash{'version'}=$version;
6449: my $scope;
6450: for ($scope=1;$scope<=$version;$scope++) {
6451: my $vkeys=$hash{"$scope:keys:$symb"};
6452: my @keys=split(/:/,$vkeys);
6453: my $key;
6454: $returnhash{"$scope:keys"}=$vkeys;
6455: foreach $key (@keys) {
1.591 albertel 6456: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6457: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6458: }
6459: }
1.168 albertel 6460: if (!(untie(%hash))) {
6461: return "error:$!";
6462: }
6463: } else {
6464: return "error:$!";
6465: }
6466: return %returnhash;
1.167 albertel 6467: }
6468:
1.9 www 6469: # ----------------------------------------------------------------------- Store
6470:
6471: sub store {
1.1269 raeburn 6472: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6473: my $home='';
6474:
1.168 albertel 6475: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6476:
1.213 www 6477: $symb=&symbclean($symb);
1.122 albertel 6478: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6479:
1.620 albertel 6480: if (!$domain) { $domain=$env{'user.domain'}; }
6481: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6482:
6483: &devalidate($symb,$stuname,$domain);
1.109 www 6484:
6485: $symb=escape($symb);
1.187 www 6486: if (!$namespace) {
1.620 albertel 6487: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6488: return '';
6489: }
6490: }
1.620 albertel 6491: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6492:
1.1434 raeburn 6493: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6494: $$storehash{'host'}=$perlvar{'lonHostID'};
6495:
1.12 www 6496: my $namevalue='';
1.800 albertel 6497: foreach my $key (keys(%$storehash)) {
6498: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6499: }
1.12 www 6500: $namevalue=~s/\&$//;
1.187 www 6501: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 6502: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6503: }
6504:
1.47 www 6505: # -------------------------------------------------------------- Critical Store
6506:
6507: sub cstore {
1.1269 raeburn 6508: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6509: my $home='';
6510:
1.168 albertel 6511: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6512:
1.213 www 6513: $symb=&symbclean($symb);
1.122 albertel 6514: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6515:
1.620 albertel 6516: if (!$domain) { $domain=$env{'user.domain'}; }
6517: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6518:
6519: &devalidate($symb,$stuname,$domain);
1.109 www 6520:
6521: $symb=escape($symb);
1.187 www 6522: if (!$namespace) {
1.620 albertel 6523: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6524: return '';
6525: }
6526: }
1.620 albertel 6527: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6528:
1.1434 raeburn 6529: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6530: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6531:
1.47 www 6532: my $namevalue='';
1.800 albertel 6533: foreach my $key (keys(%$storehash)) {
6534: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6535: }
1.47 www 6536: $namevalue=~s/\&$//;
1.187 www 6537: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6538: return critical
1.1269 raeburn 6539: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6540: }
6541:
1.9 www 6542: # --------------------------------------------------------------------- Restore
6543:
6544: sub restore {
1.124 www 6545: my ($symb,$namespace,$domain,$stuname) = @_;
6546: my $home='';
6547:
1.168 albertel 6548: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6549:
1.122 albertel 6550: if (!$symb) {
1.1224 raeburn 6551: return if ($namespace eq 'courserequests');
6552: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6553: } else {
1.1224 raeburn 6554: unless ($namespace eq 'courserequests') {
6555: $symb=&escape(&symbclean($symb));
6556: }
1.122 albertel 6557: }
1.188 www 6558: if (!$namespace) {
1.620 albertel 6559: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6560: return '';
6561: }
6562: }
1.620 albertel 6563: if (!$domain) { $domain=$env{'user.domain'}; }
6564: if (!$stuname) { $stuname=$env{'user.name'}; }
6565: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6566: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6567:
1.12 www 6568: my %returnhash=();
1.800 albertel 6569: foreach my $line (split(/\&/,$answer)) {
6570: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6571: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6572: }
1.75 www 6573: my $version;
6574: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6575: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6576: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6577: }
1.75 www 6578: }
1.13 www 6579: return %returnhash;
1.34 www 6580: }
6581:
6582: # ---------------------------------------------------------- Course Description
1.1118 foxr 6583: #
6584: #
1.34 www 6585:
6586: sub coursedescription {
1.731 albertel 6587: my ($courseid,$args)=@_;
1.34 www 6588: $courseid=~s/^\///;
1.49 www 6589: $courseid=~s/\_/\//g;
1.34 www 6590: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6591: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6592: my $normalid=$cdomain.'_'.$cnum;
6593: # need to always cache even if we get errors otherwise we keep
6594: # trying and trying and trying to get the course description.
6595: my %envhash=();
6596: my %returnhash=();
1.731 albertel 6597:
6598: my $expiretime=600;
6599: if ($env{'request.course.id'} eq $normalid) {
6600: $expiretime=120;
6601: }
6602:
6603: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6604: if (!$args->{'freshen_cache'}
6605: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6606: foreach my $key (keys(%env)) {
6607: next if ($key !~ /^\Q$prefix\E(.*)/);
6608: my ($setting) = $1;
6609: $returnhash{$setting} = $env{$key};
6610: }
6611: return %returnhash;
6612: }
6613:
1.1118 foxr 6614: # get the data again
6615:
1.731 albertel 6616: if (!$args->{'one_time'}) {
6617: $envhash{'course.'.$normalid.'.last_cache'}=time;
6618: }
1.811 albertel 6619:
1.34 www 6620: if ($chome ne 'no_host') {
1.302 albertel 6621: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6622: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6623: my $username = $env{'user.name'}; # Defult username
6624: if(defined $args->{'user'}) {
6625: $username = $args->{'user'};
6626: }
1.129 albertel 6627: $returnhash{'home'}= $chome;
6628: $returnhash{'domain'} = $cdomain;
6629: $returnhash{'num'} = $cnum;
1.741 raeburn 6630: if (!defined($returnhash{'type'})) {
6631: $returnhash{'type'} = 'Course';
6632: }
1.130 albertel 6633: while (my ($name,$value) = each %returnhash) {
1.53 www 6634: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6635: }
1.270 www 6636: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6637: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6638: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6639: $envhash{'course.'.$normalid.'.home'}=$chome;
6640: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6641: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6642: }
6643: }
1.731 albertel 6644: if (!$args->{'one_time'}) {
1.949 raeburn 6645: &appenv(\%envhash);
1.731 albertel 6646: }
1.302 albertel 6647: return %returnhash;
1.461 www 6648: }
6649:
1.1080 raeburn 6650: sub update_released_required {
6651: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6652: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6653: $cid = $env{'request.course.id'};
6654: $cdom = $env{'course.'.$cid.'.domain'};
6655: $cnum = $env{'course.'.$cid.'.num'};
6656: $chome = $env{'course.'.$cid.'.home'};
6657: }
6658: if ($needsrelease) {
6659: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6660: my $needsupdate;
6661: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6662: $needsupdate = 1;
6663: } else {
6664: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6665: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6666: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6667: $needsupdate = 1;
6668: }
6669: }
6670: if ($needsupdate) {
6671: my %needshash = (
6672: 'internal.releaserequired' => $needsrelease,
6673: );
6674: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6675: if ($putresult eq 'ok') {
6676: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6677: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6678: if (ref($crsinfo{$cid}) eq 'HASH') {
6679: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6680: &courseidput($cdom,\%crsinfo,$chome,'notime');
6681: }
6682: }
6683: }
6684: }
6685: return;
6686: }
6687:
1.461 www 6688: # -------------------------------------------------See if a user is privileged
6689:
6690: sub privileged {
1.1219 raeburn 6691: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6692: my $now = time;
1.1219 raeburn 6693: my $roles;
6694: if (ref($possroles) eq 'ARRAY') {
6695: $roles = $possroles;
6696: } else {
6697: $roles = ['dc','su'];
6698: }
6699: if (ref($possdomains) eq 'ARRAY') {
6700: my %privileged = &privileged_by_domain($possdomains,$roles);
6701: foreach my $dom (@{$possdomains}) {
6702: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6703: (ref($privileged{$dom}) eq 'HASH')) {
6704: foreach my $role (@{$roles}) {
6705: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6706: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6707: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6708: return 1 unless (($end && $end < $now) ||
6709: ($start && $start > $now));
6710: }
6711: }
6712: }
6713: }
6714: }
6715: } else {
6716: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6717: my $now = time;
1.1170 droeschl 6718:
1.1275 musolffc 6719: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6720: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 6721: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 6722: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 6723: or ($tstart && $tstart > $now);
1.1170 droeschl 6724: }
1.1219 raeburn 6725: }
6726: }
6727: return 0;
6728: }
1.1170 droeschl 6729:
1.1219 raeburn 6730: sub privileged_by_domain {
6731: my ($domains,$roles) = @_;
6732: my %privileged = ();
6733: my $cachetime = 60*60*24;
6734: my $now = time;
6735: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6736: return %privileged;
6737: }
6738: foreach my $dom (@{$domains}) {
6739: next if (ref($privileged{$dom}) eq 'HASH');
6740: my $needroles;
6741: foreach my $role (@{$roles}) {
6742: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6743: if (defined($cached)) {
6744: if (ref($result) eq 'HASH') {
6745: $privileged{$dom}{$role} = $result;
6746: }
6747: } else {
6748: $needroles = 1;
6749: }
6750: }
6751: if ($needroles) {
6752: my %dompersonnel = &get_domain_roles($dom,$roles);
6753: $privileged{$dom} = {};
6754: foreach my $server (keys(%dompersonnel)) {
6755: if (ref($dompersonnel{$server}) eq 'HASH') {
6756: foreach my $item (keys(%{$dompersonnel{$server}})) {
6757: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6758: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6759: next if ($end && $end < $now);
6760: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6761: $dompersonnel{$server}{$item};
6762: }
6763: }
6764: }
6765: if (ref($privileged{$dom}) eq 'HASH') {
6766: foreach my $role (@{$roles}) {
6767: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6768: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6769: } else {
6770: my %hash = ();
6771: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6772: }
6773: }
6774: }
6775: }
6776: }
6777: return %privileged;
1.9 www 6778: }
1.1 albertel 6779:
1.103 harris41 6780: # -------------------------------------------------------- Get user privileges
1.11 www 6781:
6782: sub rolesinit {
1.1169 droeschl 6783: my ($domain, $username) = @_;
6784: my %userroles = ('user.login.time' => time);
6785: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6786:
6787: # firstaccess and timerinterval are related to timed maps/resources.
6788: # also, blocking can be triggered by an activating timer
6789: # it's saved in the user's %env.
6790: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6791: my %timerinterval = &dump('timerinterval', $domain, $username);
6792: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6793: %timerintchk, %timerintenv);
6794:
1.1162 raeburn 6795: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6796: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6797: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6798: }
1.1169 droeschl 6799:
1.1162 raeburn 6800: foreach my $key (keys(%timerinterval)) {
6801: my ($cid,$rest) = split(/\0/,$key);
6802: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6803: }
1.1169 droeschl 6804:
1.11 www 6805: my %allroles=();
1.1162 raeburn 6806: my %allgroups=();
1.11 www 6807:
1.1274 raeburn 6808: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6809: my $role = $rolesdump{$area};
6810: $area =~ s/\_\w\w$//;
6811:
6812: my ($trole, $tend, $tstart, $group_privs);
6813:
6814: if ($role =~ /^cr/) {
6815: # Custom role, defined by a user
6816: # e.g., user.role.cr/msu/smith/mynewrole
6817: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6818: $trole = $1;
6819: ($tend, $tstart) = split('_', $2);
6820: } else {
6821: $trole = $role;
6822: }
6823: } elsif ($role =~ m|^gr/|) {
6824: # Role of member in a group, defined within a course/community
6825: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6826: ($trole, $tend, $tstart) = split(/_/, $role);
6827: next if $tstart eq '-1';
6828: ($trole, $group_privs) = split(/\//, $trole);
6829: $group_privs = &unescape($group_privs);
6830: } else {
6831: # Just a normal role, defined in roles.tab
6832: ($trole, $tend, $tstart) = split(/_/,$role);
6833: }
6834:
6835: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6836: $username);
6837: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6838:
6839: # role expired or not available yet?
6840: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6841: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6842:
6843: next if $area eq '' or $trole eq '';
6844:
6845: my $spec = "$trole.$area";
6846: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6847:
6848: if ($trole =~ /^cr\//) {
6849: # Custom role, defined by a user
6850: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6851: } elsif ($trole eq 'gr') {
6852: # Role of a member in a group, defined within a course/community
6853: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6854: next;
6855: } else {
6856: # Normal role, defined in roles.tab
6857: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6858: }
6859:
6860: my $cid = $tdomain.'_'.$trest;
6861: unless ($firstaccchk{$cid}) {
6862: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6863: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6864: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6865: $coursetimerstarts{$cid}{$item};
6866: }
6867: }
6868: $firstaccchk{$cid} = 1;
6869: }
6870: unless ($timerintchk{$cid}) {
6871: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6872: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6873: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6874: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6875: }
1.12 www 6876: }
1.1169 droeschl 6877: $timerintchk{$cid} = 1;
1.191 harris41 6878: }
1.11 www 6879: }
1.1169 droeschl 6880:
1.1341 raeburn 6881: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6882: \%allroles, \%allgroups);
1.1169 droeschl 6883: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 6884: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6885:
1.1162 raeburn 6886: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6887: }
6888:
1.567 raeburn 6889: sub set_arearole {
1.1215 raeburn 6890: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6891: unless ($nolog) {
1.567 raeburn 6892: # log the associated role with the area
1.1215 raeburn 6893: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6894: }
1.743 albertel 6895: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6896: }
6897:
6898: sub custom_roleprivs {
6899: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6900: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 6901: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6902: if (&hostname($homsvr) ne '') {
1.567 raeburn 6903: my ($rdummy,$roledef)=
6904: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6905: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6906: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6907: if (defined($syspriv)) {
1.1043 raeburn 6908: if ($trest =~ /^$match_community$/) {
6909: $syspriv =~ s/bre\&S//;
6910: }
1.567 raeburn 6911: $$allroles{'cm./'}.=':'.$syspriv;
6912: $$allroles{$spec.'./'}.=':'.$syspriv;
6913: }
6914: if ($tdomain ne '') {
6915: if (defined($dompriv)) {
6916: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6917: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6918: }
6919: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 6920: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6921: my $rolename = $1;
6922: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6923: }
1.567 raeburn 6924: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6925: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6926: }
6927: }
6928: }
6929: }
6930: }
6931:
1.1332 raeburn 6932: sub course_adhocrole_privs {
6933: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6934: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6935: if ($overrides{"internal.adhocpriv.$rolename"}) {
6936: my (%currprivs,%storeprivs);
6937: foreach my $item (split(/:/,$coursepriv)) {
6938: my ($priv,$restrict) = split(/\&/,$item);
6939: $currprivs{$priv} = $restrict;
6940: }
6941: my (%possadd,%possremove,%full);
6942: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6943: my ($priv,$restrict)=split(/\&/,$item);
6944: $full{$priv} = $restrict;
6945: }
6946: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1490 raeburn 6947: next if ($item eq '');
6948: my ($rule,$rest) = split(/=/,$item);
6949: next unless (($rule eq 'off') || ($rule eq 'on'));
6950: foreach my $priv (split(/:/,$rest)) {
6951: if ($priv ne '') {
6952: if ($rule eq 'off') {
6953: $possremove{$priv} = 1;
6954: } else {
6955: $possadd{$priv} = 1;
6956: }
6957: }
6958: }
6959: }
6960: foreach my $priv (sort(keys(%full))) {
6961: if (exists($currprivs{$priv})) {
6962: unless (exists($possremove{$priv})) {
6963: $storeprivs{$priv} = $currprivs{$priv};
6964: }
6965: } elsif (exists($possadd{$priv})) {
6966: $storeprivs{$priv} = $full{$priv};
6967: }
6968: }
6969: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6970: }
6971: return $coursepriv;
1.1332 raeburn 6972: }
6973:
1.678 raeburn 6974: sub group_roleprivs {
6975: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6976: my $access = 1;
6977: my $now = time;
6978: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6979: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6980: if ($access) {
1.811 albertel 6981: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6982: $$allgroups{$course}{$group} .=':'.$group_privs;
6983: }
6984: }
1.567 raeburn 6985:
6986: sub standard_roleprivs {
6987: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6988: if (defined($pr{$trole.':s'})) {
6989: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6990: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6991: }
6992: if ($tdomain ne '') {
6993: if (defined($pr{$trole.':d'})) {
6994: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6995: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6996: }
6997: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6998: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6999: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
7000: }
7001: }
7002: }
7003:
7004: sub set_userprivs {
1.1064 raeburn 7005: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 7006: my $author=0;
7007: my $adv=0;
1.1341 raeburn 7008: my $rar=0;
1.678 raeburn 7009: my %grouproles = ();
7010: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 7011: my @groupkeys;
1.1000 raeburn 7012: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 7013: push(@groupkeys,$role);
7014: }
7015: if (ref($groups_roles) eq 'HASH') {
7016: foreach my $key (keys(%{$groups_roles})) {
7017: unless (grep(/^\Q$key\E$/,@groupkeys)) {
7018: push(@groupkeys,$key);
7019: }
7020: }
7021: }
7022: if (@groupkeys > 0) {
7023: foreach my $role (@groupkeys) {
7024: my ($trole,$area,$sec,$extendedarea);
7025: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
7026: $trole = $1;
7027: $area = $2;
7028: $sec = $3;
7029: $extendedarea = $area.$sec;
7030: if (exists($$allgroups{$area})) {
7031: foreach my $group (keys(%{$$allgroups{$area}})) {
7032: my $spec = $trole.'.'.$extendedarea;
7033: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 7034: $$allgroups{$area}{$group};
1.1064 raeburn 7035: }
1.678 raeburn 7036: }
7037: }
7038: }
7039: }
7040: }
1.800 albertel 7041: foreach my $group (keys(%grouproles)) {
7042: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 7043: }
1.800 albertel 7044: foreach my $role (keys(%{$allroles})) {
7045: my %thesepriv;
1.941 raeburn 7046: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 7047: foreach my $item (split(/:/,$$allroles{$role})) {
7048: if ($item ne '') {
7049: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 7050: if ($restrictions eq '') {
7051: $thesepriv{$privilege}='F';
7052: } elsif ($thesepriv{$privilege} ne 'F') {
7053: $thesepriv{$privilege}.=$restrictions;
7054: }
7055: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 7056: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 7057: }
7058: }
7059: my $thesestr='';
1.1104 raeburn 7060: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 7061: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
7062: }
7063: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 7064: }
1.1341 raeburn 7065: return ($author,$adv,$rar);
1.567 raeburn 7066: }
7067:
1.994 raeburn 7068: sub role_status {
1.1104 raeburn 7069: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 7070: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 7071: my ($one,$two) = split(m{\./},$rolekey,2);
7072: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 7073: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 7074: $$where = '/'.$two;
1.994 raeburn 7075: $$trolecode=$$role.'.'.$$where;
7076: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
7077: $$tstatus='is';
1.1104 raeburn 7078: if ($$tstart && $$tstart>$update) {
1.994 raeburn 7079: $$tstatus='future';
1.1034 raeburn 7080: if ($$tstart<$now) {
7081: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 7082: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 7083: my (%allroles,%allgroups,$group_privs,
7084: %groups_roles,@rolecodes);
1.1002 raeburn 7085: my %userroles = (
7086: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
7087: );
1.1064 raeburn 7088: @rolecodes = ('cm');
1.1002 raeburn 7089: my $spec=$$role.'.'.$$where;
7090: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
7091: if ($$role =~ /^cr\//) {
7092: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 7093: push(@rolecodes,'cr');
1.1002 raeburn 7094: } elsif ($$role eq 'gr') {
1.1064 raeburn 7095: push(@rolecodes,$$role);
1.1002 raeburn 7096: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
7097: $env{'user.name'});
1.1064 raeburn 7098: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 7099: (undef,my $group_privs) = split(/\//,$trole);
7100: $group_privs = &unescape($group_privs);
7101: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 7102: 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 7103: &get_groups_roles($tdomain,$trest,
7104: \%course_roles,\@rolecodes,
7105: \%groups_roles);
1.1002 raeburn 7106: } else {
1.1064 raeburn 7107: push(@rolecodes,$$role);
1.1002 raeburn 7108: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
7109: }
1.1341 raeburn 7110: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
7111: \%groups_roles);
1.1064 raeburn 7112: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 7113: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 7114: }
7115: }
1.1034 raeburn 7116: $$tstatus = 'is';
1.1002 raeburn 7117: }
1.994 raeburn 7118: }
7119: if ($$tend) {
1.1104 raeburn 7120: if ($$tend<$update) {
1.994 raeburn 7121: $$tstatus='expired';
7122: } elsif ($$tend<$now) {
7123: $$tstatus='will_not';
7124: }
7125: }
7126: }
7127: }
7128: }
7129:
1.1104 raeburn 7130: sub get_groups_roles {
7131: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
7132: return unless((ref($cdom_courseroles) eq 'HASH') &&
7133: (ref($rolecodes) eq 'ARRAY') &&
7134: (ref($groups_roles) eq 'HASH'));
7135: if (keys(%{$cdom_courseroles}) > 0) {
7136: my ($cnum) = ($rest =~ /^($match_courseid)/);
7137: if ($cdom ne '' && $cnum ne '') {
7138: foreach my $key (keys(%{$cdom_courseroles})) {
7139: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
7140: my $crsrole = $1;
7141: my $crssec = $2;
7142: if ($crsrole =~ /^cr/) {
7143: unless (grep(/^cr$/,@{$rolecodes})) {
7144: push(@{$rolecodes},'cr');
7145: }
7146: } else {
7147: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
7148: push(@{$rolecodes},$crsrole);
7149: }
7150: }
7151: my $rolekey = "$crsrole./$cdom/$cnum";
7152: if ($crssec ne '') {
7153: $rolekey .= "/$crssec";
7154: }
7155: $rolekey .= './';
7156: $groups_roles->{$rolekey} = $rolecodes;
7157: }
7158: }
7159: }
7160: }
7161: return;
7162: }
7163:
7164: sub delete_env_groupprivs {
7165: my ($where,$courseroles,$possroles) = @_;
7166: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
7167: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
7168: unless (ref($courseroles->{$udom}) eq 'HASH') {
7169: %{$courseroles->{$udom}} =
7170: &get_my_roles('','','userroles',['active'],
7171: $possroles,[$udom],1);
7172: }
7173: if (ref($courseroles->{$udom}) eq 'HASH') {
7174: foreach my $item (keys(%{$courseroles->{$udom}})) {
7175: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
7176: my $area = '/'.$cdom.'/'.$cnum;
7177: my $privkey = "user.priv.$crsrole.$area";
7178: if ($crssec ne '') {
7179: $privkey .= '/'.$crssec;
7180: }
7181: $privkey .= ".$area/$group";
7182: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
7183: }
7184: }
7185: return;
7186: }
7187:
1.994 raeburn 7188: sub check_adhoc_privs {
1.1329 raeburn 7189: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 7190: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 7191: if ($sec) {
7192: $cckey .= '/'.$sec;
7193: }
1.1185 raeburn 7194: my $setprivs;
1.994 raeburn 7195: if ($env{$cckey}) {
7196: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 7197: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 7198: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 7199: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7200: $setprivs = 1;
1.994 raeburn 7201: }
7202: } else {
1.1330 raeburn 7203: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7204: $setprivs = 1;
1.994 raeburn 7205: }
1.1185 raeburn 7206: return $setprivs;
1.994 raeburn 7207: }
7208:
7209: sub set_adhoc_privileges {
1.1326 raeburn 7210: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 7211: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 7212: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 7213: if ($sec ne '') {
7214: $area .= '/'.$sec;
7215: }
1.994 raeburn 7216: my $spec = $role.'.'.$area;
7217: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 7218: $env{'user.name'},1);
1.1326 raeburn 7219: my %rolehash = ();
1.1332 raeburn 7220: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
7221: my $rolename = $1;
1.1326 raeburn 7222: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 7223: my %domdef = &get_domain_defaults($dcdom);
7224: if (ref($domdef{'adhocroles'}) eq 'HASH') {
7225: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
7226: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
7227: }
7228: }
1.1326 raeburn 7229: } else {
7230: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
7231: }
1.1341 raeburn 7232: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 7233: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 7234: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402 raeburn 7235: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
7236: ($caller eq 'tiny')) {
1.1088 raeburn 7237: &appenv( {'request.role' => $spec,
7238: 'request.role.domain' => $dcdom,
1.1332 raeburn 7239: 'request.course.sec' => $sec,
1.1088 raeburn 7240: }
7241: );
7242: my $tadv=0;
7243: if (&allowed('adv') eq 'F') { $tadv=1; }
7244: &appenv({'request.role.adv' => $tadv});
7245: }
1.994 raeburn 7246: }
7247:
1.12 www 7248: # --------------------------------------------------------------- get interface
7249:
7250: sub get {
1.131 albertel 7251: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7252: my $items='';
1.800 albertel 7253: foreach my $item (@$storearr) {
7254: $items.=&escape($item).'&';
1.191 harris41 7255: }
1.12 www 7256: $items=~s/\&$//;
1.620 albertel 7257: if (!$udomain) { $udomain=$env{'user.domain'}; }
7258: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 7259: my $uhome=&homeserver($uname,$udomain);
7260:
1.133 albertel 7261: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7262: my @pairs=split(/\&/,$rep);
1.273 albertel 7263: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
7264: return @pairs;
7265: }
1.15 www 7266: my %returnhash=();
1.42 www 7267: my $i=0;
1.800 albertel 7268: foreach my $item (@$storearr) {
7269: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7270: $i++;
1.191 harris41 7271: }
1.15 www 7272: return %returnhash;
1.27 www 7273: }
7274:
7275: # --------------------------------------------------------------- del interface
7276:
7277: sub del {
1.133 albertel 7278: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 7279: my $items='';
1.800 albertel 7280: foreach my $item (@$storearr) {
7281: $items.=&escape($item).'&';
1.191 harris41 7282: }
1.984 neumanie 7283:
1.27 www 7284: $items=~s/\&$//;
1.620 albertel 7285: if (!$udomain) { $udomain=$env{'user.domain'}; }
7286: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7287: my $uhome=&homeserver($uname,$udomain);
7288: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7289: }
7290:
7291: # -------------------------------------------------------------- dump interface
7292:
1.1180 droeschl 7293: sub unserialize {
7294: my ($rep, $escapedkeys) = @_;
7295:
7296: return {} if $rep =~ /^error/;
7297:
7298: my %returnhash=();
1.1252 raeburn 7299: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 7300: my ($key, $value) = split(/=/, $item, 2);
7301: $key = unescape($key) unless $escapedkeys;
7302: next if $key =~ /^error: 2 /;
1.1252 raeburn 7303: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 7304: }
7305: #return %returnhash;
7306: return \%returnhash;
7307: }
7308:
7309: # see Lond::dump_with_regexp
7310: # if $escapedkeys hash keys won't get unescaped.
1.15 www 7311: sub dump {
1.1462 raeburn 7312: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755 albertel 7313: if (!$udomain) { $udomain=$env{'user.domain'}; }
7314: if (!$uname) { $uname=$env{'user.name'}; }
7315: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 7316:
1.1266 raeburn 7317: if ($regexp) {
7318: $regexp=&escape($regexp);
7319: } else {
7320: $regexp='.';
7321: }
1.1180 droeschl 7322: if (grep { $_ eq $uhome } current_machine_ids()) {
7323: # user is hosted on this machine
1.1266 raeburn 7324: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 7325: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 7326: return %{unserialize($reply, $escapedkeys)};
7327: }
1.1462 raeburn 7328: my $rep;
7329: if ($encrypt) {
7330: $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.1463 raeburn 7331: } else {
1.1462 raeburn 7332: $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7333: }
1.755 albertel 7334: my @pairs=split(/\&/,$rep);
7335: my %returnhash=();
1.1098 foxr 7336: if (!($rep =~ /^error/ )) {
7337: foreach my $item (@pairs) {
7338: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 7339: $key = unescape($key) unless $escapedkeys;
7340: #$key = &unescape($key);
1.1098 foxr 7341: next if ($key =~ /^error: 2 /);
7342: $returnhash{$key}=&thaw_unescape($value);
7343: }
1.755 albertel 7344: }
7345: return %returnhash;
1.407 www 7346: }
7347:
1.1098 foxr 7348:
1.717 albertel 7349: # --------------------------------------------------------- dumpstore interface
7350:
7351: sub dumpstore {
7352: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 7353: # same as dump but keys must be escaped. They may contain colon separated
7354: # lists of values that may themself contain colons (e.g. symbs).
7355: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 7356: }
7357:
1.407 www 7358: # -------------------------------------------------------------- keys interface
7359:
7360: sub getkeys {
7361: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 7362: if (!$udomain) { $udomain=$env{'user.domain'}; }
7363: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 7364: my $uhome=&homeserver($uname,$udomain);
7365: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7366: my @keyarray=();
1.800 albertel 7367: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 7368: next if ($key =~ /^error: 2 /);
1.800 albertel 7369: push(@keyarray,&unescape($key));
1.407 www 7370: }
7371: return @keyarray;
1.318 matthew 7372: }
7373:
1.319 matthew 7374: # --------------------------------------------------------------- currentdump
7375: sub currentdump {
1.328 matthew 7376: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 7377: $courseid = $env{'request.course.id'} if (! defined($courseid));
7378: $sdom = $env{'user.domain'} if (! defined($sdom));
7379: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 7380: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 7381: my $rep;
7382:
7383: if (grep { $_ eq $uhome } current_machine_ids()) {
7384: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7385: $courseid)));
7386: } else {
7387: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7388: }
7389:
1.318 matthew 7390: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7391: #
1.318 matthew 7392: my %returnhash=();
1.319 matthew 7393: #
1.1343 raeburn 7394: if ($rep eq 'unknown_cmd') {
1.319 matthew 7395: # an old lond will not know currentdump
7396: # Do a dump and make it look like a currentdump
1.822 albertel 7397: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7398: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7399: my %hash = @tmp;
7400: @tmp=();
1.424 matthew 7401: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7402: } else {
7403: my @pairs=split(/\&/,$rep);
1.800 albertel 7404: foreach my $pair (@pairs) {
7405: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7406: my ($symb,$param) = split(/:/,$key);
7407: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7408: &thaw_unescape($value);
1.319 matthew 7409: }
1.191 harris41 7410: }
1.12 www 7411: return %returnhash;
1.424 matthew 7412: }
7413:
7414: sub convert_dump_to_currentdump{
7415: my %hash = %{shift()};
7416: my %returnhash;
7417: # Code ripped from lond, essentially. The only difference
7418: # here is the unescaping done by lonnet::dump(). Conceivably
7419: # we might run in to problems with parameter names =~ /^v\./
7420: while (my ($key,$value) = each(%hash)) {
7421: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7422: $symb = &unescape($symb);
7423: $param = &unescape($param);
1.424 matthew 7424: next if ($v eq 'version' || $symb eq 'keys');
7425: next if (exists($returnhash{$symb}) &&
7426: exists($returnhash{$symb}->{$param}) &&
7427: $returnhash{$symb}->{'v.'.$param} > $v);
7428: $returnhash{$symb}->{$param}=$value;
7429: $returnhash{$symb}->{'v.'.$param}=$v;
7430: }
7431: #
7432: # Remove all of the keys in the hashes which keep track of
7433: # the version of the parameter.
7434: while (my ($symb,$param_hash) = each(%returnhash)) {
7435: # use a foreach because we are going to delete from the hash.
7436: foreach my $key (keys(%$param_hash)) {
7437: delete($param_hash->{$key}) if ($key =~ /^v\./);
7438: }
7439: }
7440: return \%returnhash;
1.12 www 7441: }
7442:
1.627 albertel 7443: # ------------------------------------------------------ critical inc interface
7444:
7445: sub cinc {
7446: return &inc(@_,'critical');
7447: }
7448:
1.449 matthew 7449: # --------------------------------------------------------------- inc interface
7450:
7451: sub inc {
1.627 albertel 7452: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7453: if (!$udomain) { $udomain=$env{'user.domain'}; }
7454: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7455: my $uhome=&homeserver($uname,$udomain);
7456: my $items='';
7457: if (! ref($store)) {
7458: # got a single value, so use that instead
7459: $items = &escape($store).'=&';
7460: } elsif (ref($store) eq 'SCALAR') {
7461: $items = &escape($$store).'=&';
7462: } elsif (ref($store) eq 'ARRAY') {
7463: $items = join('=&',map {&escape($_);} @{$store});
7464: } elsif (ref($store) eq 'HASH') {
7465: while (my($key,$value) = each(%{$store})) {
7466: $items.= &escape($key).'='.&escape($value).'&';
7467: }
7468: }
7469: $items=~s/\&$//;
1.627 albertel 7470: if ($critical) {
7471: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7472: } else {
7473: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7474: }
1.449 matthew 7475: }
7476:
1.12 www 7477: # --------------------------------------------------------------- put interface
7478:
7479: sub put {
1.1462 raeburn 7480: my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620 albertel 7481: if (!$udomain) { $udomain=$env{'user.domain'}; }
7482: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7483: my $uhome=&homeserver($uname,$udomain);
1.12 www 7484: my $items='';
1.800 albertel 7485: foreach my $item (keys(%$storehash)) {
7486: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7487: }
1.12 www 7488: $items=~s/\&$//;
1.1462 raeburn 7489: if ($encrypt) {
7490: return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
7491: } else {
7492: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7493: }
1.47 www 7494: }
7495:
1.631 albertel 7496: # ------------------------------------------------------------ newput interface
7497:
7498: sub newput {
7499: my ($namespace,$storehash,$udomain,$uname)=@_;
7500: if (!$udomain) { $udomain=$env{'user.domain'}; }
7501: if (!$uname) { $uname=$env{'user.name'}; }
7502: my $uhome=&homeserver($uname,$udomain);
7503: my $items='';
7504: foreach my $key (keys(%$storehash)) {
7505: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7506: }
7507: $items=~s/\&$//;
7508: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7509: }
7510:
7511: # --------------------------------------------------------- putstore interface
7512:
1.524 raeburn 7513: sub putstore {
1.1269 raeburn 7514: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7515: if (!$udomain) { $udomain=$env{'user.domain'}; }
7516: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7517: my $uhome=&homeserver($uname,$udomain);
7518: my $items='';
1.715 albertel 7519: foreach my $key (keys(%$storehash)) {
7520: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7521: }
1.715 albertel 7522: $items=~s/\&$//;
1.716 albertel 7523: my $esc_symb=&escape($symb);
7524: my $esc_v=&escape($version);
1.715 albertel 7525: my $reply =
1.716 albertel 7526: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7527: $uhome);
1.1269 raeburn 7528: if (($tolog) && ($reply eq 'ok')) {
7529: my $namevalue='';
7530: foreach my $key (keys(%{$storehash})) {
7531: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7532: }
1.1434 raeburn 7533: my $ip = &get_requestor_ip();
7534: $namevalue .= 'ip='.&escape($ip).
1.1269 raeburn 7535: '&host='.&escape($perlvar{'lonHostID'}).
7536: '&version='.$esc_v.
7537: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
1.1494 raeburn 7538: &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
1.1269 raeburn 7539: }
1.715 albertel 7540: if ($reply eq 'unknown_cmd') {
1.716 albertel 7541: # gfall back to way things use to be done
1.715 albertel 7542: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7543: $uname);
1.524 raeburn 7544: }
1.715 albertel 7545: return $reply;
7546: }
7547:
7548: sub old_putstore {
1.716 albertel 7549: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7550: if (!$udomain) { $udomain=$env{'user.domain'}; }
7551: if (!$uname) { $uname=$env{'user.name'}; }
7552: my $uhome=&homeserver($uname,$udomain);
7553: my %newstorehash;
1.800 albertel 7554: foreach my $item (keys(%$storehash)) {
7555: my $key = $version.':'.&escape($symb).':'.$item;
7556: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7557: }
7558: my $items='';
7559: my %allitems = ();
1.800 albertel 7560: foreach my $item (keys(%newstorehash)) {
7561: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7562: my $key = $1.':keys:'.$2;
7563: $allitems{$key} .= $3.':';
7564: }
1.800 albertel 7565: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7566: }
1.800 albertel 7567: foreach my $item (keys(%allitems)) {
7568: $allitems{$item} =~ s/\:$//;
7569: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7570: }
7571: $items=~s/\&$//;
7572: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7573: }
7574:
1.47 www 7575: # ------------------------------------------------------ critical put interface
7576:
7577: sub cput {
1.134 albertel 7578: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7579: if (!$udomain) { $udomain=$env{'user.domain'}; }
7580: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7581: my $uhome=&homeserver($uname,$udomain);
1.47 www 7582: my $items='';
1.800 albertel 7583: foreach my $item (keys(%$storehash)) {
7584: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7585: }
1.47 www 7586: $items=~s/\&$//;
1.134 albertel 7587: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7588: }
7589:
7590: # -------------------------------------------------------------- eget interface
7591:
7592: sub eget {
1.133 albertel 7593: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7594: my $items='';
1.800 albertel 7595: foreach my $item (@$storearr) {
7596: $items.=&escape($item).'&';
1.191 harris41 7597: }
1.12 www 7598: $items=~s/\&$//;
1.620 albertel 7599: if (!$udomain) { $udomain=$env{'user.domain'}; }
7600: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7601: my $uhome=&homeserver($uname,$udomain);
7602: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7603: my @pairs=split(/\&/,$rep);
7604: my %returnhash=();
1.42 www 7605: my $i=0;
1.800 albertel 7606: foreach my $item (@$storearr) {
7607: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7608: $i++;
1.191 harris41 7609: }
1.12 www 7610: return %returnhash;
7611: }
7612:
1.667 albertel 7613: # ------------------------------------------------------------ tmpput interface
7614: sub tmpput {
1.802 raeburn 7615: my ($storehash,$server,$context)=@_;
1.667 albertel 7616: my $items='';
1.800 albertel 7617: foreach my $item (keys(%$storehash)) {
7618: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7619: }
7620: $items=~s/\&$//;
1.802 raeburn 7621: if (defined($context)) {
7622: $items .= ':'.&escape($context);
7623: }
1.667 albertel 7624: return &reply("tmpput:$items",$server);
7625: }
7626:
7627: # ------------------------------------------------------------ tmpget interface
7628: sub tmpget {
1.688 albertel 7629: my ($token,$server)=@_;
7630: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7631: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7632: my %returnhash;
1.1328 raeburn 7633: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7634: return %returnhash;
7635: }
1.667 albertel 7636: foreach my $item (split(/\&/,$rep)) {
7637: my ($key,$value)=split(/=/,$item);
7638: $returnhash{&unescape($key)}=&thaw_unescape($value);
7639: }
7640: return %returnhash;
7641: }
7642:
1.1113 raeburn 7643: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7644: sub tmpdel {
7645: my ($token,$server)=@_;
7646: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7647: return &reply("tmpdel:$token",$server);
7648: }
7649:
1.1198 raeburn 7650: # ------------------------------------------------------------ get_timebased_id
7651:
7652: sub get_timebased_id {
7653: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7654: $maxtries) = @_;
7655: my ($newid,$error,$dellock);
7656: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7657: return ('','ok','invalid call to get suffix');
7658: }
7659:
7660: # set defaults for any optional args for which values were not supplied
7661: if ($who eq '') {
7662: $who = $env{'user.name'}.':'.$env{'user.domain'};
7663: }
7664: if (!$locktries) {
7665: $locktries = 3;
7666: }
7667: if (!$maxtries) {
7668: $maxtries = 10;
7669: }
7670:
7671: if (($cdom eq '') || ($cnum eq '')) {
7672: if ($env{'request.course.id'}) {
7673: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7674: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7675: }
7676: if (($cdom eq '') || ($cnum eq '')) {
7677: return ('','ok','call to get suffix not in course context');
7678: }
7679: }
7680:
7681: # construct locking item
7682: my $lockhash = {
7683: $prefix."\0".'locked_'.$keyid => $who,
7684: };
7685: my $tries = 0;
7686:
7687: # attempt to get lock on nohist_$namespace file
1.1494 raeburn 7688: my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198 raeburn 7689: while (($gotlock ne 'ok') && $tries <$locktries) {
7690: $tries ++;
7691: sleep 1;
1.1494 raeburn 7692: $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198 raeburn 7693: }
7694:
7695: # attempt to get unique identifier, based on current timestamp
7696: if ($gotlock eq 'ok') {
1.1494 raeburn 7697: my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
1.1198 raeburn 7698: my $id = time;
7699: $newid = $id;
1.1268 raeburn 7700: if ($idtype eq 'addcode') {
7701: $newid .= &sixnum_code();
7702: }
1.1198 raeburn 7703: my $idtries = 0;
7704: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7705: if ($idtype eq 'concat') {
7706: $newid = $id.$idtries;
1.1268 raeburn 7707: } elsif ($idtype eq 'addcode') {
7708: $newid = $newid.&sixnum_code();
1.1198 raeburn 7709: } else {
7710: $newid ++;
7711: }
7712: $idtries ++;
7713: }
7714: if (!exists($inuse{$prefix."\0".$newid})) {
7715: my %new_item = (
7716: $prefix."\0".$newid => $who,
7717: );
1.1494 raeburn 7718: my $putresult = &put('nohist_'.$namespace,\%new_item,
1.1198 raeburn 7719: $cdom,$cnum);
7720: if ($putresult ne 'ok') {
7721: undef($newid);
7722: $error = 'error saving new item: '.$putresult;
7723: }
7724: } else {
1.1268 raeburn 7725: undef($newid);
1.1198 raeburn 7726: $error = ('error: no unique suffix available for the new item ');
7727: }
7728: # remove lock
7729: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7730: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7731: } else {
7732: $error = "error: could not obtain lockfile\n";
7733: $dellock = 'ok';
1.1276 raeburn 7734: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7735: $dellock = 'nolock';
7736: }
1.1198 raeburn 7737: }
7738: return ($newid,$dellock,$error);
7739: }
7740:
1.1268 raeburn 7741: sub sixnum_code {
7742: my $code;
7743: for (0..6) {
7744: $code .= int( rand(9) );
7745: }
7746: return $code;
7747: }
7748:
1.765 albertel 7749: # -------------------------------------------------- portfolio access checking
7750:
7751: sub portfolio_access {
1.1270 raeburn 7752: my ($requrl,$clientip) = @_;
1.765 albertel 7753: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 7754: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7755: if ($result) {
7756: my %setters;
7757: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1473 raeburn 7758: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7759: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
7760: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7761: return 'B';
7762: }
7763: } else {
1.1473 raeburn 7764: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7765: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7766: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7767: return 'B';
7768: }
7769: }
7770: }
1.765 albertel 7771: if ($result eq 'ok') {
1.766 albertel 7772: return 'F';
1.765 albertel 7773: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7774: return 'A';
1.765 albertel 7775: }
1.766 albertel 7776: return '';
1.765 albertel 7777: }
7778:
7779: sub get_portfolio_access {
1.1270 raeburn 7780: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7781:
7782: if (!ref($access_hash)) {
7783: my $current_perms = &get_portfile_permissions($udom,$unum);
7784: my %access_controls = &get_access_controls($current_perms,$group,
7785: $file_name);
7786: $access_hash = $access_controls{$file_name};
7787: }
7788:
1.1270 raeburn 7789: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7790: my $now = time;
7791: if (ref($access_hash) eq 'HASH') {
7792: foreach my $key (keys(%{$access_hash})) {
7793: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7794: if ($start > $now) {
7795: next;
7796: }
7797: if ($end && $end<$now) {
7798: next;
7799: }
7800: if ($scope eq 'public') {
7801: $public = $key;
7802: last;
7803: } elsif ($scope eq 'guest') {
7804: $guest = $key;
7805: } elsif ($scope eq 'domains') {
7806: push(@domains,$key);
7807: } elsif ($scope eq 'users') {
7808: push(@users,$key);
7809: } elsif ($scope eq 'course') {
7810: push(@courses,$key);
7811: } elsif ($scope eq 'group') {
7812: push(@groups,$key);
1.1270 raeburn 7813: } elsif ($scope eq 'ip') {
7814: push(@ips,$key);
1.765 albertel 7815: }
7816: }
7817: if ($public) {
7818: return 'ok';
1.1270 raeburn 7819: } elsif (@ips > 0) {
7820: my $allowed;
7821: foreach my $ipkey (@ips) {
7822: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7823: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7824: $allowed = 1;
7825: last;
7826: }
7827: }
7828: }
7829: if ($allowed) {
7830: return 'ok';
7831: }
1.765 albertel 7832: }
7833: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7834: if ($guest) {
7835: return $guest;
7836: }
7837: } else {
7838: if (@domains > 0) {
7839: foreach my $domkey (@domains) {
7840: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7841: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7842: return 'ok';
7843: }
7844: }
7845: }
7846: }
7847: if (@users > 0) {
7848: foreach my $userkey (@users) {
1.865 raeburn 7849: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7850: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7851: if (ref($item) eq 'HASH') {
7852: if (($item->{'uname'} eq $env{'user.name'}) &&
7853: ($item->{'udom'} eq $env{'user.domain'})) {
7854: return 'ok';
7855: }
7856: }
7857: }
7858: }
1.765 albertel 7859: }
7860: }
7861: my %roleshash;
7862: my @courses_and_groups = @courses;
7863: push(@courses_and_groups,@groups);
7864: if (@courses_and_groups > 0) {
7865: my (%allgroups,%allroles);
7866: my ($start,$end,$role,$sec,$group);
7867: foreach my $envkey (%env) {
1.1060 raeburn 7868: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7869: my $cid = $2.'_'.$3;
7870: if ($1 eq 'gr') {
7871: $group = $4;
7872: $allgroups{$cid}{$group} = $env{$envkey};
7873: } else {
7874: if ($4 eq '') {
7875: $sec = 'none';
7876: } else {
7877: $sec = $4;
7878: }
7879: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7880: }
1.811 albertel 7881: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7882: my $cid = $2.'_'.$3;
7883: if ($4 eq '') {
7884: $sec = 'none';
7885: } else {
7886: $sec = $4;
7887: }
7888: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7889: }
7890: }
7891: if (keys(%allroles) == 0) {
7892: return;
7893: }
7894: foreach my $key (@courses_and_groups) {
7895: my %content = %{$$access_hash{$key}};
7896: my $cnum = $content{'number'};
7897: my $cdom = $content{'domain'};
7898: my $cid = $cdom.'_'.$cnum;
7899: if (!exists($allroles{$cid})) {
7900: next;
7901: }
7902: foreach my $role_id (keys(%{$content{'roles'}})) {
7903: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7904: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7905: my @status = @{$content{'roles'}{$role_id}{'access'}};
7906: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7907: foreach my $role (keys(%{$allroles{$cid}})) {
7908: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7909: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7910: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7911: if (grep/^all$/,@sections) {
7912: return 'ok';
7913: } else {
7914: if (grep/^$sec$/,@sections) {
7915: return 'ok';
7916: }
7917: }
7918: }
7919: }
7920: if (keys(%{$allgroups{$cid}}) == 0) {
7921: if (grep/^none$/,@groups) {
7922: return 'ok';
7923: }
7924: } else {
7925: if (grep/^all$/,@groups) {
7926: return 'ok';
7927: }
7928: foreach my $group (keys(%{$allgroups{$cid}})) {
7929: if (grep/^$group$/,@groups) {
7930: return 'ok';
7931: }
7932: }
7933: }
7934: }
7935: }
7936: }
7937: }
7938: }
7939: if ($guest) {
7940: return $guest;
7941: }
7942: }
7943: }
7944: return;
7945: }
7946:
7947: sub course_group_datechecker {
7948: my ($dates,$now,$status) = @_;
7949: my ($start,$end) = split(/\./,$dates);
7950: if (!$start && !$end) {
7951: return 'ok';
7952: }
7953: if (grep/^active$/,@{$status}) {
7954: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7955: return 'ok';
7956: }
7957: }
7958: if (grep/^previous$/,@{$status}) {
7959: if ($end > $now ) {
7960: return 'ok';
7961: }
7962: }
7963: if (grep/^future$/,@{$status}) {
7964: if ($start > $now) {
7965: return 'ok';
7966: }
7967: }
7968: return;
7969: }
7970:
7971: sub parse_portfolio_url {
7972: my ($url) = @_;
7973:
7974: my ($type,$udom,$unum,$group,$file_name);
7975:
1.823 albertel 7976: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7977: $type = 1;
7978: $udom = $1;
7979: $unum = $2;
7980: $file_name = $3;
1.823 albertel 7981: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7982: $type = 2;
7983: $udom = $1;
7984: $unum = $2;
7985: $group = $3;
7986: $file_name = $3.'/'.$4;
7987: }
7988: if (wantarray) {
7989: return ($type,$udom,$unum,$file_name,$group);
7990: }
7991: return $type;
7992: }
7993:
7994: sub is_portfolio_url {
7995: my ($url) = @_;
7996: return scalar(&parse_portfolio_url($url));
7997: }
7998:
1.798 raeburn 7999: sub is_portfolio_file {
8000: my ($file) = @_;
1.820 raeburn 8001: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 8002: return 1;
8003: }
8004: return;
8005: }
8006:
1.1504 raeburn 8007: sub is_coursetool_logo {
8008: my ($uri) = @_;
8009: if ($env{'request.course.id'}) {
8010: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8011: if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
8012: return 1;
8013: }
8014: }
8015: return;
8016: }
8017:
1.976 raeburn 8018: sub usertools_access {
1.1084 raeburn 8019: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 8020: my ($access,%tools);
8021: if ($context eq '') {
8022: $context = 'tools';
8023: }
8024: if ($context eq 'requestcourses') {
8025: %tools = (
8026: official => 1,
8027: unofficial => 1,
1.1006 raeburn 8028: community => 1,
1.1246 raeburn 8029: textbook => 1,
1.1305 raeburn 8030: placement => 1,
1.1368 raeburn 8031: lti => 1,
1.985 raeburn 8032: );
1.1183 raeburn 8033: } elsif ($context eq 'requestauthor') {
8034: %tools = (
8035: requestauthor => 1,
8036: );
1.985 raeburn 8037: } else {
8038: %tools = (
8039: aboutme => 1,
8040: blog => 1,
1.1177 raeburn 8041: webdav => 1,
1.985 raeburn 8042: portfolio => 1,
1.1489 raeburn 8043: timezone => 1,
1.985 raeburn 8044: );
8045: }
1.976 raeburn 8046: return if (!defined($tools{$tool}));
8047:
1.1242 raeburn 8048: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 8049: $udom = $env{'user.domain'};
8050: $uname = $env{'user.name'};
8051: }
8052:
1.978 raeburn 8053: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
8054: if ($action ne 'reload') {
1.985 raeburn 8055: if ($context eq 'requestcourses') {
8056: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 8057: } elsif ($context eq 'requestauthor') {
8058: return $env{'environment.canrequest.author'};
1.985 raeburn 8059: } else {
8060: return $env{'environment.availabletools.'.$tool};
8061: }
8062: }
1.976 raeburn 8063: }
8064:
1.1183 raeburn 8065: my ($toolstatus,$inststatus,$envkey);
8066: if ($context eq 'requestauthor') {
8067: $envkey = $context;
8068: } else {
8069: $envkey = $context.'.'.$tool;
8070: }
1.976 raeburn 8071:
1.985 raeburn 8072: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8073: ($action ne 'reload')) {
1.1183 raeburn 8074: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 8075: $inststatus = $env{'environment.inststatus'};
8076: } else {
1.1084 raeburn 8077: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 8078: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 8079: $inststatus = $userenvref->{'inststatus'};
8080: } else {
1.1183 raeburn 8081: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
8082: $toolstatus = $userenv{$envkey};
1.1084 raeburn 8083: $inststatus = $userenv{'inststatus'};
8084: }
1.976 raeburn 8085: }
8086:
8087: if ($toolstatus ne '') {
8088: if ($toolstatus) {
8089: $access = 1;
8090: } else {
8091: $access = 0;
8092: }
8093: return $access;
8094: }
8095:
1.1084 raeburn 8096: my ($is_adv,%domdef);
8097: if (ref($is_advref) eq 'HASH') {
8098: $is_adv = $is_advref->{'is_adv'};
8099: } else {
8100: $is_adv = &is_advanced_user($udom,$uname);
8101: }
8102: if (ref($domdefref) eq 'HASH') {
8103: %domdef = %{$domdefref};
8104: } else {
8105: %domdef = &get_domain_defaults($udom);
8106: }
1.976 raeburn 8107: if (ref($domdef{$tool}) eq 'HASH') {
8108: if ($is_adv) {
8109: if ($domdef{$tool}{'_LC_adv'} ne '') {
8110: if ($domdef{$tool}{'_LC_adv'}) {
8111: $access = 1;
8112: } else {
8113: $access = 0;
8114: }
8115: return $access;
8116: }
8117: }
8118: if ($inststatus ne '') {
8119: my ($hasaccess,$hasnoaccess);
8120: foreach my $affiliation (split(/:/,$inststatus)) {
8121: if ($domdef{$tool}{$affiliation} ne '') {
8122: if ($domdef{$tool}{$affiliation}) {
8123: $hasaccess = 1;
8124: } else {
8125: $hasnoaccess = 1;
8126: }
8127: }
8128: }
8129: if ($hasaccess || $hasnoaccess) {
8130: if ($hasaccess) {
8131: $access = 1;
8132: } elsif ($hasnoaccess) {
8133: $access = 0;
8134: }
8135: return $access;
8136: }
8137: } else {
8138: if ($domdef{$tool}{'default'} ne '') {
8139: if ($domdef{$tool}{'default'}) {
8140: $access = 1;
8141: } elsif ($domdef{$tool}{'default'} == 0) {
8142: $access = 0;
8143: }
8144: return $access;
8145: }
8146: }
8147: } else {
1.1177 raeburn 8148: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 8149: $access = 1;
8150: } else {
8151: $access = 0;
8152: }
1.976 raeburn 8153: return $access;
8154: }
8155: }
8156:
1.1050 raeburn 8157: sub is_course_owner {
8158: my ($cdom,$cnum,$udom,$uname) = @_;
8159: if (($udom eq '') || ($uname eq '')) {
8160: $udom = $env{'user.domain'};
8161: $uname = $env{'user.name'};
8162: }
8163: unless (($udom eq '') || ($uname eq '')) {
8164: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
8165: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
8166: return 1;
8167: } else {
1.1494 raeburn 8168: my %courseinfo = &coursedescription($cdom.'/'.$cnum);
1.1050 raeburn 8169: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
8170: return 1;
8171: }
8172: }
8173: }
8174: }
8175: return;
8176: }
8177:
1.976 raeburn 8178: sub is_advanced_user {
8179: my ($udom,$uname) = @_;
1.1085 raeburn 8180: if ($udom ne '' && $uname ne '') {
8181: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 8182: if (wantarray) {
8183: return ($env{'user.adv'},$env{'user.author'});
8184: } else {
8185: return $env{'user.adv'};
8186: }
1.1085 raeburn 8187: }
8188: }
1.976 raeburn 8189: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
8190: my %allroles;
1.1128 raeburn 8191: my ($is_adv,$is_author);
1.976 raeburn 8192: foreach my $role (keys(%roleshash)) {
8193: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
8194: my $area = '/'.$tdomain.'/'.$trest;
8195: if ($sec ne '') {
8196: $area .= '/'.$sec;
8197: }
8198: if (($area ne '') && ($trole ne '')) {
8199: my $spec=$trole.'.'.$area;
8200: if ($trole =~ /^cr\//) {
8201: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
8202: } elsif ($trole ne 'gr') {
8203: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
8204: }
1.1128 raeburn 8205: if ($trole eq 'au') {
8206: $is_author = 1;
8207: }
1.976 raeburn 8208: }
8209: }
8210: foreach my $role (keys(%allroles)) {
8211: last if ($is_adv);
8212: foreach my $item (split(/:/,$allroles{$role})) {
8213: if ($item ne '') {
8214: my ($privilege,$restrictions)=split(/&/,$item);
8215: if ($privilege eq 'adv') {
8216: $is_adv = 1;
8217: last;
8218: }
8219: }
8220: }
8221: }
1.1128 raeburn 8222: if (wantarray) {
8223: return ($is_adv,$is_author);
8224: }
1.976 raeburn 8225: return $is_adv;
8226: }
1.798 raeburn 8227:
1.1035 raeburn 8228: sub check_can_request {
1.1368 raeburn 8229: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035 raeburn 8230: my $canreq = 0;
1.1368 raeburn 8231: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8232: $uname = $env{'user.name'};
8233: $udom = $env{'user.domain'};
8234: }
1.1035 raeburn 8235: my ($types,$typename) = &Apache::loncommon::course_types();
8236: my @options = ('approval','validate','autolimit');
8237: my $optregex = join('|',@options);
8238: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
1.1486 raeburn 8239: my %willtrust;
1.1035 raeburn 8240: foreach my $type (@{$types}) {
1.1368 raeburn 8241: if (&usertools_access($uname,$udom,$type,undef,
8242: 'requestcourses')) {
1.1035 raeburn 8243: $canreq ++;
1.1036 raeburn 8244: if (ref($request_domains) eq 'HASH') {
1.1368 raeburn 8245: push(@{$request_domains->{$type}},$udom);
1.1036 raeburn 8246: }
1.1368 raeburn 8247: if ($dom eq $udom) {
1.1035 raeburn 8248: $can_request->{$type} = 1;
8249: }
8250: }
1.1368 raeburn 8251: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
8252: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035 raeburn 8253: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
8254: if (@curr > 0) {
1.1036 raeburn 8255: foreach my $item (@curr) {
8256: if (ref($request_domains) eq 'HASH') {
8257: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
8258: if ($otherdom ne '') {
1.1486 raeburn 8259: unless (exists($willtrust{$otherdom})) {
8260: $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
8261: }
8262: if ($willtrust{$otherdom}) {
8263: if (ref($request_domains->{$type}) eq 'ARRAY') {
8264: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
8265: push(@{$request_domains->{$type}},$otherdom);
8266: }
8267: } else {
1.1036 raeburn 8268: push(@{$request_domains->{$type}},$otherdom);
8269: }
8270: }
8271: }
8272: }
8273: }
1.1368 raeburn 8274: unless ($dom eq $env{'user.domain'}) {
1.1036 raeburn 8275: $canreq ++;
1.1035 raeburn 8276: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
8277: $can_request->{$type} = 1;
8278: }
8279: }
8280: }
8281: }
8282: }
8283: }
8284: return $canreq;
8285: }
8286:
1.341 www 8287: # ---------------------------------------------- Custom access rule evaluation
8288:
8289: sub customaccess {
8290: my ($priv,$uri)=@_;
1.807 albertel 8291: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 8292: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 8293: $udom = &LONCAPA::clean_domain($udom);
8294: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 8295: my $access=0;
1.800 albertel 8296: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 8297: my ($effect,$realm,$role,$type)=split(/\:/,$right);
8298: if ($type eq 'user') {
8299: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 8300: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 8301: if ($tdom) {
8302: if ($tdom ne $env{'user.domain'}) { next; }
8303: }
1.896 albertel 8304: if ($tuname) {
8305: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 8306: }
8307: $access=($effect eq 'allow');
8308: last;
8309: }
8310: } else {
8311: if ($role) {
8312: if ($role ne $urole) { next; }
8313: }
8314: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8315: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8316: if ($tdom) {
8317: if ($tdom ne $udom) { next; }
8318: }
8319: if ($tcrs) {
8320: if ($tcrs ne $ucrs) { next; }
8321: }
8322: if ($tsec) {
8323: if ($tsec ne $usec) { next; }
8324: }
8325: $access=($effect eq 'allow');
8326: last;
8327: }
8328: if ($realm eq '' && $role eq '') {
8329: $access=($effect eq 'allow');
8330: }
1.402 bowersj2 8331: }
1.341 www 8332: }
8333: return $access;
8334: }
8335:
1.103 harris41 8336: # ------------------------------------------------- Check for a user privilege
1.12 www 8337:
8338: sub allowed {
1.1461 raeburn 8339: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705 albertel 8340: my $ver_orguri=$uri;
1.439 www 8341: $uri=&deversion($uri);
1.152 www 8342: my $orguri=$uri;
1.52 www 8343: $uri=&declutter($uri);
1.809 raeburn 8344:
1.810 raeburn 8345: if ($priv eq 'evb') {
1.1478 raeburn 8346: # Evade communication block restrictions for specified role in a course or domain
1.810 raeburn 8347: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8348: return $1;
8349: } else {
8350: return;
8351: }
8352: }
8353:
1.620 albertel 8354: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 8355: # Free bre access to adm and meta resources
1.1436 raeburn 8356: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$}))
1.769 albertel 8357: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8358: && ($priv eq 'bre')) {
1.14 www 8359: return 'F';
1.159 www 8360: }
8361:
1.545 banghart 8362: # Free bre access to user's own portfolio contents
1.714 raeburn 8363: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 8364: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 8365: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 8366: my %setters;
1.1473 raeburn 8367: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
8368: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
8369: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 8370: return 'B';
8371: } else {
8372: return 'F';
8373: }
1.545 banghart 8374: }
8375:
1.762 raeburn 8376: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 8377: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8378: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8379: if (exists($env{'request.course.id'})) {
8380: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8381: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8382: if (($domain eq $cdom) && ($name eq $cnum)) {
8383: my $courseprivid=$env{'request.course.id'};
8384: $courseprivid=~s/\_/\//;
8385: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8386: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8387: return $1;
1.762 raeburn 8388: } else {
8389: if ($env{'request.course.sec'}) {
8390: $courseprivid.='/'.$env{'request.course.sec'};
8391: }
8392: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8393: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8394: return $2;
8395: }
1.714 raeburn 8396: }
8397: }
8398: }
8399: }
8400:
1.159 www 8401: # Free bre to public access
8402:
8403: if ($priv eq 'bre') {
1.1362 raeburn 8404: my $copyright;
8405: unless ($uri =~ /ext\.tool/) {
8406: $copyright=&metadata($uri,'copyright');
8407: }
1.620 albertel 8408: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 8409: return 'F';
8410: }
1.238 www 8411: if ($copyright eq 'priv') {
8412: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8413: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 8414: return '';
8415: }
8416: }
8417: if ($copyright eq 'domain') {
8418: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8419: unless (($env{'user.domain'} eq $1) ||
8420: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8421: return '';
8422: }
1.262 matthew 8423: }
1.620 albertel 8424: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8425: # Library role, so allow browsing of resources in this domain.
8426: return 'F';
1.238 www 8427: }
1.341 www 8428: if ($copyright eq 'custom') {
8429: unless (&customaccess($priv,$uri)) { return ''; }
8430: }
1.14 www 8431: }
1.264 matthew 8432: # Domain coordinator is trying to create a course
1.620 albertel 8433: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8434: # uri is the requested domain in this case.
8435: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8436: # a role of dc for the domain in question.
1.620 albertel 8437: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8438: }
1.29 www 8439:
1.52 www 8440: my $thisallowed='';
8441: my $statecond=0;
8442: my $courseprivid='';
8443:
1.1039 raeburn 8444: my $ownaccess;
1.1043 raeburn 8445: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8446: if (($priv eq 'bro') && ($env{'user.author'})) {
8447: if ($uri eq '') {
8448: $ownaccess = 1;
8449: } else {
8450: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8451: my $udom = $env{'user.domain'};
8452: my $uname = $env{'user.name'};
8453: if ($uri =~ m{^\Q$udom\E/?$}) {
8454: $ownaccess = 1;
1.1040 raeburn 8455: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8456: unless ($uri =~ m{\.\./}) {
8457: $ownaccess = 1;
8458: }
8459: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8460: my $now = time;
8461: if ($uri =~ m{^([^/]+)/?$}) {
8462: my $adom = $1;
8463: foreach my $key (keys(%env)) {
1.1042 raeburn 8464: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452 raeburn 8465: my ($start,$end) = split(/\./,$env{$key});
8466: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8467: $ownaccess = 1;
8468: last;
8469: }
8470: }
8471: }
8472: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8473: my $adom = $1;
8474: my $aname = $2;
1.1042 raeburn 8475: foreach my $role ('ca','aa') {
8476: if ($env{"user.role.$role./$adom/$aname"}) {
8477: my ($start,$end) =
1.1452 raeburn 8478: split(/\./,$env{"user.role.$role./$adom/$aname"});
8479: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8480: $ownaccess = 1;
8481: last;
8482: }
1.1039 raeburn 8483: }
8484: }
8485: }
8486: }
8487: }
8488: }
8489: }
8490:
1.52 www 8491: # Course
8492:
1.620 albertel 8493: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8494: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8495: $thisallowed.=$1;
8496: }
1.52 www 8497: }
1.29 www 8498:
1.52 www 8499: # Domain
8500:
1.620 albertel 8501: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8502: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8503: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8504: $thisallowed.=$1;
8505: }
1.12 www 8506: }
1.52 www 8507:
1.1141 raeburn 8508: # User who is not author or co-author might still be able to edit
8509: # resource of an author in the domain (e.g., if Domain Coordinator).
8510: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8511: (&allowed('mdc',$env{'request.course.id'}))) {
8512: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8513: $thisallowed.=$1;
8514: }
8515: }
8516:
1.52 www 8517: # Course: uri itself is a course
1.66 www 8518: my $courseuri=$uri;
8519: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8520: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8521:
1.620 albertel 8522: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8523: =~/\Q$priv\E\&([^\:]*)/) {
1.1409 raeburn 8524: if ($priv eq 'mip') {
8525: my $rem = $1;
8526: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8527: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8528: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8529: if ($cdom ne '') {
1.1410 raeburn 8530: my %passwdconf = &get_passwdconf($cdom);
8531: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8532: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8533: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8534: my @inststatuses = split(':',$env{'environment.inststatus'});
8535: unless (@inststatuses) {
8536: @inststatuses = ('default');
8537: }
8538: foreach my $status (@inststatuses) {
8539: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8540: $thisallowed.=$rem;
8541: }
8542: }
8543: }
8544: }
1.1409 raeburn 8545: }
8546: }
8547: }
8548: } else {
8549: unless (($priv eq 'bro') && (!$ownaccess)) {
8550: $thisallowed.=$1;
8551: }
1.1039 raeburn 8552: }
1.12 www 8553: }
1.29 www 8554:
1.665 albertel 8555: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8556: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8557: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8558: $thisallowed='';
1.671 raeburn 8559: my ($match)=&is_on_map($uri);
8560: if ($match) {
8561: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8562: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 8563: my $value = $1;
1.1461 raeburn 8564: my $deeplinkblock;
8565: unless ($nodeeplinkcheck) {
8566: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8567: }
1.1402 raeburn 8568: if ($deeplinkblock) {
8569: $thisallowed='D';
8570: } elsif ($noblockcheck) {
1.1281 raeburn 8571: $thisallowed.=$value;
1.1162 raeburn 8572: } else {
1.1424 raeburn 8573: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8574: if (@blockers > 0) {
8575: $thisallowed = 'B';
8576: } else {
8577: $thisallowed.=$value;
8578: }
1.1162 raeburn 8579: }
1.671 raeburn 8580: }
8581: } else {
1.705 albertel 8582: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8583: if ($refuri) {
8584: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8585: $thisallowed='F';
1.671 raeburn 8586: } else {
8587: $refuri=&declutter($refuri);
8588: my ($match) = &is_on_map($refuri);
8589: if ($match) {
1.1461 raeburn 8590: my $deeplinkblock;
8591: unless ($nodeeplinkcheck) {
8592: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8593: }
1.1402 raeburn 8594: if ($deeplinkblock) {
8595: $thisallowed='D';
8596: } elsif ($noblockcheck) {
1.1281 raeburn 8597: $thisallowed='F';
1.1162 raeburn 8598: } else {
1.1426 raeburn 8599: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8600: if (@blockers > 0) {
8601: $thisallowed = 'B';
8602: } else {
8603: $thisallowed='F';
8604: }
1.1162 raeburn 8605: }
1.671 raeburn 8606: }
1.669 raeburn 8607: }
1.671 raeburn 8608: }
8609: }
1.314 www 8610: }
1.492 albertel 8611:
1.766 albertel 8612: if ($priv eq 'bre'
8613: && $thisallowed ne 'F'
8614: && $thisallowed ne '2'
8615: && &is_portfolio_url($uri)) {
1.1270 raeburn 8616: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8617: }
1.1250 raeburn 8618:
1.52 www 8619: # Full access at system, domain or course-wide level? Exit.
1.29 www 8620: if ($thisallowed=~/F/) {
8621: return 'F';
8622: }
8623:
1.52 www 8624: # If this is generating or modifying users, exit with special codes
1.29 www 8625:
1.643 www 8626: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8627: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8628: my ($audom,$auname)=split('/',$uri);
1.643 www 8629: # no author name given, so this just checks on the general right to make a co-author in this domain
8630: unless ($auname) { return $thisallowed; }
8631: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8632: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8633: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8634: ($audom ne $env{'request.role.domain'}))) { return ''; }
8635: }
1.52 www 8636: return $thisallowed;
8637: }
8638: #
1.103 harris41 8639: # Gathered so far: system, domain and course wide privileges
1.52 www 8640: #
8641: # Course: See if uri or referer is an individual resource that is part of
8642: # the course
8643:
1.620 albertel 8644: if ($env{'request.course.id'}) {
1.232 www 8645:
1.1504 raeburn 8646: if ($priv eq 'bre') {
8647: if (&is_coursetool_logo($uri)) {
8648: return 'F';
8649: }
8650: }
8651:
1.1409 raeburn 8652: # If this is modifying password (internal auth) domains must match for user and user's role.
8653:
8654: if ($priv eq 'mip') {
8655: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8656: return $thisallowed;
8657: } else {
8658: return '';
8659: }
8660: }
8661:
1.620 albertel 8662: $courseprivid=$env{'request.course.id'};
8663: if ($env{'request.course.sec'}) {
8664: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8665: }
8666: $courseprivid=~s/\_/\//;
8667: my $checkreferer=1;
1.232 www 8668: my ($match,$cond)=&is_on_map($uri);
8669: if ($match) {
8670: $statecond=$cond;
1.620 albertel 8671: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8672: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8673: my $value = $1;
8674: if ($priv eq 'bre') {
1.1461 raeburn 8675: my $deeplinkblock;
8676: unless ($nodeeplinkcheck) {
8677: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8678: }
1.1458 raeburn 8679: if ($deeplinkblock) {
8680: $thisallowed = 'D';
8681: } elsif ($noblockcheck) {
1.1281 raeburn 8682: $thisallowed.=$value;
1.1162 raeburn 8683: } else {
1.1424 raeburn 8684: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8685: if (@blockers > 0) {
8686: $thisallowed = 'B';
8687: } else {
8688: $thisallowed.=$value;
8689: }
1.1162 raeburn 8690: }
8691: } else {
8692: $thisallowed.=$value;
8693: }
1.52 www 8694: $checkreferer=0;
8695: }
1.29 www 8696: }
1.1424 raeburn 8697:
1.148 www 8698: if ($checkreferer) {
1.620 albertel 8699: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8700: unless ($refuri) {
1.800 albertel 8701: foreach my $key (keys(%env)) {
8702: if ($key=~/^httpref\..*\*/) {
8703: my $pattern=$key;
1.156 www 8704: $pattern=~s/^httpref\.\/res\///;
1.148 www 8705: $pattern=~s/\*/\[\^\/\]\+/g;
8706: $pattern=~s/\//\\\//g;
1.152 www 8707: if ($orguri=~/$pattern/) {
1.800 albertel 8708: $refuri=$env{$key};
1.148 www 8709: }
8710: }
1.191 harris41 8711: }
1.148 www 8712: }
1.232 www 8713:
1.148 www 8714: if ($refuri) {
1.152 www 8715: $refuri=&declutter($refuri);
1.232 www 8716: my ($match,$cond)=&is_on_map($refuri);
8717: if ($match) {
8718: my $refstatecond=$cond;
1.620 albertel 8719: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8720: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8721: my $value = $1;
8722: if ($priv eq 'bre') {
1.1461 raeburn 8723: my $deeplinkblock;
8724: unless ($nodeeplinkcheck) {
8725: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8726: }
1.1402 raeburn 8727: if ($deeplinkblock) {
8728: $thisallowed = 'D';
8729: } elsif ($noblockcheck) {
1.1281 raeburn 8730: $thisallowed.=$value;
1.1162 raeburn 8731: } else {
1.1426 raeburn 8732: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8733: if (@blockers > 0) {
8734: $thisallowed = 'B';
8735: } else {
8736: $thisallowed.=$value;
8737: }
1.1162 raeburn 8738: }
8739: } else {
8740: $thisallowed.=$value;
8741: }
1.53 www 8742: $uri=$refuri;
8743: $statecond=$refstatecond;
1.52 www 8744: }
8745: }
1.148 www 8746: }
1.29 www 8747: }
1.52 www 8748: }
1.29 www 8749:
1.52 www 8750: #
1.103 harris41 8751: # Gathered now: all privileges that could apply, and condition number
1.52 www 8752: #
8753: #
8754: # Full or no access?
8755: #
1.29 www 8756:
1.52 www 8757: if ($thisallowed=~/F/) {
8758: return 'F';
8759: }
1.29 www 8760:
1.52 www 8761: unless ($thisallowed) {
8762: return '';
8763: }
1.29 www 8764:
1.52 www 8765: # Restrictions exist, deal with them
8766: #
8767: # C:according to course preferences
8768: # R:according to resource settings
8769: # L:unless locked
8770: # X:according to user session state
8771: #
8772:
8773: # Possibly locked functionality, check all courses
1.1454 raeburn 8774: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 8775: # Locks might take effect only after 10 minutes cache expiration for other
1.1454 raeburn 8776: # courses, and 2 minutes for current course, in which user has st or ta role
8777: # which is neither expired nor a future role (unless current course).
1.52 www 8778:
1.1454 raeburn 8779: my ($needlockcheck,$now,$crsonly);
1.52 www 8780: if ($thisallowed=~/L/) {
1.1454 raeburn 8781: $now = time;
8782: if ($priv eq 'bre') {
8783: if ($uri ne '') {
8784: if ($orguri =~ m{^/+res/}) {
8785: if ($uri =~ m{^lib/templates/}) {
8786: if ($env{'request.course.id'}) {
8787: $crsonly = 1;
8788: $needlockcheck = 1;
8789: }
8790: } else {
8791: $needlockcheck = 1;
8792: }
8793: } elsif ($env{'request.course.id'}) {
8794: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8795: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8796: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8797: $crsonly = 1;
8798: }
8799: $needlockcheck = 1;
8800: }
8801: }
8802: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8803: $needlockcheck = 1;
8804: }
8805: }
8806: if ($needlockcheck) {
1.1453 raeburn 8807: foreach my $envkey (keys(%env)) {
1.54 www 8808: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8809: my $courseid=$2;
8810: my $roleid=$1.'.'.$2;
1.92 www 8811: $courseid=~s/^\///;
1.1453 raeburn 8812: unless ($env{'request.role'} eq $roleid) {
8813: my ($start,$end) = split(/\./,$env{$envkey});
8814: next unless (($now >= $start) && (!$end || $end > $now));
8815: }
1.54 www 8816: my $expiretime=600;
1.620 albertel 8817: if ($env{'request.role'} eq $roleid) {
1.54 www 8818: $expiretime=120;
8819: }
8820: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8821: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8822: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8823: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8824: }
1.620 albertel 8825: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8826: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8827: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8828: &log($env{'user.domain'},$env{'user.name'},
8829: $env{'user.home'},
1.57 www 8830: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8831: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8832: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8833: return '';
8834: }
8835: }
1.620 albertel 8836: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8837: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455 raeburn 8838: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 8839: &log($env{'user.domain'},$env{'user.name'},
8840: $env{'user.home'},
1.57 www 8841: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8842: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8843: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8844: return '';
8845: }
8846: }
8847: }
1.29 www 8848: }
1.52 www 8849: }
1.1424 raeburn 8850:
1.52 www 8851: #
8852: # Rest of the restrictions depend on selected course
8853: #
8854:
1.620 albertel 8855: unless ($env{'request.course.id'}) {
1.766 albertel 8856: if ($thisallowed eq 'A') {
8857: return 'A';
1.814 raeburn 8858: } elsif ($thisallowed eq 'B') {
8859: return 'B';
1.766 albertel 8860: } else {
8861: return '1';
8862: }
1.52 www 8863: }
1.29 www 8864:
1.52 www 8865: #
8866: # Now user is definitely in a course
8867: #
1.53 www 8868:
8869:
8870: # Course preferences
8871:
8872: if ($thisallowed=~/C/) {
1.620 albertel 8873: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8874: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8875: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8876: =~/\Q$rolecode\E/) {
1.1304 raeburn 8877: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8878: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8879: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8880: $env{'request.course.id'});
8881: }
1.237 www 8882: return '';
8883: }
8884:
1.620 albertel 8885: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8886: =~/\Q$unamedom\E/) {
1.1304 raeburn 8887: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8888: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8889: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8890: $env{'request.course.id'});
8891: }
1.54 www 8892: return '';
8893: }
1.53 www 8894: }
8895:
8896: # Resource preferences
8897:
8898: if ($thisallowed=~/R/) {
1.620 albertel 8899: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8900: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8901: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8902: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8903: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8904: }
8905: return '';
1.54 www 8906: }
1.53 www 8907: }
1.30 www 8908:
1.1461 raeburn 8909: # Restricted for deeplinked session?
8910:
8911: if ($env{'request.deeplink.login'}) {
8912: if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
8913: if (!$symb) { $symb=&symbread($uri,1); }
8914: if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
8915: return '';
8916: }
8917: }
8918: }
8919:
1.246 www 8920: # Restricted by state or randomout?
1.30 www 8921:
1.52 www 8922: if ($thisallowed=~/X/) {
1.620 albertel 8923: if ($env{'acc.randomout'}) {
1.579 albertel 8924: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8925: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8926: return '';
8927: }
1.247 www 8928: }
8929: if (&condval($statecond)) {
1.52 www 8930: return '2';
8931: } else {
8932: return '';
8933: }
8934: }
1.30 www 8935:
1.766 albertel 8936: if ($thisallowed eq 'A') {
8937: return 'A';
1.814 raeburn 8938: } elsif ($thisallowed eq 'B') {
8939: return 'B';
1.1402 raeburn 8940: } elsif ($thisallowed eq 'D') {
8941: return 'D';
1.766 albertel 8942: }
1.52 www 8943: return 'F';
1.232 www 8944: }
1.1162 raeburn 8945:
1.1192 raeburn 8946: # ------------------------------------------- Check construction space access
8947:
8948: sub constructaccess {
8949: my ($url,$setpriv)=@_;
8950:
8951: # We do not allow editing of previous versions of files
8952: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8953:
8954: # Get username and domain from URL
8955: my ($ownername,$ownerdomain,$ownerhome);
8956:
8957: ($ownerdomain,$ownername) =
1.1325 raeburn 8958: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 8959:
8960: # The URL does not really point to any authorspace, forget it
8961: unless (($ownername) && ($ownerdomain)) { return ''; }
8962:
8963: # Now we need to see if the user has access to the authorspace of
8964: # $ownername at $ownerdomain
8965:
8966: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8967: # Real author for this?
8968: $ownerhome = $env{'user.home'};
8969: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8970: return ($ownername,$ownerdomain,$ownerhome);
8971: }
1.1506 ! raeburn 8972: } elsif (&is_course($ownerdomain,$ownername)) {
! 8973: # Course Authoring Space?
1.1312 raeburn 8974: if ($env{'request.course.id'}) {
8975: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
8976: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
8977: if (&allowed('mdc',$env{'request.course.id'})) {
8978: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
8979: return ($ownername,$ownerdomain,$ownerhome);
8980: }
8981: }
8982: }
1.1506 ! raeburn 8983: return '';
! 8984: } else {
! 8985: # Co-author for this?
! 8986: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
! 8987: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
! 8988: $ownerhome = &homeserver($ownername,$ownerdomain);
! 8989: return ($ownername,$ownerdomain,$ownerhome);
! 8990: }
1.1192 raeburn 8991: }
8992:
8993: # We don't have any access right now. If we are not possibly going to do anything about this,
8994: # we might as well leave
8995: unless ($setpriv) { return ''; }
8996:
8997: # Backdoor access?
8998: my $allowed=&allowed('eco',$ownerdomain);
8999: # Nope
9000: unless ($allowed) { return ''; }
9001: # Looks like we may have access, but could be locked by the owner of the construction space
9002: if ($allowed eq 'U') {
9003: my %blocked=&get('environment',['domcoord.author'],
9004: $ownerdomain,$ownername);
9005: # Is blocked by owner
9006: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
9007: }
9008: if (($allowed eq 'F') || ($allowed eq 'U')) {
9009: # Grant temporary access
9010: my $then=$env{'user.login.time'};
1.1209 raeburn 9011: my $update=$env{'user.update.time'};
1.1192 raeburn 9012: if (!$update) { $update = $then; }
9013: my $refresh=$env{'user.refresh.time'};
9014: if (!$refresh) { $refresh = $update; }
9015: my $now = time;
9016: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
9017: $now,'ca','constructaccess');
9018: $ownerhome = &homeserver($ownername,$ownerdomain);
9019: return($ownername,$ownerdomain,$ownerhome);
9020: }
9021: # No business here
9022: return '';
9023: }
9024:
1.1282 raeburn 9025: # ----------------------------------------------------------- Content Blocking
9026:
9027: {
9028: # Caches for faster Course Contents display where content blocking
9029: # is in operation (i.e., interval param set) for timed quiz.
9030: #
9031: # User for whom data are being temporarily cached.
9032: my $cacheduser='';
1.1424 raeburn 9033: # Course for which data are being temporarily cached.
9034: my $cachedcid='';
1.1282 raeburn 9035: # Cached blockers for this user (a hash of blocking items).
9036: my %cachedblockers=();
9037: # When the data were last cached.
9038: my $cachedlast='';
9039:
9040: sub load_all_blockers {
1.1427 raeburn 9041: my ($uname,$udom)=@_;
1.1282 raeburn 9042: if (($uname ne '') && ($udom ne '')) {
9043: if (($cacheduser eq $uname.':'.$udom) &&
1.1424 raeburn 9044: ($cachedcid eq $env{'request.course.id'}) &&
1.1427 raeburn 9045: (abs($cachedlast-time)<5)) {
1.1282 raeburn 9046: return;
9047: }
9048: }
9049: $cachedlast=time;
9050: $cacheduser=$uname.':'.$udom;
1.1424 raeburn 9051: $cachedcid=$env{'request.course.id'};
1.1427 raeburn 9052: %cachedblockers = &get_commblock_resources();
1.1424 raeburn 9053: return;
1.1282 raeburn 9054: }
9055:
1.1162 raeburn 9056: sub get_comm_blocks {
9057: my ($cdom,$cnum) = @_;
9058: if ($cdom eq '' || $cnum eq '') {
9059: return unless ($env{'request.course.id'});
9060: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9061: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9062: }
9063: my %commblocks;
9064: my $hashid=$cdom.'_'.$cnum;
9065: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
9066: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
9067: %commblocks = %{$blocksref};
9068: } else {
1.1494 raeburn 9069: %commblocks = &dump('comm_block',$cdom,$cnum);
1.1162 raeburn 9070: my $cachetime = 600;
9071: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
9072: }
9073: return %commblocks;
9074: }
9075:
1.1282 raeburn 9076: sub get_commblock_resources {
9077: my ($blocks) = @_;
9078: my %blockers = ();
9079: return %blockers unless ($env{'request.course.id'});
1.1470 raeburn 9080: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9081: if ($env{'request.course.sec'}) {
9082: $courseurl .= '/'.$env{'request.course.sec'};
9083: }
9084: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162 raeburn 9085: my %commblocks;
9086: if (ref($blocks) eq 'HASH') {
9087: %commblocks = %{$blocks};
9088: } else {
9089: %commblocks = &get_comm_blocks();
9090: }
1.1282 raeburn 9091: return %blockers unless (keys(%commblocks) > 0);
9092: my $navmap = Apache::lonnavmaps::navmap->new();
9093: return %blockers unless (ref($navmap));
1.1162 raeburn 9094: my $now = time;
9095: foreach my $block (keys(%commblocks)) {
9096: if ($block =~ /^(\d+)____(\d+)$/) {
9097: my ($start,$end) = ($1,$2);
9098: if ($start <= $now && $end >= $now) {
9099: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
9100: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
9101: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 9102: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9103: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 9104: }
9105: }
9106: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 9107: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9108: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 9109: }
9110: }
9111: }
9112: }
9113: }
9114: } elsif ($block =~ /^firstaccess____(.+)$/) {
9115: my $item = $1;
9116: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
9117: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1471 raeburn 9118: my (@interval,$mapname);
1.1282 raeburn 9119: my $type = 'map';
9120: if ($item eq 'course') {
9121: $type = 'course';
9122: @interval=&EXT("resource.0.interval");
9123: } else {
9124: if ($item =~ /___\d+___/) {
9125: $type = 'resource';
9126: @interval=&EXT("resource.0.interval",$item);
1.1162 raeburn 9127: } else {
1.1471 raeburn 9128: $mapname = &deversion($item);
9129: if (ref($navmap)) {
9130: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
9131: @interval = ($timelimit,'map');
1.1162 raeburn 9132: }
9133: }
1.1282 raeburn 9134: }
1.1310 raeburn 9135: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 9136: my $timelimit = $1;
1.1282 raeburn 9137: my $first_access;
9138: if ($type eq 'resource') {
9139: $first_access=&get_first_access($interval[1],$item);
9140: } elsif ($type eq 'map') {
9141: $first_access=&get_first_access($interval[1],undef,$item);
9142: } else {
9143: $first_access=&get_first_access($interval[1]);
9144: }
9145: if ($first_access) {
1.1292 raeburn 9146: my $timesup = $first_access+$timelimit;
1.1282 raeburn 9147: if ($timesup > $now) {
9148: my $activeblock;
1.1471 raeburn 9149: if ($type eq 'resource') {
9150: if (ref($navmap)) {
9151: my $res = $navmap->getBySymb($item);
9152: if ($res->answerable()) {
9153: $activeblock = 1;
9154: }
9155: }
9156: } elsif ($type eq 'map') {
9157: my $mapsymb = &symbread($mapname,1);
9158: if (($mapsymb) && (ref($navmap))) {
9159: my $mapres = $navmap->getBySymb($mapsymb);
9160: if (ref($mapres)) {
9161: my $first = $mapres->map_start();
9162: my $finish = $mapres->map_finish();
9163: my $it = $navmap->getIterator($first,$finish,undef,0,0);
9164: if (ref($it)) {
9165: my $res;
9166: while ($res = $it->next(undef,1)) {
9167: next unless (ref($res));
9168: my $symb = $res->symb();
9169: next if (($symb eq $mapsymb) || ($symb eq ''));
9170: @interval=&EXT("resource.0.interval",$symb);
9171: if ($interval[1] eq 'map') {
9172: if ($res->answerable()) {
9173: $activeblock = 1;
9174: last;
9175: }
9176: }
9177: }
9178: }
9179: }
1.1282 raeburn 9180: }
9181: }
9182: if ($activeblock) {
9183: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
9184: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9185: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
9186: }
9187: }
9188: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
9189: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9190: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 9191: }
1.1162 raeburn 9192: }
9193: }
9194: }
9195: }
9196: }
9197: }
9198: }
9199: }
9200: }
1.1282 raeburn 9201: return %blockers;
1.1162 raeburn 9202: }
9203:
1.1282 raeburn 9204: sub has_comm_blocking {
1.1427 raeburn 9205: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282 raeburn 9206: my @blockers;
9207: return unless ($env{'request.course.id'});
9208: return unless ($priv eq 'bre');
9209: return if ($env{'request.state'} eq 'construct');
1.1470 raeburn 9210: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9211: if ($env{'request.course.sec'}) {
9212: $courseurl .= '/'.$env{'request.course.sec'};
9213: }
9214: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1427 raeburn 9215: my %blockinfo;
9216: if (ref($blocks) eq 'HASH') {
9217: %blockinfo = &get_commblock_resources($blocks);
9218: } else {
9219: &load_all_blockers($env{'user.name'},$env{'user.domain'});
9220: %blockinfo = %cachedblockers;
9221: }
9222: return unless (keys(%blockinfo) > 0);
1.1282 raeburn 9223: my (%possibles,@symbs);
9224: if (!$symb) {
1.1427 raeburn 9225: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 9226: }
1.1282 raeburn 9227: if ($symb) {
9228: @symbs = ($symb);
9229: } elsif (keys(%possibles)) {
9230: @symbs = keys(%possibles);
9231: }
9232: my $noblock;
9233: foreach my $symb (@symbs) {
9234: last if ($noblock);
9235: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427 raeburn 9236: foreach my $block (keys(%blockinfo)) {
1.1282 raeburn 9237: if ($block =~ /^firstaccess____(.+)$/) {
9238: my $item = $1;
1.1424 raeburn 9239: unless ($blocked) {
9240: if (($item eq $map) || ($item eq $symb)) {
9241: $noblock = 1;
9242: last;
9243: }
1.1282 raeburn 9244: }
9245: }
1.1427 raeburn 9246: if (ref($blockinfo{$block}) eq 'HASH') {
9247: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
9248: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282 raeburn 9249: unless (grep(/^\Q$block\E$/,@blockers)) {
9250: push(@blockers,$block);
9251: }
9252: }
9253: }
1.1427 raeburn 9254: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
9255: if ($blockinfo{$block}{'maps'}{$map}) {
1.1424 raeburn 9256: unless (grep(/^\Q$block\E$/,@blockers)) {
9257: push(@blockers,$block);
9258: }
1.1282 raeburn 9259: }
9260: }
1.1162 raeburn 9261: }
9262: }
9263: }
1.1424 raeburn 9264: unless ($noblock) {
9265: return @blockers;
9266: }
9267: return;
1.1282 raeburn 9268: }
1.1162 raeburn 9269: }
9270:
1.1402 raeburn 9271: sub deeplink_check {
9272: my ($priv,$symb,$uri) = @_;
9273: return unless ($env{'request.course.id'});
9274: return unless ($priv eq 'bre');
9275: return if ($env{'request.state'} eq 'construct');
9276: return if ($env{'request.role.adv'});
9277: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9278: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9279: my (%possibles,@symbs);
9280: if (!$symb) {
9281: $symb = &symbread($uri,1,1,1,\%possibles);
9282: }
9283: if ($symb) {
9284: @symbs = ($symb);
9285: } elsif (keys(%possibles)) {
9286: @symbs = keys(%possibles);
9287: }
9288:
1.1461 raeburn 9289: my ($deeplink_symb,$allow);
9290: if ($env{'request.deeplink.login'}) {
9291: $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1.1402 raeburn 9292: }
9293: foreach my $symb (@symbs) {
9294: last if ($allow);
9295: my $deeplink = &EXT("resource.0.deeplink",$symb);
9296: if ($deeplink eq '') {
9297: $allow = 1;
9298: } else {
1.1463 raeburn 9299: my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
9300: if ($state ne 'only') {
1.1402 raeburn 9301: $allow = 1;
1.1463 raeburn 9302: } else {
9303: my $check_deeplink_entry;
9304: if ($protect ne 'none') {
9305: my ($acctype,$item) = split(/:/,$protect);
9306: if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
9307: if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
9308: $check_deeplink_entry = 1
9309: }
9310: } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
9311: if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
9312: $check_deeplink_entry = 1;
9313: }
9314: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
9315: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
9316: $check_deeplink_entry = 1;
9317: }
9318: }
9319: }
9320: if (($protect eq 'none') || ($check_deeplink_entry)) {
1.1402 raeburn 9321: if ($scope eq 'res') {
1.1461 raeburn 9322: if ($symb eq $deeplink_symb) {
1.1402 raeburn 9323: $allow = 1;
9324: }
1.1459 raeburn 9325: } elsif (($scope eq 'map') || ($scope eq 'rec')) {
1.1463 raeburn 9326: my ($map_from_symb,$map_from_login);
1.1461 raeburn 9327: $map_from_symb = &deversion((&decode_symb($symb))[0]);
9328: if ($deeplink_symb =~ /\.(page|sequence)$/) {
9329: $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
9330: } else {
9331: $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
9332: }
1.1459 raeburn 9333: if (($map_from_symb) && ($map_from_login)) {
9334: if ($map_from_symb eq $map_from_login) {
9335: $allow = 1;
9336: } elsif ($scope eq 'rec') {
9337: my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
9338: if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
9339: $allow = 1;
9340: }
9341: }
9342: }
1.1402 raeburn 9343: }
9344: }
9345: }
9346: }
9347: }
9348: return if ($allow);
9349: return 1;
9350: }
9351:
1.1282 raeburn 9352: # -------------------------------- Deversion and split uri into path an filename
9353:
1.1133 foxr 9354: #
1.1282 raeburn 9355: # Removes the version from a URI and
1.1133 foxr 9356: # splits it in to its filename and path to the filename.
9357: # Seems like File::Basename could have done this more clearly.
9358: # Parameters:
9359: # $uri - input URI
9360: # Returns:
9361: # Two element list consisting of
9362: # $pathname - the URI up to and excluding the trailing /
9363: # $filename - The part of the URI following the last /
9364: # NOTE:
9365: # Another realization of this is simply:
9366: # use File::Basename;
9367: # ...
9368: # $uri = shift;
9369: # $filename = basename($uri);
9370: # $path = dirname($uri);
9371: # return ($filename, $path);
9372: #
9373: # The implementation below is probably faster however.
9374: #
1.710 albertel 9375: sub split_uri_for_cond {
9376: my $uri=&deversion(&declutter(shift));
9377: my @uriparts=split(/\//,$uri);
9378: my $filename=pop(@uriparts);
9379: my $pathname=join('/',@uriparts);
9380: return ($pathname,$filename);
9381: }
1.232 www 9382: # --------------------------------------------------- Is a resource on the map?
9383:
9384: sub is_on_map {
1.710 albertel 9385: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 9386: #Trying to find the conditional for the file
1.620 albertel 9387: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 9388: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 9389: if ($match) {
1.289 bowersj2 9390: return (1,$1);
9391: } else {
1.434 www 9392: return (0,0);
1.289 bowersj2 9393: }
1.12 www 9394: }
9395:
1.427 www 9396: # --------------------------------------------------------- Get symb from alias
9397:
9398: sub get_symb_from_alias {
9399: my $symb=shift;
9400: my ($map,$resid,$url)=&decode_symb($symb);
9401: # Already is a symb
9402: if ($url) { return $symb; }
9403: # Must be an alias
9404: my $aliassymb='';
9405: my %bighash;
1.620 albertel 9406: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 9407: &GDBM_READER(),0640)) {
9408: my $rid=$bighash{'mapalias_'.$symb};
9409: if ($rid) {
9410: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 9411: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9412: $resid,$bighash{'src_'.$rid});
1.427 www 9413: }
9414: untie %bighash;
9415: }
9416: return $aliassymb;
9417: }
9418:
1.12 www 9419: # ----------------------------------------------------------------- Define Role
9420:
9421: sub definerole {
9422: if (allowed('mcr','/')) {
1.1326 raeburn 9423: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 9424: foreach my $role (split(':',$sysrole)) {
9425: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9426: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9427: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9428: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9429: return "refused:s:$crole&$cqual";
9430: }
9431: }
1.191 harris41 9432: }
1.800 albertel 9433: foreach my $role (split(':',$domrole)) {
9434: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9435: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9436: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9437: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 9438: return "refused:d:$crole&$cqual";
9439: }
9440: }
1.191 harris41 9441: }
1.800 albertel 9442: foreach my $role (split(':',$courole)) {
9443: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9444: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9445: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9446: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9447: return "refused:c:$crole&$cqual";
9448: }
9449: }
1.191 harris41 9450: }
1.1326 raeburn 9451: my $uhome;
9452: if (($uname ne '') && ($udom ne '')) {
9453: $uhome = &homeserver($uname,$udom);
9454: return $uhome if ($uhome eq 'no_host');
9455: } else {
9456: $uname = $env{'user.name'};
9457: $udom = $env{'user.domain'};
9458: $uhome = $env{'user.home'};
9459: }
1.620 albertel 9460: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 9461: "$udom:$uname:rolesdef_$rolename=".
1.21 www 9462: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 9463: return reply($command,$uhome);
1.12 www 9464: } else {
9465: return 'refused';
9466: }
1.105 harris41 9467: }
9468:
9469: # ---------------- Make a metadata query against the network of library servers
9470:
9471: sub metadata_query {
1.1237 raeburn 9472: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 9473: my %rhash;
1.845 albertel 9474: my %libserv = &all_library();
1.244 matthew 9475: my @server_list = (defined($server_array) ? @$server_array
9476: : keys(%libserv) );
9477: for my $server (@server_list) {
1.1237 raeburn 9478: my $domains = '';
9479: if (ref($domains_hash) eq 'HASH') {
9480: $domains = $domains_hash->{$server};
9481: }
1.118 harris41 9482: unless ($custom or $customshow) {
1.1237 raeburn 9483: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 9484: $rhash{$server}=$reply;
9485: }
9486: else {
9487: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 9488: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 9489: $server);
9490: $rhash{$server}=$reply;
9491: }
1.112 harris41 9492: }
1.118 harris41 9493: return \%rhash;
1.240 www 9494: }
9495:
9496: # ----------------------------------------- Send log queries and wait for reply
9497:
9498: sub log_query {
9499: my ($uname,$udom,$query,%filters)=@_;
9500: my $uhome=&homeserver($uname,$udom);
9501: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 9502: my $uhost=&hostname($uhome);
1.800 albertel 9503: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 9504: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9505: $uhome);
1.479 albertel 9506: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 9507: return get_query_reply($queryid);
9508: }
9509:
1.818 raeburn 9510: # -------------------------- Update MySQL table for portfolio file
9511:
9512: sub update_portfolio_table {
1.821 raeburn 9513: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 9514: if ($group ne '') {
9515: $file_name =~s /^\Q$group\E//;
9516: }
1.818 raeburn 9517: my $homeserver = &homeserver($uname,$udom);
9518: my $queryid=
1.821 raeburn 9519: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9520: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 9521: my $reply = &get_query_reply($queryid);
9522: return $reply;
9523: }
9524:
1.899 raeburn 9525: # -------------------------- Update MySQL allusers table
9526:
9527: sub update_allusers_table {
9528: my ($uname,$udom,$names) = @_;
9529: my $homeserver = &homeserver($uname,$udom);
9530: my $queryid=
9531: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9532: 'lastname='.&escape($names->{'lastname'}).'%%'.
9533: 'firstname='.&escape($names->{'firstname'}).'%%'.
9534: 'middlename='.&escape($names->{'middlename'}).'%%'.
9535: 'generation='.&escape($names->{'generation'}).'%%'.
9536: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9537: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 9538: return;
1.899 raeburn 9539: }
9540:
1.508 raeburn 9541: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 9542:
9543: sub fetch_enrollment_query {
1.511 raeburn 9544: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 9545: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 9546: my $maxtries = 1;
1.508 raeburn 9547: if ($context eq 'automated') {
9548: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 9549: $sleep = 2;
9550: $loopmax = 100;
1.547 raeburn 9551: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 9552: } else {
9553: $homeserver = &homeserver($cnum,$dom);
9554: }
1.838 albertel 9555: my $host=&hostname($homeserver);
1.506 raeburn 9556: my $cmd = '';
1.1000 raeburn 9557: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9558: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9559: }
9560: $cmd =~ s/%%$//;
9561: $cmd = &escape($cmd);
9562: my $query = 'fetchenrollment';
1.620 albertel 9563: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9564: unless ($queryid=~/^\Q$host\E\_/) {
9565: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9566: return 'error: '.$queryid;
9567: }
1.1317 raeburn 9568: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9569: my $tries = 1;
9570: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 9571: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9572: $tries ++;
9573: }
1.526 raeburn 9574: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9575: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9576: } else {
1.901 albertel 9577: my @responses = split(/:/,$reply);
1.1322 raeburn 9578: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9579: foreach my $line (@responses) {
9580: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9581: $$replyref{$key} = $value;
9582: }
9583: } else {
1.1117 foxr 9584: my $pathname = LONCAPA::tempdir();
1.800 albertel 9585: foreach my $line (@responses) {
9586: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9587: $$replyref{$key} = $value;
9588: if ($value > 0) {
1.800 albertel 9589: foreach my $item (@{$$affiliatesref{$key}}) {
9590: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9591: my $destname = $pathname.'/'.$filename;
9592: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9593: if ($xml_classlist =~ /^error/) {
9594: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9595: } else {
1.1359 raeburn 9596: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9597: print FILE &unescape($xml_classlist);
9598: close(FILE);
1.526 raeburn 9599: } else {
9600: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9601: }
9602: }
9603: }
9604: }
9605: }
9606: }
9607: return 'ok';
9608: }
9609: return 'error';
9610: }
9611:
1.242 www 9612: sub get_query_reply {
1.1471 raeburn 9613: my ($queryid,$sleep,$loopmax) = @_;
1.1317 raeburn 9614: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9615: $sleep = 0.2;
9616: }
9617: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9618: $loopmax = 100;
9619: }
1.1117 foxr 9620: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9621: my $reply='';
1.1317 raeburn 9622: for (1..$loopmax) {
9623: sleep($sleep);
1.240 www 9624: if (-e $replyfile.'.end') {
1.1359 raeburn 9625: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9626: $reply = join('',<$fh>);
9627: close($fh);
1.240 www 9628: } else { return 'error: reply_file_error'; }
1.242 www 9629: return &unescape($reply);
9630: }
1.240 www 9631: }
1.242 www 9632: return 'timeout:'.$queryid;
1.240 www 9633: }
9634:
9635: sub courselog_query {
1.241 www 9636: #
9637: # possible filters:
9638: # url: url or symb
9639: # username
9640: # domain
9641: # action: view, submit, grade
9642: # start: timestamp
9643: # end: timestamp
9644: #
1.240 www 9645: my (%filters)=@_;
1.620 albertel 9646: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9647: if ($filters{'url'}) {
9648: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9649: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9650: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9651: }
1.620 albertel 9652: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9653: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9654: return &log_query($cname,$cdom,'courselog',%filters);
9655: }
9656:
9657: sub userlog_query {
1.858 raeburn 9658: #
9659: # possible filters:
9660: # action: log check role
9661: # start: timestamp
9662: # end: timestamp
9663: #
1.240 www 9664: my ($uname,$udom,%filters)=@_;
9665: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9666: }
9667:
1.506 raeburn 9668: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9669:
9670: sub auto_run {
1.508 raeburn 9671: my ($cnum,$cdom) = @_;
1.876 raeburn 9672: my $response = 0;
9673: my $settings;
9674: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9675: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9676: $settings = $domconfig{'autoenroll'};
9677: if ($settings->{'run'} eq '1') {
9678: $response = 1;
9679: }
9680: } else {
1.934 raeburn 9681: my $homeserver;
9682: if (&is_course($cdom,$cnum)) {
9683: $homeserver = &homeserver($cnum,$cdom);
9684: } else {
9685: $homeserver = &domain($cdom,'primary');
9686: }
9687: if ($homeserver ne 'no_host') {
9688: $response = &reply('autorun:'.$cdom,$homeserver);
9689: }
1.876 raeburn 9690: }
1.506 raeburn 9691: return $response;
9692: }
1.776 albertel 9693:
1.506 raeburn 9694: sub auto_get_sections {
1.508 raeburn 9695: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9696: my $homeserver;
9697: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9698: $homeserver = &homeserver($cnum,$cdom);
9699: }
9700: if (!defined($homeserver)) {
9701: if ($cdom =~ /^$match_domain$/) {
9702: $homeserver = &domain($cdom,'primary');
9703: }
9704: }
9705: my @secs;
9706: if (defined($homeserver)) {
9707: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9708: unless ($response eq 'refused') {
9709: @secs = split(/:/,$response);
9710: }
1.506 raeburn 9711: }
9712: return @secs;
9713: }
1.776 albertel 9714:
1.506 raeburn 9715: sub auto_new_course {
1.1099 raeburn 9716: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9717: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9718: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9719: return $response;
9720: }
1.776 albertel 9721:
1.506 raeburn 9722: sub auto_validate_courseID {
1.508 raeburn 9723: my ($cnum,$cdom,$inst_course_id) = @_;
9724: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9725: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9726: return $response;
9727: }
1.776 albertel 9728:
1.1007 raeburn 9729: sub auto_validate_instcode {
1.1020 raeburn 9730: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9731: my ($homeserver,$response);
9732: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9733: $homeserver = &homeserver($cnum,$cdom);
9734: }
9735: if (!defined($homeserver)) {
9736: if ($cdom =~ /^$match_domain$/) {
9737: $homeserver = &domain($cdom,'primary');
9738: }
9739: }
1.1065 raeburn 9740: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9741: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 9742: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9743: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9744: }
9745:
1.1444 raeburn 9746: sub auto_validate_inst_crosslist {
9747: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9748: my ($homeserver,$response);
9749: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9750: $homeserver = &homeserver($cnum,$cdom);
9751: }
9752: if (!defined($homeserver)) {
9753: if ($cdom =~ /^$match_domain$/) {
9754: $homeserver = &domain($cdom,'primary');
9755: }
9756: }
9757: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9758: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9759: &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445 raeburn 9760: &escape($coowner),$homeserver);
1.1444 raeburn 9761: }
9762: return $response;
9763: }
9764:
1.506 raeburn 9765: sub auto_create_password {
1.873 raeburn 9766: my ($cnum,$cdom,$authparam,$udom) = @_;
9767: my ($homeserver,$response);
1.506 raeburn 9768: my $create_passwd = 0;
9769: my $authchk = '';
1.873 raeburn 9770: if ($udom =~ /^$match_domain$/) {
9771: $homeserver = &domain($udom,'primary');
9772: }
9773: if ($homeserver eq '') {
9774: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9775: $homeserver = &homeserver($cnum,$cdom);
9776: }
9777: }
9778: if ($homeserver eq '') {
9779: $authchk = 'nodomain';
1.506 raeburn 9780: } else {
1.873 raeburn 9781: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9782: if ($response eq 'refused') {
9783: $authchk = 'refused';
9784: } else {
1.901 albertel 9785: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9786: }
1.506 raeburn 9787: }
9788: return ($authparam,$create_passwd,$authchk);
9789: }
9790:
1.706 raeburn 9791: sub auto_photo_permission {
9792: my ($cnum,$cdom,$students) = @_;
9793: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9794: my ($outcome,$perm_reqd,$conditions) =
9795: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9796: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9797: return (undef,undef);
9798: }
1.706 raeburn 9799: return ($outcome,$perm_reqd,$conditions);
9800: }
9801:
9802: sub auto_checkphotos {
9803: my ($uname,$udom,$pid) = @_;
9804: my $homeserver = &homeserver($uname,$udom);
9805: my ($result,$resulttype);
9806: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9807: &escape($uname).':'.&escape($pid),
9808: $homeserver));
1.709 albertel 9809: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9810: return (undef,undef);
9811: }
1.706 raeburn 9812: if ($outcome) {
9813: ($result,$resulttype) = split(/:/,$outcome);
9814: }
9815: return ($result,$resulttype);
9816: }
9817:
9818: sub auto_photochoice {
9819: my ($cnum,$cdom) = @_;
9820: my $homeserver = &homeserver($cnum,$cdom);
9821: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9822: &escape($cdom),
9823: $homeserver)));
1.709 albertel 9824: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9825: return (undef,undef);
9826: }
1.706 raeburn 9827: return ($update,$comment);
9828: }
9829:
9830: sub auto_photoupdate {
9831: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9832: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9833: my $host=&hostname($homeserver);
1.706 raeburn 9834: my $cmd = '';
9835: my $maxtries = 1;
1.800 albertel 9836: foreach my $affiliate (keys(%{$affiliatesref})) {
9837: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9838: }
9839: $cmd =~ s/%%$//;
9840: $cmd = &escape($cmd);
9841: my $query = 'institutionalphotos';
9842: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9843: unless ($queryid=~/^\Q$host\E\_/) {
9844: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9845: return 'error: '.$queryid;
9846: }
9847: my $reply = &get_query_reply($queryid);
9848: my $tries = 1;
9849: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9850: $reply = &get_query_reply($queryid);
9851: $tries ++;
9852: }
9853: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9854: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9855: } else {
9856: my @responses = split(/:/,$reply);
9857: my $outcome = shift(@responses);
9858: foreach my $item (@responses) {
9859: my ($key,$value) = split(/=/,$item);
9860: $$photo{$key} = $value;
9861: }
9862: return $outcome;
9863: }
9864: return 'error';
9865: }
9866:
1.521 raeburn 9867: sub auto_instcode_format {
1.793 albertel 9868: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9869: $cat_order) = @_;
1.521 raeburn 9870: my $courses = '';
1.772 raeburn 9871: my @homeservers;
1.521 raeburn 9872: if ($caller eq 'global') {
1.841 albertel 9873: my %servers = &get_servers($codedom,'library');
9874: foreach my $tryserver (keys(%servers)) {
9875: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9876: push(@homeservers,$tryserver);
9877: }
1.584 raeburn 9878: }
1.1022 raeburn 9879: } elsif ($caller eq 'requests') {
9880: if ($codedom =~ /^$match_domain$/) {
9881: my $chome = &domain($codedom,'primary');
9882: unless ($chome eq 'no_host') {
9883: push(@homeservers,$chome);
9884: }
9885: }
1.521 raeburn 9886: } else {
1.772 raeburn 9887: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9888: }
1.793 albertel 9889: foreach my $code (keys(%{$instcodes})) {
9890: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9891: }
9892: chop($courses);
1.772 raeburn 9893: my $ok_response = 0;
9894: my $response;
9895: while (@homeservers > 0 && $ok_response == 0) {
9896: my $server = shift(@homeservers);
9897: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9898: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9899: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9900: split(/:/,$response);
1.772 raeburn 9901: %{$codes} = (%{$codes},&str2hash($codes_str));
9902: push(@{$codetitles},&str2array($codetitles_str));
9903: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9904: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9905: $ok_response = 1;
9906: }
9907: }
9908: if ($ok_response) {
1.521 raeburn 9909: return 'ok';
1.772 raeburn 9910: } else {
9911: return $response;
1.521 raeburn 9912: }
9913: }
9914:
1.792 raeburn 9915: sub auto_instcode_defaults {
9916: my ($domain,$returnhash,$code_order) = @_;
9917: my @homeservers;
1.841 albertel 9918:
9919: my %servers = &get_servers($domain,'library');
9920: foreach my $tryserver (keys(%servers)) {
9921: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9922: push(@homeservers,$tryserver);
9923: }
1.792 raeburn 9924: }
1.841 albertel 9925:
1.792 raeburn 9926: my $response;
1.841 albertel 9927: foreach my $server (@homeservers) {
1.792 raeburn 9928: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9929: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9930:
9931: foreach my $pair (split(/\&/,$response)) {
9932: my ($name,$value)=split(/\=/,$pair);
9933: if ($name eq 'code_order') {
9934: @{$code_order} = split(/\&/,&unescape($value));
9935: } else {
9936: $returnhash->{&unescape($name)}=&unescape($value);
9937: }
9938: }
9939: return 'ok';
1.792 raeburn 9940: }
1.841 albertel 9941:
9942: return $response;
1.1003 raeburn 9943: }
9944:
9945: sub auto_possible_instcodes {
1.1007 raeburn 9946: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9947: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9948: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9949: return;
9950: }
1.1003 raeburn 9951: my (@homeservers,$uhome);
9952: if (defined(&domain($domain,'primary'))) {
9953: $uhome=&domain($domain,'primary');
9954: push(@homeservers,&domain($domain,'primary'));
9955: } else {
9956: my %servers = &get_servers($domain,'library');
9957: foreach my $tryserver (keys(%servers)) {
9958: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9959: push(@homeservers,$tryserver);
9960: }
9961: }
9962: }
9963: my $response;
9964: foreach my $server (@homeservers) {
9965: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9966: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9967: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9968: split(':',$response);
9969: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9970: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9971: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9972: my ($name,$value)=split('=',$item);
9973: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9974: }
9975: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9976: my ($name,$value)=split('=',$item);
9977: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9978: }
9979: return 'ok';
9980: }
9981: return $response;
9982: }
1.792 raeburn 9983:
1.1010 raeburn 9984: sub auto_courserequest_checks {
9985: my ($dom) = @_;
1.1020 raeburn 9986: my ($homeserver,%validations);
9987: if ($dom =~ /^$match_domain$/) {
9988: $homeserver = &domain($dom,'primary');
9989: }
9990: unless ($homeserver eq 'no_host') {
9991: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9992: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9993: my @items = split(/&/,$response);
9994: foreach my $item (@items) {
9995: my ($key,$value) = split('=',$item);
9996: $validations{&unescape($key)} = &thaw_unescape($value);
9997: }
9998: }
9999: }
1.1010 raeburn 10000: return %validations;
10001: }
10002:
1.1020 raeburn 10003: sub auto_courserequest_validation {
1.1255 raeburn 10004: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 10005: my ($homeserver,$response);
10006: if ($dom =~ /^$match_domain$/) {
10007: $homeserver = &domain($dom,'primary');
10008: }
1.1255 raeburn 10009: unless ($homeserver eq 'no_host') {
10010: my $customdata;
10011: if (ref($custominfo) eq 'HASH') {
10012: $customdata = &freeze_escape($custominfo);
10013: }
1.1020 raeburn 10014: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 10015: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 10016: ':'.&escape($instcode).':'.&escape($instseclist).':'.
10017: $customdata,$homeserver));
1.1020 raeburn 10018: }
10019: return $response;
10020: }
10021:
1.777 albertel 10022: sub auto_validate_class_sec {
1.918 raeburn 10023: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 10024: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 10025: my $ownerlist;
10026: if (ref($owners) eq 'ARRAY') {
10027: $ownerlist = join(',',@{$owners});
10028: } else {
10029: $ownerlist = $owners;
10030: }
1.773 raeburn 10031: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 10032: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 10033: return $response;
10034: }
10035:
1.1460 raeburn 10036: sub auto_instsec_reformat {
10037: my ($cdom,$action,$instsecref) = @_;
10038: return unless(($action eq 'clutter') || ($action eq 'declutter'));
10039: my @homeservers;
10040: if (defined(&domain($cdom,'primary'))) {
10041: push(@homeservers,&domain($cdom,'primary'));
10042: } else {
10043: my %servers = &get_servers($cdom,'library');
10044: foreach my $tryserver (keys(%servers)) {
10045: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10046: push(@homeservers,$tryserver);
10047: }
10048: }
10049: }
10050: my $response;
10051: my %reformatted = %{$instsecref};
10052: foreach my $server (@homeservers) {
10053: if (ref($instsecref) eq 'HASH') {
10054: my $info = &freeze_escape($instsecref);
10055: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10056: $action.':'.$info,$server);
10057: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
10058: my @items = split(/&/,$response);
10059: foreach my $item (@items) {
10060: my ($key,$value) = split(/=/,$item);
10061: $reformatted{&unescape($key)} = &thaw_unescape($value);
10062: }
10063: }
10064: }
10065: return %reformatted;
10066: }
10067:
1.1367 raeburn 10068: sub auto_validate_instclasses {
10069: my ($cdom,$cnum,$owners,$classesref) = @_;
10070: my ($homeserver,%validations);
10071: $homeserver = &homeserver($cnum,$cdom);
10072: unless ($homeserver eq 'no_host') {
10073: my $ownerlist;
10074: if (ref($owners) eq 'ARRAY') {
10075: $ownerlist = join(',',@{$owners});
10076: } else {
10077: $ownerlist = $owners;
10078: }
10079: if (ref($classesref) eq 'HASH') {
10080: my $classes = &freeze_escape($classesref);
10081: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10082: ':'.$cdom.':'.$classes,$homeserver);
10083: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10084: my @items = split(/&/,$response);
10085: foreach my $item (@items) {
10086: my ($key,$value) = split('=',$item);
10087: $validations{&unescape($key)} = &thaw_unescape($value);
10088: }
10089: }
10090: }
10091: }
10092: return %validations;
10093: }
10094:
1.1248 raeburn 10095: sub auto_crsreq_update {
10096: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 10097: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 10098: my ($homeserver,%crsreqresponse);
10099: if ($cdom =~ /^$match_domain$/) {
10100: $homeserver = &domain($cdom,'primary');
10101: }
10102: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10103: my $info;
10104: if (ref($inbound) eq 'HASH') {
10105: $info = &freeze_escape($inbound);
10106: }
10107: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10108: ':'.&escape($action).':'.&escape($ownername).':'.
10109: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 10110: &escape($title).':'.&escape($code).':'.
10111: &escape($accessstart).':'.&escape($accessend).':'.$info,
10112: $homeserver);
1.1248 raeburn 10113: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10114: my @items = split(/&/,$response);
10115: foreach my $item (@items) {
10116: my ($key,$value) = split('=',$item);
10117: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10118: }
10119: }
10120: }
10121: return \%crsreqresponse;
10122: }
10123:
1.1305 raeburn 10124: sub auto_export_grades {
1.1309 raeburn 10125: my ($cdom,$cnum,$inforef,$gradesref) = @_;
10126: my ($homeserver,%exportresponse);
10127: if ($cdom =~ /^$match_domain$/) {
10128: $homeserver = &domain($cdom,'primary');
10129: }
10130: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10131: my $info;
10132: if (ref($inforef) eq 'HASH') {
10133: $info = &freeze_escape($inforef);
10134: }
10135: if (ref($gradesref) eq 'HASH') {
10136: my $grades = &freeze_escape($gradesref);
10137: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10138: $info.':'.$grades,$homeserver);
10139: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10140: my @items = split(/&/,$response);
10141: foreach my $item (@items) {
10142: my ($key,$value) = split('=',$item);
10143: $exportresponse{&unescape($key)} = &thaw_unescape($value);
10144: }
10145: }
10146: }
10147: }
10148: return \%exportresponse;
1.1305 raeburn 10149: }
10150:
1.1287 raeburn 10151: sub check_instcode_cloning {
10152: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10153: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10154: return;
10155: }
10156: my $canclone;
10157: if (@{$code_order} > 0) {
10158: my $instcoderegexp ='^';
10159: my @clonecodes = split(/\&/,$cloner);
10160: foreach my $item (@{$code_order}) {
10161: if (grep(/^\Q$item\E=/,@clonecodes)) {
10162: foreach my $pair (@clonecodes) {
10163: my ($key,$val) = split(/\=/,$pair,2);
10164: $val = &unescape($val);
10165: if ($key eq $item) {
10166: $instcoderegexp .= '('.$val.')';
10167: last;
10168: }
10169: }
10170: } else {
10171: $instcoderegexp .= $codedefaults->{$item};
10172: }
10173: }
10174: $instcoderegexp .= '$';
10175: my (@from,@to);
10176: eval {
10177: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10178: (@to) = ($clonetocode =~ /$instcoderegexp/);
10179: };
10180: if ((@from > 0) && (@to > 0)) {
10181: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10182: if (!@diffs) {
10183: $canclone = 1;
10184: }
10185: }
10186: }
10187: return $canclone;
10188: }
10189:
10190: sub default_instcode_cloning {
10191: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10192: my (%codedefaults,@code_order,$canclone);
10193: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10194: %codedefaults = %{$codedefaultsref};
10195: @code_order = @{$codeorderref};
10196: } elsif ($clonedom) {
10197: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10198: }
10199: if (($domdefclone) && (@code_order)) {
10200: my @clonecodes = split(/\+/,$domdefclone);
10201: my $instcoderegexp ='^';
10202: foreach my $item (@code_order) {
10203: if (grep(/^\Q$item\E$/,@clonecodes)) {
10204: $instcoderegexp .= '('.$codedefaults{$item}.')';
10205: } else {
10206: $instcoderegexp .= $codedefaults{$item};
10207: }
10208: }
10209: $instcoderegexp .= '$';
10210: my (@from,@to);
10211: eval {
10212: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10213: (@to) = ($clonetocode =~ /$instcoderegexp/);
10214: };
10215: if ((@from > 0) && (@to > 0)) {
10216: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10217: if (!@diffs) {
10218: $canclone = 1;
10219: }
10220: }
10221: }
10222: return $canclone;
10223: }
10224:
1.679 raeburn 10225: # ------------------------------------------------------- Course Group routines
10226:
10227: sub get_coursegroups {
1.809 raeburn 10228: my ($cdom,$cnum,$group,$namespace) = @_;
10229: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 10230: }
10231:
1.679 raeburn 10232: sub modify_coursegroup {
10233: my ($cdom,$cnum,$groupsettings) = @_;
10234: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10235: }
10236:
1.809 raeburn 10237: sub toggle_coursegroup_status {
10238: my ($cdom,$cnum,$group,$action) = @_;
10239: my ($from_namespace,$to_namespace);
10240: if ($action eq 'delete') {
10241: $from_namespace = 'coursegroups';
10242: $to_namespace = 'deleted_groups';
10243: } else {
10244: $from_namespace = 'deleted_groups';
10245: $to_namespace = 'coursegroups';
10246: }
10247: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 10248: if (my $tmp = &error(%curr_group)) {
10249: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10250: return ('read error',$tmp);
10251: } else {
10252: my %savedsettings = %curr_group;
1.809 raeburn 10253: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 10254: my $deloutcome;
10255: if ($result eq 'ok') {
1.809 raeburn 10256: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 10257: } else {
10258: return ('write error',$result);
10259: }
10260: if ($deloutcome eq 'ok') {
10261: return 'ok';
10262: } else {
10263: return ('delete error',$deloutcome);
10264: }
10265: }
10266: }
10267:
1.679 raeburn 10268: sub modify_group_roles {
1.957 raeburn 10269: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 10270: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10271: my $role = 'gr/'.&escape($userprivs);
10272: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 10273: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 10274: if ($result eq 'ok') {
10275: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10276: }
1.679 raeburn 10277: return $result;
10278: }
10279:
10280: sub modify_coursegroup_membership {
10281: my ($cdom,$cnum,$membership) = @_;
10282: my $result = &put('groupmembership',$membership,$cdom,$cnum);
10283: return $result;
10284: }
10285:
1.682 raeburn 10286: sub get_active_groups {
10287: my ($udom,$uname,$cdom,$cnum) = @_;
10288: my $now = time;
10289: my %groups = ();
10290: foreach my $key (keys(%env)) {
1.811 albertel 10291: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 10292: my ($start,$end) = split(/\./,$env{$key});
10293: if (($end!=0) && ($end<$now)) { next; }
10294: if (($start!=0) && ($start>$now)) { next; }
10295: if ($1 eq $cdom && $2 eq $cnum) {
10296: $groups{$3} = $env{$key} ;
10297: }
10298: }
10299: }
10300: return %groups;
10301: }
10302:
1.683 raeburn 10303: sub get_group_membership {
10304: my ($cdom,$cnum,$group) = @_;
10305: return(&dump('groupmembership',$cdom,$cnum,$group));
10306: }
10307:
10308: sub get_users_groups {
10309: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 10310: my @usersgroups;
1.683 raeburn 10311: my $cachetime=1800;
10312:
10313: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 10314: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10315: if (defined($cached)) {
1.734 albertel 10316: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 10317: } else {
10318: $grouplist = '';
1.816 raeburn 10319: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 10320: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 10321: my $access_end = $env{'course.'.$courseid.
10322: '.default_enrollment_end_date'};
10323: my $now = time;
10324: foreach my $key (keys(%roleshash)) {
10325: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10326: my $group = $1;
10327: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10328: my $start = $2;
10329: my $end = $1;
10330: if ($start == -1) { next; } # deleted from group
10331: if (($start!=0) && ($start>$now)) { next; }
10332: if (($end!=0) && ($end<$now)) {
10333: if ($access_end && $access_end < $now) {
10334: if ($access_end - $end < 86400) {
10335: push(@usersgroups,$group);
1.733 raeburn 10336: }
10337: }
1.817 raeburn 10338: next;
1.733 raeburn 10339: }
1.817 raeburn 10340: push(@usersgroups,$group);
1.683 raeburn 10341: }
10342: }
10343: }
1.817 raeburn 10344: @usersgroups = &sort_course_groups($courseid,@usersgroups);
10345: $grouplist = join(':',@usersgroups);
10346: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 10347: }
1.733 raeburn 10348: return @usersgroups;
1.683 raeburn 10349: }
10350:
10351: sub devalidate_getgroups_cache {
10352: my ($udom,$uname,$cdom,$cnum)=@_;
10353: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 10354:
1.683 raeburn 10355: my $hashid="$udom:$uname:$courseid";
10356: &devalidate_cache_new('getgroups',$hashid);
10357: }
10358:
1.12 www 10359: # ------------------------------------------------------------------ Plain Text
10360:
10361: sub plaintext {
1.988 raeburn 10362: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 10363: if ($short =~ m{^cr/}) {
1.758 albertel 10364: return (split('/',$short))[-1];
10365: }
1.742 raeburn 10366: if (!defined($cid)) {
10367: $cid = $env{'request.course.id'};
10368: }
10369: my %rolenames = (
1.1008 raeburn 10370: Course => 'std',
10371: Community => 'alt1',
1.1305 raeburn 10372: Placement => 'std',
1.742 raeburn 10373: );
1.1037 raeburn 10374: if ($cid ne '') {
10375: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10376: unless ($forcedefault) {
10377: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
10378: &Apache::lonlocal::mt_escape(\$roletext);
10379: return &Apache::lonlocal::mt($roletext);
10380: }
10381: }
10382: }
10383: if ((defined($type)) && (defined($rolenames{$type})) &&
10384: (defined($rolenames{$type})) &&
10385: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 10386: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 10387: } elsif ($cid ne '') {
10388: my $crstype = $env{'course.'.$cid.'.type'};
10389: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10390: (defined($prp{$short}{$rolenames{$crstype}}))) {
10391: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10392: }
1.742 raeburn 10393: }
1.1037 raeburn 10394: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 10395: }
10396:
10397: # ----------------------------------------------------------------- Assign Role
10398:
10399: sub assignrole {
1.957 raeburn 10400: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10401: $context)=@_;
1.21 www 10402: my $mrole;
10403: if ($role =~ /^cr\//) {
1.393 www 10404: my $cwosec=$url;
1.811 albertel 10405: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.1502 raeburn 10406: if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
1.1026 raeburn 10407: my $refused = 1;
10408: if ($context eq 'requestcourses') {
10409: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10410: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10411: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10412: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10413: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10414: if ($crsenv{'internal.courseowner'} eq
10415: $env{'user.name'}.':'.$env{'user.domain'}) {
10416: $refused = '';
10417: }
10418: }
10419: }
10420: }
10421: }
10422: if ($refused) {
10423: &logthis('Refused custom assignrole: '.
10424: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10425: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10426: return 'refused';
10427: }
1.104 www 10428: }
1.21 www 10429: $mrole='cr';
1.678 raeburn 10430: } elsif ($role =~ /^gr\//) {
10431: my $cwogrp=$url;
1.811 albertel 10432: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 10433: unless (&allowed('mdg',$cwogrp)) {
10434: &logthis('Refused group assignrole: '.
10435: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10436: $env{'user.name'}.' at '.$env{'user.domain'});
10437: return 'refused';
10438: }
10439: $mrole='gr';
1.21 www 10440: } else {
1.82 www 10441: my $cwosec=$url;
1.811 albertel 10442: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 10443: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10444: my $refused;
10445: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10446: if (!(&allowed('c'.$role,$url))) {
10447: $refused = 1;
10448: }
10449: } else {
10450: $refused = 1;
10451: }
1.947 raeburn 10452: if ($refused) {
1.1045 raeburn 10453: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377 raeburn 10454: if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045 raeburn 10455: my %crsenv;
10456: if ($role eq 'cc' || $role eq 'co') {
10457: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10458: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10459: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10460: if ($crsenv{'internal.courseowner'} eq
10461: $env{'user.name'}.':'.$env{'user.domain'}) {
10462: $refused = '';
10463: }
10464: }
10465: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10466: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10467: if ($crsenv{'internal.courseowner'} eq
10468: $env{'user.name'}.':'.$env{'user.domain'}) {
10469: $refused = '';
10470: }
10471: }
10472: }
10473: }
1.1368 raeburn 10474: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10475: if ($role eq 'st') {
10476: $refused = '';
1.1377 raeburn 10477: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368 raeburn 10478: $refused = '';
10479: }
1.1017 raeburn 10480: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 10481: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 10482: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 10483: my $wrongcc;
10484: if ($cnum =~ /^$match_community$/) {
10485: $wrongcc = 1 if ($role eq 'cc');
10486: } else {
10487: $wrongcc = 1 if ($role eq 'co');
10488: }
10489: unless ($wrongcc) {
10490: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10491: if ($crsenv{'internal.courseowner'} eq
10492: $env{'user.name'}.':'.$env{'user.domain'}) {
10493: $refused = '';
10494: }
1.1017 raeburn 10495: }
10496: }
1.1183 raeburn 10497: } elsif ($context eq 'requestauthor') {
10498: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10499: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10500: if ($env{'environment.requestauthor'} eq 'automatic') {
10501: $refused = '';
10502: } else {
10503: my %domdefaults = &get_domain_defaults($udom);
10504: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10505: my $checkbystatus;
10506: if ($env{'user.adv'}) {
10507: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10508: if ($disposition eq 'automatic') {
10509: $refused = '';
10510: } elsif ($disposition eq '') {
10511: $checkbystatus = 1;
10512: }
10513: } else {
10514: $checkbystatus = 1;
10515: }
10516: if ($checkbystatus) {
10517: if ($env{'environment.inststatus'}) {
10518: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10519: foreach my $type (@inststatuses) {
10520: if (($type ne '') &&
10521: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10522: $refused = '';
10523: }
10524: }
10525: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10526: $refused = '';
10527: }
10528: }
10529: }
10530: }
10531: }
1.1017 raeburn 10532: }
10533: if ($refused) {
1.947 raeburn 10534: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10535: ' '.$role.' '.$end.' '.$start.' by '.
10536: $env{'user.name'}.' at '.$env{'user.domain'});
10537: return 'refused';
10538: }
1.932 raeburn 10539: }
1.1131 raeburn 10540: } elsif ($role eq 'au') {
10541: if ($url ne '/'.$udom.'/') {
10542: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10543: ' to assign author role for '.$uname.':'.$udom.
10544: ' in domain: '.$url.' refused (wrong domain).');
10545: return 'refused';
10546: }
1.104 www 10547: }
1.21 www 10548: $mrole=$role;
10549: }
1.620 albertel 10550: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 10551: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 10552: if ($end) { $command.='_'.$end; }
1.21 www 10553: if ($start) {
10554: if ($end) {
1.81 www 10555: $command.='_'.$start;
1.21 www 10556: } else {
1.81 www 10557: $command.='_0_'.$start;
1.21 www 10558: }
10559: }
1.739 raeburn 10560: my $origstart = $start;
10561: my $origend = $end;
1.957 raeburn 10562: my $delflag;
1.357 www 10563: # actually delete
10564: if ($deleteflag) {
1.373 www 10565: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 10566: # modify command to delete the role
1.620 albertel 10567: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 10568: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 10569: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 10570: # set start and finish to negative values for userrolelog
10571: $start=-1;
10572: $end=-1;
1.957 raeburn 10573: $delflag = 1;
1.357 www 10574: }
10575: }
10576: # send command
1.349 www 10577: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 10578: # log new user role if status is ok
1.349 www 10579: if ($answer eq 'ok') {
1.663 raeburn 10580: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 10581: if (($role eq 'cc') || ($role eq 'in') ||
10582: ($role eq 'ep') || ($role eq 'ad') ||
10583: ($role eq 'ta') || ($role eq 'st') ||
10584: ($role=~/^cr/) || ($role eq 'gr') ||
10585: ($role eq 'co')) {
1.1200 raeburn 10586: # for course roles, perform group memberships changes triggered by role change.
10587: unless ($role =~ /^gr/) {
10588: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10589: $origstart,$selfenroll,$context);
10590: }
1.1184 raeburn 10591: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10592: $selfenroll,$context);
10593: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 10594: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10595: ($role eq 'da')) {
1.1184 raeburn 10596: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10597: $context);
10598: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10599: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10600: $context);
10601: }
1.1053 raeburn 10602: if ($role eq 'cc') {
10603: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10604: }
1.349 www 10605: }
10606: return $answer;
1.169 harris41 10607: }
10608:
1.1053 raeburn 10609: sub autoupdate_coowners {
10610: my ($url,$end,$start,$uname,$udom) = @_;
10611: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10612: if (($cdom ne '') && ($cnum ne '')) {
10613: my $now = time;
10614: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10615: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10616: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10617: my $instcode = $coursehash{'internal.coursecode'};
1.1444 raeburn 10618: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 10619: if ($instcode ne '') {
1.1056 raeburn 10620: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10621: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10622: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10623: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444 raeburn 10624: unless ($result eq 'valid') {
10625: if ($xlists ne '') {
10626: foreach my $xlist (split(',',$xlists)) {
10627: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10628: $result =
1.1446 raeburn 10629: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10630: $inst_crosslist,$uname.':'.$udom);
10631: last if ($result eq 'valid');
1.1444 raeburn 10632: }
10633: }
10634: }
1.1056 raeburn 10635: if ($result eq 'valid') {
10636: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10637: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10638: push(@newcoowners,$coowner);
10639: }
10640: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10641: push(@newcoowners,$uname.':'.$udom);
10642: }
10643: @newcoowners = sort(@newcoowners);
10644: } else {
10645: push(@newcoowners,$uname.':'.$udom);
10646: }
1.1444 raeburn 10647: } elsif ($coursehash{'internal.co-owners'}) {
10648: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10649: unless ($coowner eq $uname.':'.$udom) {
10650: push(@newcoowners,$coowner);
1.1053 raeburn 10651: }
1.1444 raeburn 10652: }
10653: unless (@newcoowners > 0) {
10654: $delcoowners = 1;
10655: $coowners = '';
1.1053 raeburn 10656: }
10657: }
10658: if (@newcoowners || $delcoowners) {
10659: &store_coowners($cdom,$cnum,$coursehash{'home'},
10660: $delcoowners,@newcoowners);
10661: }
10662: }
10663: }
10664: }
10665: }
10666: }
10667: }
10668:
10669: sub store_coowners {
10670: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10671: my $cid = $cdom.'_'.$cnum;
10672: my ($coowners,$delresult,$putresult);
10673: if (@newcoowners) {
10674: $coowners = join(',',@newcoowners);
10675: my %coownershash = (
10676: 'internal.co-owners' => $coowners,
10677: );
10678: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10679: if ($putresult eq 'ok') {
10680: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10681: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10682: }
10683: }
10684: }
10685: if ($delcoowners) {
10686: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10687: if ($delresult eq 'ok') {
10688: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10689: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10690: }
10691: }
10692: }
10693: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10694: my %crsinfo =
1.1494 raeburn 10695: &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
1.1053 raeburn 10696: if (ref($crsinfo{$cid}) eq 'HASH') {
10697: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
1.1494 raeburn 10698: my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
1.1053 raeburn 10699: }
10700: }
10701: }
10702:
1.169 harris41 10703: # -------------------------------------------------- Modify user authentication
1.197 www 10704: # Overrides without validation
10705:
1.169 harris41 10706: sub modifyuserauth {
10707: my ($udom,$uname,$umode,$upass)=@_;
10708: my $uhome=&homeserver($uname,$udom);
1.1409 raeburn 10709: my $allowed;
10710: if (&allowed('mau',$udom)) {
10711: $allowed = 1;
10712: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10713: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10714: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10715: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10716: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10717: if (($cdom ne '') && ($cnum ne '')) {
10718: my $is_owner = &is_course_owner($cdom,$cnum);
10719: if ($is_owner) {
10720: $allowed = 1;
10721: }
10722: }
10723: }
10724: unless ($allowed) { return 'refused'; }
1.197 www 10725: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10726: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10727: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10728: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10729: &escape($upass),$uhome);
1.1434 raeburn 10730: my $ip = &get_requestor_ip();
1.620 albertel 10731: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10732: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434 raeburn 10733: '(Remote '.$ip.'): '.$reply);
1.197 www 10734: &log($udom,,$uname,$uhome,
1.620 albertel 10735: 'Authentication changed by '.$env{'user.domain'}.', '.
10736: $env{'user.name'}.', '.$umode.
1.1435 raeburn 10737: '(Remote '.$ip.'): '.$reply);
1.169 harris41 10738: unless ($reply eq 'ok') {
1.197 www 10739: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10740: return 'error: '.$reply;
10741: }
1.170 harris41 10742: return 'ok';
1.80 www 10743: }
10744:
1.81 www 10745: # --------------------------------------------------------------- Modify a user
1.80 www 10746:
1.81 www 10747: sub modifyuser {
1.206 matthew 10748: my ($udom, $uname, $uid,
10749: $umode, $upass, $first,
10750: $middle, $last, $gene,
1.1058 raeburn 10751: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10752: $udom= &LONCAPA::clean_domain($udom);
10753: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10754: my $showcandelete = 'none';
10755: if (ref($candelete) eq 'ARRAY') {
10756: if (@{$candelete} > 0) {
10757: $showcandelete = join(', ',@{$candelete});
10758: }
10759: }
1.81 www 10760: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10761: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10762: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10763: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10764: ' desiredhome not specified').
1.620 albertel 10765: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10766: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10767: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10768: my $newuser;
10769: if ($uhome eq 'no_host') {
10770: $newuser = 1;
1.1368 raeburn 10771: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10772: ($umode eq 'lti')) {
10773: return 'error: more information needed to create new user';
10774: }
1.1075 raeburn 10775: }
1.80 www 10776: # ----------------------------------------------------------------- Create User
1.406 albertel 10777: if (($uhome eq 'no_host') &&
1.1368 raeburn 10778: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80 www 10779: my $unhome='';
1.844 albertel 10780: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10781: $unhome = $desiredhome;
1.620 albertel 10782: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10783: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10784: } else { # load balancing routine for determining $unhome
1.81 www 10785: my $loadm=10000000;
1.841 albertel 10786: my %servers = &get_servers($udom,'library');
10787: foreach my $tryserver (keys(%servers)) {
10788: my $answer=reply('load',$tryserver);
10789: if (($answer=~/\d+/) && ($answer<$loadm)) {
10790: $loadm=$answer;
10791: $unhome=$tryserver;
10792: }
1.80 www 10793: }
10794: }
10795: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10796: return 'error: unable to find a home server for '.$uname.
10797: ' in domain '.$udom;
1.80 www 10798: }
10799: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10800: &escape($upass),$unhome);
10801: unless ($reply eq 'ok') {
10802: return 'error: '.$reply;
10803: }
1.230 stredwic 10804: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10805: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10806: return 'error: unable verify users home machine.';
1.80 www 10807: }
1.209 matthew 10808: } # End of creation of new user
1.80 www 10809: # ---------------------------------------------------------------------- Add ID
10810: if ($uid) {
10811: $uid=~tr/A-Z/a-z/;
10812: my %uidhash=&idrget($udom,$uname);
1.196 www 10813: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10814: && (!$forceid)) {
1.80 www 10815: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10816: return 'error: user id "'.$uid.'" does not match '.
10817: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10818: }
10819: } else {
1.1300 raeburn 10820: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 10821: }
10822: }
10823: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10824: my @tmp=&get('environment',
1.899 raeburn 10825: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10826: 'permanentemail','inststatus'],
1.134 albertel 10827: $udom,$uname);
1.1075 raeburn 10828: my (%names,%oldnames);
1.313 matthew 10829: if ($tmp[0] =~ m/^error:.*/) {
10830: %names=();
10831: } else {
10832: %names = @tmp;
1.1075 raeburn 10833: %oldnames = %names;
1.313 matthew 10834: }
1.388 www 10835: #
1.1058 raeburn 10836: # If name, email and/or uid are blank (e.g., because an uploaded file
10837: # of users did not contain them), do not overwrite existing values
10838: # unless field is in $candelete array ref.
10839: #
10840:
10841: my @fields = ('firstname','middlename','lastname','generation',
10842: 'permanentemail','id');
10843: my %newvalues;
10844: if (ref($candelete) eq 'ARRAY') {
10845: foreach my $field (@fields) {
10846: if (grep(/^\Q$field\E$/,@{$candelete})) {
10847: if ($field eq 'firstname') {
10848: $names{$field} = $first;
10849: } elsif ($field eq 'middlename') {
10850: $names{$field} = $middle;
10851: } elsif ($field eq 'lastname') {
10852: $names{$field} = $last;
10853: } elsif ($field eq 'generation') {
10854: $names{$field} = $gene;
10855: } elsif ($field eq 'permanentemail') {
10856: $names{$field} = $email;
10857: } elsif ($field eq 'id') {
10858: $names{$field} = $uid;
10859: }
10860: }
10861: }
10862: }
1.388 www 10863: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10864: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10865: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10866: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10867: if ($email) {
10868: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10869: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10870: }
1.899 raeburn 10871: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10872: if (defined($inststatus)) {
10873: $names{'inststatus'} = '';
10874: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10875: if (ref($usertypes) eq 'HASH') {
10876: my @okstatuses;
10877: foreach my $item (split(/:/,$inststatus)) {
10878: if (defined($usertypes->{$item})) {
10879: push(@okstatuses,$item);
10880: }
10881: }
10882: if (@okstatuses) {
10883: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10884: }
10885: }
10886: }
1.1075 raeburn 10887: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10888: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10889: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10890: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10891: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10892: } else {
10893: $logmsg .= ' during self creation';
10894: }
1.1075 raeburn 10895: my $changed;
10896: if ($newuser) {
10897: $changed = 1;
10898: } else {
10899: foreach my $field (@fields) {
10900: if ($names{$field} ne $oldnames{$field}) {
10901: $changed = 1;
10902: last;
10903: }
10904: }
10905: }
10906: unless ($changed) {
10907: $logmsg = 'No changes in user information needed for: '.$logmsg;
10908: &logthis($logmsg);
10909: return 'ok';
10910: }
10911: my $reply = &put('environment', \%names, $udom,$uname);
10912: if ($reply ne 'ok') {
10913: return 'error: '.$reply;
10914: }
1.1087 raeburn 10915: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
1.1494 raeburn 10916: &devalidate_cache_new('emailscache',$uname.':'.$udom);
1.1087 raeburn 10917: }
1.1075 raeburn 10918: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10919: &devalidate_cache_new('namescache',$uname.':'.$udom);
10920: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10921: &logthis($logmsg);
1.134 albertel 10922: return 'ok';
1.80 www 10923: }
10924:
1.81 www 10925: # -------------------------------------------------------------- Modify student
1.80 www 10926:
1.81 www 10927: sub modifystudent {
10928: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10929: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 10930: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10931: if (!$cid) {
1.620 albertel 10932: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10933: return 'not_in_class';
10934: }
1.80 www 10935: }
10936: # --------------------------------------------------------------- Make the user
1.81 www 10937: my $reply=&modifyuser
1.209 matthew 10938: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10939: $desiredhome,$email,$inststatus);
1.80 www 10940: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10941: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 10942: # student's environment
1.297 matthew 10943: $uid = undef if (!$forceid);
1.455 albertel 10944: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 10945: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 10946: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10947: return $reply;
10948: }
10949:
10950: sub modify_student_enrollment {
1.1216 raeburn 10951: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 10952: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10953: my ($cdom,$cnum,$chome);
10954: if (!$cid) {
1.620 albertel 10955: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10956: return 'not_in_class';
10957: }
1.620 albertel 10958: $cdom=$env{'course.'.$cid.'.domain'};
10959: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10960: } else {
10961: ($cdom,$cnum)=split(/_/,$cid);
10962: }
1.620 albertel 10963: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10964: if (!$chome) {
1.457 raeburn 10965: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10966: }
1.455 albertel 10967: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10968: # Make sure the user exists
1.81 www 10969: my $uhome=&homeserver($uname,$udom);
10970: if (($uhome eq '') || ($uhome eq 'no_host')) {
10971: return 'error: no such user';
10972: }
1.297 matthew 10973: # Get student data if we were not given enough information
10974: if (!defined($first) || $first eq '' ||
10975: !defined($last) || $last eq '' ||
10976: !defined($uid) || $uid eq '' ||
10977: !defined($middle) || $middle eq '' ||
10978: !defined($gene) || $gene eq '') {
1.294 matthew 10979: # They did not supply us with enough data to enroll the student, so
10980: # we need to pick up more information.
1.297 matthew 10981: my %tmp = &get('environment',
1.294 matthew 10982: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10983: ,$udom,$uname);
10984:
1.800 albertel 10985: #foreach my $key (keys(%tmp)) {
10986: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10987: #}
1.294 matthew 10988: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10989: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10990: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10991: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10992: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10993: }
1.556 albertel 10994: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10995: my $user = "$uname:$udom";
1.1494 raeburn 10996: my %old_entry = &get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10997: my $reply=cput('classlist',
1.1148 raeburn 10998: {$user =>
1.1314 raeburn 10999: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 11000: $cdom,$cnum);
1.1148 raeburn 11001: if (($reply eq 'ok') || ($reply eq 'delayed')) {
11002: &devalidate_getsection_cache($udom,$uname,$cid);
11003: } else {
1.81 www 11004: return 'error: '.$reply;
11005: }
1.297 matthew 11006: # Add student role to user
1.83 www 11007: my $uurl='/'.$cid;
1.81 www 11008: $uurl=~s/\_/\//g;
11009: if ($usec) {
11010: $uurl.='/'.$usec;
11011: }
1.1148 raeburn 11012: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
11013: $selfenroll,$context);
11014: if ($result ne 'ok') {
11015: if ($old_entry{$user} ne '') {
11016: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11017: } else {
11018: $reply = &del('classlist',[$user],$cdom,$cnum);
11019: }
11020: }
11021: return $result;
1.21 www 11022: }
11023:
1.556 albertel 11024: sub format_name {
11025: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11026: my $name;
11027: if ($first ne 'lastname') {
11028: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11029: } else {
11030: if ($lastname=~/\S/) {
11031: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11032: $name=~s/\s+,/,/;
11033: } else {
11034: $name.= $firstname.' '.$middlename.' '.$generation;
11035: }
11036: }
11037: $name=~s/^\s+//;
11038: $name=~s/\s+$//;
11039: $name=~s/\s+/ /g;
11040: return $name;
11041: }
11042:
1.84 www 11043: # ------------------------------------------------- Write to course preferences
11044:
11045: sub writecoursepref {
11046: my ($courseid,%prefs)=@_;
11047: $courseid=~s/^\///;
11048: $courseid=~s/\_/\//g;
11049: my ($cdomain,$cnum)=split(/\//,$courseid);
11050: my $chome=homeserver($cnum,$cdomain);
11051: if (($chome eq '') || ($chome eq 'no_host')) {
11052: return 'error: no such course';
11053: }
11054: my $cstring='';
1.800 albertel 11055: foreach my $pref (keys(%prefs)) {
11056: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 11057: }
1.84 www 11058: $cstring=~s/\&$//;
11059: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11060: }
11061:
11062: # ---------------------------------------------------------- Make/modify course
11063:
11064: sub createcourse {
1.741 raeburn 11065: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423 raeburn 11066: $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84 www 11067: $url=&declutter($url);
11068: my $cid='';
1.1028 raeburn 11069: if ($context eq 'requestcourses') {
11070: my $can_create = 0;
11071: my ($ownername,$ownerdom) = split(':',$course_owner);
11072: if ($udom eq $ownerdom) {
1.1423 raeburn 11073: my $reload;
11074: if (($callercontext eq 'auto') &&
11075: ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11076: $reload = 'reload';
11077: }
11078: if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028 raeburn 11079: $context)) {
11080: $can_create = 1;
11081: }
11082: } else {
11083: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11084: $category);
11085: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11086: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11087: if (@curr > 0) {
11088: my @options = qw(approval validate autolimit);
11089: my $optregex = join('|',@options);
11090: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11091: $can_create = 1;
11092: }
11093: }
11094: }
11095: }
11096: if ($can_create) {
11097: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11098: unless (&allowed('ccc',$udom)) {
11099: return 'refused';
11100: }
1.1017 raeburn 11101: }
11102: } else {
11103: return 'refused';
11104: }
1.1028 raeburn 11105: } elsif (!&allowed('ccc',$udom)) {
11106: return 'refused';
1.84 www 11107: }
1.1011 raeburn 11108: # --------------------------------------------------------------- Get Unique ID
11109: my $uname;
11110: if ($cnum =~ /^$match_courseid$/) {
11111: my $chome=&homeserver($cnum,$udom,'true');
11112: if (($chome eq '') || ($chome eq 'no_host')) {
11113: $uname = $cnum;
11114: } else {
1.1038 raeburn 11115: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 11116: }
11117: } else {
1.1038 raeburn 11118: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 11119: }
11120: return $uname if ($uname =~ /^error/);
11121: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 11122: if (!defined($course_server)) {
11123: if (defined(&domain($udom,'primary'))) {
11124: $course_server = &domain($udom,'primary');
11125: } else {
11126: $course_server = $env{'user.home'};
11127: }
11128: }
11129: my %host_servers =
1.1494 raeburn 11130: &get_servers($udom,'library');
1.1052 raeburn 11131: unless ($host_servers{$course_server}) {
11132: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 11133: }
1.84 www 11134: # ------------------------------------------------------------- Make the course
11135: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 11136: $course_server);
1.84 www 11137: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 11138: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 11139: if (($uhome eq '') || ($uhome eq 'no_host')) {
11140: return 'error: no such course';
11141: }
1.271 www 11142: # ----------------------------------------------------------------- Course made
1.516 raeburn 11143: # log existence
1.1029 raeburn 11144: my $now = time;
1.918 raeburn 11145: my $newcourse = {
11146: $udom.'_'.$uname => {
1.921 raeburn 11147: description => $description,
11148: inst_code => $inst_code,
11149: owner => $course_owner,
11150: type => $crstype,
1.1029 raeburn 11151: creator => $env{'user.name'}.':'.
11152: $env{'user.domain'},
11153: created => $now,
11154: context => $context,
1.918 raeburn 11155: },
11156: };
1.921 raeburn 11157: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 11158: # set toplevel url
1.271 www 11159: my $topurl=$url;
11160: unless ($nonstandard) {
11161: # ------------------------------------------ For standard courses, make top url
11162: my $mapurl=&clutter($url);
1.278 www 11163: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 11164: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 11165: <map>
11166: <resource id="1" type="start"></resource>
11167: <resource id="2" src="$mapurl"></resource>
11168: <resource id="3" type="finish"></resource>
11169: <link index="1" from="1" to="2"></link>
11170: <link index="2" from="2" to="3"></link>
11171: </map>
11172: ENDINITMAP
11173: $topurl=&declutter(
1.638 albertel 11174: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 11175: );
11176: }
11177: # ----------------------------------------------------------- Write preferences
1.84 www 11178: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 11179: ('description' => $description,
11180: 'url' => $topurl,
11181: 'internal.creator' => $env{'user.name'}.':'.
11182: $env{'user.domain'},
11183: 'internal.created' => $now,
11184: 'internal.creationcontext' => $context)
11185: );
1.84 www 11186: return '/'.$udom.'/'.$uname;
11187: }
11188:
1.1011 raeburn 11189: # ------------------------------------------------------------------- Create ID
11190: sub generate_coursenum {
1.1038 raeburn 11191: my ($udom,$crstype) = @_;
1.1011 raeburn 11192: my $domdesc = &domain($udom);
11193: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 11194: my $first;
11195: if ($crstype eq 'Community') {
11196: $first = '0';
11197: } else {
11198: $first = int(1+rand(9));
11199: }
11200: my $uname=$first.
1.1011 raeburn 11201: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11202: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11203: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11204: # ----------------------------------------------- Make sure that does not exist
11205: my $uhome=&homeserver($uname,$udom,'true');
11206: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 11207: if ($crstype eq 'Community') {
11208: $first = '0';
11209: } else {
11210: $first = int(1+rand(9));
11211: }
11212: $uname=$first.
1.1011 raeburn 11213: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11214: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11215: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11216: $uhome=&homeserver($uname,$udom,'true');
11217: unless (($uhome eq '') || ($uhome eq 'no_host')) {
11218: return 'error: unable to generate unique course-ID';
11219: }
11220: }
11221: return $uname;
11222: }
11223:
1.813 albertel 11224: sub is_course {
1.1167 droeschl 11225: my ($cdom, $cnum) = scalar(@_) == 1 ?
11226: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
11227:
1.1381 raeburn 11228: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11229: my $uhome=&homeserver($cnum,$cdom);
11230: my $iscourse;
11231: if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382 raeburn 11232: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381 raeburn 11233: } else {
11234: my $hashid = $cdom.':'.$cnum;
11235: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11236: unless (defined($cached)) {
11237: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11238: $cnum,undef,undef,'.');
11239: $iscourse = 0;
11240: if (exists($courses{$cdom.'_'.$cnum})) {
11241: $iscourse = 1;
11242: }
11243: &do_cache_new('iscourse',$hashid,$iscourse,3600);
11244: }
11245: }
11246: return unless ($iscourse);
1.1167 droeschl 11247: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 11248: }
11249:
1.1015 raeburn 11250: sub store_userdata {
11251: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 11252: my $result;
1.1016 raeburn 11253: if ($datakey ne '') {
1.1013 raeburn 11254: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 11255: if ($udom eq '' || $uname eq '') {
11256: $udom = $env{'user.domain'};
11257: $uname = $env{'user.name'};
11258: }
11259: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 11260: if (($uhome eq '') || ($uhome eq 'no_host')) {
11261: $result = 'error: no_host';
11262: } else {
1.1434 raeburn 11263: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 11264: $storehash->{'host'} = $perlvar{'lonHostID'};
11265:
11266: my $namevalue='';
11267: foreach my $key (keys(%{$storehash})) {
11268: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11269: }
11270: $namevalue=~s/\&$//;
1.1224 raeburn 11271: unless ($namespace eq 'courserequests') {
11272: $datakey = &escape($datakey);
11273: }
1.1105 raeburn 11274: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
11275: $namevalue,$uhome);
1.1013 raeburn 11276: }
11277: } else {
11278: $result = 'error: data to store was not a hash reference';
11279: }
11280: } else {
11281: $result= 'error: invalid requestkey';
11282: }
11283: return $result;
11284: }
11285:
1.21 www 11286: # ---------------------------------------------------------- Assign Custom Role
11287:
11288: sub assigncustomrole {
1.957 raeburn 11289: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11290: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 11291: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 11292: }
11293:
11294: # ----------------------------------------------------------------- Revoke Role
11295:
11296: sub revokerole {
1.957 raeburn 11297: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11298: my $now=time;
1.965 raeburn 11299: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 11300: }
11301:
11302: # ---------------------------------------------------------- Revoke Custom Role
11303:
11304: sub revokecustomrole {
1.957 raeburn 11305: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11306: my $now=time;
1.357 www 11307: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 11308: $deleteflag,$selfenroll,$context);
1.17 www 11309: }
11310:
1.533 banghart 11311: # ------------------------------------------------------------ Disk usage
1.535 albertel 11312: sub diskusage {
1.955 raeburn 11313: my ($udom,$uname,$directorypath,$getpropath)=@_;
11314: $directorypath =~ s/\/$//;
11315: my $listing=&reply('du2:'.&escape($directorypath).':'
11316: .&escape($getpropath).':'.&escape($uname).':'
11317: .&escape($udom),homeserver($uname,$udom));
11318: if ($listing eq 'unknown_cmd') {
11319: if ($getpropath) {
11320: $directorypath = &propath($udom,$uname).'/'.$directorypath;
11321: }
11322: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11323: }
1.514 albertel 11324: return $listing;
1.512 banghart 11325: }
11326:
1.566 banghart 11327: sub is_locked {
1.1096 raeburn 11328: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 11329: my @check;
11330: my $is_locked;
1.1093 raeburn 11331: push (@check,$file_name);
1.613 albertel 11332: my %locked = &get('file_permissions',\@check,
1.620 albertel 11333: $env{'user.domain'},$env{'user.name'});
1.615 albertel 11334: my ($tmp)=keys(%locked);
11335: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 11336:
1.566 banghart 11337: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 11338: $is_locked = 'false';
11339: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 11340: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 11341: $is_locked = 'true';
1.1096 raeburn 11342: if (ref($which) eq 'ARRAY') {
11343: push(@{$which},$entry);
11344: } else {
11345: last;
11346: }
1.745 raeburn 11347: }
11348: }
1.566 banghart 11349: } else {
11350: $is_locked = 'false';
11351: }
1.1093 raeburn 11352: return $is_locked;
1.566 banghart 11353: }
11354:
1.759 albertel 11355: sub declutter_portfile {
11356: my ($file) = @_;
1.833 albertel 11357: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 11358: return $file;
11359: }
11360:
1.559 banghart 11361: # ------------------------------------------------------------- Mark as Read Only
11362:
11363: sub mark_as_readonly {
11364: my ($domain,$user,$files,$what) = @_;
1.613 albertel 11365: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11366: my ($tmp)=keys(%current_permissions);
11367: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 11368: foreach my $file (@{$files}) {
1.759 albertel 11369: $file = &declutter_portfile($file);
1.561 banghart 11370: push(@{$current_permissions{$file}},$what);
1.559 banghart 11371: }
1.613 albertel 11372: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11373: return;
11374: }
11375:
1.572 banghart 11376: # ------------------------------------------------------------Save Selected Files
11377:
11378: sub save_selected_files {
11379: my ($user, $path, @files) = @_;
11380: my $filename = $user."savedfiles";
1.573 banghart 11381: my @other_files = &files_not_in_path($user, $path);
1.1359 raeburn 11382: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 11383: foreach my $file (@files) {
1.620 albertel 11384: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 11385: }
11386: foreach my $file (@other_files) {
1.574 banghart 11387: print (OUT $file."\n");
1.572 banghart 11388: }
1.574 banghart 11389: close (OUT);
1.572 banghart 11390: return 'ok';
11391: }
11392:
1.574 banghart 11393: sub clear_selected_files {
11394: my ($user) = @_;
11395: my $filename = $user."savedfiles";
1.1359 raeburn 11396: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 11397: print (OUT undef);
11398: close (OUT);
11399: return ("ok");
11400: }
11401:
1.572 banghart 11402: sub files_in_path {
11403: my ($user, $path) = @_;
11404: my $filename = $user."savedfiles";
11405: my %return_files;
1.1359 raeburn 11406: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 11407: while (my $line_in = <IN>) {
1.574 banghart 11408: chomp ($line_in);
11409: my @paths_and_file = split (m!/!, $line_in);
11410: my $file_part = pop (@paths_and_file);
11411: my $path_part = join ('/', @paths_and_file);
1.573 banghart 11412: $path_part.='/';
11413: my $path_and_file = $path_part.$file_part;
11414: if ($path_part eq $path) {
11415: $return_files{$file_part}= 'selected';
11416: }
11417: }
1.574 banghart 11418: close (IN);
11419: return (\%return_files);
1.572 banghart 11420: }
11421:
11422: # called in portfolio select mode, to show files selected NOT in current directory
11423: sub files_not_in_path {
11424: my ($user, $path) = @_;
11425: my $filename = $user."savedfiles";
11426: my @return_files;
11427: my $path_part;
1.1359 raeburn 11428: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 11429: while (my $line = <IN>) {
1.572 banghart 11430: #ok, I know it's clunky, but I want it to work
1.800 albertel 11431: my @paths_and_file = split(m|/|, $line);
11432: my $file_part = pop(@paths_and_file);
11433: chomp($file_part);
11434: my $path_part = join('/', @paths_and_file);
1.572 banghart 11435: $path_part .= '/';
11436: my $path_and_file = $path_part.$file_part;
11437: if ($path_part ne $path) {
1.800 albertel 11438: push(@return_files, ($path_and_file));
1.572 banghart 11439: }
11440: }
1.800 albertel 11441: close(OUT);
1.574 banghart 11442: return (@return_files);
1.572 banghart 11443: }
11444:
1.1273 raeburn 11445: #------------------------------Submitted/Handedback Portfolio Files Versioning
11446:
11447: sub portfiles_versioning {
11448: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11449: my $portfolio_root = '/userfiles/portfolio';
11450: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11451: foreach my $file (@{$portfiles}) {
11452: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11453: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11454: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11455: my $getpropath = 1;
11456: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11457: $stu_name,$getpropath);
11458: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11459: my $new_answer =
11460: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11461: if ($new_answer ne 'problem getting file') {
11462: push(@{$versioned_portfiles}, $directory.$new_answer);
11463: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11464: [$symb,$env{'request.course.id'},'graded']);
11465: }
11466: }
11467: }
11468:
11469: sub get_next_version {
11470: my ($answer_name, $answer_ext, $dir_list) = @_;
11471: my $version;
11472: if (ref($dir_list) eq 'ARRAY') {
11473: foreach my $row (@{$dir_list}) {
11474: my ($file) = split(/\&/,$row,2);
11475: my ($file_name,$file_version,$file_ext) =
11476: &file_name_version_ext($file);
11477: if (($file_name eq $answer_name) &&
11478: ($file_ext eq $answer_ext)) {
11479: # gets here if filename and extension match,
11480: # regardless of version
11481: if ($file_version ne '') {
11482: # a versioned file is found so save it for later
11483: if ($file_version > $version) {
11484: $version = $file_version;
11485: }
11486: }
11487: }
11488: }
11489: }
11490: $version ++;
11491: return($version);
11492: }
11493:
11494: sub version_selected_portfile {
11495: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11496: my ($answer_name,$answer_ver,$answer_ext) =
11497: &file_name_version_ext($file_name);
11498: my $new_answer;
11499: $env{'form.copy'} =
11500: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11501: if($env{'form.copy'} eq '-1') {
11502: $new_answer = 'problem getting file';
11503: } else {
11504: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11505: my $copy_result =
11506: &finishuserfileupload($stu_name,$domain,'copy',
11507: '/portfolio'.$directory.$new_answer);
11508: }
11509: undef($env{'form.copy'});
11510: return ($new_answer);
11511: }
11512:
11513: sub file_name_version_ext {
11514: my ($file)=@_;
11515: my @file_parts = split(/\./, $file);
11516: my ($name,$version,$ext);
11517: if (@file_parts > 1) {
11518: $ext=pop(@file_parts);
11519: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11520: $version=pop(@file_parts);
11521: }
11522: $name=join('.',@file_parts);
11523: } else {
11524: $name=join('.',@file_parts);
11525: }
11526: return($name,$version,$ext);
11527: }
11528:
1.745 raeburn 11529: #----------------------------------------------Get portfolio file permissions
1.629 banghart 11530:
1.745 raeburn 11531: sub get_portfile_permissions {
11532: my ($domain,$user) = @_;
1.613 albertel 11533: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11534: my ($tmp)=keys(%current_permissions);
11535: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11536: return \%current_permissions;
11537: }
11538:
11539: #---------------------------------------------Get portfolio file access controls
11540:
1.749 raeburn 11541: sub get_access_controls {
1.745 raeburn 11542: my ($current_permissions,$group,$file) = @_;
1.769 albertel 11543: my %access;
11544: my $real_file = $file;
11545: $file =~ s/\.meta$//;
1.745 raeburn 11546: if (defined($file)) {
1.749 raeburn 11547: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11548: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 11549: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 11550: }
11551: }
1.745 raeburn 11552: } else {
1.749 raeburn 11553: foreach my $key (keys(%{$current_permissions})) {
11554: if ($key =~ /\0accesscontrol$/) {
11555: if (defined($group)) {
11556: if ($key !~ m-^\Q$group\E/-) {
11557: next;
11558: }
11559: }
11560: my ($fullpath) = split(/\0/,$key);
11561: if (ref($$current_permissions{$key}) eq 'HASH') {
11562: foreach my $control (keys(%{$$current_permissions{$key}})) {
11563: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11564: }
11565: }
11566: }
11567: }
11568: }
11569: return %access;
11570: }
11571:
11572: sub modify_access_controls {
11573: my ($file_name,$changes,$domain,$user)=@_;
11574: my ($outcome,$deloutcome);
11575: my %store_permissions;
11576: my %new_values;
11577: my %new_control;
11578: my %translation;
11579: my @deletions = ();
11580: my $now = time;
11581: if (exists($$changes{'activate'})) {
11582: if (ref($$changes{'activate'}) eq 'HASH') {
11583: my @newitems = sort(keys(%{$$changes{'activate'}}));
11584: my $numnew = scalar(@newitems);
11585: for (my $i=0; $i<$numnew; $i++) {
11586: my $newkey = $newitems[$i];
11587: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 11588: if ($newkey =~ /^\d+:/) {
11589: $newkey =~ s/^(\d+)/$newid/;
11590: $translation{$1} = $newid;
11591: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11592: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11593: $translation{$1} = $newid;
11594: }
1.749 raeburn 11595: $new_values{$file_name."\0".$newkey} =
11596: $$changes{'activate'}{$newitems[$i]};
11597: $new_control{$newkey} = $now;
11598: }
11599: }
11600: }
11601: my %todelete;
11602: my %changed_items;
11603: foreach my $action ('delete','update') {
11604: if (exists($$changes{$action})) {
11605: if (ref($$changes{$action}) eq 'HASH') {
11606: foreach my $key (keys(%{$$changes{$action}})) {
11607: my ($itemnum) = ($key =~ /^([^:]+):/);
11608: if ($action eq 'delete') {
11609: $todelete{$itemnum} = 1;
11610: } else {
11611: $changed_items{$itemnum} = $key;
11612: }
11613: }
1.745 raeburn 11614: }
11615: }
1.749 raeburn 11616: }
11617: # get lock on access controls for file.
11618: my $lockhash = {
11619: $file_name."\0".'locked_access_records' => $env{'user.name'}.
11620: ':'.$env{'user.domain'},
11621: };
11622: my $tries = 0;
11623: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11624:
1.1288 damieng 11625: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 11626: $tries ++;
1.1289 damieng 11627: sleep(0.1);
1.749 raeburn 11628: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11629: }
11630: if ($gotlock eq 'ok') {
11631: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11632: my ($tmp)=keys(%curr_permissions);
11633: if ($tmp=~/^error:/) { undef(%curr_permissions); }
11634: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11635: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11636: if (ref($curr_controls) eq 'HASH') {
11637: foreach my $control_item (keys(%{$curr_controls})) {
11638: my ($itemnum) = ($control_item =~ /^([^:]+):/);
11639: if (defined($todelete{$itemnum})) {
11640: push(@deletions,$file_name."\0".$control_item);
11641: } else {
11642: if (defined($changed_items{$itemnum})) {
11643: $new_control{$changed_items{$itemnum}} = $now;
11644: push(@deletions,$file_name."\0".$control_item);
11645: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11646: } else {
11647: $new_control{$control_item} = $$curr_controls{$control_item};
11648: }
11649: }
1.745 raeburn 11650: }
11651: }
11652: }
1.970 raeburn 11653: my ($group);
11654: if (&is_course($domain,$user)) {
11655: ($group,my $file) = split(/\//,$file_name,2);
11656: }
1.749 raeburn 11657: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11658: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11659: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11660: # remove lock
11661: my @del_lock = ($file_name."\0".'locked_access_records');
11662: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11663: my $sqlresult =
1.970 raeburn 11664: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11665: $group);
1.749 raeburn 11666: } else {
11667: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11668: }
1.749 raeburn 11669: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11670: }
11671:
1.827 raeburn 11672: sub make_public_indefinitely {
1.1271 raeburn 11673: my (@requrl) = @_;
11674: return &automated_portfile_access('public',\@requrl);
11675: }
11676:
11677: sub automated_portfile_access {
11678: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 11679: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11680: return 'invalid';
11681: }
1.1271 raeburn 11682: my %urls;
11683: if (ref($addsref) eq 'ARRAY') {
11684: foreach my $requrl (@{$addsref}) {
11685: if (&is_portfolio_url($requrl)) {
11686: unless (exists($urls{$requrl})) {
11687: $urls{$requrl} = 'add';
11688: }
11689: }
11690: }
11691: }
11692: if (ref($delsref) eq 'ARRAY') {
11693: foreach my $requrl (@{$delsref}) {
11694: if (&is_portfolio_url($requrl)) {
11695: unless (exists($urls{$requrl})) {
11696: $urls{$requrl} = 'delete';
11697: }
11698: }
11699: }
11700: }
11701: unless (keys(%urls)) {
11702: return 'invalid';
11703: }
11704: my $ip;
11705: if ($accesstype eq 'ip') {
11706: if (ref($info) eq 'HASH') {
11707: if ($info->{'ip'} ne '') {
11708: $ip = $info->{'ip'};
11709: }
11710: }
11711: if ($ip eq '') {
11712: return 'invalid';
11713: }
11714: }
11715: my $errors;
1.827 raeburn 11716: my $now = time;
1.1271 raeburn 11717: my %current_perms;
11718: foreach my $requrl (sort(keys(%urls))) {
11719: my $action;
11720: if ($urls{$requrl} eq 'add') {
11721: $action = 'activate';
11722: } else {
11723: $action = 'none';
11724: }
11725: my $aclnum = 0;
1.827 raeburn 11726: my (undef,$udom,$unum,$file_name,$group) =
11727: &parse_portfolio_url($requrl);
1.1271 raeburn 11728: unless (exists($current_perms{$unum.':'.$udom})) {
11729: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11730: }
11731: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 11732: $group,$file_name);
11733: foreach my $key (keys(%{$access_controls{$file_name}})) {
11734: my ($num,$scope,$end,$start) =
11735: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 11736: if ($scope eq $accesstype) {
11737: if (($start <= $now) && ($end == 0)) {
11738: if ($accesstype eq 'ip') {
11739: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11740: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11741: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11742: if ($urls{$requrl} eq 'add') {
11743: $action = 'none';
11744: last;
11745: } else {
11746: $action = 'delete';
11747: $aclnum = $num;
11748: last;
11749: }
11750: }
11751: }
11752: }
11753: } elsif ($accesstype eq 'public') {
11754: if ($urls{$requrl} eq 'add') {
11755: $action = 'none';
11756: last;
11757: } else {
11758: $action = 'delete';
11759: $aclnum = $num;
11760: last;
11761: }
11762: }
11763: } elsif ($accesstype eq 'public') {
1.827 raeburn 11764: $action = 'update';
11765: $aclnum = $num;
1.1271 raeburn 11766: last;
1.827 raeburn 11767: }
11768: }
11769: }
11770: if ($action eq 'none') {
1.1271 raeburn 11771: next;
1.827 raeburn 11772: } else {
11773: my %changes;
11774: my $newend = 0;
11775: my $newstart = $now;
1.1271 raeburn 11776: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 11777: $changes{$action}{$newkey} = {
1.1271 raeburn 11778: type => $accesstype,
1.827 raeburn 11779: time => {
11780: start => $newstart,
11781: end => $newend,
11782: },
11783: };
1.1271 raeburn 11784: if ($accesstype eq 'ip') {
11785: $changes{$action}{$newkey}{'ip'} = [$ip];
11786: }
1.827 raeburn 11787: my ($outcome,$deloutcome,$new_values,$translation) =
11788: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 11789: unless ($outcome eq 'ok') {
11790: $errors .= $outcome.' ';
11791: }
1.827 raeburn 11792: }
1.1271 raeburn 11793: }
11794: if ($errors) {
11795: $errors =~ s/\s$//;
11796: return $errors;
1.827 raeburn 11797: } else {
1.1271 raeburn 11798: return 'ok';
1.827 raeburn 11799: }
11800: }
11801:
1.745 raeburn 11802: #------------------------------------------------------Get Marked as Read Only
11803:
11804: sub get_marked_as_readonly {
11805: my ($domain,$user,$what,$group) = @_;
11806: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11807: my @readonly_files;
1.629 banghart 11808: my $cmp1=$what;
11809: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11810: while (my ($file_name,$value) = each(%{$current_permissions})) {
11811: if (defined($group)) {
11812: if ($file_name !~ m-^\Q$group\E/-) {
11813: next;
11814: }
11815: }
1.561 banghart 11816: if (ref($value) eq "ARRAY"){
11817: foreach my $stored_what (@{$value}) {
1.629 banghart 11818: my $cmp2=$stored_what;
1.759 albertel 11819: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11820: $cmp2=join('',@{$stored_what});
1.745 raeburn 11821: }
1.629 banghart 11822: if ($cmp1 eq $cmp2) {
1.561 banghart 11823: push(@readonly_files, $file_name);
1.745 raeburn 11824: last;
1.563 banghart 11825: } elsif (!defined($what)) {
11826: push(@readonly_files, $file_name);
1.745 raeburn 11827: last;
1.561 banghart 11828: }
11829: }
1.745 raeburn 11830: }
1.561 banghart 11831: }
11832: return @readonly_files;
11833: }
1.577 banghart 11834: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11835:
1.577 banghart 11836: sub get_marked_as_readonly_hash {
1.745 raeburn 11837: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11838: my %readonly_files;
1.745 raeburn 11839: while (my ($file_name,$value) = each(%{$current_permissions})) {
11840: if (defined($group)) {
11841: if ($file_name !~ m-^\Q$group\E/-) {
11842: next;
11843: }
11844: }
1.577 banghart 11845: if (ref($value) eq "ARRAY"){
11846: foreach my $stored_what (@{$value}) {
1.745 raeburn 11847: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11848: foreach my $lock_descriptor(@{$stored_what}) {
11849: if ($lock_descriptor eq 'graded') {
11850: $readonly_files{$file_name} = 'graded';
11851: } elsif ($lock_descriptor eq 'handback') {
11852: $readonly_files{$file_name} = 'handback';
11853: } else {
11854: if (!exists($readonly_files{$file_name})) {
11855: $readonly_files{$file_name} = 'locked';
11856: }
11857: }
1.745 raeburn 11858: }
1.750 banghart 11859: }
1.577 banghart 11860: }
11861: }
11862: }
11863: return %readonly_files;
11864: }
1.559 banghart 11865: # ------------------------------------------------------------ Unmark as Read Only
11866:
11867: sub unmark_as_readonly {
1.629 banghart 11868: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11869: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11870: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11871: $file_name = &declutter_portfile($file_name);
1.634 albertel 11872: my $symb_crs = $what;
11873: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11874: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11875: my ($tmp)=keys(%current_permissions);
11876: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11877: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11878: foreach my $file (@readonly_files) {
1.759 albertel 11879: my $clean_file = &declutter_portfile($file);
11880: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11881: my $current_locks = $current_permissions{$file};
1.563 banghart 11882: my @new_locks;
11883: my @del_keys;
11884: if (ref($current_locks) eq "ARRAY"){
11885: foreach my $locker (@{$current_locks}) {
1.632 albertel 11886: my $compare=$locker;
1.749 raeburn 11887: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11888: $compare=join('',@{$locker});
1.746 raeburn 11889: if ($compare ne $symb_crs) {
11890: push(@new_locks, $locker);
11891: }
1.563 banghart 11892: }
11893: }
1.650 albertel 11894: if (scalar(@new_locks) > 0) {
1.563 banghart 11895: $current_permissions{$file} = \@new_locks;
11896: } else {
11897: push(@del_keys, $file);
1.613 albertel 11898: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11899: delete($current_permissions{$file});
1.563 banghart 11900: }
11901: }
1.561 banghart 11902: }
1.613 albertel 11903: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11904: return;
11905: }
1.512 banghart 11906:
1.17 www 11907: # ------------------------------------------------------------ Directory lister
11908:
11909: sub dirlist {
1.955 raeburn 11910: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11911: $uri=~s/^\///;
11912: $uri=~s/\/$//;
1.253 stredwic 11913: my ($udom, $uname);
1.955 raeburn 11914: if ($getuserdir) {
1.253 stredwic 11915: $udom = $userdomain;
11916: $uname = $username;
1.955 raeburn 11917: } else {
11918: (undef,$udom,$uname)=split(/\//,$uri);
11919: if(defined($userdomain)) {
11920: $udom = $userdomain;
11921: }
11922: if(defined($username)) {
11923: $uname = $username;
11924: }
1.253 stredwic 11925: }
1.955 raeburn 11926: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11927:
1.955 raeburn 11928: $dirRoot = $perlvar{'lonDocRoot'};
11929: if (defined($getpropath)) {
11930: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11931: $dirRoot =~ s/\/$//;
1.955 raeburn 11932: } elsif (defined($getuserdir)) {
11933: my $subdir=$uname.'__';
11934: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11935: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11936: ."/$udom/$subdir/$uname";
11937: } elsif (defined($alternateRoot)) {
11938: $dirRoot = $alternateRoot;
1.751 banghart 11939: }
1.253 stredwic 11940:
11941: if($udom) {
11942: if($uname) {
1.1135 raeburn 11943: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11944: if ($uhome eq 'no_host') {
11945: return ([],'no_host');
11946: }
1.955 raeburn 11947: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11948: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11949: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11950: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11951: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11952: } else {
11953: @listing_results = map { &unescape($_); } split(/:/,$listing);
11954: }
1.605 matthew 11955: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11956: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11957: @listing_results = split(/:/,$listing);
11958: } else {
11959: @listing_results = map { &unescape($_); } split(/:/,$listing);
11960: }
1.1135 raeburn 11961: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11962: ($listing eq 'rejected') || ($listing eq 'refused') ||
11963: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11964: return ([],$listing);
11965: } else {
11966: return (\@listing_results);
1.1135 raeburn 11967: }
1.955 raeburn 11968: } elsif(!$alternateRoot) {
1.1136 raeburn 11969: my (%allusers,%listerror);
1.841 albertel 11970: my %servers = &get_servers($udom,'library');
1.955 raeburn 11971: foreach my $tryserver (keys(%servers)) {
11972: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11973: &escape($udom),$tryserver);
11974: if ($listing eq 'unknown_cmd') {
11975: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11976: $udom, $tryserver);
11977: } else {
11978: @listing_results = map { &unescape($_); } split(/:/,$listing);
11979: }
1.841 albertel 11980: if ($listing eq 'unknown_cmd') {
11981: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11982: $udom, $tryserver);
11983: @listing_results = split(/:/,$listing);
11984: } else {
11985: @listing_results =
11986: map { &unescape($_); } split(/:/,$listing);
11987: }
1.1136 raeburn 11988: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11989: ($listing eq 'rejected') || ($listing eq 'refused') ||
11990: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11991: $listerror{$tryserver} = $listing;
11992: } else {
1.841 albertel 11993: foreach my $line (@listing_results) {
11994: my ($entry) = split(/&/,$line,2);
11995: $allusers{$entry} = 1;
11996: }
11997: }
1.253 stredwic 11998: }
1.1136 raeburn 11999: my @alluserslist=();
1.800 albertel 12000: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 12001: push(@alluserslist,$user.'&user');
1.253 stredwic 12002: }
1.1318 droeschl 12003:
12004: if (!%listerror) {
12005: # no errors
12006: return (\@alluserslist);
12007: } elsif (scalar(keys(%servers)) == 1) {
12008: # one library server, one error
12009: my ($key) = keys(%listerror);
12010: return (\@alluserslist, $listerror{$key});
12011: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
12012: # con_lost indicates that we might miss data from at least one
12013: # library server
12014: return (\@alluserslist, 'con_lost');
12015: } else {
12016: # multiple library servers and no con_lost -> data should be
12017: # complete.
12018: return (\@alluserslist);
12019: }
12020:
1.253 stredwic 12021: } else {
1.1136 raeburn 12022: return ([],'missing username');
1.253 stredwic 12023: }
1.955 raeburn 12024: } elsif(!defined($getpropath)) {
1.1136 raeburn 12025: my $path = $perlvar{'lonDocRoot'}.'/res/';
12026: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
12027: return (\@all_domains);
1.955 raeburn 12028: } else {
1.1136 raeburn 12029: return ([],'missing domain');
1.275 stredwic 12030: }
12031: }
12032:
12033: # --------------------------------------------- GetFileTimestamp
12034: # This function utilizes dirlist and returns the date stamp for
12035: # when it was last modified. It will also return an error of -1
12036: # if an error occurs
12037:
12038: sub GetFileTimestamp {
1.955 raeburn 12039: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 12040: $studentDomain = &LONCAPA::clean_domain($studentDomain);
12041: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 12042: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
12043: undef,$getuserdir);
12044: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12045: return -1;
12046: }
12047: if (ref($fileref) eq 'ARRAY') {
12048: my @stats = split('&',$fileref->[0]);
1.375 matthew 12049: # @stats contains first the filename, then the stat output
12050: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 12051: } else {
12052: return -1;
1.253 stredwic 12053: }
1.26 www 12054: }
12055:
1.712 albertel 12056: sub stat_file {
12057: my ($uri) = @_;
1.787 albertel 12058: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 12059:
1.955 raeburn 12060: my ($udom,$uname,$file);
1.712 albertel 12061: if ($uri =~ m-^/(uploaded|editupload)/-) {
12062: ($udom,$uname,$file) =
1.811 albertel 12063: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 12064: $file = 'userfiles/'.$file;
12065: }
12066: if ($uri =~ m-^/res/-) {
12067: ($udom,$uname) =
1.807 albertel 12068: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 12069: $file = $uri;
12070: }
12071:
12072: if (!$udom || !$uname || !$file) {
12073: # unable to handle the uri
12074: return ();
12075: }
1.956 raeburn 12076: my $getpropath;
12077: if ($file =~ /^userfiles\//) {
12078: $getpropath = 1;
12079: }
1.1136 raeburn 12080: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12081: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12082: return ();
12083: } else {
12084: if (ref($listref) eq 'ARRAY') {
12085: my @stats = split('&',$listref->[0]);
12086: shift(@stats); #filename is first
12087: return @stats;
12088: }
1.712 albertel 12089: }
12090: return ();
12091: }
12092:
1.1313 raeburn 12093: # --------------------------------------------------------- recursedirs
12094: # Recursive function to traverse either a specific user's Authoring Space
12095: # or corresponding Published Resource Space, and populate the hash ref:
12096: # $dirhashref with URLs of all directories, and if $filehashref hash
12097: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
1.1503 raeburn 12098: # or .rights files in resource space, and .meta, .save, .log, .bak and
12099: # .rights files in Authoring Space.
1.1313 raeburn 12100: #
12101: # Inputs:
12102: #
12103: # $is_home - true if current server is home server for user's space
1.1503 raeburn 12104: # $recurse - if true will also traverse subdirectories recursively
12105: # $include - reference to hash containing allowed file extensions. If provided,
12106: # files which do not have a matching extension will be ignored.
12107: # $exclude - reference to hash containing excluded file extensions. If provided,
12108: # files which have a matching extension will be ignored.
12109: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
12110: # directory with first file found (with acceptable extension).
1.1505 raeburn 12111: # $addtopdir - if true, set $dirhashref->{'/'} = 1
1.1313 raeburn 12112: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12113: # $relpath - Current path (relative to top level).
12114: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12115: # $filehashref - reference to hash to populate with URLs of files (Optional)
12116: #
12117: # Returns: nothing
12118: #
12119: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12120: #
12121: # Currently used by interface/londocs.pm to create linked select boxes for
12122: # directory and filename to import a Course "Author" resource into a course, and
12123: # also to create linked select boxes for Authoring Space and Directory to choose
12124: # save location for creation of a new "standard" problem from the Course Editor.
12125: #
12126:
12127: sub recursedirs {
1.1505 raeburn 12128: my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
1.1313 raeburn 12129: return unless (ref($dirhashref) eq 'HASH');
1.1503 raeburn 12130: my $docroot = $perlvar{'lonDocRoot'};
1.1313 raeburn 12131: my $currpath = $docroot.$toppath;
1.1503 raeburn 12132: if ($relpath ne '') {
1.1313 raeburn 12133: $currpath .= "/$relpath";
12134: }
1.1503 raeburn 12135: my ($savefile,$checkinc,$checkexc);
1.1313 raeburn 12136: if (ref($filehashref)) {
12137: $savefile = 1;
12138: }
1.1503 raeburn 12139: if (ref($include) eq 'HASH') {
12140: $checkinc = 1;
12141: }
12142: if (ref($exclude) eq 'HASH') {
12143: $checkexc = 1;
12144: }
1.1313 raeburn 12145: if ($is_home) {
1.1505 raeburn 12146: if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
1.1503 raeburn 12147: my $filecount = 0;
1.1313 raeburn 12148: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12149: next if ($item eq '');
12150: if (-d "$currpath/$item") {
12151: my $newpath;
1.1503 raeburn 12152: if ($relpath ne '') {
1.1313 raeburn 12153: $newpath = "$relpath/$item";
12154: } else {
12155: $newpath = $item;
12156: }
12157: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
1.1503 raeburn 12158: if ($recurse) {
1.1505 raeburn 12159: &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
1.1503 raeburn 12160: }
12161: } elsif (($savefile) || ($relpath eq '')) {
12162: next if ($nonemptydir && $filecount);
12163: if ($checkinc || $checkexc) {
12164: my ($extension) = ($item =~ /\.(\w+)$/);
12165: if ($checkinc) {
12166: next unless ($extension && $include->{$extension});
12167: }
12168: if ($checkexc) {
12169: next if ($extension && $exclude->{$extension});
12170: }
12171: }
1.1505 raeburn 12172: if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
1.1503 raeburn 12173: $dirhashref->{'/'} = 1;
12174: }
12175: if ($savefile) {
12176: if ($relpath eq '') {
12177: $filehashref->{'/'}{$item} = 1;
12178: } else {
1.1313 raeburn 12179: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12180: }
12181: }
1.1503 raeburn 12182: $filecount ++;
1.1313 raeburn 12183: }
12184: }
12185: closedir($dirh);
12186: }
12187: } else {
12188: my ($dirlistref,$listerror) =
12189: &dirlist($toppath.$relpath);
12190: my @dir_lines;
12191: my $dirptr=16384;
12192: if (ref($dirlistref) eq 'ARRAY') {
1.1503 raeburn 12193: my $filecount = 0;
1.1313 raeburn 12194: foreach my $dir_line (sort
12195: {
12196: my ($afile)=split('&',$a,2);
12197: my ($bfile)=split('&',$b,2);
12198: return (lc($afile) cmp lc($bfile));
12199: } (@{$dirlistref})) {
12200: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12201: split(/\&/,$dir_line,16);
12202: $item =~ s/\s+$//;
12203: next if (($item =~ /^\.\.?$/) || ($obs));
12204: if ($dirptr&$testdir) {
12205: my $newpath;
12206: if ($relpath) {
12207: $newpath = "$relpath/$item";
12208: } else {
12209: $newpath = $item;
12210: }
12211: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
1.1503 raeburn 12212: if ($recurse) {
1.1505 raeburn 12213: &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
1.1503 raeburn 12214: }
12215: } elsif (($savefile) || ($relpath eq '')) {
12216: next if ($nonemptydir && $filecount);
12217: if ($checkinc || $checkexc) {
12218: my $extension;
12219: if ($checkinc) {
12220: next unless ($extension && $include->{$extension});
12221: }
12222: if ($checkexc) {
12223: next if ($extension && $exclude->{$extension});
12224: }
12225: }
12226: if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12227: $dirhashref->{'/'} = 1;
12228: }
12229: if ($savefile) {
12230: if ($relpath eq '') {
12231: $filehashref->{'/'}{$item} = 1;
12232: } else {
12233: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
1.1313 raeburn 12234: }
12235: }
1.1503 raeburn 12236: $filecount ++;
1.1313 raeburn 12237: }
12238: }
12239: }
12240: }
1.1505 raeburn 12241: if ($addtopdir) {
12242: if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12243: $dirhashref->{'/'} = 1;
12244: }
12245: }
1.1313 raeburn 12246: return;
12247: }
12248:
1.1503 raeburn 12249: sub priv_exclude {
12250: return {
12251: meta => 1,
12252: save => 1,
12253: log => 1,
12254: bak => 1,
12255: rights => 1,
12256: DS_Store => 1,
12257: };
12258: }
12259:
1.26 www 12260: # -------------------------------------------------------- Value of a Condition
12261:
1.713 albertel 12262: # gets the value of a specific preevaluated condition
12263: # stored in the string $env{user.state.<cid>}
12264: # or looks up a condition reference in the bighash and if if hasn't
12265: # already been evaluated recurses into docondval to get the value of
12266: # the condition, then memoizing it to
12267: # $env{user.state.<cid>.<condition>}
1.40 www 12268: sub directcondval {
12269: my $number=shift;
1.620 albertel 12270: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 12271: &Apache::lonuserstate::evalstate();
12272: }
1.713 albertel 12273: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12274: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12275: } elsif ($number =~ /^_/) {
12276: my $sub_condition;
12277: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12278: &GDBM_READER(),0640)) {
12279: $sub_condition=$bighash{'conditions'.$number};
12280: untie(%bighash);
12281: }
12282: my $value = &docondval($sub_condition);
1.949 raeburn 12283: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 12284: return $value;
12285: }
1.620 albertel 12286: if ($env{'user.state.'.$env{'request.course.id'}}) {
12287: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 12288: } else {
12289: return 2;
12290: }
12291: }
12292:
1.713 albertel 12293: # get the collection of conditions for this resource
1.26 www 12294: sub condval {
12295: my $condidx=shift;
1.54 www 12296: my $allpathcond='';
1.713 albertel 12297: foreach my $cond (split(/\|/,$condidx)) {
12298: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12299: $allpathcond.=
12300: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12301: }
1.191 harris41 12302: }
1.54 www 12303: $allpathcond=~s/\|$//;
1.713 albertel 12304: return &docondval($allpathcond);
12305: }
12306:
12307: #evaluates an expression of conditions
12308: sub docondval {
12309: my ($allpathcond) = @_;
12310: my $result=0;
12311: if ($env{'request.course.id'}
12312: && defined($allpathcond)) {
12313: my $operand='|';
12314: my @stack;
12315: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12316: if ($chunk eq '(') {
12317: push @stack,($operand,$result);
12318: } elsif ($chunk eq ')') {
12319: my $before=pop @stack;
12320: if (pop @stack eq '&') {
12321: $result=$result>$before?$before:$result;
12322: } else {
12323: $result=$result>$before?$result:$before;
12324: }
12325: } elsif (($chunk eq '&') || ($chunk eq '|')) {
12326: $operand=$chunk;
12327: } else {
12328: my $new=directcondval($chunk);
12329: if ($operand eq '&') {
12330: $result=$result>$new?$new:$result;
12331: } else {
12332: $result=$result>$new?$result:$new;
12333: }
12334: }
12335: }
1.26 www 12336: }
12337: return $result;
1.421 albertel 12338: }
12339:
12340: # ---------------------------------------------------- Devalidate courseresdata
12341:
12342: sub devalidatecourseresdata {
12343: my ($coursenum,$coursedomain)=@_;
12344: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12345: &devalidate_cache_new('courseres',$hashid);
1.28 www 12346: }
12347:
1.763 www 12348:
1.200 www 12349: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 12350: #
12351: # Parameters:
12352: # $coursenum - Number of the course.
12353: # $coursedomain - Domain at which the course was created.
12354: # Returns:
12355: # A hash of the course parameters along (I think) with timestamps
12356: # and version info.
1.877 foxr 12357:
1.624 albertel 12358: sub get_courseresdata {
12359: my ($coursenum,$coursedomain)=@_;
1.200 www 12360: my $coursehom=&homeserver($coursenum,$coursedomain);
12361: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12362: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 12363: my %dumpreply;
1.417 albertel 12364: unless (defined($cached)) {
1.624 albertel 12365: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 12366: $result=\%dumpreply;
1.251 albertel 12367: my ($tmp) = keys(%dumpreply);
12368: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 12369: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 12370: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12371: return $tmp;
1.416 albertel 12372: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 12373: $result=undef;
1.599 albertel 12374: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 12375: }
12376: }
1.624 albertel 12377: return $result;
12378: }
12379:
1.633 albertel 12380: sub devalidateuserresdata {
12381: my ($uname,$udom)=@_;
12382: my $hashid="$udom:$uname";
12383: &devalidate_cache_new('userres',$hashid);
12384: }
12385:
1.624 albertel 12386: sub get_userresdata {
12387: my ($uname,$udom)=@_;
12388: #most student don\'t have any data set, check if there is some data
12389: if (&EXT_cache_status($udom,$uname)) { return undef; }
12390:
12391: my $hashid="$udom:$uname";
12392: my ($result,$cached)=&is_cached_new('userres',$hashid);
12393: if (!defined($cached)) {
12394: my %resourcedata=&dump('resourcedata',$udom,$uname);
12395: $result=\%resourcedata;
12396: &do_cache_new('userres',$hashid,$result,600);
12397: }
12398: my ($tmp)=keys(%$result);
12399: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12400: return $result;
12401: }
12402: #error 2 occurs when the .db doesn't exist
12403: if ($tmp!~/error: 2 /) {
1.1294 raeburn 12404: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12405: &logthis("<font color=\"blue\">WARNING:".
12406: " Trying to get resource data for ".
12407: $uname." at ".$udom.": ".
12408: $tmp."</font>");
12409: }
1.624 albertel 12410: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 12411: #&EXT_cache_set($udom,$uname);
12412: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 12413: undef($tmp); # not really an error so don't send it back
1.624 albertel 12414: }
12415: return $tmp;
12416: }
1.879 foxr 12417: #----------------------------------------------- resdata - return resource data
12418: # Purpose:
12419: # Return resource data for either users or for a course.
12420: # Parameters:
12421: # $name - Course/user name.
12422: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 12423: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 12424: # $mapp - decluttered URL of enclosing map
12425: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
12426: # $recurseup - Ref to array of map URLs, starting with map containing
12427: # $mapp up through hierarchy of nested maps to top level map.
12428: # $courseid - CourseID (first part of param identifier).
12429: # $modifier - Middle part of param identifier.
12430: # $what - Last part of param identifier.
1.879 foxr 12431: # @which - Array of names of resources desired.
12432: # Returns:
12433: # The value of the first reasource in @which that is found in the
12434: # resource hash.
12435: # Exceptional Conditions:
12436: # If the $type passed in is not valid (not the string 'course' or
12437: # 'user', an undefined reference is returned.
12438: # If none of the resources are found, an undef is returned
1.624 albertel 12439: sub resdata {
1.1301 raeburn 12440: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12441: $modifier,$what,@which)=@_;
1.624 albertel 12442: my $result;
12443: if ($type eq 'course') {
12444: $result=&get_courseresdata($name,$domain);
12445: } elsif ($type eq 'user') {
12446: $result=&get_userresdata($name,$domain);
12447: }
12448: if (!ref($result)) { return $result; }
1.251 albertel 12449: foreach my $item (@which) {
1.1301 raeburn 12450: if ($item->[1] eq 'course') {
12451: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12452: unless ($$recursed) {
1.1302 raeburn 12453: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 12454: $$recursed = 1;
12455: }
12456: foreach my $item (@${recurseup}) {
12457: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12458: last if (defined($result->{$norecursechk}));
12459: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12460: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12461: }
12462: }
12463: }
12464: if (defined($result->{$item->[0]})) {
1.927 albertel 12465: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 12466: }
1.250 albertel 12467: }
1.291 albertel 12468: return undef;
1.200 www 12469: }
12470:
1.1360 raeburn 12471: sub get_domain_lti {
12472: my ($cdom,$context) = @_;
1.1483 raeburn 12473: my ($name,$cachename,%lti);
1.1360 raeburn 12474: if ($context eq 'consumer') {
12475: $name = 'ltitools';
12476: } elsif ($context eq 'provider') {
12477: $name = 'lti';
1.1483 raeburn 12478: } elsif ($context eq 'linkprot') {
12479: $name = 'ltisec';
1.1360 raeburn 12480: } else {
12481: return %lti;
12482: }
1.1483 raeburn 12483:
12484: if ($context eq 'linkprot') {
12485: $cachename = $context;
12486: } else {
12487: $cachename = $name;
12488: }
12489:
12490: my ($result,$cached)=&is_cached_new($cachename,$cdom);
1.1298 raeburn 12491: if (defined($cached)) {
12492: if (ref($result) eq 'HASH') {
1.1360 raeburn 12493: %lti = %{$result};
1.1298 raeburn 12494: }
12495: } else {
1.1360 raeburn 12496: my %domconfig = &get_dom('configuration',[$name],$cdom);
12497: if (ref($domconfig{$name}) eq 'HASH') {
1.1483 raeburn 12498: if ($context eq 'linkprot') {
12499: if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12500: %lti = %{$domconfig{$name}{'linkprot'}};
12501: }
12502: } else {
12503: %lti = %{$domconfig{$name}};
12504: }
12505: if (($context eq 'consumer') && (keys(%lti))) {
12506: my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
12507: if (ref($encdomconfig{$name}) eq 'HASH') {
12508: foreach my $id (keys(%lti)) {
12509: if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12510: foreach my $item ('key','secret') {
12511: $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12512: }
1.1344 raeburn 12513: }
12514: }
12515: }
12516: }
1.1298 raeburn 12517: }
12518: my $cachetime = 24*60*60;
1.1483 raeburn 12519: &do_cache_new($cachename,$cdom,\%lti,$cachetime);
1.1298 raeburn 12520: }
1.1360 raeburn 12521: return %lti;
1.1298 raeburn 12522: }
12523:
1.1463 raeburn 12524: sub get_course_lti {
12525: my ($cnum,$cdom) = @_;
12526: my $hashid=$cdom.'_'.$cnum;
12527: my %courselti;
12528: my ($result,$cached)=&is_cached_new('courselti',$hashid);
12529: if (defined($cached)) {
12530: if (ref($result) eq 'HASH') {
12531: %courselti = %{$result};
12532: }
12533: } else {
12534: %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
12535: my $cachetime = 24*60*60;
12536: &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
12537: }
12538: return %courselti;
12539: }
12540:
1.1479 raeburn 12541: sub courselti_itemid {
12542: my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12543: my ($chome,$itemid);
12544: $chome = &homeserver($cnum,$cdom);
12545: return if ($chome eq 'no_host');
12546: if (ref($params) eq 'HASH') {
12547: my $rep;
12548: if (grep { $_ eq $chome } current_machine_ids()) {
12549: $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12550: } else {
12551: my $escurl = &escape($url);
12552: my $escmethod = &escape($method);
12553: my $items = &freeze_escape($params);
12554: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12555: }
12556: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12557: ($rep eq 'unknown_cmd')) {
12558: $itemid = $rep;
12559: }
12560: }
12561: return $itemid;
12562: }
12563:
12564: sub domainlti_itemid {
12565: my ($cdom,$url,$method,$params,$context) = @_;
12566: my ($primary_id,$itemid);
12567: $primary_id = &domain($cdom,'primary');
12568: return if ($primary_id eq '');
12569: if (ref($params) eq 'HASH') {
12570: my $rep;
12571: if (grep { $_ eq $primary_id } current_machine_ids()) {
12572: $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12573: } else {
12574: my $cnum = '';
12575: my $escurl = &escape($url);
12576: my $escmethod = &escape($method);
12577: my $items = &freeze_escape($params);
12578: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12579: }
12580: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12581: ($rep eq 'unknown_cmd')) {
12582: $itemid = $rep;
12583: }
12584: }
12585: return $itemid;
12586: }
12587:
1.1496 raeburn 12588: sub count_supptools {
12589: my ($cnum,$cdom,$ignorecache,$reload)=@_;
12590: my $hashid=$cnum.':'.$cdom;
12591: my ($numexttools,$cached);
12592: unless ($ignorecache) {
12593: ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
12594: }
12595: unless (defined($cached)) {
12596: my $chome=&homeserver($cnum,$cdom);
12597: $numexttools = 0;
12598: unless ($chome eq 'no_host') {
1.1500 raeburn 12599: my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
1.1496 raeburn 12600: if (ref($supplemental) eq 'HASH') {
12601: if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12602: foreach my $key (keys(%{$supplemental->{'ids'}})) {
12603: if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
12604: $numexttools ++;
12605: }
12606: }
12607: }
12608: }
12609: }
12610: &do_cache_new('supptools',$hashid,$numexttools,600);
12611: }
12612: return $numexttools;
12613: }
12614:
12615: sub has_unhidden_suppfiles {
1.1498 raeburn 12616: my ($cnum,$cdom,$ignorecache,$possdel)=@_;
1.1236 raeburn 12617: my $hashid=$cnum.':'.$cdom;
1.1496 raeburn 12618: my ($showsupp,$cached);
1.1236 raeburn 12619: unless ($ignorecache) {
1.1496 raeburn 12620: ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
1.1236 raeburn 12621: }
12622: unless (defined($cached)) {
12623: my $chome=&homeserver($cnum,$cdom);
12624: unless ($chome eq 'no_host') {
1.1500 raeburn 12625: my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
1.1496 raeburn 12626: if (ref($supplemental) eq 'HASH') {
12627: if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12628: foreach my $key (keys(%{$supplemental->{'ids'}})) {
12629: next if ($key =~ /\.sequence$/);
12630: if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
12631: foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
12632: unless ($supplemental->{'hidden'}->{$id}) {
12633: $showsupp = 1;
12634: last;
12635: }
12636: }
12637: }
12638: last if ($showsupp);
12639: }
12640: }
12641: }
1.1236 raeburn 12642: }
1.1496 raeburn 12643: &do_cache_new('showsupp',$hashid,$showsupp,600);
1.1236 raeburn 12644: }
1.1496 raeburn 12645: return $showsupp;
12646: }
12647:
1.379 matthew 12648: #
12649: # EXT resource caching routines
12650: #
12651:
1.1302 raeburn 12652: {
12653: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12654: #
12655: # The course for which we cache
12656: my $cachedmapkey='';
12657: # The cached recursive maps for this course
12658: my %cachedmaps=();
12659: # When this was last done
12660: my $cachedmaptime='';
12661:
1.379 matthew 12662: sub clear_EXT_cache_status {
1.383 albertel 12663: &delenv('cache.EXT.');
1.379 matthew 12664: }
12665:
12666: sub EXT_cache_status {
12667: my ($target_domain,$target_user) = @_;
1.383 albertel 12668: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 12669: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 12670: # We know already the user has no data
12671: return 1;
12672: } else {
12673: return 0;
12674: }
12675: }
12676:
12677: sub EXT_cache_set {
12678: my ($target_domain,$target_user) = @_;
1.383 albertel 12679: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 12680: #&appenv({$cachename => time});
1.379 matthew 12681: }
12682:
1.28 www 12683: # --------------------------------------------------------- Value of a Variable
1.58 www 12684: sub EXT {
1.715 albertel 12685:
1.1461 raeburn 12686: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
1.68 www 12687: unless ($varname) { return ''; }
1.218 albertel 12688: #get real user name/domain, courseid and symb
12689: my $courseid;
1.359 albertel 12690: my $publicuser;
1.427 www 12691: if ($symbparm) {
12692: $symbparm=&get_symb_from_alias($symbparm);
12693: }
1.218 albertel 12694: if (!($uname && $udom)) {
1.790 albertel 12695: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 12696: if (!$symbparm) { $symbparm=$cursymb; }
12697: } else {
1.620 albertel 12698: $courseid=$env{'request.course.id'};
1.218 albertel 12699: }
1.48 www 12700: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12701: my $rest;
1.320 albertel 12702: if (defined($therest[0])) {
1.48 www 12703: $rest=join('.',@therest);
12704: } else {
12705: $rest='';
12706: }
1.320 albertel 12707:
1.57 www 12708: my $qualifierrest=$qualifier;
12709: if ($rest) { $qualifierrest.='.'.$rest; }
12710: my $spacequalifierrest=$space;
12711: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 12712: if ($realm eq 'user') {
1.48 www 12713: # --------------------------------------------------------------- user.resource
12714: if ($space eq 'resource') {
1.651 albertel 12715: if ( (defined($Apache::lonhomework::parsing_a_problem)
12716: || defined($Apache::lonhomework::parsing_a_task))
12717: &&
1.1469 raeburn 12718: ($symbparm eq &symbread()) ) {
1.744 albertel 12719: # if we are in the middle of processing the resource the
12720: # get the value we are planning on committing
12721: if (defined($Apache::lonhomework::results{$qualifierrest})) {
12722: return $Apache::lonhomework::results{$qualifierrest};
12723: } else {
12724: return $Apache::lonhomework::history{$qualifierrest};
12725: }
1.335 albertel 12726: } else {
1.359 albertel 12727: my %restored;
1.620 albertel 12728: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 12729: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12730: } else {
12731: %restored=&restore($symbparm,$courseid,$udom,$uname);
12732: }
1.335 albertel 12733: return $restored{$qualifierrest};
12734: }
1.48 www 12735: # ----------------------------------------------------------------- user.access
12736: } elsif ($space eq 'access') {
1.218 albertel 12737: # FIXME - not supporting calls for a specific user
1.48 www 12738: return &allowed($qualifier,$rest);
12739: # ------------------------------------------ user.preferences, user.environment
12740: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 12741: if (($uname eq $env{'user.name'}) &&
12742: ($udom eq $env{'user.domain'})) {
12743: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 12744: } else {
1.359 albertel 12745: my %returnhash;
12746: if (!$publicuser) {
12747: %returnhash=&userenvironment($udom,$uname,
12748: $qualifierrest);
12749: }
1.218 albertel 12750: return $returnhash{$qualifierrest};
12751: }
1.48 www 12752: # ----------------------------------------------------------------- user.course
12753: } elsif ($space eq 'course') {
1.218 albertel 12754: # FIXME - not supporting calls for a specific user
1.620 albertel 12755: return $env{join('.',('request.course',$qualifier))};
1.48 www 12756: # ------------------------------------------------------------------- user.role
12757: } elsif ($space eq 'role') {
1.218 albertel 12758: # FIXME - not supporting calls for a specific user
1.620 albertel 12759: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 12760: if ($qualifier eq 'value') {
12761: return $role;
12762: } elsif ($qualifier eq 'extent') {
12763: return $where;
12764: }
12765: # ----------------------------------------------------------------- user.domain
12766: } elsif ($space eq 'domain') {
1.218 albertel 12767: return $udom;
1.48 www 12768: # ------------------------------------------------------------------- user.name
12769: } elsif ($space eq 'name') {
1.218 albertel 12770: return $uname;
1.48 www 12771: # ---------------------------------------------------- Any other user namespace
1.29 www 12772: } else {
1.359 albertel 12773: my %reply;
12774: if (!$publicuser) {
12775: %reply=&get($space,[$qualifierrest],$udom,$uname);
12776: }
12777: return $reply{$qualifierrest};
1.48 www 12778: }
1.236 www 12779: } elsif ($realm eq 'query') {
12780: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 12781: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12782: [$spacequalifierrest]);
1.620 albertel 12783: return $env{'form.'.$spacequalifierrest};
1.236 www 12784: } elsif ($realm eq 'request') {
1.48 www 12785: # ------------------------------------------------------------- request.browser
12786: if ($space eq 'browser') {
1.1145 bisitz 12787: return $env{'browser.'.$qualifier};
1.57 www 12788: # ------------------------------------------------------------ request.filename
12789: } else {
1.620 albertel 12790: return $env{'request.'.$spacequalifierrest};
1.29 www 12791: }
1.28 www 12792: } elsif ($realm eq 'course') {
1.48 www 12793: # ---------------------------------------------------------- course.description
1.620 albertel 12794: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 12795: } elsif ($realm eq 'resource') {
1.165 www 12796:
1.620 albertel 12797: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 12798: if (!$symbparm) { $symbparm=&symbread(); }
12799: }
1.693 albertel 12800:
1.1232 raeburn 12801: if ($qualifier eq '') {
12802: if ($space eq 'title') {
12803: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12804: return &gettitle($symbparm);
12805: }
1.693 albertel 12806:
1.1232 raeburn 12807: if ($space eq 'map') {
12808: my ($map) = &decode_symb($symbparm);
12809: return &symbread($map);
12810: }
12811: if ($space eq 'maptitle') {
12812: my ($map) = &decode_symb($symbparm);
12813: return &gettitle($map);
12814: }
12815: if ($space eq 'filename') {
12816: if ($symbparm) {
12817: return &clutter((&decode_symb($symbparm))[2]);
12818: }
12819: return &hreflocation('',$env{'request.filename'});
1.905 albertel 12820: }
1.1232 raeburn 12821:
1.1233 raeburn 12822: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12823: if ($space eq 'visibleparts') {
12824: my $navmap = Apache::lonnavmaps::navmap->new();
12825: my $item;
12826: if (ref($navmap)) {
12827: my $res = $navmap->getBySymb($symbparm);
12828: my $parts = $res->parts();
12829: if (ref($parts) eq 'ARRAY') {
12830: $item = join(',',@{$parts});
12831: }
12832: undef($navmap);
1.1232 raeburn 12833: }
1.1233 raeburn 12834: return $item;
1.1232 raeburn 12835: }
12836: }
12837: }
1.693 albertel 12838:
1.1301 raeburn 12839: my ($section, $group, @groups, @recurseup, $recursed);
1.1461 raeburn 12840: if (ref($recurseupref) eq 'ARRAY') {
12841: @recurseup = @{$recurseupref};
12842: $recursed = 1;
12843: }
1.1301 raeburn 12844: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 12845: if (($courseid eq '') && ($cid)) {
12846: $courseid = $cid;
12847: }
12848: if (($symbparm && $courseid) &&
12849: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 12850:
1.218 albertel 12851: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 12852:
1.60 www 12853: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 12854: my $symbp=$symbparm;
1.1301 raeburn 12855: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 12856: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 12857: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 12858: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 12859: if (($env{'user.name'} eq $uname) &&
12860: ($env{'user.domain'} eq $udom)) {
12861: $section=$env{'request.course.sec'};
1.733 raeburn 12862: @groups = split(/:/,$env{'request.course.groups'});
12863: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 12864: } else {
1.539 albertel 12865: if (! defined($usection)) {
1.551 albertel 12866: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 12867: } else {
12868: $section = $usection;
12869: }
1.733 raeburn 12870: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 12871: }
12872:
12873: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12874: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 12875: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 12876: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12877:
1.593 albertel 12878: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 12879: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 12880: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 12881: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 12882:
1.60 www 12883: # ----------------------------------------------------------- first, check user
1.624 albertel 12884:
1.1301 raeburn 12885: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12886: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 12887: ([$courselevelr,'resource'],
12888: [$courselevelm,'map' ],
1.1301 raeburn 12889: [$courseleveli,'map' ],
1.927 albertel 12890: [$courselevel, 'course' ]));
1.931 albertel 12891: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 12892:
1.594 albertel 12893: # ------------------------------------------------ second, check some of course
1.684 raeburn 12894: my $coursereply;
1.691 raeburn 12895: if (@groups > 0) {
12896: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 12897: $recurseparm,$mapparm,$spacequalifierrest,
12898: $mapp,\$recursed,\@recurseup);
12899: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 12900: }
1.96 www 12901:
1.684 raeburn 12902: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 12903: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12904: 'course',$mapp,\$recursed,\@recurseup,
12905: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 12906: ([$seclevelr, 'resource'],
12907: [$seclevelm, 'map' ],
1.1301 raeburn 12908: [$secleveli, 'map' ],
1.927 albertel 12909: [$seclevel, 'course' ],
12910: [$courselevelr,'resource']));
12911: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 12912:
1.60 www 12913: # ------------------------------------------------------ third, check map parms
1.218 albertel 12914: my %parmhash=();
12915: my $thisparm='';
12916: if (tie(%parmhash,'GDBM_File',
1.620 albertel 12917: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 12918: &GDBM_READER(),0640)) {
1.218 albertel 12919: $thisparm=$parmhash{$symbparm};
12920: untie(%parmhash);
12921: }
1.927 albertel 12922: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 12923: }
1.594 albertel 12924: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 12925:
12926: my $what = $spacequalifierrest;
12927: $what=~s/\./\_/;
1.282 albertel 12928: my $filename;
12929: if (!$symbparm) { $symbparm=&symbread(); }
12930: if ($symbparm) {
1.409 www 12931: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 12932: } else {
1.620 albertel 12933: $filename=$env{'request.filename'};
1.282 albertel 12934: }
1.1362 raeburn 12935: my $toolsymb;
12936: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12937: $toolsymb = $symbparm;
12938: }
12939: my $metadata=&metadata($filename,$what,$toolsymb);
1.927 albertel 12940: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362 raeburn 12941: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927 albertel 12942: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 12943:
1.1301 raeburn 12944: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 12945: if ($symbparm && defined($courseid) &&
1.620 albertel 12946: $courseid eq $env{'request.course.id'}) {
1.624 albertel 12947: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12948: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12949: 'course',$mapp,\$recursed,\@recurseup,
12950: $courseid,'.',$spacequalifierrest,
1.927 albertel 12951: ([$courselevelm,'map' ],
1.1301 raeburn 12952: [$courseleveli,'map' ],
1.927 albertel 12953: [$courselevel, 'course']));
12954: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 12955: }
1.145 www 12956: # ------------------------------------------------------------------ Cascade up
1.218 albertel 12957: unless ($space eq '0') {
1.336 albertel 12958: my @parts=split(/_/,$space);
12959: my $id=pop(@parts);
12960: my $part=join('_',@parts);
12961: if ($part eq '') { $part='0'; }
1.927 albertel 12962: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 12963: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 12964: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 12965: }
1.395 albertel 12966: if ($recurse) { return undef; }
1.1362 raeburn 12967: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927 albertel 12968: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 12969: # ---------------------------------------------------- Any other user namespace
12970: } elsif ($realm eq 'environment') {
12971: # ----------------------------------------------------------------- environment
1.620 albertel 12972: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12973: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 12974: } else {
1.770 albertel 12975: if ($uname eq 'anonymous' && $udom eq '') {
12976: return '';
12977: }
1.219 albertel 12978: my %returnhash=&userenvironment($udom,$uname,
12979: $spacequalifierrest);
12980: return $returnhash{$spacequalifierrest};
12981: }
1.28 www 12982: } elsif ($realm eq 'system') {
1.48 www 12983: # ----------------------------------------------------------------- system.time
12984: if ($space eq 'time') {
12985: return time;
12986: }
1.696 albertel 12987: } elsif ($realm eq 'server') {
12988: # ----------------------------------------------------------------- system.time
12989: if ($space eq 'name') {
12990: return $ENV{'SERVER_NAME'};
12991: }
1.1415 raeburn 12992: } elsif ($realm eq 'client') {
12993: if ($space eq 'remote_addr') {
1.1441 raeburn 12994: return &get_requestor_ip();
1.1415 raeburn 12995: }
1.28 www 12996: }
1.48 www 12997: return '';
1.61 www 12998: }
12999:
1.927 albertel 13000: sub get_reply {
13001: my ($reply_value) = @_;
1.940 raeburn 13002: if (ref($reply_value) eq 'ARRAY') {
13003: if (wantarray) {
13004: return @$reply_value;
13005: }
13006: return $reply_value->[0];
13007: } else {
13008: return $reply_value;
1.927 albertel 13009: }
13010: }
13011:
1.691 raeburn 13012: sub check_group_parms {
1.1301 raeburn 13013: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
13014: $recursed,$recurseupref) = @_;
13015: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
13016: [$what,'course']);
13017: my $coursereply;
1.691 raeburn 13018: foreach my $group (@{$groups}) {
1.1301 raeburn 13019: my @groupitems = ();
1.691 raeburn 13020: foreach my $level (@levels) {
1.927 albertel 13021: my $item = $courseid.'.['.$group.'].'.$level->[0];
13022: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 13023: }
1.1301 raeburn 13024: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
13025: $env{'course.'.$courseid.'.domain'},
13026: 'course',$mapp,$recursed,$recurseupref,
13027: $courseid,'.['.$group.'].',$what,
13028: @groupitems);
13029: last if (defined($coursereply));
1.691 raeburn 13030: }
13031: return $coursereply;
13032: }
13033:
1.1301 raeburn 13034: sub get_map_hierarchy {
1.1302 raeburn 13035: my ($mapname,$courseid) = @_;
13036: my @recurseup = ();
1.1301 raeburn 13037: if ($mapname) {
1.1302 raeburn 13038: if (($cachedmapkey eq $courseid) &&
13039: (abs($cachedmaptime-time)<5)) {
13040: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
13041: return @{$cachedmaps{$mapname}};
13042: }
13043: }
1.1301 raeburn 13044: my $navmap = Apache::lonnavmaps::navmap->new();
13045: if (ref($navmap)) {
13046: @recurseup = $navmap->recurseup_maps($mapname);
13047: undef($navmap);
1.1302 raeburn 13048: $cachedmaps{$mapname} = \@recurseup;
13049: $cachedmaptime=time;
13050: $cachedmapkey=$courseid;
1.1301 raeburn 13051: }
13052: }
13053: return @recurseup;
13054: }
13055:
1.1302 raeburn 13056: }
13057:
1.691 raeburn 13058: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 13059: my ($courseid,@groups) = @_;
13060: @groups = sort(@groups);
1.691 raeburn 13061: return @groups;
13062: }
13063:
1.395 albertel 13064: sub packages_tab_default {
1.1362 raeburn 13065: my ($uri,$varname,$toolsymb)=@_;
1.395 albertel 13066: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 13067:
13068: my (@extension,@specifics,$do_default);
1.1362 raeburn 13069: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395 albertel 13070: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 13071: if ($pack_type eq 'default') {
13072: $do_default=1;
13073: } elsif ($pack_type eq 'extension') {
13074: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 13075: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 13076: # only look at packages defaults for packages that this id is
1.738 albertel 13077: push(@specifics,[$package,$pack_type,$pack_part]);
13078: }
13079: }
13080: # first look for a package that matches the requested part id
13081: foreach my $package (@specifics) {
13082: my (undef,$pack_type,$pack_part)=@{$package};
13083: next if ($pack_part ne $part);
13084: if (defined($packagetab{"$pack_type&$name&default"})) {
13085: return $packagetab{"$pack_type&$name&default"};
13086: }
13087: }
13088: # look for any possible matching non extension_ package
13089: foreach my $package (@specifics) {
13090: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 13091: if (defined($packagetab{"$pack_type&$name&default"})) {
13092: return $packagetab{"$pack_type&$name&default"};
13093: }
1.585 albertel 13094: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 13095: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13096: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 13097: }
13098: }
1.738 albertel 13099: # look for any posible extension_ match
13100: foreach my $package (@extension) {
13101: my ($package,$pack_type)=@{$package};
13102: if (defined($packagetab{"$pack_type&$name&default"})) {
13103: return $packagetab{"$pack_type&$name&default"};
13104: }
13105: if (defined($packagetab{$package."&$name&default"})) {
13106: return $packagetab{$package."&$name&default"};
13107: }
13108: }
13109: # look for a global default setting
13110: if ($do_default && defined($packagetab{"default&$name&default"})) {
13111: return $packagetab{"default&$name&default"};
13112: }
1.395 albertel 13113: return undef;
13114: }
13115:
1.334 albertel 13116: sub add_prefix_and_part {
13117: my ($prefix,$part)=@_;
13118: my $keyroot;
13119: if (defined($prefix) && $prefix !~ /^__/) {
13120: # prefix that has a part already
13121: $keyroot=$prefix;
13122: } elsif (defined($prefix)) {
13123: # prefix that is missing a part
13124: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13125: } else {
13126: # no prefix at all
13127: if (defined($part)) { $keyroot='_'.$part; }
13128: }
13129: return $keyroot;
13130: }
13131:
1.71 www 13132: # ---------------------------------------------------------------- Get metadata
13133:
1.599 albertel 13134: my %metaentry;
1.1070 www 13135: my %importedpartids;
1.1369 raeburn 13136: my %importedrespids;
1.71 www 13137: sub metadata {
1.1362 raeburn 13138: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71 www 13139: $uri=&declutter($uri);
1.288 albertel 13140: # if it is a non metadata possible uri return quickly
1.529 albertel 13141: if (($uri eq '') ||
13142: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 13143: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 13144: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 13145: return undef;
13146: }
1.1261 raeburn 13147: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 13148: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 13149: return undef;
1.288 albertel 13150: }
1.73 www 13151: my $filename=$uri;
13152: $uri=~s/\.meta$//;
1.172 www 13153: #
13154: # Is the metadata already cached?
1.177 www 13155: # Look at timestamp of caching
1.172 www 13156: # Everything is cached by the main uri, libraries are never directly cached
13157: #
1.428 albertel 13158: if (!defined($liburi)) {
1.599 albertel 13159: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 13160: if (defined($cached)) { return $result->{':'.$what}; }
13161: }
1.1362 raeburn 13162:
13163: #
13164: # If the uri is for an external tool the file from
13165: # which metadata should be retrieved depends on whether
13166: # the tool had been configured to be gradable (set in the Course
13167: # Editor or Resource Editor).
13168: #
13169: # If a valid symb has been included as the third arg in the call
13170: # to &metadata() that can be used to retrieve the value of
13171: # parameter_0_gradable set for the resource, and included in the
13172: # uploaded map containing the tool. The value is retrieved via
13173: # &EXT(), if a valid symb is available. Otherwise the value of
13174: # gradable in the exttool_$marker.db file for the tool instance
1.1364 raeburn 13175: # is retrieved via &get().
13176: #
13177: # When lonuserstate::traceroute() calls lonnet::EXT() for
13178: # hiddenresource and encrypturl (during course initialization)
13179: # the map-level parameter for resource.0.gradable included in the
13180: # uploaded map containing the tool will not yet have been stored
13181: # in the user_course_parms.db file for the user's session, so in
13182: # this case fall back to retrieving gradable status from the
13183: # exttool_$marker.db file.
1.1362 raeburn 13184: #
13185: # In order to avoid an infinite loop, &metadata() will return
13186: # before a call to &EXT(), if the uri is for an external tool
13187: # and the $what for which metadata is being requested is
13188: # parameter_0_gradable or 0_gradable.
13189: #
13190:
13191: if ($uri =~ /ext\.tool$/) {
13192: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13193: return;
13194: } else {
13195: my ($checked,$use_passback);
13196: if ($toolsymb ne '') {
13197: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364 raeburn 13198: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362 raeburn 13199: $checked = 1;
13200: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13201: $use_passback = 1;
13202: }
13203: }
13204: }
13205: unless ($checked) {
13206: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13207: $marker=~s/\D//g;
1.1363 raeburn 13208: if ($marker) {
1.1362 raeburn 13209: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13210: $use_passback = $toolsettings{'gradable'};
13211: }
13212: }
13213: if ($use_passback) {
13214: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13215: } else {
13216: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13217: }
13218: }
13219: }
13220:
1.428 albertel 13221: {
1.1069 www 13222: # Imported parts would go here
1.1369 raeburn 13223: my @origfiletagids=();
1.1069 www 13224: my $importedparts=0;
1.1369 raeburn 13225:
13226: # Imported responseids would go here
13227: my $importedresponses=0;
1.172 www 13228: #
13229: # Is this a recursive call for a library?
13230: #
1.599 albertel 13231: # if (! exists($metacache{$uri})) {
13232: # $metacache{$uri}={};
13233: # }
1.924 albertel 13234: my $cachetime = 60*60;
1.171 www 13235: if ($liburi) {
13236: $liburi=&declutter($liburi);
13237: $filename=$liburi;
1.401 bowersj2 13238: } else {
1.599 albertel 13239: &devalidate_cache_new('meta',$uri);
13240: undef(%metaentry);
1.401 bowersj2 13241: }
1.140 www 13242: my %metathesekeys=();
1.73 www 13243: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 13244: my $metastring;
1.1140 www 13245: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 13246: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 13247: $metastring =
1.929 albertel 13248: &Apache::lonnet::ssi_body($which,
1.924 albertel 13249: ('grade_target' => 'meta'));
13250: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 13251: } elsif (($uri !~ m -^(editupload)/-) &&
13252: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 13253: my $file=&filelocation('',&clutter($filename));
1.599 albertel 13254: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 13255: $metastring=&getfile($file);
1.489 albertel 13256: }
1.208 albertel 13257: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 13258: my $token;
1.140 www 13259: undef %metathesekeys;
1.71 www 13260: while ($token=$parser->get_token) {
1.339 albertel 13261: if ($token->[0] eq 'S') {
13262: if (defined($token->[2]->{'package'})) {
1.172 www 13263: #
13264: # This is a package - get package info
13265: #
1.339 albertel 13266: my $package=$token->[2]->{'package'};
13267: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13268: if (defined($token->[2]->{'id'})) {
13269: $keyroot.='_'.$token->[2]->{'id'};
13270: }
1.599 albertel 13271: if ($metaentry{':packages'}) {
13272: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 13273: } else {
1.599 albertel 13274: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 13275: }
1.736 albertel 13276: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 13277: my $part=$keyroot;
13278: $part=~s/^\_//;
1.736 albertel 13279: if ($pack_entry=~/^\Q$package\E\&/ ||
13280: $pack_entry=~/^\Q$package\E_0\&/) {
13281: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 13282: # ignore package.tab specified default values
13283: # here &package_tab_default() will fetch those
13284: if ($subp eq 'default') { next; }
1.736 albertel 13285: my $value=$packagetab{$pack_entry};
1.432 albertel 13286: my $unikey;
13287: if ($pack =~ /_0$/) {
13288: $unikey='parameter_0_'.$name;
13289: $part=0;
13290: } else {
13291: $unikey='parameter'.$keyroot.'_'.$name;
13292: }
1.339 albertel 13293: if ($subp eq 'display') {
13294: $value.=' [Part: '.$part.']';
13295: }
1.599 albertel 13296: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 13297: $metathesekeys{$unikey}=1;
1.599 albertel 13298: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13299: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 13300: }
1.599 albertel 13301: if (defined($metaentry{':'.$unikey.'.default'})) {
13302: $metaentry{':'.$unikey}=
13303: $metaentry{':'.$unikey.'.default'};
1.356 albertel 13304: }
1.339 albertel 13305: }
13306: }
13307: } else {
1.172 www 13308: #
13309: # This is not a package - some other kind of start tag
1.339 albertel 13310: #
13311: my $entry=$token->[1];
1.1068 www 13312: my $unikey='';
1.175 www 13313:
1.339 albertel 13314: if ($entry eq 'import') {
1.175 www 13315: #
13316: # Importing a library here
1.339 albertel 13317: #
1.1067 www 13318: my $location=$parser->get_text('/import');
13319: my $dir=$filename;
13320: $dir=~s|[^/]*$||;
13321: $location=&filelocation($dir,$location);
1.1369 raeburn 13322:
13323: my $importid=$token->[2]->{'id'};
1.1068 www 13324: my $importmode=$token->[2]->{'importmode'};
1.1369 raeburn 13325: #
13326: # Check metadata for imported file to
13327: # see if it contained response items
13328: #
1.1372 raeburn 13329: my ($origfile,@libfilekeys);
1.1370 raeburn 13330: my %currmetaentry = %metaentry;
1.1372 raeburn 13331: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13332: $depthcount+1));
13333: if (grep(/^responseorder$/,@libfilekeys)) {
13334: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13335: undef,$depthcount+1);
13336: if ($libresponseorder ne '') {
13337: if ($#origfiletagids<0) {
13338: undef(%importedrespids);
13339: undef(%importedpartids);
13340: }
1.1373 raeburn 13341: my @respids = split(/\s*,\s*/,$libresponseorder);
13342: if (@respids) {
13343: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13344: }
13345: if ($importedrespids{$importid} ne '') {
1.1372 raeburn 13346: $importedresponses = 1;
1.1369 raeburn 13347: # We need to get the original file and the imported file to get the response order correct
13348: # Load and inspect original file
1.1372 raeburn 13349: if ($#origfiletagids<0) {
13350: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13351: $origfile=&getfile($origfilelocation);
13352: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13353: }
1.1369 raeburn 13354: }
13355: }
13356: }
1.1370 raeburn 13357: # Do not overwrite contents of %metaentry hash for resource itself with
13358: # hash populated for imported library file
13359: %metaentry = %currmetaentry;
13360: undef(%currmetaentry);
1.1374 raeburn 13361: if ($importmode eq 'part') {
1.1068 www 13362: # Import as part(s)
1.1069 www 13363: $importedparts=1;
13364: # We need to get the original file and the imported file to get the part order correct
13365: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369 raeburn 13366: # Load and inspect original file if we didn't do that already
13367: if ($#origfiletagids<0) {
13368: undef(%importedrespids);
13369: undef(%importedpartids);
13370: if ($origfile eq '') {
13371: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13372: $origfile=&getfile($origfilelocation);
13373: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13374: }
1.1070 www 13375: }
1.1372 raeburn 13376: my @impfilepartids;
13377: # If <partorder> tag is included in metadata for the imported file
13378: # get the parts in the imported file from that.
13379: if (grep(/^partorder$/,@libfilekeys)) {
13380: %currmetaentry = %metaentry;
13381: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13382: $depthcount+1);
13383: %metaentry = %currmetaentry;
13384: undef(%currmetaentry);
13385: if ($libpartorder ne '') {
13386: @impfilepartids=split(/\s*,\s*/,$libpartorder);
13387: }
13388: } else {
13389: # If no <partorder> tag available, load and inspect imported file
13390: my $impfile=&getfile($location);
13391: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13392: }
1.1069 www 13393: if ($#impfilepartids>=0) {
13394: # This problem had parts
1.1070 www 13395: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 13396: } else {
13397: # Importing by turning a single problem into a problem part
13398: # It gets the import-tags ID as part-ID
13399: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 13400: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 13401: }
1.1068 www 13402: } else {
1.1374 raeburn 13403: # Import as problem or as normal import
13404: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13405: unless ($importmode eq 'problem') {
1.1068 www 13406: # Normal import
1.1374 raeburn 13407: if (defined($token->[2]->{'id'})) {
13408: $unikey.='_'.$token->[2]->{'id'};
13409: }
13410: }
13411: # Check metadata for imported file to
13412: # see if it contained parts
13413: if (grep(/^partorder$/,@libfilekeys)) {
13414: %currmetaentry = %metaentry;
13415: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13416: $depthcount+1);
13417: %metaentry = %currmetaentry;
13418: undef(%currmetaentry);
13419: if ($libpartorder ne '') {
13420: $importedparts = 1;
13421: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13422: }
13423: }
1.1067 www 13424: }
1.339 albertel 13425: if ($depthcount<20) {
1.736 albertel 13426: my $metadata =
1.1362 raeburn 13427: &metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736 albertel 13428: $depthcount+1);
13429: foreach my $meta (split(',',$metadata)) {
13430: $metaentry{':'.$meta}=$metaentry{':'.$meta};
13431: $metathesekeys{$meta}=1;
1.339 albertel 13432: }
1.1068 www 13433: }
1.1067 www 13434: } else {
13435: #
13436: # Not importing, some other kind of non-package, non-library start tag
13437: #
13438: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13439: if (defined($token->[2]->{'id'})) {
13440: $unikey.='_'.$token->[2]->{'id'};
13441: }
1.339 albertel 13442: if (defined($token->[2]->{'name'})) {
13443: $unikey.='_'.$token->[2]->{'name'};
13444: }
13445: $metathesekeys{$unikey}=1;
1.736 albertel 13446: foreach my $param (@{$token->[3]}) {
13447: $metaentry{':'.$unikey.'.'.$param} =
13448: $token->[2]->{$param};
1.339 albertel 13449: }
13450: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 13451: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 13452: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13453: # only ws inside the tag, and not in default, so use default
13454: # as value
1.599 albertel 13455: $metaentry{':'.$unikey}=$default;
1.908 albertel 13456: } elsif ( $internaltext =~ /\S/ ) {
13457: # something interesting inside the tag
13458: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 13459: } else {
1.908 albertel 13460: # no interesting values, don't set a default
1.339 albertel 13461: }
1.172 www 13462: # end of not-a-package not-a-library import
1.339 albertel 13463: }
1.172 www 13464: # end of not-a-package start tag
1.339 albertel 13465: }
1.172 www 13466: # the next is the end of "start tag"
1.339 albertel 13467: }
13468: }
1.483 albertel 13469: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 13470: $extension = lc($extension);
13471: if ($extension eq 'htm') { $extension='html'; }
13472:
1.737 albertel 13473: foreach my $key (keys(%packagetab)) {
1.483 albertel 13474: #no specific packages #how's our extension
13475: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 13476: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 13477: \%metathesekeys);
13478: }
1.883 albertel 13479:
13480: if (!exists($metaentry{':packages'})
13481: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 13482: foreach my $key (keys(%packagetab)) {
1.483 albertel 13483: #no specific packages well let's get default then
13484: if ($key!~/^default&/) { next; }
1.488 albertel 13485: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 13486: \%metathesekeys);
13487: }
13488: }
1.338 www 13489: # are there custom rights to evaluate
1.599 albertel 13490: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 13491:
1.338 www 13492: #
13493: # Importing a rights file here
1.339 albertel 13494: #
13495: unless ($depthcount) {
1.599 albertel 13496: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 13497: my $dir=$filename;
13498: $dir=~s|[^/]*$||;
13499: $location=&filelocation($dir,$location);
1.736 albertel 13500: my $rights_metadata =
1.1362 raeburn 13501: &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736 albertel 13502: $depthcount+1);
13503: foreach my $rights (split(',',$rights_metadata)) {
13504: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13505: $metathesekeys{$rights}=1;
1.339 albertel 13506: }
13507: }
13508: }
1.737 albertel 13509: # uniqifiy package listing
13510: my %seen;
13511: my @uniq_packages =
13512: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13513: $metaentry{':packages'} = join(',',@uniq_packages);
13514:
1.1369 raeburn 13515: if (($importedresponses) || ($importedparts)) {
13516: if ($importedparts) {
1.1070 www 13517: # We had imported parts and need to rebuild partorder
1.1369 raeburn 13518: $metaentry{':partorder'}='';
13519: $metathesekeys{'partorder'}=1;
13520: }
13521: if ($importedresponses) {
13522: # We had imported responses and need to rebuil responseorder
13523: $metaentry{':responseorder'}='';
13524: $metathesekeys{'responseorder'}=1;
13525: }
13526: for (my $index=0;$index<$#origfiletagids;$index+=2) {
13527: my $origid = $origfiletagids[$index+1];
13528: if ($origfiletagids[$index] eq 'part') {
13529: # Original part, part of the problem
13530: if ($importedparts) {
13531: $metaentry{':partorder'}.=','.$origid;
13532: }
13533: } elsif ($origfiletagids[$index] eq 'import') {
13534: if ($importedparts) {
13535: # We have imported parts at this position
1.1373 raeburn 13536: if ($importedpartids{$origid} ne '') {
13537: $metaentry{':partorder'}.=','.$importedpartids{$origid};
13538: }
1.1369 raeburn 13539: }
13540: if ($importedresponses) {
13541: # We have imported responses at this position
1.1373 raeburn 13542: if ($importedrespids{$origid} ne '') {
13543: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369 raeburn 13544: }
13545: }
13546: } else {
13547: # Original response item, part of the problem
13548: if ($importedresponses) {
13549: $metaentry{':responseorder'}.=','.$origid;
13550: }
13551: }
13552: }
13553: if ($importedparts) {
13554: $metaentry{':partorder'}=~s/^\,//;
13555: }
13556: if ($importedresponses) {
13557: $metaentry{':responseorder'}=~s/^\,//;
13558: }
1.1070 www 13559: }
1.737 albertel 13560: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 13561: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 13562: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371 raeburn 13563: unless ($liburi) {
13564: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13565: }
1.177 www 13566: # this is the end of "was not already recently cached
1.71 www 13567: }
1.599 albertel 13568: return $metaentry{':'.$what};
1.261 albertel 13569: }
13570:
1.488 albertel 13571: sub metadata_create_package_def {
1.483 albertel 13572: my ($uri,$key,$package,$metathesekeys)=@_;
13573: my ($pack,$name,$subp)=split(/\&/,$key);
13574: if ($subp eq 'default') { next; }
13575:
1.599 albertel 13576: if (defined($metaentry{':packages'})) {
13577: $metaentry{':packages'}.=','.$package;
1.483 albertel 13578: } else {
1.599 albertel 13579: $metaentry{':packages'}=$package;
1.483 albertel 13580: }
13581: my $value=$packagetab{$key};
13582: my $unikey;
13583: $unikey='parameter_0_'.$name;
1.599 albertel 13584: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 13585: $$metathesekeys{$unikey}=1;
1.599 albertel 13586: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13587: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 13588: }
1.599 albertel 13589: if (defined($metaentry{':'.$unikey.'.default'})) {
13590: $metaentry{':'.$unikey}=
13591: $metaentry{':'.$unikey.'.default'};
1.483 albertel 13592: }
13593: }
13594:
1.261 albertel 13595: sub metadata_generate_part0 {
13596: my ($metadata,$metacache,$uri) = @_;
13597: my %allnames;
1.737 albertel 13598: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 13599: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 13600: my $part=$$metacache{':'.$metakey.'.part'};
13601: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 13602: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 13603: $allnames{$name}=$part;
13604: }
13605: }
13606: }
13607: foreach my $name (keys(%allnames)) {
13608: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 13609: my $key=":parameter_0_$name";
1.261 albertel 13610: $$metacache{"$key.part"}='0';
13611: $$metacache{"$key.name"}=$name;
1.428 albertel 13612: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 13613: $allnames{$name}.'_'.$name.
13614: '.type'};
1.428 albertel 13615: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 13616: '.display'};
1.644 www 13617: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 13618: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 13619: $$metacache{"$key.display"}=$olddis;
13620: }
1.71 www 13621: }
13622:
1.764 albertel 13623: # ------------------------------------------------------ Devalidate title cache
13624:
13625: sub devalidate_title_cache {
13626: my ($url)=@_;
13627: if (!$env{'request.course.id'}) { return; }
13628: my $symb=&symbread($url);
13629: if (!$symb) { return; }
13630: my $key=$env{'request.course.id'}."\0".$symb;
13631: &devalidate_cache_new('title',$key);
13632: }
13633:
1.1014 droeschl 13634: # ------------------------------------------------- Get the title of a course
13635:
13636: sub current_course_title {
13637: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13638: }
1.301 www 13639: # ------------------------------------------------- Get the title of a resource
13640:
13641: sub gettitle {
13642: my $urlsymb=shift;
13643: my $symb=&symbread($urlsymb);
1.534 albertel 13644: if ($symb) {
1.620 albertel 13645: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 13646: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 13647: if (defined($cached)) {
13648: return $result;
13649: }
1.534 albertel 13650: my ($map,$resid,$url)=&decode_symb($symb);
13651: my $title='';
1.907 albertel 13652: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13653: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13654: } else {
13655: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13656: &GDBM_READER(),0640)) {
13657: my $mapid=$bighash{'map_pc_'.&clutter($map)};
13658: $title=$bighash{'title_'.$mapid.'.'.$resid};
13659: untie(%bighash);
13660: }
1.534 albertel 13661: }
13662: $title=~s/\&colon\;/\:/gs;
13663: if ($title) {
1.1159 www 13664: # Remember both $symb and $title for dynamic metadata
13665: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 13666: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 13667: # Cache this title and then return it
1.599 albertel 13668: return &do_cache_new('title',$key,$title,600);
1.534 albertel 13669: }
13670: $urlsymb=$url;
13671: }
13672: my $title=&metadata($urlsymb,'title');
13673: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
13674: return $title;
1.301 www 13675: }
1.613 albertel 13676:
1.614 albertel 13677: sub get_slot {
13678: my ($which,$cnum,$cdom)=@_;
13679: if (!$cnum || !$cdom) {
1.790 albertel 13680: (undef,my $courseid)=&whichuser();
1.620 albertel 13681: $cdom=$env{'course.'.$courseid.'.domain'};
13682: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 13683: }
1.703 albertel 13684: my $key=join("\0",'slots',$cdom,$cnum,$which);
13685: my %slotinfo;
13686: if (exists($remembered{$key})) {
13687: $slotinfo{$which} = $remembered{$key};
13688: } else {
13689: %slotinfo=&get('slots',[$which],$cdom,$cnum);
13690: &Apache::lonhomework::showhash(%slotinfo);
13691: my ($tmp)=keys(%slotinfo);
13692: if ($tmp=~/^error:/) { return (); }
13693: $remembered{$key} = $slotinfo{$which};
13694: }
1.616 albertel 13695: if (ref($slotinfo{$which}) eq 'HASH') {
13696: return %{$slotinfo{$which}};
13697: }
13698: return $slotinfo{$which};
1.614 albertel 13699: }
1.1150 raeburn 13700:
13701: sub get_reservable_slots {
13702: my ($cnum,$cdom,$uname,$udom) = @_;
13703: my $now = time;
13704: my $reservable_info;
13705: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13706: if (exists($remembered{$key})) {
13707: $reservable_info = $remembered{$key};
13708: } else {
13709: my %resv;
13710: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13711: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13712: $reservable_info = \%resv;
13713: $remembered{$key} = $reservable_info;
13714: }
13715: return $reservable_info;
13716: }
13717:
13718: sub get_course_slots {
13719: my ($cnum,$cdom) = @_;
13720: my $hashid=$cnum.':'.$cdom;
1.1494 raeburn 13721: my ($result,$cached) = &is_cached_new('allslots',$hashid);
1.1150 raeburn 13722: if (defined($cached)) {
13723: if (ref($result) eq 'HASH') {
13724: return %{$result};
13725: }
13726: } else {
1.1494 raeburn 13727: my %slots=&dump('slots',$cdom,$cnum);
1.1150 raeburn 13728: my ($tmp) = keys(%slots);
13729: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 13730: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 13731: return %slots;
13732: }
13733: }
13734: return;
13735: }
13736:
13737: sub devalidate_slots_cache {
13738: my ($cnum,$cdom)=@_;
13739: my $hashid=$cnum.':'.$cdom;
13740: &devalidate_cache_new('allslots',$hashid);
13741: }
13742:
1.1181 raeburn 13743: sub get_coursechange {
13744: my ($cdom,$cnum) = @_;
13745: if ($cdom eq '' || $cnum eq '') {
13746: return unless ($env{'request.course.id'});
13747: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13748: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13749: }
13750: my $hashid=$cdom.'_'.$cnum;
13751: my ($change,$cached)=&is_cached_new('crschange',$hashid);
13752: if ((defined($cached)) && ($change ne '')) {
13753: return $change;
13754: } else {
13755: my %crshash;
13756: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13757: if ($crshash{'internal.contentchange'} eq '') {
13758: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13759: if ($change eq '') {
13760: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13761: $change = $crshash{'internal.created'};
13762: }
13763: } else {
13764: $change = $crshash{'internal.contentchange'};
13765: }
13766: my $cachetime = 600;
13767: &do_cache_new('crschange',$hashid,$change,$cachetime);
13768: }
13769: return $change;
13770: }
13771:
13772: sub devalidate_coursechange_cache {
1.1496 raeburn 13773: my ($cdom,$cnum)=@_;
13774: my $hashid=$cdom.'_'.$cnum;
1.1181 raeburn 13775: &devalidate_cache_new('crschange',$hashid);
13776: }
13777:
1.1496 raeburn 13778: sub get_suppchange {
13779: my ($cdom,$cnum) = @_;
13780: if ($cdom eq '' || $cnum eq '') {
13781: return unless ($env{'request.course.id'});
13782: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13783: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13784: }
13785: my $hashid=$cdom.'_'.$cnum;
13786: my ($change,$cached)=&is_cached_new('suppchange',$hashid);
13787: if ((defined($cached)) && ($change ne '')) {
13788: return $change;
13789: } else {
13790: my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
13791: if ($crshash{'internal.supplementalchange'} eq '') {
13792: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13793: if ($change eq '') {
13794: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13795: $change = $crshash{'internal.created'};
13796: }
13797: } else {
13798: $change = $crshash{'internal.supplementalchange'};
13799: }
13800: my $cachetime = 600;
13801: &do_cache_new('suppchange',$hashid,$change,$cachetime);
13802: }
13803: return $change;
13804: }
13805:
13806: sub devalidate_suppchange_cache {
13807: my ($cdom,$cnum)=@_;
13808: my $hashid=$cdom.'_'.$cnum;
13809: &devalidate_cache_new('suppchange',$hashid);
13810: }
13811:
1.1497 raeburn 13812: sub update_supp_caches {
13813: my ($cdom,$cnum) = @_;
13814: my %servers = &internet_dom_servers($cdom);
13815: my @ids=¤t_machine_ids();
13816: foreach my $server (keys(%servers)) {
13817: next if (grep(/^\Q$server\E$/,@ids));
13818: my $hashid=$cnum.':'.$cdom;
13819: my $cachekey = &escape('showsupp').':'.&escape($hashid);
13820: &remote_devalidate_cache($server,[$cachekey]);
13821: }
13822: &has_unhidden_suppfiles($cnum,$cdom,1,1);
13823: &count_supptools($cnum,$cdom,1);
13824: my $now = time;
13825: if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
13826: &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
13827: }
13828: &put('environment',{'internal.supplementalchange' => $now},
13829: $cdom,$cnum);
13830: &Apache::lonnet::appenv(
13831: {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
13832: &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
13833: }
13834:
1.31 www 13835: # ------------------------------------------------- Update symbolic store links
13836:
13837: sub symblist {
13838: my ($mapname,%newhash)=@_;
1.438 www 13839: $mapname=&deversion(&declutter($mapname));
1.31 www 13840: my %hash;
1.620 albertel 13841: if (($env{'request.course.fn'}) && (%newhash)) {
13842: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 13843: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 13844: foreach my $url (keys(%newhash)) {
1.711 albertel 13845: next if ($url eq 'last_known'
13846: && $env{'form.no_update_last_known'});
13847: $hash{declutter($url)}=&encode_symb($mapname,
13848: $newhash{$url}->[1],
13849: $newhash{$url}->[0]);
1.191 harris41 13850: }
1.31 www 13851: if (untie(%hash)) {
13852: return 'ok';
13853: }
13854: }
13855: }
13856: return 'error';
1.212 www 13857: }
13858:
13859: # --------------------------------------------------------------- Verify a symb
13860:
13861: sub symbverify {
1.1190 raeburn 13862: my ($symb,$thisurl,$encstate)=@_;
1.510 www 13863: my $thisfn=$thisurl;
1.439 www 13864: $thisfn=&declutter($thisfn);
1.215 www 13865: # direct jump to resource in page or to a sequence - will construct own symbs
13866: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13867: # check URL part
1.409 www 13868: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 13869:
1.431 www 13870: unless ($url eq $thisfn) { return 0; }
1.213 www 13871:
1.216 www 13872: $symb=&symbclean($symb);
1.510 www 13873: $thisurl=&deversion($thisurl);
1.439 www 13874: $thisfn=&deversion($thisfn);
1.213 www 13875:
13876: my %bighash;
13877: my $okay=0;
1.431 www 13878:
1.620 albertel 13879: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13880: &GDBM_READER(),0640)) {
1.1032 raeburn 13881: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13882: $thisurl =~ s/\?.+$//;
1.1204 raeburn 13883: if ($map =~ m{^uploaded/.+\.page$}) {
13884: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13885: $thisurl =~ s{^\Qhttp://https://\E}{https://};
13886: }
13887: }
13888: my $ids;
1.1419 raeburn 13889: if ($map =~ m{^uploaded/.+\.page$}) {
13890: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204 raeburn 13891: } else {
13892: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 13893: }
1.1102 raeburn 13894: unless ($ids) {
13895: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
13896: $ids=$bighash{$idkey};
1.216 www 13897: }
13898: if ($ids) {
13899: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 13900: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 13901: $symb =~ s/\?.+$//;
1.1202 raeburn 13902: }
1.800 albertel 13903: foreach my $id (split(/\,/,$ids)) {
13904: my ($mapid,$resid)=split(/\./,$id);
1.216 www 13905: if (
13906: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 13907: eq $symb) {
13908: if (ref($encstate)) {
13909: $$encstate = $bighash{'encrypted_'.$id};
13910: }
1.620 albertel 13911: if (($env{'request.role.adv'}) ||
1.1101 raeburn 13912: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13913: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 13914: $okay=1;
1.1202 raeburn 13915: last;
1.582 albertel 13916: }
13917: }
1.216 www 13918: }
13919: }
1.213 www 13920: untie(%bighash);
13921: }
13922: return $okay;
1.31 www 13923: }
13924:
1.210 www 13925: # --------------------------------------------------------------- Clean-up symb
13926:
13927: sub symbclean {
13928: my $symb=shift;
1.568 albertel 13929: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 13930: # remove version from map
13931: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 13932:
1.210 www 13933: # remove version from URL
13934: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 13935:
1.507 www 13936: # remove wrapper
13937:
1.510 www 13938: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 13939: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 13940: return $symb;
1.409 www 13941: }
13942:
13943: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 13944:
13945: sub encode_symb {
13946: my ($map,$resid,$url)=@_;
13947: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13948: }
1.409 www 13949:
13950: sub decode_symb {
1.568 albertel 13951: my $symb=shift;
13952: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13953: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 13954: return (&fixversion($map),$resid,&fixversion($url));
13955: }
13956:
13957: sub fixversion {
13958: my $fn=shift;
1.609 banghart 13959: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 13960: my %bighash;
13961: my $uri=&clutter($fn);
1.620 albertel 13962: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 13963: # is this cached?
1.599 albertel 13964: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 13965: if (defined($cached)) { return $result; }
13966: # unfortunately not cached, or expired
1.620 albertel 13967: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 13968: &GDBM_READER(),0640)) {
13969: if ($bighash{'version_'.$uri}) {
13970: my $version=$bighash{'version_'.$uri};
1.444 www 13971: unless (($version eq 'mostrecent') ||
13972: ($version==&getversion($uri))) {
1.440 www 13973: $uri=~s/\.(\w+)$/\.$version\.$1/;
13974: }
13975: }
13976: untie %bighash;
1.413 www 13977: }
1.599 albertel 13978: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 13979: }
13980:
13981: sub deversion {
13982: my $url=shift;
13983: $url=~s/\.\d+\.(\w+)$/\.$1/;
13984: return $url;
1.210 www 13985: }
13986:
1.31 www 13987: # ------------------------------------------------------ Return symb list entry
13988:
13989: sub symbread {
1.1424 raeburn 13990: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427 raeburn 13991: $ignoresymbdb,$noenccheck)=@_;
1.1265 raeburn 13992: my $cache_str='request.symbread.cached.'.$thisfn;
1.1427 raeburn 13993: if (defined($env{$cache_str})) {
1.1424 raeburn 13994: unless (ref($possibles) eq 'HASH') {
13995: if ($ignorecachednull) {
13996: return $env{$cache_str} unless ($env{$cache_str} eq '');
13997: } else {
13998: return $env{$cache_str};
13999: }
1.1282 raeburn 14000: }
14001: }
1.242 www 14002: # no filename provided? try from environment
1.1265 raeburn 14003: unless ($thisfn) {
1.620 albertel 14004: if ($env{'request.symb'}) {
1.1427 raeburn 14005: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 14006: }
1.620 albertel 14007: $thisfn=$env{'request.filename'};
1.44 www 14008: }
1.569 albertel 14009: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 14010: # is that filename actually a symb? Verify, clean, and return
14011: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 14012: if (&symbverify($thisfn,$1)) {
1.1427 raeburn 14013: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 14014: }
1.242 www 14015: }
1.44 www 14016: $thisfn=declutter($thisfn);
1.31 www 14017: my %hash;
1.37 www 14018: my %bighash;
14019: my $syval='';
1.620 albertel 14020: if (($env{'request.course.fn'}) && ($thisfn)) {
1.1427 raeburn 14021: unless ($ignoresymbdb) {
1.1424 raeburn 14022: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14023: &GDBM_READER(),0640)) {
1.1487 raeburn 14024: $syval=$hash{$thisfn};
1.1424 raeburn 14025: untie(%hash);
14026: }
1.1427 raeburn 14027: if ($syval && $checkforblock) {
14028: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424 raeburn 14029: if (@blockers) {
14030: $syval='';
14031: }
14032: }
1.37 www 14033: }
14034: # ---------------------------------------------------------- There was an entry
14035: if ($syval) {
1.601 albertel 14036: #unless ($syval=~/\_\d+$/) {
1.620 albertel 14037: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 14038: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 14039: #return $env{$cache_str}='';
1.601 albertel 14040: #}
14041: #$syval.=$1;
14042: #}
1.37 www 14043: } else {
14044: # ------------------------------------------------------- Was not in symb table
1.620 albertel 14045: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 14046: &GDBM_READER(),0640)) {
1.37 www 14047: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 14048: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 14049: unless ($ids) {
14050: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 14051: }
14052: unless ($ids) {
14053: # alias?
14054: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 14055: }
1.37 www 14056: if ($ids) {
14057: # ------------------------------------------------------------------- Has ID(s)
14058: my @possibilities=split(/\,/,$ids);
1.39 www 14059: if ($#possibilities==0) {
14060: # ----------------------------------------------- There is only one possibility
1.37 www 14061: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 14062: $syval=&encode_symb($bighash{'map_id_'.$mapid},
14063: $resid,$thisfn);
1.1282 raeburn 14064: if (ref($possibles) eq 'HASH') {
1.1424 raeburn 14065: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14066: $possibles->{$syval} = 1;
14067: }
1.1282 raeburn 14068: }
14069: if ($checkforblock) {
1.1424 raeburn 14070: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426 raeburn 14071: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424 raeburn 14072: if (@blockers) {
14073: $syval = '';
1.1425 raeburn 14074: untie(%bighash);
14075: return $env{$cache_str}='';
1.1424 raeburn 14076: }
1.1282 raeburn 14077: }
14078: }
14079: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 14080: # ------------------------------------------ There is more than one possibility
14081: my $realpossible=0;
1.800 albertel 14082: foreach my $id (@possibilities) {
14083: my $file=$bighash{'src_'.$id};
1.1282 raeburn 14084: my $canaccess;
14085: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14086: $canaccess = 1;
14087: } else {
14088: $canaccess = &allowed('bre',$file);
14089: }
14090: if ($canaccess) {
14091: my ($mapid,$resid)=split(/\./,$id);
14092: if ($bighash{'map_type_'.$mapid} ne 'page') {
14093: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14094: $resid,$thisfn);
1.1424 raeburn 14095: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426 raeburn 14096: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282 raeburn 14097: if ($checkforblock) {
1.1426 raeburn 14098: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424 raeburn 14099: if (@blockers > 0) {
14100: $syval = '';
14101: } else {
1.1282 raeburn 14102: $syval = $poss_syval;
14103: $realpossible++;
14104: }
14105: } else {
14106: $syval = $poss_syval;
14107: $realpossible++;
14108: }
1.1424 raeburn 14109: if ($syval) {
14110: if (ref($possibles) eq 'HASH') {
14111: $possibles->{$syval} = 1;
14112: }
14113: }
1.1282 raeburn 14114: }
1.39 www 14115: }
1.191 harris41 14116: }
1.39 www 14117: if ($realpossible!=1) { $syval=''; }
1.249 www 14118: } else {
14119: $syval='';
1.37 www 14120: }
14121: }
1.1282 raeburn 14122: untie(%bighash);
1.481 raeburn 14123: }
1.31 www 14124: }
1.62 www 14125: if ($syval) {
1.1427 raeburn 14126: return $env{$cache_str}=$syval;
1.62 www 14127: }
1.31 www 14128: }
1.949 raeburn 14129: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 14130: return $env{$cache_str}='';
1.31 www 14131: }
14132:
14133: # ---------------------------------------------------------- Return random seed
14134:
1.32 www 14135: sub numval {
14136: my $txt=shift;
14137: $txt=~tr/A-J/0-9/;
14138: $txt=~tr/a-j/0-9/;
14139: $txt=~tr/K-T/0-9/;
14140: $txt=~tr/k-t/0-9/;
14141: $txt=~tr/U-Z/0-5/;
14142: $txt=~tr/u-z/0-5/;
14143: $txt=~s/\D//g;
1.564 albertel 14144: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 14145: return int($txt);
1.368 albertel 14146: }
14147:
1.484 albertel 14148: sub numval2 {
14149: my $txt=shift;
14150: $txt=~tr/A-J/0-9/;
14151: $txt=~tr/a-j/0-9/;
14152: $txt=~tr/K-T/0-9/;
14153: $txt=~tr/k-t/0-9/;
14154: $txt=~tr/U-Z/0-5/;
14155: $txt=~tr/u-z/0-5/;
14156: $txt=~s/\D//g;
14157: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14158: my $total;
14159: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 14160: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 14161: return int($total);
14162: }
14163:
1.575 albertel 14164: sub numval3 {
14165: use integer;
14166: my $txt=shift;
14167: $txt=~tr/A-J/0-9/;
14168: $txt=~tr/a-j/0-9/;
14169: $txt=~tr/K-T/0-9/;
14170: $txt=~tr/k-t/0-9/;
14171: $txt=~tr/U-Z/0-5/;
14172: $txt=~tr/u-z/0-5/;
14173: $txt=~s/\D//g;
14174: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14175: my $total;
14176: foreach my $val (@txts) { $total+=$val; }
14177: if ($_64bit) { $total=(($total<<32)>>32); }
14178: return $total;
14179: }
14180:
1.675 albertel 14181: sub digest {
14182: my ($data)=@_;
14183: my $digest=&Digest::MD5::md5($data);
14184: my ($a,$b,$c,$d)=unpack("iiii",$digest);
14185: my ($e,$f);
14186: {
14187: use integer;
14188: $e=($a+$b);
14189: $f=($c+$d);
14190: if ($_64bit) {
14191: $e=(($e<<32)>>32);
14192: $f=(($f<<32)>>32);
14193: }
14194: }
14195: if (wantarray) {
14196: return ($e,$f);
14197: } else {
14198: my $g;
14199: {
14200: use integer;
14201: $g=($e+$f);
14202: if ($_64bit) {
14203: $g=(($g<<32)>>32);
14204: }
14205: }
14206: return $g;
14207: }
14208: }
14209:
1.368 albertel 14210: sub latest_rnd_algorithm_id {
1.675 albertel 14211: return '64bit5';
1.366 albertel 14212: }
1.32 www 14213:
1.503 albertel 14214: sub get_rand_alg {
14215: my ($courseid)=@_;
1.790 albertel 14216: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 14217: if ($courseid) {
1.620 albertel 14218: return $env{"course.$courseid.rndseed"};
1.503 albertel 14219: }
14220: return &latest_rnd_algorithm_id();
14221: }
14222:
1.562 albertel 14223: sub validCODE {
14224: my ($CODE)=@_;
14225: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14226: return 0;
14227: }
14228:
1.491 albertel 14229: sub getCODE {
1.620 albertel 14230: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 14231: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14232: defined($Apache::lonhomework::parsing_a_task) ) &&
14233: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 14234: return $Apache::lonhomework::history{'resource.CODE'};
14235: }
14236: return undef;
14237: }
1.1133 foxr 14238: #
14239: # Determines the random seed for a specific context:
14240: #
14241: # parameters:
14242: # symb - in course context the symb for the seed.
14243: # course_id - The course id of the form domain_coursenum.
14244: # domain - Domain for the user.
14245: # course - Course for the user.
14246: # cenv - environment of the course.
14247: #
14248: # NOTE:
14249: # All parameters are picked out of the environment if missing
14250: # or not defined.
14251: # If a symb cannot be determined the current time is used instead.
14252: #
14253: # For a given well defined symb, courside, domain, username,
14254: # and course environment, the seed is reproducible.
14255: #
1.31 www 14256: sub rndseed {
1.1133 foxr 14257: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 14258: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 14259: if (!defined($symb)) {
1.366 albertel 14260: unless ($symb=$wsymb) { return time; }
14261: }
1.1146 foxr 14262: if (!defined $courseid) {
14263: $courseid=$wcourseid;
14264: }
14265: if (!defined $domain) { $domain=$wdomain; }
14266: if (!defined $username) { $username=$wusername }
1.1133 foxr 14267:
14268: my $which;
14269: if (defined($cenv->{'rndseed'})) {
14270: $which = $cenv->{'rndseed'};
14271: } else {
14272: $which =&get_rand_alg($courseid);
14273: }
1.491 albertel 14274: if (defined(&getCODE())) {
1.1133 foxr 14275:
1.675 albertel 14276: if ($which eq '64bit5') {
14277: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14278: } elsif ($which eq '64bit4') {
1.575 albertel 14279: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14280: } else {
14281: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14282: }
1.675 albertel 14283: } elsif ($which eq '64bit5') {
14284: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 14285: } elsif ($which eq '64bit4') {
14286: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 14287: } elsif ($which eq '64bit3') {
14288: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 14289: } elsif ($which eq '64bit2') {
14290: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 14291: } elsif ($which eq '64bit') {
14292: return &rndseed_64bit($symb,$courseid,$domain,$username);
14293: }
14294: return &rndseed_32bit($symb,$courseid,$domain,$username);
14295: }
14296:
14297: sub rndseed_32bit {
14298: my ($symb,$courseid,$domain,$username)=@_;
14299: {
14300: use integer;
14301: my $symbchck=unpack("%32C*",$symb) << 27;
14302: my $symbseed=numval($symb) << 22;
14303: my $namechck=unpack("%32C*",$username) << 17;
14304: my $nameseed=numval($username) << 12;
14305: my $domainseed=unpack("%32C*",$domain) << 7;
14306: my $courseseed=unpack("%32C*",$courseid);
14307: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 14308: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14309: #&logthis("rndseed :$num:$symb");
1.564 albertel 14310: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 14311: return $num;
14312: }
14313: }
14314:
14315: sub rndseed_64bit {
14316: my ($symb,$courseid,$domain,$username)=@_;
14317: {
14318: use integer;
14319: my $symbchck=unpack("%32S*",$symb) << 21;
14320: my $symbseed=numval($symb) << 10;
14321: my $namechck=unpack("%32S*",$username);
14322:
14323: my $nameseed=numval($username) << 21;
14324: my $domainseed=unpack("%32S*",$domain) << 10;
14325: my $courseseed=unpack("%32S*",$courseid);
14326:
14327: my $num1=$symbchck+$symbseed+$namechck;
14328: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14329: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14330: #&logthis("rndseed :$num:$symb");
1.564 albertel 14331: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 14332: return "$num1,$num2";
1.155 albertel 14333: }
1.366 albertel 14334: }
14335:
1.443 albertel 14336: sub rndseed_64bit2 {
14337: my ($symb,$courseid,$domain,$username)=@_;
14338: {
14339: use integer;
14340: # strings need to be an even # of cahracters long, it it is odd the
14341: # last characters gets thrown away
14342: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14343: my $symbseed=numval($symb) << 10;
14344: my $namechck=unpack("%32S*",$username.' ');
14345:
14346: my $nameseed=numval($username) << 21;
1.501 albertel 14347: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14348: my $courseseed=unpack("%32S*",$courseid.' ');
14349:
14350: my $num1=$symbchck+$symbseed+$namechck;
14351: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14352: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14353: #&logthis("rndseed :$num:$symb");
1.803 albertel 14354: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 14355: return "$num1,$num2";
14356: }
14357: }
14358:
14359: sub rndseed_64bit3 {
14360: my ($symb,$courseid,$domain,$username)=@_;
14361: {
14362: use integer;
14363: # strings need to be an even # of cahracters long, it it is odd the
14364: # last characters gets thrown away
14365: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14366: my $symbseed=numval2($symb) << 10;
14367: my $namechck=unpack("%32S*",$username.' ');
14368:
14369: my $nameseed=numval2($username) << 21;
1.443 albertel 14370: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14371: my $courseseed=unpack("%32S*",$courseid.' ');
14372:
14373: my $num1=$symbchck+$symbseed+$namechck;
14374: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14375: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14376: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 14377: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14378:
1.503 albertel 14379: return "$num1:$num2";
1.443 albertel 14380: }
14381: }
14382:
1.575 albertel 14383: sub rndseed_64bit4 {
14384: my ($symb,$courseid,$domain,$username)=@_;
14385: {
14386: use integer;
14387: # strings need to be an even # of cahracters long, it it is odd the
14388: # last characters gets thrown away
14389: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14390: my $symbseed=numval3($symb) << 10;
14391: my $namechck=unpack("%32S*",$username.' ');
14392:
14393: my $nameseed=numval3($username) << 21;
14394: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14395: my $courseseed=unpack("%32S*",$courseid.' ');
14396:
14397: my $num1=$symbchck+$symbseed+$namechck;
14398: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14399: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14400: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 14401: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14402:
1.575 albertel 14403: return "$num1:$num2";
14404: }
14405: }
14406:
1.675 albertel 14407: sub rndseed_64bit5 {
14408: my ($symb,$courseid,$domain,$username)=@_;
14409: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14410: return "$num1:$num2";
14411: }
14412:
1.366 albertel 14413: sub rndseed_CODE_64bit {
14414: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 14415: {
1.366 albertel 14416: use integer;
1.443 albertel 14417: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 14418: my $symbseed=numval2($symb);
1.491 albertel 14419: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14420: my $CODEseed=numval(&getCODE());
1.443 albertel 14421: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 14422: my $num1=$symbseed+$CODEchck;
14423: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14424: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14425: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 14426: if ($_64bit) { $num1=(($num1<<32)>>32); }
14427: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 14428: return "$num1:$num2";
1.366 albertel 14429: }
14430: }
14431:
1.575 albertel 14432: sub rndseed_CODE_64bit4 {
14433: my ($symb,$courseid,$domain,$username)=@_;
14434: {
14435: use integer;
14436: my $symbchck=unpack("%32S*",$symb.' ') << 16;
14437: my $symbseed=numval3($symb);
14438: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14439: my $CODEseed=numval3(&getCODE());
14440: my $courseseed=unpack("%32S*",$courseid.' ');
14441: my $num1=$symbseed+$CODEchck;
14442: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14443: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14444: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 14445: if ($_64bit) { $num1=(($num1<<32)>>32); }
14446: if ($_64bit) { $num2=(($num2<<32)>>32); }
14447: return "$num1:$num2";
14448: }
14449: }
14450:
1.675 albertel 14451: sub rndseed_CODE_64bit5 {
14452: my ($symb,$courseid,$domain,$username)=@_;
14453: my $code = &getCODE();
14454: my ($num1,$num2)=&digest("$symb,$courseid,$code");
14455: return "$num1:$num2";
14456: }
14457:
1.366 albertel 14458: sub setup_random_from_rndseed {
14459: my ($rndseed)=@_;
1.503 albertel 14460: if ($rndseed =~/([,:])/) {
1.1262 raeburn 14461: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14462: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14463: &Math::Random::random_set_seed_from_phrase($rndseed);
14464: } else {
14465: &Math::Random::random_set_seed($num1,$num2);
14466: }
1.366 albertel 14467: } else {
14468: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 14469: }
1.36 albertel 14470: }
14471:
1.474 albertel 14472: sub latest_receipt_algorithm_id {
1.835 albertel 14473: return 'receipt3';
1.474 albertel 14474: }
14475:
1.480 www 14476: sub recunique {
14477: my $fucourseid=shift;
14478: my $unique;
1.835 albertel 14479: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14480: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14481: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 14482: } else {
14483: $unique=$perlvar{'lonReceipt'};
14484: }
14485: return unpack("%32C*",$unique);
14486: }
14487:
14488: sub recprefix {
14489: my $fucourseid=shift;
14490: my $prefix;
1.835 albertel 14491: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14492: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14493: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 14494: } else {
14495: $prefix=$perlvar{'lonHostID'};
14496: }
14497: return unpack("%32C*",$prefix);
14498: }
14499:
1.76 www 14500: sub ireceipt {
1.474 albertel 14501: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 14502:
14503: my $return =&recprefix($fucourseid).'-';
14504:
14505: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14506: $env{'request.state'} eq 'construct') {
14507: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14508: return $return;
14509: }
14510:
1.76 www 14511: my $cuname=unpack("%32C*",$funame);
14512: my $cudom=unpack("%32C*",$fudom);
14513: my $cucourseid=unpack("%32C*",$fucourseid);
14514: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 14515: my $cunique=&recunique($fucourseid);
1.474 albertel 14516: my $cpart=unpack("%32S*",$part);
1.835 albertel 14517: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14518:
1.790 albertel 14519: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 14520:
14521: $return.= ($cunique%$cuname+
14522: $cunique%$cudom+
14523: $cusymb%$cuname+
14524: $cusymb%$cudom+
14525: $cucourseid%$cuname+
14526: $cucourseid%$cudom+
14527: $cpart%$cuname+
14528: $cpart%$cudom);
14529: } else {
14530: $return.= ($cunique%$cuname+
14531: $cunique%$cudom+
14532: $cusymb%$cuname+
14533: $cusymb%$cudom+
14534: $cucourseid%$cuname+
14535: $cucourseid%$cudom);
14536: }
14537: return $return;
1.76 www 14538: }
14539:
14540: sub receipt {
1.474 albertel 14541: my ($part)=@_;
1.790 albertel 14542: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 14543: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 14544: }
1.260 ng 14545:
1.790 albertel 14546: sub whichuser {
14547: my ($passedsymb)=@_;
14548: my ($symb,$courseid,$domain,$name,$publicuser);
14549: if (defined($env{'form.grade_symb'})) {
14550: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14551: my $allowed=&allowed('vgr',$tmp_courseid);
14552: if (!$allowed &&
14553: exists($env{'request.course.sec'}) &&
14554: $env{'request.course.sec'} !~ /^\s*$/) {
14555: $allowed=&allowed('vgr',$tmp_courseid.
14556: '/'.$env{'request.course.sec'});
14557: }
14558: if ($allowed) {
14559: ($symb)=&get_env_multiple('form.grade_symb');
14560: $courseid=$tmp_courseid;
14561: ($domain)=&get_env_multiple('form.grade_domain');
14562: ($name)=&get_env_multiple('form.grade_username');
14563: return ($symb,$courseid,$domain,$name,$publicuser);
14564: }
14565: }
14566: if (!$passedsymb) {
14567: $symb=&symbread();
14568: } else {
14569: $symb=$passedsymb;
14570: }
14571: $courseid=$env{'request.course.id'};
14572: $domain=$env{'user.domain'};
14573: $name=$env{'user.name'};
14574: if ($name eq 'public' && $domain eq 'public') {
14575: if (!defined($env{'form.username'})) {
14576: $env{'form.username'}.=time.rand(10000000);
14577: }
14578: $name.=$env{'form.username'};
14579: }
14580: return ($symb,$courseid,$domain,$name,$publicuser);
14581:
14582: }
14583:
1.36 albertel 14584: # ------------------------------------------------------------ Serves up a file
1.472 albertel 14585: # returns either the contents of the file or
14586: # -1 if the file doesn't exist
1.481 raeburn 14587: #
14588: # if the target is a file that was uploaded via DOCS,
14589: # a check will be made to see if a current copy exists on the local server,
14590: # if it does this will be served, otherwise a copy will be retrieved from
14591: # the home server for the course and stored in /home/httpd/html/userfiles on
14592: # the local server.
1.472 albertel 14593:
1.36 albertel 14594: sub getfile {
1.538 albertel 14595: my ($file) = @_;
1.609 banghart 14596: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 14597: &repcopy($file);
14598: return &readfile($file);
14599: }
14600:
14601: sub repcopy_userfile {
14602: my ($file)=@_;
1.1142 raeburn 14603: my $londocroot = $perlvar{'lonDocRoot'};
14604: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 14605: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 14606: my ($cdom,$cnum,$filename) =
1.811 albertel 14607: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 14608: my $uri="/uploaded/$cdom/$cnum/$filename";
14609: if (-e "$file") {
1.828 www 14610: # we already have a local copy, check it out
1.538 albertel 14611: my @fileinfo = stat($file);
1.828 www 14612: my $rtncode;
14613: my $info;
1.538 albertel 14614: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 14615: if ($lwpresp ne 'ok') {
1.828 www 14616: # there is no such file anymore, even though we had a local copy
1.482 albertel 14617: if ($rtncode eq '404') {
1.538 albertel 14618: unlink($file);
1.482 albertel 14619: }
14620: return -1;
14621: }
14622: if ($info < $fileinfo[9]) {
1.828 www 14623: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 14624: return 'ok';
1.828 www 14625: } else {
14626: # the file is outdated, get rid of it
14627: unlink($file);
1.482 albertel 14628: }
1.828 www 14629: }
14630: # one way or the other, at this point, we don't have the file
14631: # construct the correct path for the file
14632: my @parts = ($cdom,$cnum);
14633: if ($filename =~ m|^(.+)/[^/]+$|) {
14634: push @parts, split(/\//,$1);
14635: }
14636: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14637: foreach my $part (@parts) {
14638: $path .= '/'.$part;
14639: if (!-e $path) {
14640: mkdir($path,0770);
1.482 albertel 14641: }
14642: }
1.828 www 14643: # now the path exists for sure
14644: # get a user agent
14645: my $transferfile=$file.'.in.transfer';
14646: # FIXME: this should flock
14647: if (-e $transferfile) { return 'ok'; }
14648: my $request;
14649: $uri=~s/^\///;
1.980 raeburn 14650: my $homeserver = &homeserver($cnum,$cdom);
1.1398 raeburn 14651: my $hostname = &hostname($homeserver);
1.980 raeburn 14652: my $protocol = $protocol{$homeserver};
14653: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14654: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345 raeburn 14655: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828 www 14656: # did it work?
14657: if ($response->is_error()) {
14658: unlink($transferfile);
14659: &logthis("Userfile repcopy failed for $uri");
14660: return -1;
14661: }
14662: # worked, rename the transfer file
14663: rename($transferfile,$file);
1.607 raeburn 14664: return 'ok';
1.481 raeburn 14665: }
14666:
1.517 albertel 14667: sub tokenwrapper {
14668: my $uri=shift;
1.980 raeburn 14669: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 14670: $uri=~s|^/||;
1.620 albertel 14671: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 14672: my $token=$1;
1.552 albertel 14673: my (undef,$udom,$uname,$file)=split('/',$uri,4);
14674: if ($udom && $uname && $file) {
14675: $file=~s|(\?\.*)*$||;
1.949 raeburn 14676: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 14677: my $homeserver = &homeserver($uname,$udom);
1.1397 raeburn 14678: my $hostname = &hostname($homeserver);
1.980 raeburn 14679: my $protocol = $protocol{$homeserver};
14680: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14681: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 14682: (($uri=~/\?/)?'&':'?').'token='.$token.
14683: '&tokenissued='.$perlvar{'lonHostID'};
14684: } else {
14685: return '/adm/notfound.html';
14686: }
14687: }
14688:
1.828 www 14689: # call with reqtype HEAD: get last modification time
14690: # call with reqtype GET: get the file contents
14691: # Do not call this with reqtype GET for large files! It loads everything into memory
14692: #
1.481 raeburn 14693: sub getuploaded {
14694: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14695: $uri=~s/^\///;
1.980 raeburn 14696: my $homeserver = &homeserver($cnum,$cdom);
1.1397 raeburn 14697: my $hostname = &hostname($homeserver);
1.980 raeburn 14698: my $protocol = $protocol{$homeserver};
14699: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14700: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 14701: my $request=new HTTP::Request($reqtype,$uri);
1.1345 raeburn 14702: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481 raeburn 14703: $$rtncode = $response->code;
1.482 albertel 14704: if (! $response->is_success()) {
14705: return 'failed';
14706: }
14707: if ($reqtype eq 'HEAD') {
1.486 www 14708: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 14709: } elsif ($reqtype eq 'GET') {
14710: $$info = $response->content;
1.472 albertel 14711: }
1.482 albertel 14712: return 'ok';
1.36 albertel 14713: }
14714:
1.481 raeburn 14715: sub readfile {
14716: my $file = shift;
14717: if ( (! -e $file ) || ($file eq '') ) { return -1; };
14718: my $fh;
1.1359 raeburn 14719: open($fh,"<",$file);
1.481 raeburn 14720: my $a='';
1.800 albertel 14721: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 14722: return $a;
14723: }
14724:
1.36 albertel 14725: sub filelocation {
1.590 banghart 14726: my ($dir,$file) = @_;
14727: my $location;
14728: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 14729:
14730: if ($file =~ m-^/adm/-) {
14731: $file=~s-^/adm/wrapper/-/-;
14732: $file=~s-^/adm/coursedocs/showdoc/-/-;
14733: }
1.882 albertel 14734:
1.1139 www 14735: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 14736: $location = $file;
1.609 banghart 14737: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 14738: my ($udom,$uname,$filename)=
1.811 albertel 14739: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 14740: my $home=&homeserver($uname,$udom);
14741: my $is_me=0;
14742: my @ids=¤t_machine_ids();
14743: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14744: if ($is_me) {
1.1117 foxr 14745: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 14746: } else {
14747: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14748: $udom.'/'.$uname.'/'.$filename;
14749: }
1.882 albertel 14750: } elsif ($file =~ m-^/adm/-) {
14751: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 14752: } else {
14753: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 14754: $file=~s:^/(res|priv)/:/:;
14755: my $space=$1;
1.590 banghart 14756: if ( !( $file =~ m:^/:) ) {
14757: $location = $dir. '/'.$file;
14758: } else {
1.1142 raeburn 14759: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 14760: }
1.59 albertel 14761: }
1.590 banghart 14762: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 14763: while ($location=~m{/\.\./}) {
14764: if ($location =~ m{/[^/]+/\.\./}) {
14765: $location=~ s{/[^/]+/\.\./}{/}g;
14766: } else {
14767: $location=~ s{/\.\./}{/}g;
14768: }
14769: } #remove dir/..
1.590 banghart 14770: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14771: return $location;
1.46 www 14772: }
1.36 albertel 14773:
1.46 www 14774: sub hreflocation {
14775: my ($dir,$file)=@_;
1.980 raeburn 14776: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 14777: $file=filelocation($dir,$file);
1.700 albertel 14778: } elsif ($file=~m-^/adm/-) {
14779: $file=~s-^/adm/wrapper/-/-;
14780: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 14781: }
14782: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14783: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14784: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 14785: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14786: {/uploaded/$1/$2/}x;
1.46 www 14787: }
1.913 albertel 14788: if ($file=~ m{^/userfiles/}) {
14789: $file =~ s{^/userfiles/}{/uploaded/};
14790: }
1.462 albertel 14791: return $file;
1.465 albertel 14792: }
14793:
1.1139 www 14794:
14795:
14796:
14797:
1.465 albertel 14798: sub current_machine_domains {
1.853 albertel 14799: return &machine_domains(&hostname($perlvar{'lonHostID'}));
14800: }
14801:
14802: sub machine_domains {
14803: my ($hostname) = @_;
1.465 albertel 14804: my @domains;
1.838 albertel 14805: my %hostname = &all_hostnames();
1.465 albertel 14806: while( my($id, $name) = each(%hostname)) {
1.467 matthew 14807: # &logthis("-$id-$name-$hostname-");
1.465 albertel 14808: if ($hostname eq $name) {
1.844 albertel 14809: push(@domains,&host_domain($id));
1.465 albertel 14810: }
14811: }
14812: return @domains;
14813: }
14814:
14815: sub current_machine_ids {
1.853 albertel 14816: return &machine_ids(&hostname($perlvar{'lonHostID'}));
14817: }
14818:
14819: sub machine_ids {
14820: my ($hostname) = @_;
14821: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 14822: my @ids;
1.888 albertel 14823: my %name_to_host = &all_names();
1.889 albertel 14824: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14825: return @{ $name_to_host{$hostname} };
14826: }
14827: return;
1.31 www 14828: }
14829:
1.824 raeburn 14830: sub additional_machine_domains {
14831: my @domains;
1.1466 raeburn 14832: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14833: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14834: while (my $line = <$fh>) {
14835: chomp($line);
14836: $line =~ s/\s//g;
14837: push(@domains,$line);
14838: }
14839: close($fh);
14840: }
1.824 raeburn 14841: }
14842: return @domains;
14843: }
14844:
14845: sub default_login_domain {
14846: my $domain = $perlvar{'lonDefDomain'};
14847: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14848: foreach my $posdom (¤t_machine_domains(),
14849: &additional_machine_domains()) {
14850: if (lc($posdom) eq lc($testdomain)) {
14851: $domain=$posdom;
14852: last;
14853: }
14854: }
14855: return $domain;
14856: }
14857:
1.1414 raeburn 14858: sub shared_institution {
1.1439 raeburn 14859: my ($dom,$lonhost) = @_;
14860: if ($lonhost eq '') {
14861: $lonhost = $perlvar{'lonHostID'};
14862: }
1.1414 raeburn 14863: my $same_intdom;
1.1439 raeburn 14864: my $hostintdom = &internet_dom($lonhost);
1.1414 raeburn 14865: if ($hostintdom ne '') {
14866: my %iphost = &get_iphost();
14867: my $primary_id = &domain($dom,'primary');
14868: my $primary_ip = &get_host_ip($primary_id);
14869: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14870: foreach my $id (@{$iphost{$primary_ip}}) {
14871: my $intdom = &internet_dom($id);
14872: if ($intdom eq $hostintdom) {
14873: $same_intdom = 1;
14874: last;
14875: }
14876: }
14877: }
14878: }
14879: return $same_intdom;
14880: }
14881:
1.1398 raeburn 14882: sub uses_sts {
14883: my ($ignore_cache) = @_;
14884: my $lonhost = $perlvar{'lonHostID'};
14885: my $hostname = &hostname($lonhost);
14886: my $sts_on;
14887: if ($protocol{$lonhost} eq 'https') {
14888: my $cachetime = 12*3600;
14889: if (!$ignore_cache) {
14890: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14891: if (defined($cached)) {
14892: return $sts_on;
14893: }
14894: }
14895: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14896: my $request=new HTTP::Request('HEAD',$url);
14897: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14898: if ($response->is_success) {
14899: my $has_sts = $response->header('Strict-Transport-Security');
14900: if ($has_sts eq '') {
14901: $sts_on = 0;
14902: } else {
14903: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14904: my $maxage = $1;
14905: if ($maxage) {
14906: $sts_on = 1;
14907: } else {
14908: $sts_on = 0;
14909: }
14910: } else {
14911: $sts_on = 0;
14912: }
14913: }
14914: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14915: }
14916: }
14917: return;
14918: }
14919:
1.1449 raeburn 14920: sub waf_allssl {
14921: my ($host_name) = @_;
14922: my $alias = &get_proxy_alias();
14923: if ($host_name eq '') {
14924: $host_name = $ENV{'SERVER_NAME'};
14925: }
14926: if (($host_name ne '') && ($alias eq $host_name)) {
14927: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14928: my %defdomdefaults = &get_domain_defaults($serverhomedom);
14929: if ($defdomdefaults{'waf_sslopt'}) {
14930: return $defdomdefaults{'waf_sslopt'};
14931: }
14932: }
14933: return;
14934: }
14935:
1.1434 raeburn 14936: sub get_requestor_ip {
14937: my ($r,$nolookup,$noproxy) = @_;
14938: my $from_ip;
14939: if (ref($r)) {
1.1447 raeburn 14940: if ($r->can('useragent_ip')) {
14941: if ($noproxy && $r->can('client_ip')) {
14942: $from_ip = $r->client_ip();
14943: } else {
14944: $from_ip = $r->useragent_ip();
14945: }
14946: } elsif ($r->connection->can('remote_ip')) {
14947: $from_ip = $r->connection->remote_ip();
14948: } else {
14949: $from_ip = $r->get_remote_host($nolookup);
14950: }
1.1434 raeburn 14951: } else {
14952: $from_ip = $ENV{'REMOTE_ADDR'};
14953: }
14954: return $from_ip if ($noproxy);
14955: # Who controls proxy settings for server
14956: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14957: my $proxyinfo = &get_proxy_settings($dom_in_use);
14958: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437 raeburn 14959: if ($proxyinfo->{'vpnint'}) {
14960: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434 raeburn 14961: return $from_ip;
14962: }
14963: }
14964: if ($proxyinfo->{'trusted'}) {
14965: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14966: my $ipheader = $proxyinfo->{'ipheader'};
14967: my ($ip,$xfor);
14968: if (ref($r)) {
14969: if ($ipheader) {
14970: $ip = $r->headers_in->{$ipheader};
14971: }
14972: $xfor = $r->headers_in->{'X-Forwarded-For'};
14973: } else {
14974: if ($ipheader) {
14975: $ip = $ENV{'HTTP_'.uc($ipheader)};
14976: }
14977: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14978: }
14979: if (($ip eq '') && ($xfor ne '')) {
14980: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14981: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14982: $ip = $poss_ip;
1.1435 raeburn 14983: last;
1.1434 raeburn 14984: }
14985: }
14986: }
14987: if ($ip ne '') {
14988: return $ip;
14989: }
14990: }
14991: }
14992: }
14993: return $from_ip;
14994: }
14995:
14996: sub get_proxy_settings {
14997: my ($dom_in_use) = @_;
1.1494 raeburn 14998: my %domdefaults = &get_domain_defaults($dom_in_use);
1.1434 raeburn 14999: my $proxyinfo = {
15000: ipheader => $domdefaults{'waf_ipheader'},
15001: trusted => $domdefaults{'waf_trusted'},
1.1437 raeburn 15002: vpnint => $domdefaults{'waf_vpnint'},
1.1438 raeburn 15003: vpnext => $domdefaults{'waf_vpnext'},
1.1449 raeburn 15004: sslopt => $domdefaults{'waf_sslopt'},
1.1434 raeburn 15005: };
15006: return $proxyinfo;
15007: }
15008:
15009: sub ip_match {
15010: my ($ip,$pattern_str) = @_;
15011: $ip=Net::CIDR::cidrvalidate($ip);
15012: if ($ip) {
15013: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
15014: }
15015: return;
15016: }
15017:
15018: sub get_proxy_alias {
1.1450 raeburn 15019: my ($lonid) = @_;
15020: if ($lonid eq '') {
15021: $lonid = $perlvar{'lonHostID'};
15022: }
15023: if (!defined(&hostname($lonid))) {
15024: return;
15025: }
15026: if ($lonid ne '') {
15027: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434 raeburn 15028: if ($cached) {
15029: return $alias;
15030: }
1.1494 raeburn 15031: my $dom = &host_domain($lonid);
1.1434 raeburn 15032: if ($dom ne '') {
15033: my $cachetime = 60*60*24;
15034: my %domconfig =
1.1494 raeburn 15035: &get_dom('configuration',['wafproxy'],$dom);
1.1437 raeburn 15036: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15037: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450 raeburn 15038: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
15039: }
15040: }
15041: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
15042: }
15043: }
15044: return;
15045: }
15046:
15047: sub use_proxy_alias {
15048: my ($r,$lonid) = @_;
15049: my $alias = &get_proxy_alias($lonid);
15050: if ($alias) {
15051: my $dom = &host_domain($lonid);
15052: if ($dom ne '') {
1.1467 raeburn 15053: my $proxyinfo = &get_proxy_settings($dom);
1.1450 raeburn 15054: my ($vpnint,$remote_ip);
15055: if (ref($proxyinfo) eq 'HASH') {
15056: $vpnint = $proxyinfo->{'vpnint'};
15057: if ($vpnint) {
15058: $remote_ip = &get_requestor_ip($r,1,1);
1.1434 raeburn 15059: }
15060: }
1.1450 raeburn 15061: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
15062: return $alias;
15063: }
1.1434 raeburn 15064: }
15065: }
15066: return;
15067: }
15068:
1.1474 raeburn 15069: sub alias_sso {
1.1467 raeburn 15070: my ($lonid) = @_;
15071: if ($lonid eq '') {
15072: $lonid = $perlvar{'lonHostID'};
15073: }
15074: if (!defined(&hostname($lonid))) {
15075: return;
15076: }
15077: if ($lonid ne '') {
15078: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15079: if ($cached) {
15080: return $use_alias;
15081: }
1.1494 raeburn 15082: my $dom = &host_domain($lonid);
1.1467 raeburn 15083: if ($dom ne '') {
15084: my $cachetime = 60*60*24;
15085: my %domconfig =
1.1494 raeburn 15086: &get_dom('configuration',['wafproxy'],$dom);
1.1467 raeburn 15087: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15088: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15089: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15090: }
15091: }
15092: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15093: }
15094: }
15095: return;
15096: }
15097:
1.1465 raeburn 15098: sub get_saml_landing {
15099: my ($lonid) = @_;
15100: if ($lonid eq '') {
15101: my $defdom = &default_login_domain();
15102: my @hosts = ¤t_machine_ids();
15103: if (@hosts > 1) {
15104: foreach my $hostid (@hosts) {
15105: if (&host_domain($hostid) eq $defdom) {
15106: $lonid = $hostid;
15107: last;
15108: }
15109: }
15110: } else {
15111: $lonid = $perlvar{'lonHostID'};
15112: }
15113: if ($lonid) {
1.1494 raeburn 15114: unless (&host_domain($lonid) eq $defdom) {
1.1465 raeburn 15115: return;
15116: }
15117: } else {
15118: return;
15119: }
15120: } elsif (!defined(&hostname($lonid))) {
15121: return;
15122: }
15123: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15124: if ($cached) {
15125: return $landing;
15126: }
1.1494 raeburn 15127: my $dom = &host_domain($lonid);
1.1465 raeburn 15128: if ($dom ne '') {
15129: my $cachetime = 60*60*24;
15130: my %domconfig =
1.1494 raeburn 15131: &get_dom('configuration',['login'],$dom);
1.1465 raeburn 15132: if (ref($domconfig{'login'}) eq 'HASH') {
15133: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15134: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15135: $landing = 1;
15136: }
15137: }
15138: }
15139: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15140: }
15141: return;
15142: }
15143:
1.31 www 15144: # ------------------------------------------------------------- Declutters URLs
15145:
15146: sub declutter {
15147: my $thisfn=shift;
1.569 albertel 15148: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 15149: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15150: $thisfn=~s{^/home/httpd/html}{};
15151: }
1.31 www 15152: $thisfn=~s/^\///;
1.697 albertel 15153: $thisfn=~s|^adm/wrapper/||;
15154: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 15155: $thisfn=~s/^res\///;
1.1172 bisitz 15156: $thisfn=~s/^priv\///;
1.1032 raeburn 15157: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15158: $thisfn=~s/\?.+$//;
15159: }
1.268 www 15160: return $thisfn;
15161: }
15162:
15163: # ------------------------------------------------------------- Clutter up URLs
15164:
15165: sub clutter {
15166: my $thisfn='/'.&declutter(shift);
1.887 albertel 15167: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 15168: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 15169: $thisfn='/res'.$thisfn;
15170: }
1.1031 raeburn 15171: if ($thisfn !~m|^/adm|) {
15172: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 15173: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 15174: } else {
15175: my ($ext) = ($thisfn =~ /\.(\w+)$/);
15176: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 15177: if ($embstyle eq 'ssi'
15178: || ($embstyle eq 'hdn')
15179: || ($embstyle eq 'rat')
15180: || ($embstyle eq 'prv')
15181: || ($embstyle eq 'ign')) {
15182: #do nothing with these
15183: } elsif (($embstyle eq 'img')
1.695 albertel 15184: || ($embstyle eq 'emb')
15185: || ($embstyle eq 'wrp')) {
15186: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 15187: } elsif ($embstyle eq 'unk'
15188: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 15189: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 15190: } else {
1.718 www 15191: # &logthis("Got a blank emb style");
1.695 albertel 15192: }
1.694 albertel 15193: }
1.1343 raeburn 15194: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 15195: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 15196: }
1.31 www 15197: return $thisfn;
1.12 www 15198: }
15199:
1.787 albertel 15200: sub clutter_with_no_wrapper {
15201: my $uri = &clutter(shift);
15202: if ($uri =~ m-^/adm/-) {
15203: $uri =~ s-^/adm/wrapper/-/-;
15204: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
15205: }
15206: return $uri;
15207: }
15208:
1.557 albertel 15209: sub freeze_escape {
15210: my ($value)=@_;
15211: if (ref($value)) {
15212: $value=&nfreeze($value);
15213: return '__FROZEN__'.&escape($value);
15214: }
15215: return &escape($value);
15216: }
15217:
1.11 www 15218:
1.557 albertel 15219: sub thaw_unescape {
15220: my ($value)=@_;
15221: if ($value =~ /^__FROZEN__/) {
15222: substr($value,0,10,undef);
15223: $value=&unescape($value);
15224: return &thaw($value);
15225: }
15226: return &unescape($value);
15227: }
15228:
1.436 albertel 15229: sub correct_line_ends {
15230: my ($result)=@_;
15231: $$result =~s/\r\n/\n/mg;
15232: $$result =~s/\r/\n/mg;
1.415 albertel 15233: }
1.1 albertel 15234: # ================================================================ Main Program
15235:
1.184 www 15236: sub goodbye {
1.204 albertel 15237: &logthis("Starting Shut down");
1.443 albertel 15238: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 15239: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 15240: #converted
1.599 albertel 15241: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 15242: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15243: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15244: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 15245: #1.1 only
1.870 albertel 15246: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15247: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15248: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15249: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15250: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 15251: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15252: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 15253: &flushcourselogs();
15254: &logthis("Shutting down");
15255: }
15256:
1.852 albertel 15257: sub get_dns {
1.1210 raeburn 15258: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 15259: if (!$ignore_cache) {
15260: my ($content,$cached)=
1.1494 raeburn 15261: &is_cached_new('dns',$url);
1.869 albertel 15262: if ($cached) {
1.1210 raeburn 15263: &$func($content,$hashref);
1.869 albertel 15264: return;
15265: }
15266: }
15267:
15268: my %alldns;
1.1379 raeburn 15269: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15270: foreach my $dns (<$config>) {
15271: next if ($dns !~ /^\^(\S*)/x);
15272: my $line = $1;
15273: my ($host,$protocol) = split(/:/,$line);
15274: if ($protocol ne 'https') {
15275: $protocol = 'http';
15276: }
15277: $alldns{$host} = $protocol;
1.979 raeburn 15278: }
1.1379 raeburn 15279: close($config);
1.869 albertel 15280: }
15281: while (%alldns) {
1.1263 raeburn 15282: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456 raeburn 15283: my ($contents,@content);
15284: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15285: my $command = (split('/',$url))[3];
15286: my ($dir,$file) = &parse_getdns_url($command,$url);
15287: delete($alldns{$dns});
15288: next if (($dir eq '') || ($file eq ''));
15289: if (open(my $config,'<',"$dir/$file")) {
1.1457 raeburn 15290: @content = <$config>;
1.1456 raeburn 15291: close($config);
15292: }
15293: if ($url eq '/adm/dns/loncapaCRL') {
15294: $contents = join('',@content);
15295: }
15296: } else {
15297: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15298: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15299: delete($alldns{$dns});
15300: next if ($response->is_error());
15301: if ($url eq '/adm/dns/loncapaCRL') {
15302: $contents = $response->content;
15303: } else {
15304: @content = split("\n",$response->content);
15305: }
15306: }
1.1379 raeburn 15307: if ($url eq '/adm/dns/loncapaCRL') {
1.1456 raeburn 15308: return &$func($contents);
1.1379 raeburn 15309: } else {
15310: unless ($nocache) {
15311: &do_cache_new('dns',$url,\@content,30*24*60*60);
15312: }
15313: &$func(\@content,$hashref);
15314: return;
15315: }
15316: }
15317: my $which = (split('/',$url,4))[3];
15318: if ($which eq 'loncapaCRL') {
15319: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15320: if (-e $diskfile) {
15321: &logthis("unable to contact DNS, on disk file $diskfile not updated");
15322: } else {
15323: &logthis("unable to contact DNS, no on disk file $diskfile available");
15324: }
15325: } else {
15326: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15327: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15328: my @content = <$config>;
15329: close($config);
15330: &$func(\@content,$hashref);
15331: }
1.852 albertel 15332: }
1.1210 raeburn 15333: return;
15334: }
15335:
15336: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 15337: sub parse_dns_checksums_tab {
1.1210 raeburn 15338: my ($lines,$hashref) = @_;
1.1264 raeburn 15339: my $lonhost = $perlvar{'lonHostID'};
1.1494 raeburn 15340: my $machine_dom = &host_domain($lonhost);
1.1210 raeburn 15341: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 15342: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15343: my $webconfdir = '/etc/httpd/conf';
15344: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15345: $webconfdir = '/etc/apache2';
15346: } elsif ($distro =~ /^sles(\d+)$/) {
15347: if ($1 >= 10) {
15348: $webconfdir = '/etc/apache2';
15349: }
15350: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15351: if ($1 >= 10.0) {
15352: $webconfdir = '/etc/apache2';
15353: }
15354: }
1.1210 raeburn 15355: my ($release,$timestamp) = split(/\-/,$loncaparev);
15356: my (%chksum,%revnum);
15357: if (ref($lines) eq 'ARRAY') {
15358: chomp(@{$lines});
1.1238 raeburn 15359: my $version = shift(@{$lines});
15360: if ($version eq $release) {
1.1210 raeburn 15361: foreach my $line (@{$lines}) {
1.1238 raeburn 15362: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 15363: if ($file =~ m{^/etc/httpd/conf}) {
15364: if ($webconfdir eq '/etc/apache2') {
15365: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15366: }
15367: }
1.1238 raeburn 15368: $chksum{$file} = $shasum;
15369: $revnum{$file} = $version;
1.1210 raeburn 15370: }
15371: if (ref($hashref) eq 'HASH') {
15372: %{$hashref} = (
15373: sums => \%chksum,
15374: versions => \%revnum,
15375: );
15376: }
15377: }
15378: }
1.869 albertel 15379: return;
1.852 albertel 15380: }
1.1210 raeburn 15381:
15382: sub fetch_dns_checksums {
1.1238 raeburn 15383: my %checksums;
1.1494 raeburn 15384: my $machine_dom = &host_domain($perlvar{'lonHostID'});
1.1260 raeburn 15385: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 15386: my ($release,$timestamp) = split(/\-/,$loncaparev);
15387: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 15388: \%checksums);
1.1210 raeburn 15389: return \%checksums;
15390: }
15391:
1.1379 raeburn 15392: sub fetch_crl_pemfile {
15393: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15394: }
15395:
15396: sub save_crl_pem {
1.1456 raeburn 15397: my ($content) = @_;
1.1380 raeburn 15398: my ($msg,$hadchanges);
1.1456 raeburn 15399: if ($content ne '') {
1.1379 raeburn 15400: my $now = time;
15401: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15402: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15403: if (open(my $fh,'>',"$tmpcrl")) {
1.1456 raeburn 15404: print $fh $content;
1.1379 raeburn 15405: close($fh);
15406: if (-e $lonca) {
15407: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15408: my $check = <PIPE>;
15409: close(PIPE);
15410: chomp($check);
15411: if ($check eq 'verify OK') {
15412: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380 raeburn 15413: my $backup;
1.1379 raeburn 15414: if (-e $dest) {
1.1380 raeburn 15415: if (&File::Copy::move($dest,"$dest.bak")) {
15416: $backup = 'ok';
15417: }
1.1379 raeburn 15418: }
15419: if (&File::Copy::move($tmpcrl,$dest)) {
15420: $msg = 'ok';
1.1380 raeburn 15421: if ($backup) {
15422: my (%oldnums,%newnums);
15423: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15424: while (<PIPE>) {
15425: $oldnums{(split(/:/))[1]} = 1;
15426: }
15427: close(PIPE);
15428: }
15429: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15430: while(<PIPE>) {
15431: $newnums{(split(/:/))[1]} = 1;
15432: }
15433: close(PIPE);
15434: }
15435: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15436: unless (exists($oldnums{$key})) {
15437: $hadchanges = 1;
15438: last;
15439: }
15440: }
15441: unless ($hadchanges) {
15442: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15443: unless (exists($newnums{$key})) {
15444: $hadchanges = 1;
15445: last;
15446: }
15447: }
15448: }
15449: }
1.1379 raeburn 15450: }
15451: } else {
15452: unlink($tmpcrl);
15453: }
15454: } else {
15455: unlink($tmpcrl);
15456: }
15457: } else {
15458: unlink($tmpcrl);
15459: }
15460: }
15461: }
1.1380 raeburn 15462: return ($msg,$hadchanges);
1.1379 raeburn 15463: }
15464:
1.1456 raeburn 15465: sub parse_getdns_url {
15466: my ($command,$url) = @_;
15467: my $dir = $perlvar{'lonTabDir'};
15468: my $file;
15469: if ($command eq 'hosts') {
15470: $file = 'dns_hosts.tab';
15471: } elsif ($command eq 'domain') {
15472: $file = 'dns_domain.tab';
15473: } elsif ($command eq 'checksums') {
15474: my $version = (split('/',$url))[4];
15475: $file = "dns_checksums/$version.tab",
15476: } elsif ($command eq 'loncapaCRL') {
15477: $dir = $perlvar{'lonCertificateDirectory'};
15478: $file = $perlvar{'lonnetCertRevocationList'};
15479: }
15480: return ($dir,$file);
15481: }
15482:
1.327 albertel 15483: # ------------------------------------------------------------ Read domain file
15484: {
1.852 albertel 15485: my $loaded;
1.846 albertel 15486: my %domain;
15487:
1.852 albertel 15488: sub parse_domain_tab {
15489: my ($lines) = @_;
15490: foreach my $line (@$lines) {
15491: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 15492:
1.846 albertel 15493: chomp($line);
1.852 albertel 15494: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 15495: my %this_domain;
15496: foreach my $field ('description', 'auth_def', 'auth_arg_def',
15497: 'lang_def', 'city', 'longi', 'lati',
15498: 'primary') {
15499: $this_domain{$field} = shift(@elements);
15500: }
15501: $domain{$name} = \%this_domain;
1.852 albertel 15502: }
15503: }
1.864 albertel 15504:
15505: sub reset_domain_info {
15506: undef($loaded);
15507: undef(%domain);
15508: }
15509:
1.852 albertel 15510: sub load_domain_tab {
1.1293 raeburn 15511: my ($ignore_cache,$nocache) = @_;
15512: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 15513: my $fh;
1.1359 raeburn 15514: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 15515: my @lines = <$fh>;
15516: &parse_domain_tab(\@lines);
1.448 albertel 15517: }
1.852 albertel 15518: close($fh);
15519: $loaded = 1;
1.327 albertel 15520: }
1.846 albertel 15521:
15522: sub domain {
1.852 albertel 15523: &load_domain_tab() if (!$loaded);
15524:
1.846 albertel 15525: my ($name,$what) = @_;
15526: return if ( !exists($domain{$name}) );
15527:
15528: if (!$what) {
15529: return $domain{$name}{'description'};
15530: }
15531: return $domain{$name}{$what};
15532: }
1.974 raeburn 15533:
15534: sub domain_info {
15535: &load_domain_tab() if (!$loaded);
15536: return %domain;
15537: }
15538:
1.327 albertel 15539: }
15540:
15541:
1.1 albertel 15542: # ------------------------------------------------------------- Read hosts file
15543: {
1.838 albertel 15544: my %hostname;
1.844 albertel 15545: my %hostdom;
1.845 albertel 15546: my %libserv;
1.852 albertel 15547: my $loaded;
1.888 albertel 15548: my %name_to_host;
1.1074 raeburn 15549: my %internetdom;
1.1107 raeburn 15550: my %LC_dns_serv;
1.852 albertel 15551:
15552: sub parse_hosts_tab {
15553: my ($file) = @_;
15554: foreach my $configline (@$file) {
15555: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 15556: chomp($configline);
15557: if ($configline =~ /^\^/) {
15558: if ($configline =~ /^\^([\w.\-]+)/) {
15559: $LC_dns_serv{$1} = 1;
15560: }
15561: next;
15562: }
1.1074 raeburn 15563: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 15564: $name=~s/\s//g;
15565: if ($id && $domain && $role && $name) {
1.1351 raeburn 15566: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15567: my $curr = $hostname{$id};
15568: my $skip;
15569: if (ref($name_to_host{$curr}) eq 'ARRAY') {
15570: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15571: $skip = 1;
15572: } else {
15573: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15574: }
15575: }
15576: unless ($skip) {
15577: push(@{$name_to_host{$name}},$id);
15578: }
15579: } else {
15580: push(@{$name_to_host{$name}},$id);
15581: }
1.852 albertel 15582: $hostname{$id}=$name;
15583: $hostdom{$id}=$domain;
15584: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 15585: if (defined($protocol)) {
15586: if ($protocol eq 'https') {
15587: $protocol{$id} = $protocol;
15588: } else {
15589: $protocol{$id} = 'http';
15590: }
1.968 raeburn 15591: } else {
1.969 raeburn 15592: $protocol{$id} = 'http';
1.968 raeburn 15593: }
1.1074 raeburn 15594: if (defined($intdom)) {
15595: $internetdom{$id} = $intdom;
15596: }
1.852 albertel 15597: }
15598: }
15599: }
1.864 albertel 15600:
15601: sub reset_hosts_info {
1.897 albertel 15602: &purge_remembered();
1.864 albertel 15603: &reset_domain_info();
15604: &reset_hosts_ip_info();
1.1339 raeburn 15605: undef(%internetdom);
1.892 albertel 15606: undef(%name_to_host);
1.864 albertel 15607: undef(%hostname);
15608: undef(%hostdom);
15609: undef(%libserv);
15610: undef($loaded);
15611: }
1.1 albertel 15612:
1.852 albertel 15613: sub load_hosts_tab {
1.1293 raeburn 15614: my ($ignore_cache,$nocache) = @_;
15615: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359 raeburn 15616: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 15617: my @config = <$config>;
15618: &parse_hosts_tab(\@config);
15619: close($config);
15620: $loaded=1;
1.1 albertel 15621: }
1.852 albertel 15622:
1.838 albertel 15623: sub hostname {
1.852 albertel 15624: &load_hosts_tab() if (!$loaded);
15625:
1.838 albertel 15626: my ($lonid) = @_;
15627: return $hostname{$lonid};
15628: }
1.845 albertel 15629:
1.838 albertel 15630: sub all_hostnames {
1.852 albertel 15631: &load_hosts_tab() if (!$loaded);
15632:
1.838 albertel 15633: return %hostname;
15634: }
1.845 albertel 15635:
1.888 albertel 15636: sub all_names {
1.1293 raeburn 15637: my ($ignore_cache,$nocache) = @_;
15638: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 15639:
15640: return %name_to_host;
15641: }
15642:
1.974 raeburn 15643: sub all_host_domain {
15644: &load_hosts_tab() if (!$loaded);
15645: return %hostdom;
15646: }
15647:
1.1339 raeburn 15648: sub all_host_intdom {
15649: &load_hosts_tab() if (!$loaded);
15650: return %internetdom;
15651: }
15652:
1.845 albertel 15653: sub is_library {
1.852 albertel 15654: &load_hosts_tab() if (!$loaded);
15655:
1.845 albertel 15656: return exists($libserv{$_[0]});
15657: }
15658:
15659: sub all_library {
1.852 albertel 15660: &load_hosts_tab() if (!$loaded);
15661:
1.845 albertel 15662: return %libserv;
15663: }
15664:
1.1062 droeschl 15665: sub unique_library {
15666: #2x reverse removes all hostnames that appear more than once
15667: my %unique = reverse &all_library();
15668: return reverse %unique;
15669: }
15670:
1.841 albertel 15671: sub get_servers {
1.852 albertel 15672: &load_hosts_tab() if (!$loaded);
15673:
1.841 albertel 15674: my ($domain,$type) = @_;
15675: my %possible_hosts = ($type eq 'library') ? %libserv
15676: : %hostname;
15677: my %result;
1.842 albertel 15678: if (ref($domain) eq 'ARRAY') {
15679: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 15680: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 15681: $result{$host} = $hostname;
15682: }
15683: }
15684: } else {
15685: while ( my ($host,$hostname) = each(%possible_hosts)) {
15686: if ($hostdom{$host} eq $domain) {
15687: $result{$host} = $hostname;
15688: }
1.841 albertel 15689: }
15690: }
15691: return %result;
15692: }
1.845 albertel 15693:
1.1062 droeschl 15694: sub get_unique_servers {
15695: my %unique = reverse &get_servers(@_);
15696: return reverse %unique;
15697: }
15698:
1.844 albertel 15699: sub host_domain {
1.852 albertel 15700: &load_hosts_tab() if (!$loaded);
15701:
1.844 albertel 15702: my ($lonid) = @_;
15703: return $hostdom{$lonid};
15704: }
15705:
1.841 albertel 15706: sub all_domains {
1.852 albertel 15707: &load_hosts_tab() if (!$loaded);
15708:
1.841 albertel 15709: my %seen;
15710: my @uniq = grep(!$seen{$_}++, values(%hostdom));
15711: return @uniq;
15712: }
1.1074 raeburn 15713:
15714: sub internet_dom {
15715: &load_hosts_tab() if (!$loaded);
15716:
15717: my ($lonid) = @_;
15718: return $internetdom{$lonid};
15719: }
1.1107 raeburn 15720:
15721: sub is_LC_dns {
15722: &load_hosts_tab() if (!$loaded);
15723:
15724: my ($hostname) = @_;
15725: return exists($LC_dns_serv{$hostname});
15726: }
15727:
1.1 albertel 15728: }
15729:
1.847 albertel 15730: {
15731: my %iphost;
1.856 albertel 15732: my %name_to_ip;
15733: my %lonid_to_ip;
1.869 albertel 15734:
1.847 albertel 15735: sub get_hosts_from_ip {
15736: my ($ip) = @_;
15737: my %iphosts = &get_iphost();
15738: if (ref($iphosts{$ip})) {
15739: return @{$iphosts{$ip}};
15740: }
15741: return;
1.839 albertel 15742: }
1.864 albertel 15743:
15744: sub reset_hosts_ip_info {
15745: undef(%iphost);
15746: undef(%name_to_ip);
15747: undef(%lonid_to_ip);
15748: }
1.856 albertel 15749:
15750: sub get_host_ip {
15751: my ($lonid) = @_;
15752: if (exists($lonid_to_ip{$lonid})) {
15753: return $lonid_to_ip{$lonid};
15754: }
15755: my $name=&hostname($lonid);
15756: my $ip = gethostbyname($name);
15757: return if (!$ip || length($ip) ne 4);
15758: $ip=inet_ntoa($ip);
15759: $name_to_ip{$name} = $ip;
15760: $lonid_to_ip{$lonid} = $ip;
15761: return $ip;
15762: }
1.847 albertel 15763:
15764: sub get_iphost {
1.1293 raeburn 15765: my ($ignore_cache,$nocache) = @_;
1.894 albertel 15766:
1.869 albertel 15767: if (!$ignore_cache) {
15768: if (%iphost) {
15769: return %iphost;
15770: }
15771: my ($ip_info,$cached)=
1.1494 raeburn 15772: &is_cached_new('iphost','iphost');
1.869 albertel 15773: if ($cached) {
15774: %iphost = %{$ip_info->[0]};
15775: %name_to_ip = %{$ip_info->[1]};
15776: %lonid_to_ip = %{$ip_info->[2]};
15777: return %iphost;
15778: }
15779: }
1.894 albertel 15780:
15781: # get yesterday's info for fallback
15782: my %old_name_to_ip;
15783: my ($ip_info,$cached)=
1.1495 raeburn 15784: &is_cached_new('iphost','iphost');
1.894 albertel 15785: if ($cached) {
15786: %old_name_to_ip = %{$ip_info->[1]};
15787: }
15788:
1.1293 raeburn 15789: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 15790: foreach my $name (keys(%name_to_host)) {
1.847 albertel 15791: my $ip;
15792: if (!exists($name_to_ip{$name})) {
15793: $ip = gethostbyname($name);
15794: if (!$ip || length($ip) ne 4) {
1.894 albertel 15795: if (defined($old_name_to_ip{$name})) {
15796: $ip = $old_name_to_ip{$name};
15797: &logthis("Can't find $name defaulting to old $ip");
15798: } else {
15799: &logthis("Name $name no IP found");
15800: next;
15801: }
15802: } else {
15803: $ip=inet_ntoa($ip);
1.847 albertel 15804: }
15805: $name_to_ip{$name} = $ip;
15806: } else {
15807: $ip = $name_to_ip{$name};
1.653 albertel 15808: }
1.888 albertel 15809: foreach my $id (@{ $name_to_host{$name} }) {
15810: $lonid_to_ip{$id} = $ip;
15811: }
15812: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 15813: }
1.1293 raeburn 15814: unless ($nocache) {
15815: &do_cache_new('iphost','iphost',
15816: [\%iphost,\%name_to_ip,\%lonid_to_ip],
15817: 48*60*60);
15818: }
1.869 albertel 15819:
1.847 albertel 15820: return %iphost;
1.598 albertel 15821: }
15822:
1.992 raeburn 15823: #
15824: # Given a DNS returns the loncapa host name for that DNS
15825: #
15826: sub host_from_dns {
15827: my ($dns) = @_;
15828: my @hosts;
15829: my $ip;
15830:
1.993 raeburn 15831: if (exists($name_to_ip{$dns})) {
1.992 raeburn 15832: $ip = $name_to_ip{$dns};
15833: }
15834: if (!$ip) {
15835: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15836: if (length($ip) == 4) {
15837: $ip = &IO::Socket::inet_ntoa($ip);
15838: }
15839: }
15840: if ($ip) {
15841: @hosts = get_hosts_from_ip($ip);
15842: return $hosts[0];
15843: }
15844: return undef;
1.986 foxr 15845: }
1.992 raeburn 15846:
1.1074 raeburn 15847: sub get_internet_names {
15848: my ($lonid) = @_;
15849: return if ($lonid eq '');
15850: my ($idnref,$cached)=
1.1494 raeburn 15851: &is_cached_new('internetnames',$lonid);
1.1074 raeburn 15852: if ($cached) {
15853: return $idnref;
15854: }
15855: my $ip = &get_host_ip($lonid);
15856: my @hosts = &get_hosts_from_ip($ip);
15857: my %iphost = &get_iphost();
15858: my (@idns,%seen);
15859: foreach my $id (@hosts) {
15860: my $dom = &host_domain($id);
15861: my $prim_id = &domain($dom,'primary');
15862: my $prim_ip = &get_host_ip($prim_id);
15863: next if ($seen{$prim_ip});
15864: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15865: foreach my $id (@{$iphost{$prim_ip}}) {
15866: my $intdom = &internet_dom($id);
15867: unless (grep(/^\Q$intdom\E$/,@idns)) {
15868: push(@idns,$intdom);
15869: }
15870: }
15871: }
15872: $seen{$prim_ip} = 1;
15873: }
1.1219 raeburn 15874: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 15875: }
15876:
1.986 foxr 15877: }
15878:
1.1079 raeburn 15879: sub all_loncaparevs {
1.1249 raeburn 15880: 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 15881: }
15882:
1.1227 raeburn 15883: # ---------------------------------------------------------- Read loncaparev table
15884: {
15885: sub load_loncaparevs {
15886: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359 raeburn 15887: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227 raeburn 15888: while (my $configline=<$config>) {
15889: chomp($configline);
15890: my ($hostid,$loncaparev)=split(/:/,$configline);
15891: $loncaparevs{$hostid}=$loncaparev;
15892: }
15893: close($config);
15894: }
15895: }
15896: }
15897: }
15898:
15899: # ---------------------------------------------------------- Read serverhostID table
15900: {
15901: sub load_serverhomeIDs {
15902: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359 raeburn 15903: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227 raeburn 15904: while (my $configline=<$config>) {
15905: chomp($configline);
15906: my ($name,$id)=split(/:/,$configline);
15907: $serverhomeIDs{$name}=$id;
15908: }
15909: close($config);
15910: }
15911: }
15912: }
15913: }
15914:
15915:
1.862 albertel 15916: BEGIN {
15917:
15918: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15919: unless ($readit) {
15920: {
15921: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15922: %perlvar = (%perlvar,%{$configvars});
15923: }
15924:
15925:
1.1 albertel 15926: # ------------------------------------------------------ Read spare server file
15927: {
1.1359 raeburn 15928: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 15929:
15930: while (my $configline=<$config>) {
15931: chomp($configline);
1.284 matthew 15932: if ($configline) {
1.784 albertel 15933: my ($host,$type) = split(':',$configline,2);
1.785 albertel 15934: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 15935: push(@{ $spareid{$type} }, $host);
1.1 albertel 15936: }
15937: }
1.448 albertel 15938: close($config);
1.1 albertel 15939: }
1.11 www 15940: # ------------------------------------------------------------ Read permissions
15941: {
1.1359 raeburn 15942: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 15943:
15944: while (my $configline=<$config>) {
1.448 albertel 15945: chomp($configline);
15946: if ($configline) {
15947: my ($role,$perm)=split(/ /,$configline);
15948: if ($perm ne '') { $pr{$role}=$perm; }
15949: }
1.11 www 15950: }
1.448 albertel 15951: close($config);
1.11 www 15952: }
15953:
15954: # -------------------------------------------- Read plain texts for permissions
15955: {
1.1359 raeburn 15956: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 15957:
15958: while (my $configline=<$config>) {
1.448 albertel 15959: chomp($configline);
15960: if ($configline) {
1.742 raeburn 15961: my ($short,@plain)=split(/:/,$configline);
15962: %{$prp{$short}} = ();
15963: if (@plain > 0) {
15964: $prp{$short}{'std'} = $plain[0];
15965: for (my $i=1; $i<@plain; $i++) {
15966: $prp{$short}{'alt'.$i} = $plain[$i];
15967: }
15968: }
1.448 albertel 15969: }
1.135 www 15970: }
1.448 albertel 15971: close($config);
1.135 www 15972: }
15973:
15974: # ---------------------------------------------------------- Read package table
15975: {
1.1359 raeburn 15976: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 15977:
15978: while (my $configline=<$config>) {
1.483 albertel 15979: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 15980: chomp($configline);
15981: my ($short,$plain)=split(/:/,$configline);
15982: my ($pack,$name)=split(/\&/,$short);
15983: if ($plain ne '') {
15984: $packagetab{$pack.'&'.$name.'&name'}=$name;
15985: $packagetab{$short}=$plain;
15986: }
1.11 www 15987: }
1.448 albertel 15988: close($config);
1.329 matthew 15989: }
15990:
1.1073 raeburn 15991: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 15992:
15993: &load_loncaparevs();
1.1073 raeburn 15994:
1.1074 raeburn 15995: # ---------------------------------------------------------- Read serverhostID table
15996:
1.1227 raeburn 15997: &load_serverhomeIDs();
15998:
15999: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 16000: {
16001: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
16002: if (-e $file) {
16003: my $parser = HTML::LCParser->new($file);
16004: while (my $token = $parser->get_token()) {
16005: if ($token->[0] eq 'S') {
16006: my $item = $token->[1];
16007: my $name = $token->[2]{'name'};
16008: my $value = $token->[2]{'value'};
1.1285 raeburn 16009: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 16010: my $namematch = $token->[2]{'namematch'};
16011: if ($item eq 'parameter') {
16012: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
16013: my $release = $parser->get_text();
16014: $release =~ s/(^\s*|\s*$ )//gx;
16015: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
16016: }
16017: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 16018: my $release = $parser->get_text();
16019: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 16020: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 16021: }
16022: }
16023: }
16024: }
1.1073 raeburn 16025: }
16026:
1.1138 raeburn 16027: # ---------------------------------------------------------- Read managers table
16028: {
16029: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359 raeburn 16030: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 16031: while (my $configline=<$config>) {
16032: chomp($configline);
16033: next if ($configline =~ /^\#/);
16034: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
16035: $managerstab{$configline} = 1;
16036: }
16037: }
16038: close($config);
16039: }
16040: }
16041: }
16042:
1.329 matthew 16043: # ------------- set up temporary directory
16044: {
1.1117 foxr 16045: $tmpdir = LONCAPA::tempdir();
1.329 matthew 16046:
1.11 www 16047: }
16048:
1.1405 raeburn 16049: # ------------- set default texengine (domain default overrides this)
16050: {
16051: $deftex = LONCAPA::texengine();
16052: }
16053:
1.1416 raeburn 16054: # ------------- set default minimum length for passwords for internal auth users
16055: {
16056: $passwdmin = LONCAPA::passwd_min();
16057: }
16058:
1.794 albertel 16059: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
16060: 'compress_threshold'=> 20_000,
16061: });
1.185 www 16062:
1.281 www 16063: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 16064: $dumpcount=0;
1.958 www 16065: $locknum=0;
1.22 www 16066:
1.163 harris41 16067: &logtouch();
1.672 albertel 16068: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 16069: $readit=1;
1.564 albertel 16070: {
16071: use integer;
16072: my $test=(2**32)+1;
1.568 albertel 16073: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 16074: &logthis(" Detected 64bit platform ($_64bit)");
16075: }
1.195 www 16076: }
1.1 albertel 16077: }
1.179 www 16078:
1.1 albertel 16079: 1;
1.191 harris41 16080: __END__
16081:
1.243 albertel 16082: =pod
16083:
1.191 harris41 16084: =head1 NAME
16085:
1.243 albertel 16086: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 16087:
16088: =head1 SYNOPSIS
16089:
1.243 albertel 16090: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 16091:
16092: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16093:
1.243 albertel 16094: Common parameters:
16095:
16096: =over 4
16097:
16098: =item *
16099:
16100: $uname : an internal username (if $cname expecting a course Id specifically)
16101:
16102: =item *
16103:
16104: $udom : a domain (if $cdom expecting a course's domain specifically)
16105:
16106: =item *
16107:
16108: $symb : a resource instance identifier
16109:
16110: =item *
16111:
16112: $namespace : the name of a .db file that contains the data needed or
16113: being set.
16114:
16115: =back
16116:
1.394 bowersj2 16117: =head1 OVERVIEW
1.191 harris41 16118:
1.394 bowersj2 16119: lonnet provides subroutines which interact with the
16120: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16121: about classes, users, and resources.
1.243 albertel 16122:
16123: For many of these objects you can also use this to store data about
16124: them or modify them in various ways.
1.191 harris41 16125:
1.394 bowersj2 16126: =head2 Symbs
1.191 harris41 16127:
1.394 bowersj2 16128: To identify a specific instance of a resource, LON-CAPA uses symbols
16129: or "symbs"X<symb>. These identifiers are built from the URL of the
16130: map, the resource number of the resource in the map, and the URL of
16131: the resource itself. The latter is somewhat redundant, but might help
16132: if maps change.
16133:
16134: An example is
16135:
16136: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16137:
16138: The respective map entry is
16139:
16140: <resource id="19" src="/res/msu/korte/tests/part12.problem"
16141: title="Problem 2">
16142: </resource>
16143:
16144: Symbs are used by the random number generator, as well as to store and
16145: restore data specific to a certain instance of for example a problem.
16146:
16147: =head2 Storing And Retrieving Data
16148:
16149: X<store()>X<cstore()>X<restore()>Three of the most important functions
16150: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16151: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16152: is is the non-critical message twin of cstore. These functions are for
16153: handlers to store a perl hash to a user's permanent data space in an
16154: easy manner, and to retrieve it again on another call. It is expected
16155: that a handler would use this once at the beginning to retrieve data,
16156: and then again once at the end to send only the new data back.
16157:
16158: The data is stored in the user's data directory on the user's
16159: homeserver under the ID of the course.
16160:
16161: The hash that is returned by restore will have all of the previous
16162: value for all of the elements of the hash.
16163:
16164: Example:
16165:
16166: #creating a hash
16167: my %hash;
16168: $hash{'foo'}='bar';
16169:
16170: #storing it
16171: &Apache::lonnet::cstore(\%hash);
16172:
16173: #changing a value
16174: $hash{'foo'}='notbar';
16175:
16176: #adding a new value
16177: $hash{'bar'}='foo';
16178: &Apache::lonnet::cstore(\%hash);
16179:
16180: #retrieving the hash
16181: my %history=&Apache::lonnet::restore();
16182:
16183: #print the hash
16184: foreach my $key (sort(keys(%history))) {
16185: print("\%history{$key} = $history{$key}");
16186: }
16187:
16188: Will print out:
1.191 harris41 16189:
1.394 bowersj2 16190: %history{1:foo} = bar
16191: %history{1:keys} = foo:timestamp
16192: %history{1:timestamp} = 990455579
16193: %history{2:bar} = foo
16194: %history{2:foo} = notbar
16195: %history{2:keys} = foo:bar:timestamp
16196: %history{2:timestamp} = 990455580
16197: %history{bar} = foo
16198: %history{foo} = notbar
16199: %history{timestamp} = 990455580
16200: %history{version} = 2
16201:
16202: Note that the special hash entries C<keys>, C<version> and
16203: C<timestamp> were added to the hash. C<version> will be equal to the
16204: total number of versions of the data that have been stored. The
16205: C<timestamp> attribute will be the UNIX time the hash was
16206: stored. C<keys> is available in every historical section to list which
16207: keys were added or changed at a specific historical revision of a
16208: hash.
16209:
16210: B<Warning>: do not store the hash that restore returns directly. This
16211: will cause a mess since it will restore the historical keys as if the
16212: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 16213:
1.394 bowersj2 16214: Calling convention:
1.191 harris41 16215:
1.1225 raeburn 16216: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 16217: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 16218:
1.394 bowersj2 16219: For more detailed information, see lonnet specific documentation.
1.191 harris41 16220:
1.394 bowersj2 16221: =head1 RETURN MESSAGES
1.191 harris41 16222:
1.394 bowersj2 16223: =over 4
1.191 harris41 16224:
1.394 bowersj2 16225: =item * B<con_lost>: unable to contact remote host
1.191 harris41 16226:
1.394 bowersj2 16227: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16228: when the connection is brought back up
1.191 harris41 16229:
1.394 bowersj2 16230: =item * B<con_failed>: unable to contact remote host and unable to save message
16231: for later delivery
1.191 harris41 16232:
1.967 bisitz 16233: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 16234:
1.394 bowersj2 16235: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 16236: that was requested
1.191 harris41 16237:
1.243 albertel 16238: =back
1.191 harris41 16239:
1.243 albertel 16240: =head1 PUBLIC SUBROUTINES
1.191 harris41 16241:
1.243 albertel 16242: =head2 Session Environment Functions
1.191 harris41 16243:
1.243 albertel 16244: =over 4
1.191 harris41 16245:
1.394 bowersj2 16246: =item *
16247: X<appenv()>
1.949 raeburn 16248: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 16249: the user envirnoment file, and will be restored for each access this
1.620 albertel 16250: user makes during this session, also modifies the %env for the current
1.949 raeburn 16251: process. Optional rolesarrayref - if defined contains a reference to an array
16252: of roles which are exempt from the restriction on modifying user.role entries
16253: in the user's environment.db and in %env.
1.191 harris41 16254:
16255: =item *
1.394 bowersj2 16256: X<delenv()>
1.987 raeburn 16257: B<delenv($delthis,$regexp)>: removes all items from the session
16258: environment file that begin with $delthis. If the
16259: optional second arg - $regexp - is true, $delthis is treated as a
16260: regular expression, otherwise \Q$delthis\E is used.
16261: The values are also deleted from the current processes %env.
1.191 harris41 16262:
1.795 albertel 16263: =item * get_env_multiple($name)
16264:
16265: gets $name from the %env hash, it seemlessly handles the cases where multiple
16266: values may be defined and end up as an array ref.
16267:
16268: returns an array of values
16269:
1.243 albertel 16270: =back
16271:
16272: =head2 User Information
1.191 harris41 16273:
1.243 albertel 16274: =over 4
1.191 harris41 16275:
16276: =item *
1.394 bowersj2 16277: X<queryauthenticate()>
16278: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 16279: authentication scheme
16280:
16281: =item *
1.394 bowersj2 16282: X<authenticate()>
1.1073 raeburn 16283: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 16284: authenticate user from domain's lib servers (first use the current
16285: one). C<$upass> should be the users password.
1.1073 raeburn 16286: $checkdefauth is optional (value is 1 if a check should be made to
16287: authenticate user using default authentication method, and allow
16288: account creation if username does not have account in the domain).
16289: $clientcancheckhost is optional (value is 1 if checking whether the
16290: server can host will occur on the client side in lonauth.pm).
1.191 harris41 16291:
16292: =item *
1.394 bowersj2 16293: X<homeserver()>
16294: B<homeserver($uname,$udom)>: find the server which has
16295: the user's directory and files (there must be only one), this caches
16296: the answer, and also caches if there is a borken connection.
1.191 harris41 16297:
16298: =item *
1.394 bowersj2 16299: X<idget()>
1.1300 raeburn 16300: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
16301: a list of student/employee IDs or clicker IDs
16302: (student/employee IDs are a unique resource in a domain, there must be
16303: only 1 ID per username, and only 1 username per ID in a specific domain).
16304: clickerIDs are not necessarily unique, as students might share clickers.
16305: (returns hash: id=>name,id=>name)
1.191 harris41 16306:
16307: =item *
1.394 bowersj2 16308: X<idrget()>
16309: B<idrget($udom,@unames)>: find the IDs behind a list of
16310: usernames (returns hash: name=>id,name=>id)
1.191 harris41 16311:
16312: =item *
1.394 bowersj2 16313: X<idput()>
1.1300 raeburn 16314: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
16315: names and associated student/employee IDs or clicker IDs.
16316:
16317: =item *
16318: X<iddel()>
16319: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
16320: student/employee ID or clicker ID username look-ups from domain.
16321: The homeserver ($uhome) and namespace ($namespace) are optional.
16322: If no $uhome is provided, it will be determined usig &homeserver()
16323: for each user. If no $namespace is provided, the default is ids.
16324:
16325: =item *
16326: X<updateclickers()>
16327: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
16328: clicker ID-to-username look-ups in clickers.db on library server.
16329: Permitted actions are add or del (i.e., add or delete). The
16330: clickers.db contains clickerID as keys (escaped), and each corresponding
16331: value is an escaped comma-separated list of usernames (for whom the
16332: library server is the homeserver), who registered that particular ID.
16333: If $critical is true, the update will be sent via &critical, otherwise
16334: &reply() will be used.
1.191 harris41 16335:
16336: =item *
1.394 bowersj2 16337: X<rolesinit()>
1.1169 droeschl 16338: B<rolesinit($udom,$username)>: get user privileges.
16339: returns user role, first access and timer interval hashes
1.243 albertel 16340:
16341: =item *
1.1171 droeschl 16342: X<privileged()>
16343: B<privileged($username,$domain)>: returns a true if user has a
16344: privileged and active role (i.e. su or dc), false otherwise.
16345:
16346: =item *
1.551 albertel 16347: X<getsection()>
16348: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 16349: course $cname, return section name/number or '' for "not in course"
16350: and '-1' for "no section"
16351:
16352: =item *
1.394 bowersj2 16353: X<userenvironment()>
16354: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 16355: passed in @what from the requested user's environment, returns a hash
16356:
1.858 raeburn 16357: =item *
16358: X<userlog_query()>
1.859 albertel 16359: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16360: activity.log file. %filters defines filters applied when parsing the
16361: log file. These can be start or end timestamps, or the type of action
16362: - log to look for Login or Logout events, check for Checkin or
16363: Checkout, role for role selection. The response is in the form
16364: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
16365: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 16366:
1.243 albertel 16367: =back
16368:
16369: =head2 User Roles
16370:
16371: =over 4
16372:
16373: =item *
16374:
1.1284 raeburn 16375: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
16376: returns codes for allowed actions.
16377:
16378: The first argument is required, all others are optional.
16379:
16380: $priv is the privilege being checked.
16381: $uri contains additional information about what is being checked for access (e.g.,
16382: URL, course ID etc.).
16383: $symb is the unique resource instance identifier in a course; if needed,
16384: but not provided, it will be retrieved via a call to &symbread().
16385: $role is the role for which a priv is being checked (only used if priv is evb).
16386: $clientip is the user's IP address (only used when checking for access to portfolio
16387: files).
16388: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
16389: prevents recursive calls to &allowed.
16390:
1.243 albertel 16391: F: full access
16392: U,I,K: authentication modes (cxx only)
16393: '': forbidden
16394: 1: user needs to choose course
16395: 2: browse allowed
1.766 albertel 16396: A: passphrase authentication needed
1.1284 raeburn 16397: B: access temporarily blocked because of a blocking event in a course.
1.1402 raeburn 16398: D: access blocked because access is required via session initiated via deep-link
1.243 albertel 16399:
16400: =item *
16401:
1.1192 raeburn 16402: constructaccess($url,$setpriv) : check for access to construction space URL
16403:
16404: See if the owner domain and name in the URL match those in the
16405: expected environment. If so, return three element list
16406: ($ownername,$ownerdomain,$ownerhome).
16407:
16408: Otherwise return the null string.
16409:
16410: If second argument 'setpriv' is true, it assigns the privileges,
16411: and returns the same three element list, unless the owner has
16412: blocked "ad hoc" Domain Coordinator access to the Author Space,
16413: in which case the null string is returned.
16414:
16415: =item *
16416:
1.1326 raeburn 16417: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16418: define a custom role rolename set privileges in format of lonTabs/roles.tab
16419: for system, domain, and course level. $uname and $udom are optional (current
16420: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 16421:
16422: =item *
16423:
1.988 raeburn 16424: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
16425: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 16426: $type is Course (default) or Community.
1.988 raeburn 16427: If $forcedefault evaluates to true, text returned will be default
16428: text for $type. Otherwise, if this is a course, the text returned
16429: will be a custom name for the role (if defined in the course's
16430: environment). If no custom name is defined the default is returned.
16431:
1.832 raeburn 16432: =item *
16433:
1.1219 raeburn 16434: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 16435: All arguments are optional. Returns a hash of a roles, either for
16436: co-author/assistant author roles for a user's Construction Space
1.906 albertel 16437: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 16438: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16439: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16440: For each key, value is set to colon-separated start and end times for
16441: the role. If no username and domain are specified, will default to
1.934 raeburn 16442: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 16443: of role statuses (active, future or previous), roles
16444: (e.g., cc,in, st etc.) and domains of the roles which can be used
16445: to restrict the list of roles reported. If no array ref is
16446: provided for types, will default to return only active roles.
1.834 albertel 16447:
1.1195 raeburn 16448: =item *
16449:
16450: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 16451: user: $uname:$udom has a role in the course: $cdom_$cnum.
16452:
16453: Additional optional arguments are: $type (if role checking is to be restricted
16454: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 16455: available roles) or future (roles available in the future), and
16456: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 16457: have active Domain Coordinator role in course's domain or in additional
16458: domains (specified in 'Domains to check for privileged users' in course
16459: environment -- set via: Course Settings -> Classlists and staff listing).
16460:
16461: =item *
16462:
16463: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16464: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16465: $possdomains and $possroles are optional array refs -- to domains to check and
16466: roles to check. If $possdomains is not specified, a dump will be done of the
16467: users' roles.db to check for a dc or su role in any domain. This can be
16468: time consuming if &privileged is called repeatedly (e.g., when displaying a
16469: classlist), so in such cases, supplying a $possdomains array is preferred, as
16470: this then allows &privileged_by_domain() to be used, which caches the identity
16471: of privileged users, eliminating the need for repeated calls to &dump().
16472:
16473: =item *
16474:
16475: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16476: where the outer hash keys are domains specified in the $possdomains array ref,
16477: next inner hash keys are privileged roles specified in the $roles array ref,
16478: and the innermost hash contains key = value pairs for username:domain = end:start
16479: for active or future "privileged" users with that role in that domain. To avoid
16480: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16481: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 16482:
1.243 albertel 16483: =back
16484:
16485: =head2 User Modification
16486:
16487: =over 4
16488:
16489: =item *
16490:
1.957 raeburn 16491: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 16492: user for the level given by URL. Optional start and end dates (leave empty
16493: string or zero for "no date")
1.191 harris41 16494:
16495: =item *
16496:
1.243 albertel 16497: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16498: change a users, password, possible return values are: ok,
16499: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16500: refused
1.191 harris41 16501:
16502: =item *
16503:
1.243 albertel 16504: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 16505:
16506: =item *
16507:
1.1058 raeburn 16508: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16509: $forceid,$desiredhome,$email,$inststatus,$candelete) :
16510:
16511: will update user information (firstname,middlename,lastname,generation,
16512: permanentemail), and if forceid is true, student/employee ID also.
16513: A user's institutional affiliation(s) can also be updated.
16514: User information fields will not be overwritten with empty entries
16515: unless the field is included in the $candelete array reference.
16516: This array is included when a single user is modified via "Manage Users",
16517: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 16518:
16519: =item *
16520:
1.286 matthew 16521: modifystudent
16522:
1.957 raeburn 16523: modify a student's enrollment and identification information.
1.1235 raeburn 16524: The course id is resolved based on the current user's environment.
16525: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 16526: associated with a course.
16527:
1.297 matthew 16528: This call is essentially a wrapper for lonnet::modifyuser and
16529: lonnet::modify_student_enrollment
1.286 matthew 16530:
16531: Inputs:
16532:
16533: =over 4
16534:
1.957 raeburn 16535: =item B<$udom> Student's loncapa domain
1.286 matthew 16536:
1.957 raeburn 16537: =item B<$uname> Student's loncapa login name
1.286 matthew 16538:
1.964 bisitz 16539: =item B<$uid> Student/Employee ID
1.286 matthew 16540:
1.957 raeburn 16541: =item B<$umode> Student's authentication mode
1.286 matthew 16542:
1.957 raeburn 16543: =item B<$upass> Student's password
1.286 matthew 16544:
1.957 raeburn 16545: =item B<$first> Student's first name
1.286 matthew 16546:
1.957 raeburn 16547: =item B<$middle> Student's middle name
1.286 matthew 16548:
1.957 raeburn 16549: =item B<$last> Student's last name
1.286 matthew 16550:
1.957 raeburn 16551: =item B<$gene> Student's generation
1.286 matthew 16552:
1.957 raeburn 16553: =item B<$usec> Student's section in course
1.286 matthew 16554:
16555: =item B<$end> Unix time of the roles expiration
16556:
16557: =item B<$start> Unix time of the roles start date
16558:
16559: =item B<$forceid> If defined, allow $uid to be changed
16560:
16561: =item B<$desiredhome> server to use as home server for student
16562:
1.957 raeburn 16563: =item B<$email> Student's permanent e-mail address
16564:
16565: =item B<$type> Type of enrollment (auto or manual)
16566:
1.963 raeburn 16567: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
16568:
16569: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 16570:
1.963 raeburn 16571: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 16572:
1.963 raeburn 16573: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 16574:
1.1216 raeburn 16575: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16576:
16577: =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 16578:
1.286 matthew 16579: =back
1.297 matthew 16580:
16581: =item *
16582:
16583: modify_student_enrollment
16584:
1.1235 raeburn 16585: Change a student's enrollment status in a class. The environment variable
1.297 matthew 16586: 'role.request.course' must be defined for this function to proceed.
16587:
16588: Inputs:
16589:
16590: =over 4
16591:
1.1235 raeburn 16592: =item $udom, student's domain
1.297 matthew 16593:
1.1235 raeburn 16594: =item $uname, student's name
1.297 matthew 16595:
1.1235 raeburn 16596: =item $uid, student's user id
1.297 matthew 16597:
1.1235 raeburn 16598: =item $first, student's first name
1.297 matthew 16599:
16600: =item $middle
16601:
16602: =item $last
16603:
16604: =item $gene
16605:
16606: =item $usec
16607:
16608: =item $end
16609:
16610: =item $start
16611:
1.957 raeburn 16612: =item $type
16613:
16614: =item $locktype
16615:
16616: =item $cid
16617:
16618: =item $selfenroll
16619:
16620: =item $context
16621:
1.1216 raeburn 16622: =item $credits, number of credits student will earn from this class
16623:
1.1314 raeburn 16624: =item $instsec, institutional course section code for student
16625:
1.297 matthew 16626: =back
16627:
1.191 harris41 16628:
16629: =item *
16630:
1.243 albertel 16631: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16632: custom role; give a custom role to a user for the level given by URL. Specify
16633: name and domain of role author, and role name
1.191 harris41 16634:
16635: =item *
16636:
1.243 albertel 16637: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 16638:
16639: =item *
16640:
1.243 albertel 16641: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16642:
16643: =back
16644:
16645: =head2 Course Infomation
16646:
16647: =over 4
1.191 harris41 16648:
16649: =item *
16650:
1.1118 foxr 16651: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 16652: specified course id, including all environment settings for the
16653: course, the description of the course will be in the hash under the
16654: key 'description'
1.191 harris41 16655:
1.1118 foxr 16656: $options is an optional parameter that if supplied is a hash reference that controls
16657: what how this function works. It has the following key/values:
16658:
16659: =over 4
16660:
16661: =item freshen_cache
16662:
16663: If defined, and the environment cache for the course is valid, it is
16664: returned in the returned hash.
16665:
16666: =item one_time
16667:
16668: If defined, the last cache time is set to _now_
16669:
16670: =item user
16671:
16672: If defined, the supplied username is used instead of the current user.
16673:
16674:
16675: =back
16676:
1.191 harris41 16677: =item *
16678:
1.624 albertel 16679: resdata($name,$domain,$type,@which) : request for current parameter
16680: setting for a specific $type, where $type is either 'course' or 'user',
16681: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 16682: answers for 10 minutes.
1.243 albertel 16683:
1.877 foxr 16684: =item *
16685:
16686: get_courseresdata($courseid, $domain) : dump the entire course resource
16687: data base, returning a hash that is keyed by the resource name and has
16688: values that are the resource value. I believe that the timestamps and
16689: versions are also returned.
16690:
1.243 albertel 16691: =back
16692:
16693: =head2 Course Modification
16694:
16695: =over 4
1.191 harris41 16696:
16697: =item *
16698:
1.243 albertel 16699: writecoursepref($courseid,%prefs) : write preferences (environment
16700: database) for a course
1.191 harris41 16701:
16702: =item *
16703:
1.1011 raeburn 16704: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16705:
16706: =item *
16707:
1.1038 raeburn 16708: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 16709:
1.1167 droeschl 16710: =item *
16711:
16712: is_course($courseid), is_course($cdom, $cnum)
16713:
16714: Accepts either a combined $courseid (in the form of domain_courseid) or the
16715: two component version $cdom, $cnum. It checks if the specified course exists.
16716:
16717: Returns:
16718: undef if the course doesn't exist, otherwise
16719: in scalar context the combined courseid.
16720: in list context the two components of the course identifier, domain and
16721: courseid.
16722:
1.243 albertel 16723: =back
16724:
1.1401 raeburn 16725: =head2 Bubblesheet Configuration
16726:
16727: =over 4
16728:
16729: =item *
16730:
16731: get_scantron_config($which)
16732:
16733: $which - the name of the configuration to parse from the file.
16734:
16735: Parses and returns the bubblesheet configuration line selected as a
16736: hash of configuration file fields.
16737:
16738:
16739: Returns:
16740: If the named configuration is not in the file, an empty
16741: hash is returned.
16742:
16743: a hash with the fields
16744: name - internal name for the this configuration setup
16745: description - text to display to operator that describes this config
16746: CODElocation - if 0 or the string 'none'
16747: - no CODE exists for this config
16748: if -1 || the string 'letter'
16749: - a CODE exists for this config and is
16750: a string of letters
16751: Unsupported value (but planned for future support)
16752: if a positive integer
16753: - The CODE exists as the first n items from
16754: the question section of the form
16755: if the string 'number'
16756: - The CODE exists for this config and is
16757: a string of numbers
16758: CODEstart - (only matter if a CODE exists) column in the line where
16759: the CODE starts
16760: CODElength - length of the CODE
16761: IDstart - column where the student/employee ID starts
16762: IDlength - length of the student/employee ID info
16763: Qstart - column where the information from the bubbled
16764: 'questions' start
16765: Qlength - number of columns comprising a single bubble line from
16766: the sheet. (usually either 1 or 10)
16767: Qon - either a single character representing the character used
16768: to signal a bubble was chosen in the positional setup, or
16769: the string 'letter' if the letter of the chosen bubble is
16770: in the final, or 'number' if a number representing the
16771: chosen bubble is in the file (1->A 0->J)
16772: Qoff - the character used to represent that a bubble was
16773: left blank
16774: PaperID - if the scanning process generates a unique number for each
16775: sheet scanned the column that this ID number starts in
16776: PaperIDlength - number of columns that comprise the unique ID number
16777: for the sheet of paper
16778: FirstName - column that the first name starts in
16779: FirstNameLength - number of columns that the first name spans
16780: LastName - column that the last name starts in
16781: LastNameLength - number of columns that the last name spans
16782: BubblesPerRow - number of bubbles available in each row used to
16783: bubble an answer. (If not specified, 10 assumed).
16784:
16785:
16786: =item *
16787:
16788: get_scantronformat_file($cdom)
16789:
16790: $cdom - the course's domain (optional); if not supplied, uses
16791: domain for current $env{'request.course.id'}.
16792:
16793: Returns an array containing lines from the scantron format file for
16794: the domain of the course.
16795:
16796: If a url for a custom.tab file is listed in domain's configuration.db,
16797: lines are from this file.
16798:
16799: Otherwise, if a default.tab has been published in RES space by the
16800: domainconfig user, lines are from this file.
16801:
16802: Otherwise, fall back to getting lines from the legacy file on the
16803: local server: /home/httpd/lonTabs/default_scantronformat.tab
16804:
16805: =back
16806:
1.243 albertel 16807: =head2 Resource Subroutines
16808:
16809: =over 4
1.191 harris41 16810:
16811: =item *
16812:
1.243 albertel 16813: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 16814:
16815: =item *
16816:
1.243 albertel 16817: repcopy($filename) : subscribes to the requested file, and attempts to
16818: replicate from the owning library server, Might return
1.607 raeburn 16819: 'unavailable', 'not_found', 'forbidden', 'ok', or
16820: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 16821: resource. Expects the local filesystem pathname
16822: (/home/httpd/html/res/....)
16823:
16824: =back
16825:
16826: =head2 Resource Information
16827:
16828: =over 4
1.191 harris41 16829:
16830: =item *
16831:
1.1228 raeburn 16832: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
16833: and returns the value of a variety of different possible values,
16834: $varname should be a request string, and the other parameters can be
16835: used to specify who and what one is asking about. Ordinarily, $cid
16836: does not need to be specified, as it is retrived from
16837: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16838: within lonuserstate::loadmap() when initializing a course, before
16839: $env{'request.course.id'} has been set, so it needs to be provided
16840: in that one case.
1.243 albertel 16841:
16842: Possible values for $varname are environment.lastname (or other item
16843: from the envirnment hash), user.name (or someother aspect about the
16844: user), resource.0.maxtries (or some other part and parameter of a
16845: resource)
1.204 albertel 16846:
16847: =item *
16848:
1.243 albertel 16849: directcondval($number) : get current value of a condition; reads from a state
16850: string
1.204 albertel 16851:
16852: =item *
16853:
1.243 albertel 16854: condval($condidx) : value of condition index based on state
1.204 albertel 16855:
16856: =item *
16857:
1.1362 raeburn 16858: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243 albertel 16859: resource's metadata, $what should be either a specific key, or either
16860: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362 raeburn 16861: packages that this resource currently uses, the last 3 arguments are
16862: only used internally for recursive metadata.
16863:
16864: the toolsymb is only used where the uri is for an external tool (for which
16865: the uri as well as the symb are guaranteed to be unique).
1.243 albertel 16866:
1.1371 raeburn 16867: this function automatically caches all requests except any made recursively
16868: to retrieve a list of metadata keys for an imported library file ($liburi is
16869: defined).
1.191 harris41 16870:
16871: =item *
16872:
1.243 albertel 16873: metadata_query($query,$custom,$customshow) : make a metadata query against the
16874: network of library servers; returns file handle of where SQL and regex results
16875: will be stored for query
1.191 harris41 16876:
16877: =item *
16878:
1.1282 raeburn 16879: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
16880: return symbolic list entry (all arguments optional).
16881:
16882: Args: filename is the filename (including path) for the file for which a symb
16883: is required; donotrecurse, if true will prevent calls to allowed() being made
16884: to check access status if more than one resource was found in the bighash
16885: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
16886: a randompick); ignorecachednull, if true will prevent a symb of '' being
16887: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16888: cause possible symbs to be checked to determine if they are subject to content
16889: blocking, if so they will not be included as possible symbs; possibles is a
16890: ref to a hash, which, as a side effect, will be populated with all possible
16891: symbs (content blocking not tested).
16892:
1.243 albertel 16893: returns the data handle
1.191 harris41 16894:
16895: =item *
16896:
1.1190 raeburn 16897: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16898: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 16899: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 16900: on failure, user must be in a course, as it assumes the existence of
16901: the course initial hash, and uses $env('request.course.id'}. The third
16902: arg is an optional reference to a scalar. If this arg is passed in the
16903: call to symbverify, it will be set to 1 if the symb has been set to be
16904: encrypted; otherwise it will be null.
1.191 harris41 16905:
16906: =item *
16907:
1.243 albertel 16908: symbclean($symb) : removes versions numbers from a symb, returns the
16909: cleaned symb
1.191 harris41 16910:
16911: =item *
16912:
1.243 albertel 16913: is_on_map($uri) : checks if the $uri is somewhere on the current
16914: course map, user must be in a course for it to work.
1.191 harris41 16915:
16916: =item *
16917:
1.243 albertel 16918: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 16919:
16920: =item *
16921:
1.243 albertel 16922: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16923: a random seed, all arguments are optional, if they aren't sent it uses the
16924: environment to derive them. Note: if symb isn't sent and it can't get one
16925: from &symbread it will use the current time as its return value
1.191 harris41 16926:
16927: =item *
16928:
1.243 albertel 16929: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16930: unfakeable, receipt
1.191 harris41 16931:
16932: =item *
16933:
1.620 albertel 16934: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 16935:
16936: =item *
16937:
1.243 albertel 16938: countacc($url) : count the number of accesses to a given URL
1.191 harris41 16939:
16940: =item *
16941:
1.243 albertel 16942: 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 16943:
16944: =item *
16945:
1.243 albertel 16946: 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 16947:
16948: =item *
16949:
1.243 albertel 16950: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 16951:
16952: =item *
16953:
1.243 albertel 16954: devalidate($symb) : devalidate temporary spreadsheet calculations,
16955: forcing spreadsheet to reevaluate the resource scores next time.
16956:
1.1195 raeburn 16957: =item *
16958:
1.1196 raeburn 16959: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16960: when viewing in course context.
1.1195 raeburn 16961:
1.1196 raeburn 16962: input: six args -- filename (decluttered), course number, course domain,
16963: url, symb (if registered) and group (if this is a
16964: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 16965:
1.1196 raeburn 16966: output: array of five scalars --
1.1195 raeburn 16967: $cfile -- url for file editing if editable on current server
16968: $home -- homeserver of resource (i.e., for author if published,
16969: or course if uploaded.).
16970: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 16971: $forceedit -- 1 if icon/link should be to go to edit mode
16972: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 16973:
16974: =item *
16975:
16976: is_course_upload($file,$cnum,$cdom)
16977:
16978: Used in course context to determine if current file was uploaded to
16979: the course (i.e., would be found in /userfiles/docs on the course's
16980: homeserver.
16981:
16982: input: 3 args -- filename (decluttered), course number and course domain.
16983: output: boolean -- 1 if file was uploaded.
16984:
1.243 albertel 16985: =back
16986:
16987: =head2 Storing/Retreiving Data
16988:
16989: =over 4
1.191 harris41 16990:
16991: =item *
16992:
1.1269 raeburn 16993: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16994: permanently for this url; hashref needs to be given and should be a \%hashname;
16995: the remaining args aren't required and if they aren't passed or are '' they will
16996: be derived from the env (with the exception of $laststore, which is an
16997: optional arg used when a user's submission is stored in grading).
16998: $laststore is $version=$timestamp, where $version is the most recent version
16999: number retrieved for the corresponding $symb in the $namespace db file, and
17000: $timestamp is the timestamp for that transaction (UNIX time).
17001: $laststore is currently only passed when cstore() is called by
17002: structuretags::finalize_storage().
1.191 harris41 17003:
17004: =item *
17005:
1.1269 raeburn 17006: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
17007: but uses critical subroutine
1.191 harris41 17008:
17009: =item *
17010:
1.243 albertel 17011: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
17012: all args are optional
1.191 harris41 17013:
17014: =item *
17015:
1.717 albertel 17016: dumpstore($namespace,$udom,$uname,$regexp,$range) :
17017: dumps the complete (or key matching regexp) namespace into a hash
17018: ($udom, $uname, $regexp, $range are optional) for a namespace that is
17019: normally &store()ed into
17020:
17021: $range should be either an integer '100' (give me the first 100
17022: matching records)
17023: or be two integers sperated by a - with no spaces
17024: '30-50' (give me the 30th through the 50th matching
17025: records)
17026:
17027:
17028: =item *
17029:
1.1269 raeburn 17030: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 17031: replaces a &store() version of data with a replacement set of data
17032: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 17033: reference. If $tolog is true, the transaction is logged in the courselog
17034: with an action=PUTSTORE.
1.717 albertel 17035:
17036: =item *
17037:
1.243 albertel 17038: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
17039: works very similar to store/cstore, but all data is stored in a
17040: temporary location and can be reset using tmpreset, $storehash should
17041: be a hash reference, returns nothing on success
1.191 harris41 17042:
17043: =item *
17044:
1.243 albertel 17045: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
17046: similar to restore, but all data is stored in a temporary location and
17047: can be reset using tmpreset. Returns a hash of values on success,
17048: error string otherwise.
1.191 harris41 17049:
17050: =item *
17051:
1.243 albertel 17052: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
17053: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 17054:
17055: =item *
17056:
1.243 albertel 17057: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17058: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 17059:
17060: =item *
17061:
1.243 albertel 17062: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
17063: namesp ($udom and $uname are optional)
1.191 harris41 17064:
17065: =item *
17066:
1.702 albertel 17067: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 17068: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 17069: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 17070:
1.702 albertel 17071: $range should be either an integer '100' (give me the first 100
17072: matching records)
17073: or be two integers sperated by a - with no spaces
17074: '30-50' (give me the 30th through the 50th matching
17075: records)
1.449 matthew 17076: =item *
17077:
17078: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17079: $store can be a scalar, an array reference, or if the amount to be
17080: incremented is > 1, a hash reference.
17081:
17082: ($udom and $uname are optional)
1.191 harris41 17083:
17084: =item *
17085:
1.243 albertel 17086: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17087: ($udom and $uname are optional)
1.191 harris41 17088:
17089: =item *
17090:
1.243 albertel 17091: cput($namespace,$storehash,$udom,$uname) : critical put
17092: ($udom and $uname are optional)
1.191 harris41 17093:
17094: =item *
17095:
1.748 albertel 17096: newput($namespace,$storehash,$udom,$uname) :
17097:
17098: Attempts to store the items in the $storehash, but only if they don't
17099: currently exist, if this succeeds you can be certain that you have
17100: successfully created a new key value pair in the $namespace db.
17101:
17102:
17103: Args:
17104: $namespace: name of database to store values to
17105: $storehash: hashref to store to the db
17106: $udom: (optional) domain of user containing the db
17107: $uname: (optional) name of user caontaining the db
17108:
17109: Returns:
17110: 'ok' -> succeeded in storing all keys of $storehash
17111: 'key_exists: <key>' -> failed to anything out of $storehash, as at
17112: least <key> already existed in the db (other
17113: requested keys may also already exist)
1.967 bisitz 17114: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 17115: 'con_lost' -> unable to contact request server
17116: 'refused' -> action was not allowed by remote machine
17117:
17118:
17119: =item *
17120:
1.243 albertel 17121: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17122: reference filled in from namesp (encrypts the return communication)
17123: ($udom and $uname are optional)
1.191 harris41 17124:
17125: =item *
17126:
1.243 albertel 17127: log($udom,$name,$home,$message) : write to permanent log for user; use
17128: critical subroutine
17129:
1.806 raeburn 17130: =item *
17131:
1.860 raeburn 17132: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17133: array reference filled in from namespace found in domain level on either
17134: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 17135:
17136: =item *
17137:
1.860 raeburn 17138: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
17139: domain level either on specified domain server ($uhome) or primary domain
17140: server ($udom and $uhome are optional)
1.806 raeburn 17141:
1.943 raeburn 17142: =item *
17143:
1.1240 raeburn 17144: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
17145: for: authentication, language, quotas, timezone, date locale, and portal URL in
17146: the target domain.
17147:
17148: May also include additional key => value pairs for the following groups:
17149:
17150: =over
17151:
17152: =item
17153: disk quotas (MB allocated by default to portfolios and authoring spaces).
17154:
17155: =over
17156:
17157: =item defaultquota, authorquota
17158:
17159: =back
17160:
17161: =item
17162: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17163: portfolio for users).
17164:
17165: =over
17166:
17167: =item
17168: aboutme, blog, webdav, portfolio
17169:
17170: =back
17171:
17172: =item
17173: requestcourses: ability to request courses, and how requests are processed.
17174:
17175: =over
17176:
17177: =item
1.1305 raeburn 17178: official, unofficial, community, textbook, placement
1.1240 raeburn 17179:
17180: =back
17181:
17182: =item
17183: inststatus: types of institutional affiliation, and order in which they are displayed.
17184:
17185: =over
17186:
17187: =item
1.1256 raeburn 17188: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 17189:
17190: =back
17191:
17192: =item
17193: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17194: for course's uploaded content.
17195:
17196: =over
17197:
17198: =item
1.1246 raeburn 17199: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 17200: communityquota, textbookquota, placementquota
1.1240 raeburn 17201:
17202: =back
17203:
17204: =item
17205: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17206: on your servers.
17207:
17208: =over
17209:
17210: =item
17211: remotesessions, hostedsessions
17212:
17213: =back
17214:
17215: =back
17216:
17217: In cases where a domain coordinator has never used the "Set Domain Configuration"
17218: utility to create a configuration.db file on a domain's primary library server
17219: only the following domain defaults: auth_def, auth_arg_def, lang_def
17220: -- corresponding values are authentication type (internal, krb4, krb5,
17221: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
17222: will be available. Values are retrieved from cache (if current), unless the
17223: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17224: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17225:
17226: Typical usage:
1.943 raeburn 17227:
1.1240 raeburn 17228: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 17229:
1.243 albertel 17230: =back
17231:
17232: =head2 Network Status Functions
17233:
17234: =over 4
1.191 harris41 17235:
17236: =item *
17237:
1.1137 raeburn 17238: dirlist() : return directory list based on URI (first arg).
17239:
17240: Inputs: 1 required, 5 optional.
17241:
17242: =over
17243:
17244: =item
17245: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17246:
17247: =item
17248: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
17249:
17250: =item
17251: $username - username of user/course to be listed. Extracted from $uri if absent.
17252:
17253: =item
17254: $getpropath - boolean: 1 if prepend path using &propath().
17255:
17256: =item
17257: $getuserdir - boolean: 1 if prepend path for "userfiles".
17258:
17259: =item
17260: $alternateRoot - path to prepend in place of path from $uri.
17261:
17262: =back
17263:
17264: Returns: Array of up to two items.
17265:
17266: =over
17267:
17268: a reference to an array of files/subdirectories
17269:
17270: =over
17271:
17272: Each element in the array of files/subdirectories is a & separated list of
17273: item name and the result of running stat on the item. If dirlist was requested
17274: for a file instead of a directory, the item name will be ''. For a directory
17275: listing, if the item is a metadata file, the element will end &N&M
17276: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17277: default copyright set (1).
17278:
17279: =back
17280:
17281: a scalar containing error condition (if encountered).
17282:
17283: =over
17284:
17285: =item
17286: no_host (no homeserver identified for $username:$domain).
17287:
17288: =item
17289: no_such_host (server contacted for listing not identified as valid host).
17290:
17291: =item
17292: con_lost (connection to remote server failed).
17293:
17294: =item
17295: refused (invalid $username:$domain received on lond side).
17296:
17297: =item
17298: no_such_dir (directory at specified path on lond side does not exist).
17299:
17300: =item
17301: empty (directory at specified path on lond side is empty).
17302:
17303: =over
17304:
17305: This is currently not encountered because the &ls3, &ls2,
17306: &ls (_handler) routines on the lond side do not filter out
17307: . and .. from a directory listing.
17308:
17309: =back
17310:
17311: =back
17312:
17313: =back
1.191 harris41 17314:
17315: =item *
17316:
1.243 albertel 17317: spareserver() : find server with least workload from spare.tab
17318:
1.986 foxr 17319:
17320: =item *
17321:
17322: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17323: if there is no corresponding loncapa host.
17324:
1.243 albertel 17325: =back
17326:
1.986 foxr 17327:
1.243 albertel 17328: =head2 Apache Request
17329:
17330: =over 4
1.191 harris41 17331:
17332: =item *
17333:
1.243 albertel 17334: ssi($url,%hash) : server side include, does a complete request cycle on url to
17335: localhost, posts hash
17336:
17337: =back
17338:
17339: =head2 Data to String to Data
17340:
17341: =over 4
1.191 harris41 17342:
17343: =item *
17344:
1.243 albertel 17345: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17346: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 17347:
17348: =item *
17349:
1.243 albertel 17350: hashref2str($hashref) : convert a hashref into a string complete with
17351: escaping and '=' and '&' separators, supports elements that are
17352: arrayrefs and hashrefs
1.191 harris41 17353:
17354: =item *
17355:
1.243 albertel 17356: arrayref2str($arrayref) : convert an arrayref into a string complete
17357: with escaping and '&' separators, supports elements that are arrayrefs
17358: and hashrefs
1.191 harris41 17359:
17360: =item *
17361:
1.243 albertel 17362: str2hash($string) : convert string to hash using unescaping and
17363: splitting on '=' and '&', supports elements that are arrayrefs and
17364: hashrefs
1.191 harris41 17365:
17366: =item *
17367:
1.243 albertel 17368: str2array($string) : convert string to hash using unescaping and
17369: splitting on '&', supports elements that are arrayrefs and hashrefs
17370:
17371: =back
17372:
17373: =head2 Logging Routines
17374:
17375:
17376: These routines allow one to make log messages in the lonnet.log and
17377: lonnet.perm logfiles.
1.191 harris41 17378:
1.1119 foxr 17379: =over 4
17380:
1.191 harris41 17381: =item *
17382:
1.243 albertel 17383: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 17384:
17385: =item *
17386:
1.243 albertel 17387: logthis() : append message to the normal lonnet.log file, it gets
17388: preiodically rolled over and deleted.
1.191 harris41 17389:
17390: =item *
17391:
1.243 albertel 17392: logperm() : append a permanent message to lonnet.perm.log, this log
17393: file never gets deleted by any automated portion of the system, only
17394: messages of critical importance should go in here.
17395:
1.1119 foxr 17396:
1.243 albertel 17397: =back
17398:
17399: =head2 General File Helper Routines
17400:
17401: =over 4
1.191 harris41 17402:
17403: =item *
17404:
1.481 raeburn 17405: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17406: (a) files in /uploaded
17407: (i) If a local copy of the file exists -
17408: compares modification date of local copy with last-modified date for
17409: definitive version stored on home server for course. If local copy is
17410: stale, requests a new version from the home server and stores it.
17411: If the original has been removed from the home server, then local copy
17412: is unlinked.
17413: (ii) If local copy does not exist -
17414: requests the file from the home server and stores it.
17415:
17416: If $caller is 'uploadrep':
17417: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17418: for request for files originally uploaded via DOCS.
17419: - returns 'ok' if fresh local copy now available, -1 otherwise.
17420:
17421: Otherwise:
17422: This indicates a call from the content generation phase of the request.
17423: - returns the entire contents of the file or -1.
17424:
17425: (b) files in /res
17426: - returns the entire contents of a file or -1;
17427: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 17428:
1.712 albertel 17429:
17430: =item *
17431:
17432: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17433: reference
17434:
17435: returns either a stat() list of data about the file or an empty list
17436: if the file doesn't exist or couldn't find out about it (connection
17437: problems or user unknown)
17438:
1.191 harris41 17439: =item *
17440:
1.243 albertel 17441: filelocation($dir,$file) : returns file system location of a file
17442: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17443: directory that relative $file lookups are to looked in ($dir of /a/dir
17444: and a file of ../bob will become /a/bob)
1.191 harris41 17445:
17446: =item *
17447:
17448: hreflocation($dir,$file) : returns file system location or a URL; same as
17449: filelocation except for hrefs
17450:
17451: =item *
17452:
1.1261 raeburn 17453: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17454: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 17455:
1.243 albertel 17456: =back
17457:
1.608 albertel 17458: =head2 Usererfile file routines (/uploaded*)
17459:
17460: =over 4
17461:
17462: =item *
17463:
17464: userfileupload(): main rotine for putting a file in a user or course's
17465: filespace, arguments are,
17466:
1.620 albertel 17467: formname - required - this is the name of the element in $env where the
1.608 albertel 17468: filename, and the contents of the file to create/modifed exist
1.620 albertel 17469: the filename is in $env{'form.'.$formname.'.filename'} and the
17470: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 17471: context - if coursedoc, store the file in the course of the active role
17472: of the current user;
17473: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17474: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 17475: subdir - required - subdirectory to put the file in under ../userfiles/
17476: if undefined, it will be placed in "unknown"
17477:
17478: (This routine calls clean_filename() to remove any dangerous
17479: characters from the filename, and then calls finuserfileupload() to
17480: complete the transaction)
17481:
17482: returns either the url of the uploaded file (/uploaded/....) if successful
17483: and /adm/notfound.html if unsuccessful
17484:
17485: =item *
17486:
17487: clean_filename(): routine for cleaing a filename up for storage in
17488: userfile space, argument is:
17489:
17490: filename - proposed filename
17491:
17492: returns: the new clean filename
17493:
17494: =item *
17495:
1.1090 raeburn 17496: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 17497: userspace, probably shouldn't be called directly
17498:
17499: docuname: username or courseid of destination for the file
17500: docudom: domain of user/course of destination for the file
17501: formname: same as for userfileupload()
1.1090 raeburn 17502: fname: filename (including subdirectories) for the file
17503: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401 raeburn 17504: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 17505: allfiles: reference to hash used to store objects found by parser
17506: codebase: reference to hash used for codebases of java objects found by parser
17507: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17508: thumbheight: height (pixels) of thumbnail to be created for uploaded image
17509: resizewidth: width to be used to resize image using resizeImage from ImageMagick
17510: resizeheight: height to be used to resize image using resizeImage from ImageMagick
17511: context: if 'overwrite', will move the uploaded file from its temporary location to
17512: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 17513: mimetype: reference to scalar to accommodate mime type determined
17514: from File::MMagic if $parser = parse.
1.608 albertel 17515:
17516: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 17517: and /adm/notfound.html if unsuccessful (or an error message if context
17518: was 'overwrite').
17519:
1.608 albertel 17520:
17521: =item *
17522:
17523: renameuserfile(): renames an existing userfile to a new name
17524:
17525: Args:
17526: docuname: username or courseid of destination for the file
17527: docudom: domain of user/course of destination for the file
17528: old: current file name (including any subdirs under userfiles)
17529: new: desired file name (including any subdirs under userfiles)
17530:
17531: =item *
17532:
17533: mkdiruserfile(): creates a directory is a userfiles dir
17534:
17535: Args:
17536: docuname: username or courseid of destination for the file
17537: docudom: domain of user/course of destination for the file
17538: dir: dir to create (including any subdirs under userfiles)
17539:
17540: =item *
17541:
17542: removeuserfile(): removes a file that exists in userfiles
17543:
17544: Args:
17545: docuname: username or courseid of destination for the file
17546: docudom: domain of user/course of destination for the file
17547: fname: filname to delete (including any subdirs under userfiles)
17548:
17549: =item *
17550:
17551: removeuploadedurl(): convience function for removeuserfile()
17552:
17553: Args:
17554: url: a full /uploaded/... url to delete
17555:
1.747 albertel 17556: =item *
17557:
17558: get_portfile_permissions():
17559: Args:
17560: domain: domain of user or course contain the portfolio files
17561: user: name of user or num of course contain the portfolio files
17562: Returns:
17563: hashref of a dump of the proper file_permissions.db
17564:
17565:
17566: =item *
17567:
17568: get_access_controls():
17569:
17570: Args:
17571: current_permissions: the hash ref returned from get_portfile_permissions()
17572: group: (optional) the group you want the files associated with
17573: file: (optional) the file you want access info on
17574:
17575: Returns:
1.749 raeburn 17576: a hash (keys are file names) of hashes containing
17577: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17578: values are XML containing access control settings (see below)
1.747 albertel 17579:
17580: Internal notes:
17581:
1.749 raeburn 17582: access controls are stored in file_permissions.db as key=value pairs.
17583: key -> path to file/file_name\0uniqueID:scope_end_start
17584: where scope -> public,guest,course,group,domains or users.
17585: end -> UNIX time for end of access (0 -> no end date)
17586: start -> UNIX time for start of access
17587:
17588: value -> XML description of access control
17589: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17590: <start></start>
17591: <end></end>
17592:
17593: <password></password> for scope type = guest
17594:
17595: <domain></domain> for scope type = course or group
17596: <number></number>
17597: <roles id="">
17598: <role></role>
17599: <access></access>
17600: <section></section>
17601: <group></group>
17602: </roles>
17603:
17604: <dom></dom> for scope type = domains
17605:
17606: <users> for scope type = users
17607: <user>
17608: <uname></uname>
17609: <udom></udom>
17610: </user>
17611: </users>
17612: </scope>
17613:
17614: Access data is also aggregated for each file in an additional key=value pair:
17615: key -> path to file/file_name\0accesscontrol
17616: value -> reference to hash
17617: hash contains key = value pairs
17618: where key = uniqueID:scope_end_start
17619: value = UNIX time record was last updated
17620:
17621: Used to improve speed of look-ups of access controls for each file.
17622:
17623: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17624:
1.1198 raeburn 17625: =item *
17626:
1.749 raeburn 17627: modify_access_controls():
17628:
17629: Modifies access controls for a portfolio file
17630: Args
17631: 1. file name
17632: 2. reference to hash of required changes,
17633: 3. domain
17634: 4. username
17635: where domain,username are the domain of the portfolio owner
17636: (either a user or a course)
17637:
17638: Returns:
17639: 1. result of additions or updates ('ok' or 'error', with error message).
17640: 2. result of deletions ('ok' or 'error', with error message).
17641: 3. reference to hash of any new or updated access controls.
17642: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17643: key = integer (inbound ID)
1.1198 raeburn 17644: value = uniqueID
17645:
17646: =item *
17647:
17648: get_timebased_id():
17649:
17650: Attempts to get a unique timestamp-based suffix for use with items added to a
17651: course via the Course Editor (e.g., folders, composite pages,
17652: group bulletin boards).
17653:
17654: Args: (first three required; six others optional)
17655:
17656: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17657: docssequence, or name of group
17658:
17659: 2. keyid (alphanumeric): name of temporary locking key in hash,
17660: e.g., num, boardids
17661:
17662: 3. namespace: name of gdbm file used to store suffixes already assigned;
17663: file will be named nohist_namespace.db
17664:
17665: 4. cdom: domain of course; default is current course domain from %env
17666:
17667: 5. cnum: course number; default is current course number from %env
17668:
17669: 6. idtype: set to concat if an additional digit is to be appended to the
17670: unix timestamp to form the suffix, if the plain timestamp is already
17671: in use. Default is to not do this, but simply increment the unix
17672: timestamp by 1 until a unique key is obtained.
17673:
17674: 7. who: holder of locking key; defaults to user:domain for user.
17675:
17676: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
17677: retrying); default is 3.
17678:
17679: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
17680:
17681: Returns:
17682:
17683: 1. suffix obtained (numeric)
17684:
17685: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17686:
17687: 3. error: contains (localized) error message if an error occurred.
17688:
1.747 albertel 17689:
1.608 albertel 17690: =back
17691:
1.243 albertel 17692: =head2 HTTP Helper Routines
17693:
17694: =over 4
17695:
1.191 harris41 17696: =item *
17697:
17698: escape() : unpack non-word characters into CGI-compatible hex codes
17699:
17700: =item *
17701:
17702: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17703:
1.243 albertel 17704: =back
17705:
17706: =head1 PRIVATE SUBROUTINES
17707:
17708: =head2 Underlying communication routines (Shouldn't call)
17709:
17710: =over 4
17711:
17712: =item *
17713:
17714: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17715:
17716: =item *
17717:
17718: reply() : uses subreply to send a message to remote machine, logs all failures
17719:
17720: =item *
17721:
17722: critical() : passes a critical message to another server; if cannot
17723: get through then place message in connection buffer directory and
17724: returns con_delayed, if incapable of saving message, returns
17725: con_failed
17726:
17727: =item *
17728:
17729: reconlonc() : tries to reconnect lonc client processes.
17730:
17731: =back
17732:
17733: =head2 Resource Access Logging
17734:
17735: =over 4
17736:
17737: =item *
17738:
17739: flushcourselogs() : flush (save) buffer logs and access logs
17740:
17741: =item *
17742:
17743: courselog($what) : save message for course in hash
17744:
17745: =item *
17746:
17747: courseacclog($what) : save message for course using &courselog(). Perform
17748: special processing for specific resource types (problems, exams, quizzes, etc).
17749:
1.191 harris41 17750: =item *
17751:
17752: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17753: as a PerlChildExitHandler
1.243 albertel 17754:
17755: =back
17756:
17757: =head2 Other
17758:
17759: =over 4
17760:
17761: =item *
17762:
17763: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 17764:
17765: =back
17766:
17767: =cut
1.877 foxr 17768:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>