Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1499
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1499 ! raeburn 4: # $Id: lonnet.pm,v 1.1498 2022/10/22 20:45:35 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.1482 raeburn 2701: 'trust','helpsettings','wafproxy','ltisec'],$domain);
1.1305 raeburn 2702: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2703: if (ref($domconfig{'defaults'}) eq 'HASH') {
2704: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2705: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2706: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2707: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2708: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2709: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1492 raeburn 2710: $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
2711: $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
1.1340 raeburn 2712: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2713: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2714: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1484 raeburn 2715: $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943 raeburn 2716: } else {
2717: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2718: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2719: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2720: }
1.976 raeburn 2721: if (ref($domconfig{'quotas'}) eq 'HASH') {
2722: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2723: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2724: } else {
2725: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2726: }
1.1177 raeburn 2727: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2728: foreach my $item (@usertools) {
2729: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2730: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2731: }
2732: }
1.1229 raeburn 2733: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2734: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2735: }
1.976 raeburn 2736: }
1.985 raeburn 2737: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2738: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2739: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2740: }
2741: }
1.1183 raeburn 2742: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2743: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2744: }
1.989 raeburn 2745: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2746: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2747: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2748: }
2749: }
1.1047 raeburn 2750: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2751: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2752: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1476 raeburn 2753: $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1277 raeburn 2754: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2755: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2756: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2757: }
1.1254 raeburn 2758: foreach my $type (@coursetypes) {
2759: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2760: unless ($type eq 'community') {
2761: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2762: }
2763: }
2764: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2765: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2766: }
1.1277 raeburn 2767: if ($domdefaults{'postsubmit'} eq 'on') {
2768: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2769: $domdefaults{$type.'postsubtimeout'} =
2770: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2771: }
2772: }
1.1230 raeburn 2773: }
1.1286 raeburn 2774: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2775: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2776: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2777: if (@clonecodes) {
2778: $domdefaults{'canclone'} = join('+',@clonecodes);
2779: }
2780: }
2781: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2782: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2783: }
1.1356 raeburn 2784: if ($domconfig{'coursedefaults'}{'texengine'}) {
2785: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
1.1480 raeburn 2786: }
2787: if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
2788: $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
2789: }
1.1047 raeburn 2790: }
1.1073 raeburn 2791: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2792: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2793: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2794: }
2795: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2796: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2797: }
1.1279 raeburn 2798: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2799: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2800: }
1.1440 raeburn 2801: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439 raeburn 2802: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2803: }
1.1073 raeburn 2804: }
1.1254 raeburn 2805: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2806: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2807: my @settings = ('types','registered','enroll_dates','access_dates','section',
2808: 'approval','limit');
2809: foreach my $type (@coursetypes) {
2810: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2811: my @mgrdc = ();
2812: foreach my $item (@settings) {
2813: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2814: push(@mgrdc,$item);
2815: }
2816: }
2817: if (@mgrdc) {
2818: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2819: }
2820: }
2821: }
2822: }
2823: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2824: foreach my $type (@coursetypes) {
2825: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2826: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2827: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2828: }
2829: }
2830: }
2831: }
2832: }
1.1258 raeburn 2833: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2834: $domdefaults{'catauth'} = 'std';
2835: $domdefaults{'catunauth'} = 'std';
1.1413 raeburn 2836: if ($domconfig{'coursecategories'}{'auth'}) {
1.1258 raeburn 2837: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2838: }
2839: if ($domconfig{'coursecategories'}{'unauth'}) {
2840: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2841: }
2842: }
1.1315 raeburn 2843: if (ref($domconfig{'ssl'}) eq 'HASH') {
2844: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2845: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2846: }
1.1338 raeburn 2847: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2848: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2849: }
2850: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2851: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315 raeburn 2852: }
2853: }
1.1320 raeburn 2854: if (ref($domconfig{'trust'}) eq 'HASH') {
2855: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2856: foreach my $prefix (@prefixes) {
2857: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2858: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2859: }
2860: }
2861: }
1.1314 raeburn 2862: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2863: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1477 raeburn 2864: $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1314 raeburn 2865: }
1.1332 raeburn 2866: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2867: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2868: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2869: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2870: }
2871: }
1.1434 raeburn 2872: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1449 raeburn 2873: foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
1.1434 raeburn 2874: if ($domconfig{'wafproxy'}{$item}) {
2875: $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
2876: }
2877: }
1.1482 raeburn 2878: }
2879: if (ref($domconfig{'ltisec'}) eq 'HASH') {
2880: if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
2881: $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
2882: $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
2883: $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
2884: }
2885: if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
2886: if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
2887: $domdefaults{'privhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
2888: }
2889: }
2890: }
1.1219 raeburn 2891: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2892: return %domdefaults;
2893: }
2894:
1.1412 raeburn 2895: sub get_dom_cats {
2896: my ($dom) = @_;
2897: return unless (&domain($dom));
2898: my ($cats,$cached)=&is_cached_new('cats',$dom);
2899: unless (defined($cached)) {
2900: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2901: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2902: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2903: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2904: } else {
2905: $cats = {};
2906: }
2907: } else {
2908: $cats = {};
2909: }
1.1494 raeburn 2910: &do_cache_new('cats',$dom,$cats,3600);
1.1412 raeburn 2911: }
1.1413 raeburn 2912: return $cats;
2913: }
2914:
2915: sub get_dom_instcats {
2916: my ($dom) = @_;
2917: return unless (&domain($dom));
2918: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2919: unless (defined($cached)) {
2920: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2921: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2922: if ($totcodes > 0) {
2923: my $caller = 'global';
2924: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2925: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2926: $instcats = {
2927: codes => \%codes,
2928: codetitles => \@codetitles,
2929: cat_titles => \%cat_titles,
2930: cat_order => \%cat_order,
2931: };
2932: &do_cache_new('instcats',$dom,$instcats,3600);
2933: }
2934: }
2935: }
2936: return $instcats;
2937: }
2938:
2939: sub retrieve_instcodes {
2940: my ($coursecodes,$dom) = @_;
2941: my $totcodes;
2942: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2943: foreach my $course (keys(%courses)) {
2944: if (ref($courses{$course}) eq 'HASH') {
2945: if ($courses{$course}{'inst_code'} ne '') {
2946: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2947: $totcodes ++;
2948: }
2949: }
2950: }
2951: return $totcodes;
1.1412 raeburn 2952: }
2953:
1.1311 raeburn 2954: sub course_portal_url {
1.1451 raeburn 2955: my ($cnum,$cdom,$r) = @_;
1.1311 raeburn 2956: my $chome = &homeserver($cnum,$cdom);
2957: my $hostname = &hostname($chome);
2958: my $protocol = $protocol{$chome};
2959: $protocol = 'http' if ($protocol ne 'https');
2960: my %domdefaults = &get_domain_defaults($cdom);
2961: my $firsturl;
2962: if ($domdefaults{'portal_def'}) {
2963: $firsturl = $domdefaults{'portal_def'};
2964: } else {
1.1494 raeburn 2965: my $alias = &use_proxy_alias($r,$chome);
1.1451 raeburn 2966: $hostname = $alias if ($alias ne '');
1.1311 raeburn 2967: $firsturl = $protocol.'://'.$hostname;
2968: }
2969: return $firsturl;
2970: }
2971:
1.1492 raeburn 2972: sub url_prefix {
2973: my ($r,$dom,$home,$context) = @_;
2974: my $prefix;
2975: my %domdefs = &get_domain_defaults($dom);
2976: if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
2977: if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
2978: $prefix = $1;
2979: }
2980: }
2981: if ($prefix eq '') {
2982: my $hostname = &hostname($home);
2983: my $protocol = $protocol{$home};
2984: $protocol = 'http' if ($protocol{$home} ne 'https');
2985: my $alias = &use_proxy_alias($r,$home);
2986: $hostname = $alias if ($alias ne '');
2987: $prefix = $protocol.'://'.$hostname;
2988: }
2989: return $prefix;
2990: }
2991:
1.1407 raeburn 2992: # --------------------------------------------- Get domain config for passwords
2993:
2994: sub get_passwdconf {
2995: my ($dom) = @_;
2996: my (%passwdconf,$gotconf,$lookup);
2997: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2998: if (defined($cached)) {
2999: if (ref($result) eq 'HASH') {
3000: %passwdconf = %{$result};
3001: $gotconf = 1;
3002: }
3003: }
3004: unless ($gotconf) {
3005: my %domconfig = &get_dom('configuration',['passwords'],$dom);
3006: if (ref($domconfig{'passwords'}) eq 'HASH') {
3007: %passwdconf = %{$domconfig{'passwords'}};
3008: }
3009: my $cachetime = 24*60*60;
3010: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
3011: }
3012: return %passwdconf;
3013: }
3014:
1.344 www 3015: # --------------------------------------------------- Assign a key to a student
3016:
3017: sub assign_access_key {
1.364 www 3018: #
3019: # a valid key looks like uname:udom#comments
3020: # comments are being appended
3021: #
1.498 www 3022: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
3023: $kdom=
1.620 albertel 3024: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 3025: $knum=
1.620 albertel 3026: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 3027: $cdom=
1.620 albertel 3028: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3029: $cnum=
1.620 albertel 3030: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3031: $udom=$env{'user.name'} unless (defined($udom));
3032: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 3033: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 3034: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 3035: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 3036: # assigned to this person
3037: # - this should not happen,
1.345 www 3038: # unless something went wrong
3039: # the first time around
3040: # ready to assign
1.364 www 3041: $logentry=$1.'; '.$logentry;
1.496 www 3042: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 3043: $kdom,$knum) eq 'ok') {
1.345 www 3044: # key now belongs to user
1.346 www 3045: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 3046: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 3047: &appenv({'environment.'.$envkey => $ckey});
1.345 www 3048: return 'ok';
3049: } else {
3050: return
3051: 'error: Count not permanently assign key, will need to be re-entered later.';
3052: }
3053: } else {
3054: return 'error: Could not assign key, try again later.';
3055: }
1.364 www 3056: } elsif (!$existing{$ckey}) {
1.345 www 3057: # the key does not exist
3058: return 'error: The key does not exist';
3059: } else {
3060: # the key is somebody else's
3061: return 'error: The key is already in use';
3062: }
1.344 www 3063: }
3064:
1.364 www 3065: # ------------------------------------------ put an additional comment on a key
3066:
3067: sub comment_access_key {
3068: #
3069: # a valid key looks like uname:udom#comments
3070: # comments are being appended
3071: #
3072: my ($ckey,$cdom,$cnum,$logentry)=@_;
3073: $cdom=
1.620 albertel 3074: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 3075: $cnum=
1.620 albertel 3076: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 3077: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
3078: if ($existing{$ckey}) {
3079: $existing{$ckey}.='; '.$logentry;
3080: # ready to assign
1.367 www 3081: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 3082: $cdom,$cnum) eq 'ok') {
3083: return 'ok';
3084: } else {
3085: return 'error: Count not store comment.';
3086: }
3087: } else {
3088: # the key does not exist
3089: return 'error: The key does not exist';
3090: }
3091: }
3092:
1.344 www 3093: # ------------------------------------------------------ Generate a set of keys
3094:
3095: sub generate_access_keys {
1.364 www 3096: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 3097: $cdom=
1.620 albertel 3098: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3099: $cnum=
1.620 albertel 3100: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 3101: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 3102: unless (($cdom) && ($cnum)) { return 0; }
3103: if ($number>10000) { return 0; }
3104: sleep(2); # make sure don't get same seed twice
3105: srand(time()^($$+($$<<15))); # from "Programming Perl"
3106: my $total=0;
3107: for (my $i=1;$i<=$number;$i++) {
3108: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
3109: sprintf("%lx",int(100000*rand)).'-'.
3110: sprintf("%lx",int(100000*rand));
3111: $newkey=~s/1/g/g; # folks mix up 1 and l
3112: $newkey=~s/0/h/g; # and also 0 and O
3113: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
3114: if ($existing{$newkey}) {
3115: $i--;
3116: } else {
1.364 www 3117: if (&put('accesskeys',
3118: { $newkey => '# generated '.localtime().
1.620 albertel 3119: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 3120: '; '.$logentry },
3121: $cdom,$cnum) eq 'ok') {
1.344 www 3122: $total++;
3123: }
3124: }
3125: }
1.620 albertel 3126: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 3127: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
3128: return $total;
3129: }
3130:
3131: # ------------------------------------------------------- Validate an accesskey
3132:
3133: sub validate_access_key {
3134: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
3135: $cdom=
1.620 albertel 3136: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3137: $cnum=
1.620 albertel 3138: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3139: $udom=$env{'user.domain'} unless (defined($udom));
3140: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 3141: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 3142: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 3143: }
3144:
3145: # ------------------------------------- Find the section of student in a course
1.652 albertel 3146: sub devalidate_getsection_cache {
3147: my ($udom,$unam,$courseid)=@_;
3148: my $hashid="$udom:$unam:$courseid";
3149: &devalidate_cache_new('getsection',$hashid);
3150: }
1.298 matthew 3151:
1.815 albertel 3152: sub courseid_to_courseurl {
3153: my ($courseid) = @_;
3154: #already url style courseid
3155: return $courseid if ($courseid =~ m{^/});
3156:
3157: if (exists($env{'course.'.$courseid.'.num'})) {
3158: my $cnum = $env{'course.'.$courseid.'.num'};
3159: my $cdom = $env{'course.'.$courseid.'.domain'};
3160: return "/$cdom/$cnum";
3161: }
3162:
1.1494 raeburn 3163: my %courseinfo=&coursedescription($courseid);
1.815 albertel 3164: if (exists($courseinfo{'num'})) {
3165: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
3166: }
3167:
3168: return undef;
3169: }
3170:
1.298 matthew 3171: sub getsection {
3172: my ($udom,$unam,$courseid)=@_;
1.599 albertel 3173: my $cachetime=1800;
1.551 albertel 3174:
3175: my $hashid="$udom:$unam:$courseid";
1.599 albertel 3176: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 3177: if (defined($cached)) { return $result; }
3178:
1.298 matthew 3179: my %Pending;
3180: my %Expired;
3181: #
3182: # Each role can either have not started yet (pending), be active,
3183: # or have expired.
3184: #
3185: # If there is an active role, we are done.
3186: #
3187: # If there is more than one role which has not started yet,
3188: # choose the one which will start sooner
3189: # If there is one role which has not started yet, return it.
3190: #
3191: # If there is more than one expired role, choose the one which ended last.
3192: # If there is a role which has expired, return it.
3193: #
1.815 albertel 3194: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 3195: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 3196: foreach my $key (keys(%roleshash)) {
1.479 albertel 3197: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 3198: my $section=$1;
3199: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 3200: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 3201: my $now=time;
1.548 albertel 3202: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 3203: $Expired{$end}=$section;
3204: next;
3205: }
1.548 albertel 3206: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 3207: $Pending{$start}=$section;
3208: next;
3209: }
1.599 albertel 3210: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 3211: }
3212: #
3213: # Presumedly there will be few matching roles from the above
3214: # loop and the sorting time will be negligible.
3215: if (scalar(keys(%Pending))) {
3216: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 3217: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 3218: }
3219: if (scalar(keys(%Expired))) {
3220: my @sorted = sort {$a <=> $b} keys(%Expired);
3221: my $time = pop(@sorted);
1.599 albertel 3222: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 3223: }
1.599 albertel 3224: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 3225: }
1.70 www 3226:
1.599 albertel 3227: sub save_cache {
3228: &purge_remembered();
1.722 albertel 3229: #&Apache::loncommon::validate_page();
1.620 albertel 3230: undef(%env);
1.780 albertel 3231: undef($env_loaded);
1.599 albertel 3232: }
1.452 albertel 3233:
1.599 albertel 3234: my $to_remember=-1;
3235: my %remembered;
3236: my %accessed;
3237: my $kicks=0;
3238: my $hits=0;
1.849 albertel 3239: sub make_key {
3240: my ($name,$id) = @_;
1.872 albertel 3241: if (length($id) > 65
3242: && length(&escape($id)) > 200) {
3243: $id=length($id).':'.&Digest::MD5::md5_hex($id);
3244: }
1.849 albertel 3245: return &escape($name.':'.$id);
3246: }
3247:
1.599 albertel 3248: sub devalidate_cache_new {
3249: my ($name,$id,$debug) = @_;
3250: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 3251: my $remembered_id=$name.':'.$id;
1.849 albertel 3252: $id=&make_key($name,$id);
1.599 albertel 3253: $memcache->delete($id);
1.1319 damieng 3254: delete($remembered{$remembered_id});
3255: delete($accessed{$remembered_id});
1.599 albertel 3256: }
3257:
3258: sub is_cached_new {
3259: my ($name,$id,$debug) = @_;
1.1319 damieng 3260: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
3261: if (exists($remembered{$remembered_id})) {
3262: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
3263: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3264: $hits++;
1.1319 damieng 3265: return ($remembered{$remembered_id},1);
1.599 albertel 3266: }
1.1319 damieng 3267: $id=&make_key($name,$id);
1.599 albertel 3268: my $value = $memcache->get($id);
3269: if (!(defined($value))) {
3270: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 3271: return (undef,undef);
1.416 albertel 3272: }
1.599 albertel 3273: if ($value eq '__undef__') {
3274: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3275: $value=undef;
3276: }
1.1319 damieng 3277: &make_room($remembered_id,$value,$debug);
1.599 albertel 3278: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3279: return ($value,1);
3280: }
3281:
3282: sub do_cache_new {
3283: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 3284: my $remembered_id=$name.':'.$id;
1.849 albertel 3285: $id=&make_key($name,$id);
1.599 albertel 3286: my $setvalue=$value;
3287: if (!defined($setvalue)) {
3288: $setvalue='__undef__';
3289: }
1.623 albertel 3290: if (!defined($time) ) {
3291: $time=600;
3292: }
1.599 albertel 3293: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 3294: my $result = $memcache->set($id,$setvalue,$time);
3295: if (! $result) {
1.872 albertel 3296: &logthis("caching of id -> $id failed");
1.910 albertel 3297: $memcache->disconnect_all();
1.872 albertel 3298: }
1.600 albertel 3299: # need to make a copy of $value
1.1319 damieng 3300: &make_room($remembered_id,$value,$debug);
1.599 albertel 3301: return $value;
3302: }
3303:
3304: sub make_room {
1.1319 damieng 3305: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 3306:
1.1319 damieng 3307: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 3308: : $value;
1.599 albertel 3309: if ($to_remember<0) { return; }
1.1319 damieng 3310: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3311: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3312: my $to_kick;
3313: my $max_time=0;
3314: foreach my $other (keys(%accessed)) {
3315: if (&tv_interval($accessed{$other}) > $max_time) {
3316: $to_kick=$other;
3317: $max_time=&tv_interval($accessed{$other});
3318: }
3319: }
3320: delete($remembered{$to_kick});
3321: delete($accessed{$to_kick});
3322: $kicks++;
3323: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 3324: return;
3325: }
3326:
1.599 albertel 3327: sub purge_remembered {
1.604 albertel 3328: #&logthis("Tossing ".scalar(keys(%remembered)));
3329: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 3330: undef(%remembered);
3331: undef(%accessed);
1.428 albertel 3332: }
1.70 www 3333: # ------------------------------------- Read an entry from a user's environment
3334:
3335: sub userenvironment {
3336: my ($udom,$unam,@what)=@_;
1.976 raeburn 3337: my $items;
3338: foreach my $item (@what) {
3339: $items.=&escape($item).'&';
3340: }
3341: $items=~s/\&$//;
1.70 www 3342: my %returnhash=();
1.1009 raeburn 3343: my $uhome = &homeserver($unam,$udom);
3344: unless ($uhome eq 'no_host') {
3345: my @answer=split(/\&/,
3346: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 3347: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3348: return %returnhash;
3349: }
1.1009 raeburn 3350: my $i;
3351: for ($i=0;$i<=$#what;$i++) {
3352: $returnhash{$what[$i]}=&unescape($answer[$i]);
3353: }
1.70 www 3354: }
3355: return %returnhash;
1.1 albertel 3356: }
3357:
1.617 albertel 3358: # ---------------------------------------------------------- Get a studentphoto
3359: sub studentphoto {
3360: my ($udom,$unam,$ext) = @_;
1.1494 raeburn 3361: my $home=&homeserver($unam,$udom);
1.706 raeburn 3362: if (defined($env{'request.course.id'})) {
1.708 raeburn 3363: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 3364: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3365: return(&retrievestudentphoto($udom,$unam,$ext));
3366: } else {
3367: my ($result,$perm_reqd)=
1.1494 raeburn 3368: &auto_photo_permission($unam,$udom);
1.706 raeburn 3369: if ($result eq 'ok') {
3370: if (!($perm_reqd eq 'yes')) {
3371: return(&retrievestudentphoto($udom,$unam,$ext));
3372: }
3373: }
3374: }
3375: }
3376: } else {
3377: my ($result,$perm_reqd) =
1.1494 raeburn 3378: &auto_photo_permission($unam,$udom);
1.706 raeburn 3379: if ($result eq 'ok') {
3380: if (!($perm_reqd eq 'yes')) {
3381: return(&retrievestudentphoto($udom,$unam,$ext));
3382: }
3383: }
3384: }
3385: return '/adm/lonKaputt/lonlogo_broken.gif';
3386: }
3387:
3388: sub retrievestudentphoto {
3389: my ($udom,$unam,$ext,$type) = @_;
1.1494 raeburn 3390: my $home=&homeserver($unam,$udom);
3391: my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
1.706 raeburn 3392: if ($ret eq 'ok') {
3393: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3394: if ($type eq 'thumbnail') {
3395: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3396: }
1.1494 raeburn 3397: my $tokenurl=&tokenwrapper($url);
1.706 raeburn 3398: return $tokenurl;
3399: } else {
3400: if ($type eq 'thumbnail') {
3401: return '/adm/lonKaputt/genericstudent_tn.gif';
3402: } else {
3403: return '/adm/lonKaputt/lonlogo_broken.gif';
3404: }
1.617 albertel 3405: }
3406: }
3407:
1.263 www 3408: # -------------------------------------------------------------------- New chat
3409:
3410: sub chatsend {
1.724 raeburn 3411: my ($newentry,$anon,$group)=@_;
1.620 albertel 3412: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3413: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3414: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 3415: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 3416: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 3417: &escape($newentry)).':'.$group,$chome);
1.292 www 3418: }
3419:
3420: # ------------------------------------------ Find current version of a resource
3421:
3422: sub getversion {
3423: my $fname=&clutter(shift);
1.1189 raeburn 3424: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3425: return ¤tversion(&filelocation('',$fname));
3426: }
3427:
3428: sub currentversion {
3429: my $fname=shift;
3430: my $author=$fname;
3431: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3432: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3433: my $home=&homeserver($uname,$udom);
1.292 www 3434: if ($home eq 'no_host') {
3435: return -1;
3436: }
1.1112 www 3437: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3438: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3439: return -1;
3440: }
1.1112 www 3441: return $answer;
1.263 www 3442: }
3443:
1.1111 www 3444: #
3445: # Return special version number of resource if set by override, empty otherwise
3446: #
3447: sub usedversion {
3448: my $fname=shift;
3449: unless ($fname) { $fname=$env{'request.uri'}; }
3450: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3451: if ($urlversion) { return $urlversion; }
3452: return '';
3453: }
3454:
1.1 albertel 3455: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3456:
1.1 albertel 3457: sub subscribe {
3458: my $fname=shift;
1.761 raeburn 3459: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3460: $fname=~s/[\n\r]//g;
1.1 albertel 3461: my $author=$fname;
3462: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3463: my ($udom,$uname)=split(/\//,$author);
3464: my $home=homeserver($uname,$udom);
1.335 albertel 3465: if ($home eq 'no_host') {
3466: return 'not_found';
1.1 albertel 3467: }
3468: my $answer=reply("sub:$fname",$home);
1.64 www 3469: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3470: $answer.=' by '.$home;
3471: }
1.1 albertel 3472: return $answer;
3473: }
3474:
1.8 www 3475: # -------------------------------------------------------------- Replicate file
3476:
3477: sub repcopy {
3478: my $filename=shift;
1.23 www 3479: $filename=~s/\/+/\//g;
1.1142 raeburn 3480: my $londocroot = $perlvar{'lonDocRoot'};
3481: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3482: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3483: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3484: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3485: return &repcopy_userfile($filename);
3486: }
1.532 albertel 3487: $filename=~s/[\n\r]//g;
1.8 www 3488: my $transname="$filename.in.transfer";
1.828 www 3489: # FIXME: this should flock
1.607 raeburn 3490: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3491: my $remoteurl=subscribe($filename);
1.64 www 3492: if ($remoteurl =~ /^con_lost by/) {
3493: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3494: return 'unavailable';
1.8 www 3495: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3496: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3497: return 'not_found';
1.64 www 3498: } elsif ($remoteurl =~ /^rejected by/) {
3499: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3500: return 'forbidden';
1.20 www 3501: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3502: return 'ok';
1.8 www 3503: } else {
1.290 www 3504: my $author=$filename;
3505: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3506: my ($udom,$uname)=split(/\//,$author);
3507: my $home=homeserver($uname,$udom);
3508: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3509: my @parts=split(/\//,$filename);
3510: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3511: if ($path ne "$londocroot/res") {
1.8 www 3512: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3513: return 'bad_request';
1.8 www 3514: }
3515: my $count;
3516: for ($count=5;$count<$#parts;$count++) {
3517: $path.="/$parts[$count]";
3518: if ((-e $path)!=1) {
3519: mkdir($path,0777);
3520: }
3521: }
3522: my $request=new HTTP::Request('GET',"$remoteurl");
1.1345 raeburn 3523: my $response;
3524: if ($remoteurl =~ m{/raw/}) {
3525: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3526: } else {
3527: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3528: }
1.8 www 3529: if ($response->is_error()) {
3530: unlink($transname);
3531: my $message=$response->status_line;
1.672 albertel 3532: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3533: ." LWP get: $message: $filename</font>");
1.607 raeburn 3534: return 'unavailable';
1.8 www 3535: } else {
1.16 www 3536: if ($remoteurl!~/\.meta$/) {
3537: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345 raeburn 3538: my $mresponse;
3539: if ($remoteurl =~ m{/raw/}) {
3540: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3541: } else {
3542: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3543: }
1.16 www 3544: if ($mresponse->is_error()) {
3545: unlink($filename.'.meta');
3546: &logthis(
1.672 albertel 3547: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3548: }
3549: }
1.8 www 3550: rename($transname,$filename);
1.607 raeburn 3551: return 'ok';
1.8 www 3552: }
1.290 www 3553: }
1.8 www 3554: }
1.330 www 3555: }
3556:
1.1422 raeburn 3557: # ------------------------------------------------- Unsubscribe from a resource
3558:
3559: sub unsubscribe {
3560: my ($fname) = @_;
3561: my $answer;
3562: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3563: $fname=~s/[\n\r]//g;
3564: my $author=$fname;
3565: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3566: my ($udom,$uname)=split(/\//,$author);
3567: my $home=homeserver($uname,$udom);
3568: if ($home eq 'no_host') {
3569: $answer = 'no_host';
3570: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3571: $answer = 'home';
3572: } else {
3573: my $defdom = $perlvar{'lonDefDomain'};
3574: if (&will_trust('content',$defdom,$udom)) {
3575: $answer = reply("unsub:$fname",$home);
3576: } else {
3577: $answer = 'untrusted';
3578: }
3579: }
3580: return $answer;
3581: }
3582:
1.330 www 3583: # ------------------------------------------------ Get server side include body
3584: sub ssi_body {
1.381 albertel 3585: my ($filelink,%form)=@_;
1.606 matthew 3586: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3587: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3588: }
1.953 www 3589: my $output='';
3590: my $response;
1.980 raeburn 3591: if ($filelink=~/^https?\:/) {
1.954 raeburn 3592: ($output,$response)=&externalssi($filelink);
1.953 www 3593: } else {
1.1004 droeschl 3594: $filelink .= $filelink=~/\?/ ? '&' : '?';
3595: $filelink .= 'inhibitmenu=yes';
1.953 www 3596: ($output,$response)=&ssi($filelink,%form);
3597: }
1.778 albertel 3598: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3599: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3600: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3601: if (wantarray) {
3602: return ($output, $response);
3603: } else {
3604: return $output;
3605: }
1.8 www 3606: }
3607:
1.15 www 3608: # --------------------------------------------------------- Server Side Include
3609:
1.782 albertel 3610: sub absolute_url {
1.1447 raeburn 3611: my ($host_name,$unalias,$keep_proto) = @_;
1.782 albertel 3612: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3613: if ($host_name eq '') {
3614: $host_name = $ENV{'SERVER_NAME'};
3615: }
1.1447 raeburn 3616: if ($unalias) {
3617: my $alias = &get_proxy_alias();
3618: if ($alias eq $host_name) {
3619: my $lonhost = $perlvar{'lonHostID'};
3620: my $hostname = &hostname($lonhost);
3621: my $lcproto;
3622: if (($keep_proto) || ($hostname eq '')) {
3623: $lcproto = $protocol;
3624: } else {
3625: $lcproto = $protocol{$lonhost};
3626: $lcproto = 'http' if ($lcproto ne 'https');
3627: $lcproto .= '://';
3628: }
3629: unless ($hostname eq '') {
3630: return $lcproto.$hostname;
3631: }
3632: }
3633: }
1.782 albertel 3634: return $protocol.$host_name;
3635: }
3636:
1.942 foxr 3637: #
3638: # Server side include.
3639: # Parameters:
3640: # fn Possibly encrypted resource name/id.
3641: # form Hash that describes how the rendering should be done
3642: # and other things.
1.944 foxr 3643: # Returns:
1.950 raeburn 3644: # Scalar context: The content of the response.
3645: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3646: #
1.15 www 3647: sub ssi {
3648:
1.944 foxr 3649: my ($fn,%form)=@_;
1.1447 raeburn 3650: my ($host,$request,$response);
3651: $host = &absolute_url('',1);
1.711 albertel 3652:
3653: $form{'no_update_last_known'}=1;
1.895 albertel 3654: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3655: if (%form) {
1.1447 raeburn 3656: $request=new HTTP::Request('POST',$host.$fn);
1.1272 droeschl 3657: $request->content(join('&',map {
3658: my $name = escape($_);
3659: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3660: ? join("&$name=", map {escape($_) } @{$form{$_}})
3661: : &escape($form{$_}) );
3662: } keys(%form)));
1.23 www 3663: } else {
1.1447 raeburn 3664: $request=new HTTP::Request('GET',$host.$fn);
1.23 www 3665: }
3666:
1.15 www 3667: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345 raeburn 3668: my $lonhost = $perlvar{'lonHostID'};
1.1385 raeburn 3669: my $islocal;
3670: if (($env{'request.course.id'}) &&
3671: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3672: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3673: ($form{'grade_symb'} ne '') &&
1.1494 raeburn 3674: (&allowed('mgr',$env{'request.course.id'}.
3675: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1385 raeburn 3676: $islocal = 1;
3677: }
1.1447 raeburn 3678: $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
3679: '','','',$islocal);
1.1182 foxr 3680:
1.944 foxr 3681: if (wantarray) {
1.1345 raeburn 3682: return ($response->content, $response);
1.944 foxr 3683: } else {
1.1345 raeburn 3684: return $response->content;
1.942 foxr 3685: }
1.324 www 3686: }
3687:
3688: sub externalssi {
3689: my ($url)=@_;
3690: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 3691: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954 raeburn 3692: if (wantarray) {
3693: return ($response->content, $response);
3694: } else {
3695: return $response->content;
3696: }
1.15 www 3697: }
1.254 www 3698:
1.1354 raeburn 3699:
3700: # If the local copy of a replicated resource is outdated, trigger a
3701: # connection from the homeserver to flush the delayed queue. If no update
3702: # happens, remove local copies of outdated resource (and corresponding
3703: # metadata file).
3704:
1.1352 raeburn 3705: sub remove_stale_resfile {
3706: my ($url) = @_;
1.1354 raeburn 3707: my $removed;
1.1352 raeburn 3708: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3709: my $audom = $1;
3710: my $auname = $2;
1.1353 raeburn 3711: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352 raeburn 3712: my $homeserver = &homeserver($auname,$audom);
3713: unless (($homeserver eq 'no_host') ||
3714: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3715: my $fname = &filelocation('',$url);
3716: if (-e $fname) {
3717: my $hostname = &hostname($homeserver);
3718: if ($hostname) {
1.1397 raeburn 3719: my $protocol = $protocol{$homeserver};
3720: $protocol = 'http' if ($protocol ne 'https');
1.1352 raeburn 3721: my $uri = &declutter($url);
3722: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3723: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3724: if ($response->is_success()) {
3725: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3726: my $locmodtime = (stat($fname))[9];
3727: if ($locmodtime < $remmodtime) {
1.1354 raeburn 3728: my $stale;
3729: my $answer = &reply('pong',$homeserver);
3730: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3731: sleep(0.2);
3732: $locmodtime = (stat($fname))[9];
3733: if ($locmodtime < $remmodtime) {
3734: my $posstransfer = $fname.'.in.transfer';
3735: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3736: $removed = 1;
3737: } else {
3738: $stale = 1;
3739: }
3740: } else {
3741: $removed = 1;
3742: }
3743: } else {
3744: $stale = 1;
3745: }
3746: if ($stale) {
1.1421 raeburn 3747: if (unlink($fname)) {
3748: if ($uri!~/\.meta$/) {
3749: if (-e $fname.'.meta') {
3750: unlink($fname.'.meta');
3751: }
3752: }
1.1422 raeburn 3753: my $unsubresult = &unsubscribe($fname);
3754: unless ($unsubresult eq 'ok') {
3755: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3756: }
1.1421 raeburn 3757: $removed = 1;
1.1354 raeburn 3758: }
1.1352 raeburn 3759: }
3760: }
3761: }
3762: }
3763: }
3764: }
3765: }
3766: }
1.1354 raeburn 3767: return $removed;
1.1352 raeburn 3768: }
3769:
1.492 albertel 3770: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3771:
3772: sub allowuploaded {
3773: my ($srcurl,$url)=@_;
3774: $url=&clutter(&declutter($url));
3775: my $dir=$url;
3776: $dir=~s/\/[^\/]+$//;
3777: my %httpref=();
3778: my $httpurl=&hreflocation('',$url);
3779: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3780: &Apache::lonnet::appenv(\%httpref);
1.254 www 3781: }
1.477 raeburn 3782:
1.1193 raeburn 3783: #
3784: # Determine if the current user should be able to edit a particular resource,
3785: # when viewing in course context.
3786: # (a) When viewing resource used to determine if "Edit" item is included in
3787: # Functions.
3788: # (b) When displaying folder contents in course editor, used to determine if
3789: # "Edit" link will be displayed alongside resource.
3790: #
1.1196 raeburn 3791: # input: six args -- filename (decluttered), course number, course domain,
3792: # url, symb (if registered) and group (if this is a group
3793: # item -- e.g., bulletin board, group page etc.).
3794: # output: array of five scalars --
1.1193 raeburn 3795: # $cfile -- url for file editing if editable on current server
3796: # $home -- homeserver of resource (i.e., for author if published,
3797: # or course if uploaded.).
3798: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3799: # $forceedit -- 1 if icon/link should be to go to edit mode
3800: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3801: #
3802:
3803: sub can_edit_resource {
1.1194 raeburn 3804: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3805: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3806: #
3807: # For aboutme pages user can only edit his/her own.
3808: #
1.1199 raeburn 3809: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3810: my ($sdom,$sname) = ($1,$2);
3811: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3812: $home = $env{'user.home'};
3813: $cfile = $resurl;
3814: if ($env{'form.forceedit'}) {
3815: $forceview = 1;
3816: } else {
3817: $forceedit = 1;
3818: }
3819: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3820: } else {
3821: return;
3822: }
3823: }
3824:
3825: if ($env{'request.course.id'}) {
1.1494 raeburn 3826: my $crsedit = &allowed('mdc',$env{'request.course.id'});
1.1194 raeburn 3827: if ($group ne '') {
3828: # if this is a group homepage or group bulletin board, check group privs
3829: my $allowed = 0;
1.1197 raeburn 3830: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3831: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3832: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3833: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3834: $allowed = 1;
3835: }
1.1197 raeburn 3836: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3837: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3838: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3839: $allowed = 1;
3840: }
3841: }
3842: if ($allowed) {
3843: $home=&homeserver($cnum,$cdom);
3844: if ($env{'form.forceedit'}) {
3845: $forceview = 1;
3846: } else {
3847: $forceedit = 1;
3848: }
3849: $cfile = $resurl;
3850: } else {
3851: return;
3852: }
3853: } else {
1.1208 raeburn 3854: if ($resurl =~ m{^/?adm/viewclasslist$}) {
1.1494 raeburn 3855: unless (&allowed('opa',$env{'request.course.id'})) {
1.1208 raeburn 3856: return;
3857: }
3858: } elsif (!$crsedit) {
1.1194 raeburn 3859: #
3860: # No edit allowed where CC has switched to student role.
3861: #
3862: return;
3863: }
3864: }
3865: }
3866:
1.1193 raeburn 3867: if ($file ne '') {
3868: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3869: if (&is_course_upload($file,$cnum,$cdom)) {
3870: $uploaded = 1;
3871: $incourse = 1;
1.1193 raeburn 3872: if ($file =~/\.(htm|html|css|js|txt)$/) {
3873: $cfile = &hreflocation('',$file);
1.1201 raeburn 3874: if ($env{'form.forceedit'}) {
3875: $forceview = 1;
3876: } else {
3877: $forceedit = 1;
3878: }
1.1194 raeburn 3879: }
3880: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3881: $incourse = 1;
3882: if ($env{'form.forceedit'}) {
3883: $forceview = 1;
3884: } else {
3885: $forceedit = 1;
3886: }
3887: $cfile = $resurl;
3888: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3889: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3890: $incourse = 1;
3891: if ($env{'form.forceedit'}) {
3892: $forceview = 1;
3893: } else {
3894: $forceedit = 1;
3895: }
3896: $cfile = $resurl;
1.1199 raeburn 3897: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3898: $incourse = 1;
3899: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3900: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3901: $incourse = 1;
1.1199 raeburn 3902: if ($env{'form.forceedit'}) {
3903: $forceview = 1;
3904: } else {
3905: $forceedit = 1;
3906: }
3907: $cfile = $resurl;
1.1419 raeburn 3908: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3909: my ($map,$id,$res) = &decode_symb($symb);
3910: if ($map =~ /\.page$/) {
3911: $incourse = 1;
3912: if ($env{'form.forceedit'}) {
3913: $forceview = 1;
3914: $cfile = $map;
3915: } else {
3916: $forceedit = 1;
3917: $cfile = '/adm/wrapper'.$resurl;
3918: }
3919: }
1.1343 raeburn 3920: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3921: $incourse = 1;
3922: if ($env{'form.forceedit'}) {
3923: $forceview = 1;
3924: } else {
3925: $forceedit = 1;
3926: }
3927: $cfile = $resurl;
1.1208 raeburn 3928: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3929: $incourse = 1;
3930: if ($env{'form.forceedit'}) {
3931: $forceview = 1;
3932: } else {
3933: $forceedit = 1;
3934: }
3935: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3936: }
3937: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3938: my $template = '/res/lib/templates/simpleproblem.problem';
3939: if (&is_on_map($template)) {
3940: $incourse = 1;
3941: $forceview = 1;
3942: $cfile = $template;
1.1193 raeburn 3943: }
1.1199 raeburn 3944: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418 raeburn 3945: $incourse = 1;
3946: if ($env{'form.forceedit'}) {
3947: $forceview = 1;
3948: } else {
3949: $forceedit = 1;
3950: }
3951: $cfile = $resurl;
1.1343 raeburn 3952: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298 raeburn 3953: $incourse = 1;
3954: if ($env{'form.forceedit'}) {
3955: $forceview = 1;
3956: } else {
3957: $forceedit = 1;
3958: }
3959: $cfile = $resurl;
1.1199 raeburn 3960: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3961: $incourse = 1;
3962: $forceview = 1;
3963: if ($symb) {
3964: my ($map,$id,$res)=&decode_symb($symb);
3965: $env{'request.symb'} = $symb;
3966: $cfile = &clutter($res);
3967: } else {
3968: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3969: my $escfile = &unescape($cfile);
1.1343 raeburn 3970: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3971: $cfile = '/adm/wrapper'.$escfile;
3972: } else {
3973: $escfile =~ s{^http://}{};
3974: $cfile = &escape("/adm/wrapper/ext/$escfile");
3975: }
1.1199 raeburn 3976: }
1.1234 raeburn 3977: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3978: if ($env{'form.forceedit'}) {
3979: $forceview = 1;
3980: } else {
3981: $forceedit = 1;
3982: }
3983: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3984: }
3985: }
1.1194 raeburn 3986: if ($uploaded || $incourse) {
3987: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3988: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3989: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3990: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3991: # Check that the user has permission to edit this resource
3992: my $setpriv = 1;
3993: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3994: if (defined($cfudom)) {
3995: $home=&homeserver($cfuname,$cfudom);
3996: $cfile=$file;
3997: }
3998: }
1.1194 raeburn 3999: if (($cfile ne '') && (!$incourse || $uploaded) &&
4000: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 4001: my @ids=¤t_machine_ids();
4002: unless (grep(/^\Q$home\E$/,@ids)) {
4003: $switchserver=1;
4004: }
4005: }
4006: }
1.1194 raeburn 4007: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 4008: }
4009:
4010: sub is_course_upload {
4011: my ($file,$cnum,$cdom) = @_;
4012: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
4013: $uploadpath =~ s{^\/}{};
1.1201 raeburn 4014: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
4015: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 4016: return 1;
4017: }
4018: return;
4019: }
4020:
1.1194 raeburn 4021: sub in_course {
1.1195 raeburn 4022: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
4023: if ($hideprivileged) {
4024: my $skipuser;
1.1219 raeburn 4025: my %coursehash = &coursedescription($cdom.'_'.$cnum);
4026: my @possdoms = ($cdom);
4027: if ($coursehash{'checkforpriv'}) {
4028: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4029: }
4030: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 4031: $skipuser = 1;
4032: if ($coursehash{'nothideprivileged'}) {
4033: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4034: my $user;
4035: if ($item =~ /:/) {
4036: $user = $item;
4037: } else {
4038: $user = join(':',split(/[\@]/,$item));
4039: }
4040: if ($user eq $uname.':'.$udom) {
4041: undef($skipuser);
4042: last;
4043: }
4044: }
4045: }
4046: if ($skipuser) {
4047: return 0;
4048: }
4049: }
4050: }
1.1194 raeburn 4051: $type ||= 'any';
4052: if (!defined($cdom) || !defined($cnum)) {
4053: my $cid = $env{'request.course.id'};
4054: $cdom = $env{'course.'.$cid.'.domain'};
4055: $cnum = $env{'course.'.$cid.'.num'};
4056: }
4057: my $typesref;
1.1195 raeburn 4058: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 4059: $typesref = ['active','previous','future'];
4060: } elsif ($type eq 'previous' || $type eq 'future') {
4061: $typesref = [$type];
4062: }
4063: my %roles = &get_my_roles($uname,$udom,'userroles',
4064: $typesref,undef,[$cdom]);
4065: my ($tmp) = keys(%roles);
4066: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
4067: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
4068: if (@course_roles > 0) {
4069: return 1;
4070: }
4071: return 0;
4072: }
4073:
1.478 albertel 4074: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 4075: # input: action, courseID, current domain, intended
1.637 raeburn 4076: # path to file, source of file, instruction to parse file for objects,
4077: # ref to hash for embedded objects,
4078: # ref to hash for codebase of java objects.
1.1095 raeburn 4079: # reference to scalar to accommodate mime type determined
4080: # from File::MMagic if $parser = parse.
1.637 raeburn 4081: #
1.485 raeburn 4082: # output: url to file (if action was uploaddoc),
4083: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 4084: #
1.478 albertel 4085: # Allows directory structure to be used within lonUsers/../userfiles/ for a
4086: # course.
1.477 raeburn 4087: #
1.478 albertel 4088: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4089: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
4090: # course's home server.
1.477 raeburn 4091: #
1.478 albertel 4092: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
4093: # be copied from $source (current location) to
4094: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4095: # and will then be copied to
4096: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
4097: # course's home server.
1.485 raeburn 4098: #
1.481 raeburn 4099: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 4100: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 4101: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4102: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
4103: # in course's home server.
1.637 raeburn 4104: #
1.477 raeburn 4105:
4106: sub process_coursefile {
1.1095 raeburn 4107: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
4108: $mimetype)=@_;
1.477 raeburn 4109: my $fetchresult;
1.638 albertel 4110: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 4111: if ($action eq 'propagate') {
1.638 albertel 4112: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4113: $home);
1.481 raeburn 4114: } else {
1.477 raeburn 4115: my $fpath = '';
4116: my $fname = $file;
1.478 albertel 4117: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 4118: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 4119: my $filepath = &build_filepath($fpath);
1.481 raeburn 4120: if ($action eq 'copy') {
4121: if ($source eq '') {
4122: $fetchresult = 'no source file';
4123: return $fetchresult;
4124: } else {
4125: my $destination = $filepath.'/'.$fname;
4126: rename($source,$destination);
4127: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4128: $home);
1.481 raeburn 4129: }
4130: } elsif ($action eq 'uploaddoc') {
1.1359 raeburn 4131: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 4132: print $fh $env{'form.'.$source};
1.481 raeburn 4133: close($fh);
1.637 raeburn 4134: if ($parser eq 'parse') {
1.1024 raeburn 4135: my $mm = new File::MMagic;
1.1095 raeburn 4136: my $type = $mm->checktype_filename($filepath.'/'.$fname);
4137: if ($type eq 'text/html') {
1.1024 raeburn 4138: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
4139: unless ($parse_result eq 'ok') {
4140: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
4141: }
1.637 raeburn 4142: }
1.1095 raeburn 4143: if (ref($mimetype)) {
4144: $$mimetype = $type;
4145: }
1.637 raeburn 4146: }
1.477 raeburn 4147: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4148: $home);
1.481 raeburn 4149: if ($fetchresult eq 'ok') {
4150: return '/uploaded/'.$fpath.'/'.$fname;
4151: } else {
4152: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4153: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 4154: return '/adm/notfound.html';
4155: }
1.477 raeburn 4156: }
4157: }
1.485 raeburn 4158: unless ( $fetchresult eq 'ok') {
1.477 raeburn 4159: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4160: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 4161: }
4162: return $fetchresult;
4163: }
4164:
1.637 raeburn 4165: sub build_filepath {
4166: my ($fpath) = @_;
4167: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
4168: unless ($fpath eq '') {
4169: my @parts=split('/',$fpath);
4170: foreach my $part (@parts) {
4171: $filepath.= '/'.$part;
4172: if ((-e $filepath)!=1) {
4173: mkdir($filepath,0777);
4174: }
4175: }
4176: }
4177: return $filepath;
4178: }
4179:
4180: sub store_edited_file {
1.638 albertel 4181: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 4182: my $file = $primary_url;
4183: $file =~ s#^/uploaded/$docudom/$docuname/##;
4184: my $fpath = '';
4185: my $fname = $file;
4186: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
4187: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
4188: my $filepath = &build_filepath($fpath);
1.1359 raeburn 4189: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 4190: print $fh $content;
4191: close($fh);
1.638 albertel 4192: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 4193: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4194: $home);
1.637 raeburn 4195: if ($$fetchresult eq 'ok') {
4196: return '/uploaded/'.$fpath.'/'.$fname;
4197: } else {
1.638 albertel 4198: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4199: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 4200: return '/adm/notfound.html';
4201: }
4202: }
4203:
1.531 albertel 4204: sub clean_filename {
1.831 albertel 4205: my ($fname,$args)=@_;
1.315 www 4206: # Replace Windows backslashes by forward slashes
1.257 www 4207: $fname=~s/\\/\//g;
1.831 albertel 4208: if (!$args->{'keep_path'}) {
4209: # Get rid of everything but the actual filename
4210: $fname=~s/^.*\/([^\/]+)$/$1/;
4211: }
1.315 www 4212: # Replace spaces by underscores
4213: $fname=~s/\s+/\_/g;
1.1406 raeburn 4214: # Transliterate non-ascii text to ascii
4215: my $lang = &Apache::lonlocal::current_language();
4216: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 4217: # Replace all other weird characters by nothing
1.831 albertel 4218: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 4219: # Replace all .\d. sequences with _\d. so they no longer look like version
4220: # numbers
4221: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443 raeburn 4222: # Replace three or more adjacent underscores with one for consistency
4223: # with loncfile::filename_check() so complete url can be extracted by
4224: # lonnet::decode_symb()
4225: $fname=~s/_{3,}/_/g;
1.531 albertel 4226: return $fname;
4227: }
1.1406 raeburn 4228:
1.1051 raeburn 4229: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4230: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4231: # image with the same aspect ratio as the original, but with dimensions which do
4232: # not exceed $resizewidth and $resizeheight.
4233:
1.984 neumanie 4234: sub resizeImage {
1.1051 raeburn 4235: my ($img_path,$resizewidth,$resizeheight) = @_;
4236: my $ima = Image::Magick->new;
4237: my $resized;
4238: if (-e $img_path) {
4239: $ima->Read($img_path);
4240: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4241: my $width = $ima->Get('width');
4242: my $height = $ima->Get('height');
4243: if ($width > $resizewidth) {
4244: my $factor = $width/$resizewidth;
4245: my $newheight = $height/$factor;
4246: $ima->Scale(width=>$resizewidth,height=>$newheight);
4247: $resized = 1;
4248: }
4249: }
4250: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4251: my $width = $ima->Get('width');
4252: my $height = $ima->Get('height');
4253: if ($height > $resizeheight) {
4254: my $factor = $height/$resizeheight;
4255: my $newwidth = $width/$factor;
4256: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4257: $resized = 1;
4258: }
4259: }
4260: if ($resized) {
4261: $ima->Write($img_path);
4262: }
4263: }
4264: return;
1.977 amueller 4265: }
4266:
1.608 albertel 4267: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 4268: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 4269: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 4270: # $context - possible values: coursedoc, existingfile, overwrite,
1.1401 raeburn 4271: # canceloverwrite, scantron or ''.
1.1090 raeburn 4272: # if 'coursedoc': upload to the current course
4273: # if 'existingfile': write file to tmp/overwrites directory
4274: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4275: # $context is passed as argument to &finishuserfileupload
1.686 albertel 4276: # $subdir - directory in userfile to store the file into
1.1401 raeburn 4277: # $parser - instruction to parse file for objects ($parser = parse) or
4278: # if context is 'scantron', $parser is hashref of csv column mapping
4279: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4280: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 4281: # $allfiles - reference to hash for embedded objects
4282: # $codebase - reference to hash for codebase of java objects
4283: # $desuname - username for permanent storage of uploaded file
4284: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 4285: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4286: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 4287: # $resizewidth - width (pixels) to which to resize uploaded image
4288: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 4289: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 4290: # from File::MMagic.
1.858 raeburn 4291: #
1.686 albertel 4292: # output: url of file in userspace, or error: <message>
4293: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 4294:
1.531 albertel 4295: sub userfileupload {
1.1090 raeburn 4296: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 4297: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 4298: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 4299: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 4300: $fname=&clean_filename($fname);
1.1090 raeburn 4301: # See if there is anything left
1.257 www 4302: unless ($fname) { return 'error: no uploaded file'; }
1.1406 raeburn 4303: # If filename now begins with a . prepend unix timestamp _ milliseconds
4304: if ($fname =~ /^\./) {
4305: my ($s,$usec) = &gettimeofday();
4306: while (length($usec) < 6) {
4307: $usec = '0'.$usec;
4308: }
4309: $fname = $s.'_'.substr($usec,0,3).$fname;
4310: }
1.1090 raeburn 4311: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4312: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4313: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4314: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 4315: my $now = time;
1.1090 raeburn 4316: my $filepath;
1.1095 raeburn 4317: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 4318: $filepath = 'tmp/helprequests/'.$now;
4319: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4320: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4321: '_'.$env{'user.domain'}.'/pending';
4322: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4323: my ($docuname,$docudom);
1.1350 raeburn 4324: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 4325: $docudom = $destudom;
4326: } else {
4327: $docudom = $env{'user.domain'};
4328: }
1.1350 raeburn 4329: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 4330: $docuname = $destuname;
4331: } else {
4332: $docuname = $env{'user.name'};
4333: }
4334: if (exists($env{'form.group'})) {
4335: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4336: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4337: }
4338: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4339: if ($context eq 'canceloverwrite') {
4340: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4341: if (-e $tempfile) {
4342: my @info = stat($tempfile);
4343: if ($info[9] eq $env{'form.timestamp'}) {
4344: unlink($tempfile);
4345: }
4346: }
4347: return;
1.523 raeburn 4348: }
4349: }
1.1090 raeburn 4350: # Create the directory if not present
1.741 raeburn 4351: my @parts=split(/\//,$filepath);
4352: my $fullpath = $perlvar{'lonDaemons'};
4353: for (my $i=0;$i<@parts;$i++) {
4354: $fullpath .= '/'.$parts[$i];
4355: if ((-e $fullpath)!=1) {
4356: mkdir($fullpath,0777);
4357: }
4358: }
1.1359 raeburn 4359: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 4360: print $fh $env{'form.'.$formname};
4361: close($fh);
1.1090 raeburn 4362: if ($context eq 'existingfile') {
4363: my @info = stat($fullpath.'/'.$fname);
4364: return ($fullpath.'/'.$fname,$info[9]);
4365: } else {
4366: return $fullpath.'/'.$fname;
4367: }
1.523 raeburn 4368: }
1.995 raeburn 4369: if ($subdir eq 'scantron') {
4370: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 4371: } else {
1.995 raeburn 4372: $fname="$subdir/$fname";
4373: }
1.1090 raeburn 4374: if ($context eq 'coursedoc') {
1.638 albertel 4375: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4376: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 4377: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 4378: return &finishuserfileupload($docuname,$docudom,
4379: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 4380: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 4381: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 4382: } else {
1.1218 raeburn 4383: if ($env{'form.folder'}) {
4384: $fname=$env{'form.folder'}.'/'.$fname;
4385: }
1.638 albertel 4386: return &process_coursefile('uploaddoc',$docuname,$docudom,
4387: $fname,$formname,$parser,
1.1095 raeburn 4388: $allfiles,$codebase,$mimetype);
1.481 raeburn 4389: }
1.719 banghart 4390: } elsif (defined($destuname)) {
4391: my $docuname=$destuname;
4392: my $docudom=$destudom;
1.860 raeburn 4393: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4394: $parser,$allfiles,$codebase,
1.1051 raeburn 4395: $thumbwidth,$thumbheight,
1.1095 raeburn 4396: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4397: } else {
1.638 albertel 4398: my $docuname=$env{'user.name'};
4399: my $docudom=$env{'user.domain'};
1.1220 raeburn 4400: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 4401: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4402: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4403: }
1.860 raeburn 4404: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4405: $parser,$allfiles,$codebase,
1.1051 raeburn 4406: $thumbwidth,$thumbheight,
1.1095 raeburn 4407: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4408: }
1.271 www 4409: }
4410:
4411: sub finishuserfileupload {
1.860 raeburn 4412: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4413: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4414: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4415: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4416:
1.860 raeburn 4417: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4418: $file=$fname;
4419: if ($fname=~m|/|) {
4420: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4421: $path.=$fnamepath.'/';
4422: }
1.259 www 4423: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4424: my $count;
4425: for ($count=4;$count<=$#parts;$count++) {
4426: $filepath.="/$parts[$count]";
4427: if ((-e $filepath)!=1) {
4428: mkdir($filepath,0777);
4429: }
4430: }
1.984 neumanie 4431:
1.258 www 4432: # Save the file
4433: {
1.1359 raeburn 4434: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4435: &logthis('Failed to create '.$filepath.'/'.$file);
4436: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4437: return '/adm/notfound.html';
4438: }
1.1090 raeburn 4439: if ($context eq 'overwrite') {
1.1117 foxr 4440: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4441: my $target = $filepath.'/'.$file;
4442: if (-e $source) {
4443: my @info = stat($source);
4444: if ($info[9] eq $env{'form.timestamp'}) {
4445: unless (&File::Copy::move($source,$target)) {
4446: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4447: return "Moving from $source failed";
4448: }
4449: } else {
4450: return "Temporary file: $source had unexpected date/time for last modification";
4451: }
4452: } else {
4453: return "Temporary file: $source missing";
4454: }
4455: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4456: &logthis('Failed to write to '.$filepath.'/'.$file);
4457: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4458: return '/adm/notfound.html';
4459: }
1.570 albertel 4460: close(FH);
1.1051 raeburn 4461: if ($resizewidth && $resizeheight) {
4462: my $mm = new File::MMagic;
4463: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4464: if ($mime_type =~ m{^image/}) {
4465: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4466: }
1.977 amueller 4467: }
1.258 www 4468: }
1.1152 raeburn 4469: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4470: if (ref($mimetype)) {
4471: if ($$mimetype eq '') {
4472: my $mm = new File::MMagic;
4473: my $type = $mm->checktype_filename($filepath.'/'.$file);
4474: $$mimetype = $type;
4475: }
4476: }
4477: }
1.1401 raeburn 4478: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4479: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4480: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4481: $allfiles,$codebase);
4482: unless ($parse_result eq 'ok') {
4483: &logthis('Failed to parse '.$filepath.$file.
4484: ' for embedded media: '.$parse_result);
4485: }
1.637 raeburn 4486: }
1.1401 raeburn 4487: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4488: my $format = $env{'form.scantron_format'};
4489: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4490: }
1.860 raeburn 4491: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4492: my $input = $filepath.'/'.$file;
4493: my $output = $filepath.'/'.'tn-'.$file;
4494: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359 raeburn 4495: my @args = ('convert','-sample',$thumbsize,$input,$output);
4496: system({$args[0]} @args);
1.860 raeburn 4497: if (-e $filepath.'/'.'tn-'.$file) {
4498: $fetchthumb = 1;
4499: }
4500: }
1.858 raeburn 4501:
1.259 www 4502: # Notify homeserver to grep it
4503: #
1.984 neumanie 4504: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4505: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4506: if ($fetchresult eq 'ok') {
1.860 raeburn 4507: if ($fetchthumb) {
4508: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4509: if ($thumbresult ne 'ok') {
4510: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4511: $docuhome.': '.$thumbresult);
4512: }
4513: }
1.259 www 4514: #
1.258 www 4515: # Return the URL to it
1.494 albertel 4516: return '/uploaded/'.$path.$file;
1.263 www 4517: } else {
1.494 albertel 4518: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4519: ': '.$fetchresult);
1.263 www 4520: return '/adm/notfound.html';
1.858 raeburn 4521: }
1.493 albertel 4522: }
4523:
1.637 raeburn 4524: sub extract_embedded_items {
1.961 raeburn 4525: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4526: my @state = ();
1.1164 raeburn 4527: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4528: my %javafiles = (
4529: codebase => '',
4530: code => '',
4531: archive => ''
4532: );
4533: my %mediafiles = (
4534: src => '',
4535: movie => '',
4536: );
1.648 raeburn 4537: my $p;
4538: if ($content) {
4539: $p = HTML::LCParser->new($content);
4540: } else {
1.961 raeburn 4541: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4542: }
1.641 albertel 4543: while (my $t=$p->get_token()) {
1.640 albertel 4544: if ($t->[0] eq 'S') {
4545: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4546: push(@state, $tagname);
1.648 raeburn 4547: if (lc($tagname) eq 'allow') {
4548: &add_filetype($allfiles,$attr->{'src'},'src');
4549: }
1.640 albertel 4550: if (lc($tagname) eq 'img') {
4551: &add_filetype($allfiles,$attr->{'src'},'src');
4552: }
1.886 albertel 4553: if (lc($tagname) eq 'a') {
1.1222 raeburn 4554: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 4555: &add_filetype($allfiles,$attr->{'href'},'href');
4556: }
1.886 albertel 4557: }
1.645 raeburn 4558: if (lc($tagname) eq 'script') {
1.1164 raeburn 4559: my $src;
1.645 raeburn 4560: if ($attr->{'archive'} =~ /\.jar$/i) {
4561: &add_filetype($allfiles,$attr->{'archive'},'archive');
4562: } else {
1.1164 raeburn 4563: if ($attr->{'src'} ne '') {
4564: $src = $attr->{'src'};
4565: &add_filetype($allfiles,$src,'src');
4566: }
4567: }
4568: my $text = $p->get_trimmed_text();
4569: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4570: my @swfargs = split(/,/,$1);
4571: foreach my $item (@swfargs) {
4572: $item =~ s/["']//g;
4573: $item =~ s/^\s+//;
4574: $item =~ s/\s+$//;
4575: }
4576: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4577: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4578: push(@{$related{$swfargs[0]}},$swfargs[2]);
4579: } else {
4580: $related{$swfargs[0]} = [$swfargs[2]];
4581: }
4582: }
1.645 raeburn 4583: }
4584: }
4585: if (lc($tagname) eq 'link') {
4586: if (lc($attr->{'rel'}) eq 'stylesheet') {
4587: &add_filetype($allfiles,$attr->{'href'},'href');
4588: }
4589: }
1.640 albertel 4590: if (lc($tagname) eq 'object' ||
4591: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4592: foreach my $item (keys(%javafiles)) {
4593: $javafiles{$item} = '';
4594: }
1.1164 raeburn 4595: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4596: $lastids{lc($tagname)} = $attr->{'id'};
4597: }
1.640 albertel 4598: }
4599: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4600: my $name = lc($attr->{'name'});
4601: foreach my $item (keys(%javafiles)) {
4602: if ($name eq $item) {
4603: $javafiles{$item} = $attr->{'value'};
4604: last;
4605: }
4606: }
1.1164 raeburn 4607: my $pathfrom;
1.640 albertel 4608: foreach my $item (keys(%mediafiles)) {
4609: if ($name eq $item) {
1.1164 raeburn 4610: $pathfrom = $attr->{'value'};
4611: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4612: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4613: last;
4614: }
4615: }
1.1164 raeburn 4616: if ($name eq 'flashvars') {
4617: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4618: }
4619: if ($pathfrom ne '') {
4620: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4621: $pathfrom);
4622: }
1.640 albertel 4623: }
4624: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4625: foreach my $item (keys(%javafiles)) {
4626: if ($attr->{$item}) {
4627: $javafiles{$item} = $attr->{$item};
4628: last;
4629: }
4630: }
4631: foreach my $item (keys(%mediafiles)) {
4632: if ($attr->{$item}) {
4633: &add_filetype($allfiles,$attr->{$item},$item);
4634: last;
4635: }
4636: }
1.1164 raeburn 4637: if (lc($tagname) eq 'embed') {
4638: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4639: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4640: $attr->{'src'});
4641: }
4642: }
1.640 albertel 4643: }
1.1243 raeburn 4644: if (lc($tagname) eq 'iframe') {
4645: my $src = $attr->{'src'} ;
4646: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4647: &add_filetype($allfiles,$src,'src');
4648: } elsif ($src =~ m{^/}) {
4649: if ($env{'request.course.id'}) {
4650: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4651: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4652: my $url = &hreflocation('',$fullpath);
4653: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4654: my $relpath = $1;
4655: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4656: &add_filetype($allfiles,$1,'src');
4657: }
4658: }
4659: }
4660: }
4661: }
1.1164 raeburn 4662: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 4663: pop(@state);
1.1164 raeburn 4664: }
1.640 albertel 4665: } elsif ($t->[0] eq 'E') {
4666: my ($tagname) = ($t->[1]);
4667: if ($javafiles{'codebase'} ne '') {
4668: $javafiles{'codebase'} .= '/';
4669: }
4670: if (lc($tagname) eq 'applet' ||
4671: lc($tagname) eq 'object' ||
4672: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4673: ) {
4674: foreach my $item (keys(%javafiles)) {
4675: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4676: my $file=$javafiles{'codebase'}.$javafiles{$item};
4677: &add_filetype($allfiles,$file,$item);
4678: }
4679: }
4680: }
4681: pop @state;
4682: }
4683: }
1.1164 raeburn 4684: foreach my $id (sort(keys(%flashvars))) {
4685: if ($shockwave{$id} ne '') {
4686: my @pairs = split(/\&/,$flashvars{$id});
4687: foreach my $pair (@pairs) {
4688: my ($key,$value) = split(/\=/,$pair);
4689: if ($key eq 'thumb') {
4690: &add_filetype($allfiles,$value,$key);
4691: } elsif ($key eq 'content') {
4692: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4693: my ($ext) = ($value =~ /\.([^.]+)$/);
4694: if ($ext ne '') {
4695: &add_filetype($allfiles,$path.$value,$ext);
4696: }
4697: }
4698: }
4699: }
4700: }
1.637 raeburn 4701: return 'ok';
4702: }
4703:
1.639 albertel 4704: sub add_filetype {
4705: my ($allfiles,$file,$type)=@_;
4706: if (exists($allfiles->{$file})) {
4707: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4708: push(@{$allfiles->{$file}}, &escape($type));
4709: }
4710: } else {
4711: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4712: }
4713: }
4714:
1.1164 raeburn 4715: sub embedded_dependency {
4716: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4717: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4718: if (($identifier ne '') &&
4719: (ref($related->{$identifier}) eq 'ARRAY') &&
4720: ($pathfrom ne '')) {
4721: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4722: foreach my $dep (@{$related->{$identifier}}) {
4723: &add_filetype($allfiles,$path.$dep,'object');
4724: }
4725: }
4726: }
4727: return;
4728: }
4729:
1.1401 raeburn 4730: sub bubblesheet_converter {
4731: my ($cdom,$fullpath,$config,$format) = @_;
4732: if ((&domain($cdom) ne '') &&
1.1403 raeburn 4733: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401 raeburn 4734: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404 raeburn 4735: my (%csvcols,%csvoptions);
4736: if (ref($config->{'fields'}) eq 'HASH') {
4737: %csvcols = %{$config->{'fields'}};
4738: }
4739: if (ref($config->{'options'}) eq 'HASH') {
4740: %csvoptions = %{$config->{'options'}};
4741: }
1.1401 raeburn 4742: my %csvbynum = reverse(%csvcols);
4743: my %scantronconf = &get_scantron_config($format,$cdom);
4744: if (keys(%scantronconf)) {
4745: my %bynum = (
4746: $scantronconf{CODEstart} => 'CODEstart',
4747: $scantronconf{IDstart} => 'IDstart',
4748: $scantronconf{PaperID} => 'PaperID',
4749: $scantronconf{FirstName} => 'FirstName',
4750: $scantronconf{LastName} => 'LastName',
4751: $scantronconf{Qstart} => 'Qstart',
4752: );
4753: my @ordered;
4754: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403 raeburn 4755: push(@ordered,$bynum{$item});
1.1401 raeburn 4756: }
4757: my %mapstart = (
4758: CODEstart => 'CODE',
4759: IDstart => 'ID',
4760: PaperID => 'PaperID',
4761: FirstName => 'FirstName',
4762: LastName => 'LastName',
4763: Qstart => 'FirstQuestion',
4764: );
4765: my %maplength = (
4766: CODEstart => 'CODElength',
4767: IDstart => 'IDlength',
4768: PaperID => 'PaperIDlength',
4769: FirstName => 'FirstNamelength',
4770: LastName => 'LastNamelength',
4771: );
4772: if (open(my $fh,'<',$fullpath)) {
4773: my $output;
1.1403 raeburn 4774: my %lettdig = &letter_to_digits();
4775: my %diglett = reverse(%lettdig);
4776: my $numletts = scalar(keys(%lettdig));
1.1404 raeburn 4777: my $num = 0;
1.1401 raeburn 4778: while (my $line=<$fh>) {
1.1404 raeburn 4779: $num ++;
4780: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401 raeburn 4781: $line =~ s{[\r\n]+$}{};
4782: my %found;
1.1475 raeburn 4783: my @values = split(/,/,$line,-1);
1.1401 raeburn 4784: my ($qstart,$record);
4785: for (my $i=0; $i<@values; $i++) {
1.1403 raeburn 4786: if ((($qstart ne '') && ($i > $qstart)) ||
4787: ($csvbynum{$i} eq 'FirstQuestion')) {
4788: if ($values[$i] eq '') {
4789: $values[$i] = $scantronconf{'Qoff'};
4790: } elsif ($scantronconf{'Qon'} eq 'number') {
4791: if ($values[$i] =~ /^[A-Ja-j]$/) {
4792: $values[$i] = $lettdig{uc($values[$i])};
4793: }
4794: } elsif ($scantronconf{'Qon'} eq 'letter') {
4795: if ($values[$i] =~ /^[0-9]$/) {
4796: $values[$i] = $diglett{$values[$i]};
4797: }
4798: } else {
4799: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4800: my $digit;
4801: if ($values[$i] =~ /^[A-Ja-j]$/) {
4802: $digit = $lettdig{uc($values[$i])}-1;
4803: if ($values[$i] eq 'J') {
4804: $digit += $numletts;
4805: }
4806: } elsif ($values[$i] =~ /^[0-9]$/) {
4807: $digit = $values[$i]-1;
4808: if ($values[$i] eq '0') {
4809: $digit += $numletts;
4810: }
4811: }
4812: my $qval='';
4813: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4814: if ($j == $digit) {
4815: $qval .= $scantronconf{'Qon'};
4816: } else {
4817: $qval .= $scantronconf{'Qoff'};
4818: }
4819: }
4820: $values[$i] = $qval;
4821: }
4822: }
4823: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4824: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4825: }
4826: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4827: if ($numblank > 0) {
4828: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4829: }
1.1401 raeburn 4830: if ($csvbynum{$i} eq 'FirstQuestion') {
4831: $qstart = $i;
1.1403 raeburn 4832: $found{$csvbynum{$i}} = $values[$i];
1.1401 raeburn 4833: } else {
1.1403 raeburn 4834: $found{'FirstQuestion'} .= $values[$i];
4835: }
4836: } elsif (exists($csvbynum{$i})) {
1.1404 raeburn 4837: if ($csvoptions{'rem'}) {
4838: $values[$i] =~ s/^\s+//;
4839: }
4840: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403 raeburn 4841: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4842: $values[$i] = '0'.$values[$i];
1.1401 raeburn 4843: }
4844: }
4845: $found{$csvbynum{$i}} = $values[$i];
4846: }
4847: }
4848: foreach my $item (@ordered) {
4849: my $currlength = 1+length($record);
4850: my $numspaces = $scantronconf{$item} - $currlength;
4851: if ($numspaces > 0) {
4852: $record .= (' ' x $numspaces);
4853: }
4854: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4855: unless ($item eq 'Qstart') {
4856: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4857: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4858: }
4859: }
4860: $record .= $found{$mapstart{$item}};
4861: }
4862: }
4863: $output .= "$record\n";
4864: }
4865: close($fh);
4866: if ($output) {
4867: if (open(my $fh,'>',$fullpath)) {
4868: print $fh $output;
4869: close($fh);
4870: }
4871: }
4872: }
4873: }
4874: return;
4875: }
4876: }
4877:
1.1403 raeburn 4878: sub letter_to_digits {
4879: my %lettdig = (
4880: A => 1,
4881: B => 2,
4882: C => 3,
4883: D => 4,
4884: E => 5,
4885: F => 6,
4886: G => 7,
4887: H => 8,
4888: I => 9,
4889: J => 0,
4890: );
4891: return %lettdig;
4892: }
4893:
1.1401 raeburn 4894: sub get_scantron_config {
4895: my ($which,$cdom) = @_;
4896: my @lines = &get_scantronformat_file($cdom);
4897: my %config;
4898: #FIXME probably should move to XML it has already gotten a bit much now
4899: foreach my $line (@lines) {
4900: my ($name,$descrip)=split(/:/,$line);
4901: if ($name ne $which ) { next; }
4902: chomp($line);
4903: my @config=split(/:/,$line);
4904: $config{'name'}=$config[0];
4905: $config{'description'}=$config[1];
4906: $config{'CODElocation'}=$config[2];
4907: $config{'CODEstart'}=$config[3];
4908: $config{'CODElength'}=$config[4];
4909: $config{'IDstart'}=$config[5];
4910: $config{'IDlength'}=$config[6];
4911: $config{'Qstart'}=$config[7];
4912: $config{'Qlength'}=$config[8];
4913: $config{'Qoff'}=$config[9];
4914: $config{'Qon'}=$config[10];
4915: $config{'PaperID'}=$config[11];
4916: $config{'PaperIDlength'}=$config[12];
4917: $config{'FirstName'}=$config[13];
4918: $config{'FirstNamelength'}=$config[14];
4919: $config{'LastName'}=$config[15];
4920: $config{'LastNamelength'}=$config[16];
4921: $config{'BubblesPerRow'}=$config[17];
4922: last;
4923: }
4924: return %config;
4925: }
4926:
4927: sub get_scantronformat_file {
4928: my ($cdom) = @_;
4929: if ($cdom eq '') {
4930: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4931: }
4932: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4933: my $gottab = 0;
4934: my @lines;
4935: if (ref($domconfig{'scantron'}) eq 'HASH') {
4936: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4937: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4938: if ($formatfile ne '-1') {
4939: @lines = split("\n",$formatfile,-1);
4940: $gottab = 1;
4941: }
4942: }
4943: }
4944: if (!$gottab) {
4945: my $confname = $cdom.'-domainconfig';
4946: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4947: my $formatfile = &getfile($default);
4948: if ($formatfile ne '-1') {
4949: @lines = split("\n",$formatfile,-1);
4950: $gottab = 1;
4951: }
4952: }
4953: if (!$gottab) {
4954: my @domains = ¤t_machine_domains();
4955: if (grep(/^\Q$cdom\E$/,@domains)) {
4956: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4957: @lines = <$fh>;
4958: close($fh);
1.1403 raeburn 4959: }
1.1401 raeburn 4960: } else {
4961: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4962: @lines = <$fh>;
4963: close($fh);
4964: }
4965: }
1.1488 raeburn 4966: chomp(@lines);
1.1401 raeburn 4967: }
4968: return @lines;
4969: }
4970:
1.493 albertel 4971: sub removeuploadedurl {
1.984 neumanie 4972: my ($url)=@_;
4973: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4974: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4975: }
4976:
4977: sub removeuserfile {
4978: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4979: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4980: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4981: if ($result eq 'ok') {
1.798 raeburn 4982: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4983: my $metafile = $fname.'.meta';
4984: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4985: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4986: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4987: my $sqlresult =
1.823 albertel 4988: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4989: 'portfolio_metadata',$group,
4990: 'delete');
1.798 raeburn 4991: }
4992: }
4993: return $result;
1.257 www 4994: }
1.15 www 4995:
1.530 albertel 4996: sub mkdiruserfile {
4997: my ($docuname,$docudom,$dir)=@_;
4998: my $home=&homeserver($docuname,$docudom);
4999: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
5000: }
5001:
1.531 albertel 5002: sub renameuserfile {
5003: my ($docuname,$docudom,$old,$new)=@_;
5004: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 5005: my $result = &reply("renameuserfile:$docudom:$docuname:".
5006: &escape("$old").':'.&escape("$new"),$home);
5007: if ($result eq 'ok') {
5008: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
5009: my $oldmeta = $old.'.meta';
5010: my $newmeta = $new.'.meta';
5011: my $metaresult =
5012: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 5013: my $url = "/uploaded/$docudom/$docuname/$old";
5014: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 5015: my $sqlresult =
1.823 albertel 5016: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 5017: 'portfolio_metadata',$group,
5018: 'delete');
1.798 raeburn 5019: }
5020: }
5021: return $result;
1.531 albertel 5022: }
5023:
1.14 www 5024: # ------------------------------------------------------------------------- Log
5025:
5026: sub log {
5027: my ($dom,$nam,$hom,$what)=@_;
1.47 www 5028: return critical("log:$dom:$nam:$what",$hom);
1.157 www 5029: }
5030:
5031: # ------------------------------------------------------------------ Course Log
1.352 www 5032: #
5033: # This routine flushes several buffers of non-mission-critical nature
5034: #
1.157 www 5035:
5036: sub flushcourselogs {
1.352 www 5037: &logthis('Flushing log buffers');
5038: #
5039: # course logs
5040: # This is a log of all transactions in a course, which can be used
5041: # for data mining purposes
5042: #
5043: # It also collects the courseid database, which lists last transaction
5044: # times and course titles for all courseids
5045: #
5046: my %courseidbuffer=();
1.921 raeburn 5047: foreach my $crsid (keys(%courselogs)) {
1.352 www 5048: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 5049: &escape($courselogs{$crsid}),
5050: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 5051: delete $courselogs{$crsid};
5052: } else {
5053: &logthis('Failed to flush log buffer for '.$crsid);
5054: if (length($courselogs{$crsid})>40000) {
1.672 albertel 5055: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 5056: " exceeded maximum size, deleting.</font>");
5057: delete $courselogs{$crsid};
5058: }
1.352 www 5059: }
1.920 raeburn 5060: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 5061: 'description' => $coursedescrbuf{$crsid},
5062: 'inst_code' => $courseinstcodebuf{$crsid},
5063: 'type' => $coursetypebuf{$crsid},
5064: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 5065: };
1.191 harris41 5066: }
1.352 www 5067: #
5068: # Write course id database (reverse lookup) to homeserver of courses
5069: # Is used in pickcourse
5070: #
1.840 albertel 5071: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 5072: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 5073: $courseidbuffer{$crs_home},
5074: $crs_home,'timeonly');
1.352 www 5075: }
5076: #
5077: # File accesses
5078: # Writes to the dynamic metadata of resources to get hit counts, etc.
5079: #
1.449 matthew 5080: foreach my $entry (keys(%accesshash)) {
1.458 matthew 5081: if ($entry =~ /___count$/) {
5082: my ($dom,$name);
1.807 albertel 5083: ($dom,$name,undef)=
1.811 albertel 5084: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 5085: if (! defined($dom) || $dom eq '' ||
5086: ! defined($name) || $name eq '') {
1.620 albertel 5087: my $cid = $env{'request.course.id'};
1.1472 raeburn 5088: #
5089: # FIXME 11/29/2021
5090: # Typo in rev. 1.458 (2003/12/09)??
5091: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
5092: #
5093: # While these ramain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
5094: # $dom and $name will always be null, so the &inc() call will default to storing this data
5095: # in a nohist_accesscount.db file for the user rather than the course.
5096: #
5097: # That said there is a lot of noise in the data being stored.
5098: # So counts for prtspool/ and adm/ etc. are recorded.
5099: #
5100: # A review of which items ending '___count' are written to %accesshash should likely be
5101: # made before deciding whether to set these to 'course.' instead of 'request.'
5102: #
5103: # Under the current scheme each user receives a nohist_accesscount.db file listing
5104: # accesses for things which are not published resources, regardless of course, and
5105: # there is not a nohist_accesscount.db file in a course, which might log accesses from
5106: # anyone in the course for things which are not published resources.
5107: #
5108: # For an author, nohist_accesscount.db ends up having records for other items
5109: # mixed up with the legitimate access counts for the author's published resources.
5110: #
1.620 albertel 5111: $dom = $env{'request.'.$cid.'.domain'};
5112: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 5113: }
1.450 matthew 5114: my $value = $accesshash{$entry};
5115: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
5116: my %temphash=($url => $value);
1.449 matthew 5117: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
5118: if ($result eq 'ok') {
5119: delete $accesshash{$entry};
5120: }
5121: } else {
1.811 albertel 5122: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 5123: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 5124: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 5125: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
5126: delete $accesshash{$entry};
5127: }
1.185 www 5128: }
1.191 harris41 5129: }
1.352 www 5130: #
5131: # Roles
5132: # Reverse lookup of user roles for course faculty/staff and co-authorship
5133: #
1.800 albertel 5134: foreach my $entry (keys(%userrolehash)) {
1.351 www 5135: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 5136: split(/\:/,$entry);
1.1494 raeburn 5137: if (&put('nohist_userroles',
1.351 www 5138: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 5139: $rudom,$runame) eq 'ok') {
5140: delete $userrolehash{$entry};
5141: }
5142: }
1.662 raeburn 5143: #
1.1334 raeburn 5144: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 5145: #
5146: my %domrolebuffer = ();
1.1000 raeburn 5147: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 5148: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 5149: if ($domrolebuffer{$rudom}) {
5150: $domrolebuffer{$rudom}.='&'.&escape($entry).
5151: '='.&escape($domainrolehash{$entry});
5152: } else {
5153: $domrolebuffer{$rudom}.=&escape($entry).
5154: '='.&escape($domainrolehash{$entry});
5155: }
5156: delete $domainrolehash{$entry};
5157: }
5158: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 5159: my %servers;
5160: if (defined(&domain($dom,'primary'))) {
5161: my $primary=&domain($dom,'primary');
5162: my $hostname=&hostname($primary);
5163: $servers{$primary} = $hostname;
5164: } else {
5165: %servers = &get_servers($dom,'library');
5166: }
1.841 albertel 5167: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 5168: if (&reply('domroleput:'.$dom.':'.
5169: $domrolebuffer{$dom},$tryserver) eq 'ok') {
5170: last;
5171: } else {
1.841 albertel 5172: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
5173: }
1.662 raeburn 5174: }
5175: }
1.186 www 5176: $dumpcount++;
1.157 www 5177: }
5178:
5179: sub courselog {
5180: my $what=shift;
1.158 www 5181: $what=time.':'.$what;
1.620 albertel 5182: unless ($env{'request.course.id'}) { return ''; }
5183: $coursedombuf{$env{'request.course.id'}}=
5184: $env{'course.'.$env{'request.course.id'}.'.domain'};
5185: $coursenumbuf{$env{'request.course.id'}}=
5186: $env{'course.'.$env{'request.course.id'}.'.num'};
5187: $coursehombuf{$env{'request.course.id'}}=
5188: $env{'course.'.$env{'request.course.id'}.'.home'};
5189: $coursedescrbuf{$env{'request.course.id'}}=
5190: $env{'course.'.$env{'request.course.id'}.'.description'};
5191: $courseinstcodebuf{$env{'request.course.id'}}=
5192: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
5193: $courseownerbuf{$env{'request.course.id'}}=
5194: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 5195: $coursetypebuf{$env{'request.course.id'}}=
5196: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 5197: if (defined $courselogs{$env{'request.course.id'}}) {
5198: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 5199: } else {
1.620 albertel 5200: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 5201: }
1.620 albertel 5202: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 5203: &flushcourselogs();
5204: }
1.158 www 5205: }
5206:
5207: sub courseacclog {
5208: my $fnsymb=shift;
1.620 albertel 5209: unless ($env{'request.course.id'}) { return ''; }
5210: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 5211: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 5212: $what.=':POST';
1.583 matthew 5213: # FIXME: Probably ought to escape things....
1.800 albertel 5214: foreach my $key (keys(%env)) {
5215: if ($key=~/^form\.(.*)/) {
1.975 raeburn 5216: my $formitem = $1;
5217: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
5218: $what.=':'.$formitem.'='.$env{$key};
5219: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432 raeburn 5220: if ($formitem eq 'proctorpassword') {
1.1433 raeburn 5221: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432 raeburn 5222: } else {
5223: $what.=':'.$formitem.'='.$env{$key};
5224: }
1.975 raeburn 5225: }
1.158 www 5226: }
1.191 harris41 5227: }
1.583 matthew 5228: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
5229: # FIXME: We should not be depending on a form parameter that someone
5230: # editing lonsearchcat.pm might change in the future.
1.620 albertel 5231: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 5232: $what.= ':POST';
5233: # FIXME: Probably ought to escape things....
5234: foreach my $element ('courseexp','crsfulltext','crsrelated',
5235: 'crsdiscuss') {
1.620 albertel 5236: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 5237: }
5238: }
1.158 www 5239: }
5240: &courselog($what);
1.149 www 5241: }
5242:
1.185 www 5243: sub countacc {
5244: my $url=&declutter(shift);
1.458 matthew 5245: return if (! defined($url) || $url eq '');
1.620 albertel 5246: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 5247: #
5248: # Mark that this url was used in this course
5249: #
1.620 albertel 5250: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 5251: #
5252: # Increase the access count for this resource in this child process
5253: #
1.281 www 5254: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 5255: $accesshash{$key}++;
1.185 www 5256: }
1.349 www 5257:
1.361 www 5258: sub linklog {
5259: my ($from,$to)=@_;
5260: $from=&declutter($from);
5261: $to=&declutter($to);
5262: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5263: $accesshash{$to.'___'.$from.'___goto'}=1;
5264: }
1.1160 www 5265:
5266: sub statslog {
5267: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5268: if ($users<2) { return; }
5269: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5270: 'course' => $env{'request.course.id'},
5271: 'sections' => '"all"',
5272: 'num_students' => $users,
5273: 'part' => $part,
5274: 'symb' => $symb,
5275: 'mean_tries' => $av_attempts,
5276: 'deg_of_diff' => $degdiff});
5277: foreach my $key (keys(%dynstore)) {
5278: $accesshash{$key}=$dynstore{$key};
5279: }
5280: }
1.361 www 5281:
1.349 www 5282: sub userrolelog {
5283: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 5284: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 5285: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5286: $userrolehash
5287: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 5288: =$tend.':'.$tstart;
1.662 raeburn 5289: }
1.1169 droeschl 5290: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 5291: $userrolehash
5292: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5293: =$tend.':'.$tstart;
5294: }
1.1334 raeburn 5295: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 5296: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5297: $domainrolehash
5298: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5299: = $tend.':'.$tstart;
5300: }
1.351 www 5301: }
5302:
1.957 raeburn 5303: sub courserolelog {
5304: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 5305: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5306: my $cdom = $1;
5307: my $cnum = $2;
5308: my $sec = $3;
5309: my $namespace = 'rolelog';
5310: my %storehash = (
5311: role => $trole,
5312: start => $tstart,
5313: end => $tend,
5314: selfenroll => $selfenroll,
5315: context => $context,
5316: );
5317: if ($trole eq 'gr') {
5318: $namespace = 'groupslog';
5319: $storehash{'group'} = $sec;
5320: } else {
5321: $storehash{'section'} = $sec;
5322: }
1.1188 raeburn 5323: &write_log('course',$namespace,\%storehash,$delflag,$username,
5324: $domain,$cnum,$cdom);
1.1184 raeburn 5325: if (($trole ne 'st') || ($sec ne '')) {
5326: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 5327: }
5328: }
5329: return;
5330: }
5331:
1.1184 raeburn 5332: sub domainrolelog {
5333: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5334: if ($area =~ m{^/($match_domain)/$}) {
5335: my $cdom = $1;
1.1494 raeburn 5336: my $domconfiguser = &get_domainconfiguser($cdom);
1.1184 raeburn 5337: my $namespace = 'rolelog';
5338: my %storehash = (
5339: role => $trole,
5340: start => $tstart,
5341: end => $tend,
5342: context => $context,
5343: );
1.1188 raeburn 5344: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5345: $domain,$domconfiguser,$cdom);
1.1184 raeburn 5346: }
5347: return;
5348:
5349: }
5350:
5351: sub coauthorrolelog {
5352: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5353: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5354: my $audom = $1;
5355: my $auname = $2;
5356: my $namespace = 'rolelog';
5357: my %storehash = (
5358: role => $trole,
5359: start => $tstart,
5360: end => $tend,
5361: context => $context,
5362: );
1.1188 raeburn 5363: &write_log('author',$namespace,\%storehash,$delflag,$username,
5364: $domain,$auname,$audom);
1.1184 raeburn 5365: }
5366: return;
5367: }
5368:
1.351 www 5369: sub get_course_adv_roles {
1.948 raeburn 5370: my ($cid,$codes) = @_;
1.620 albertel 5371: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 5372: my %coursehash=&coursedescription($cid);
1.988 raeburn 5373: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 5374: my %nothide=();
1.800 albertel 5375: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 5376: if ($user !~ /:/) {
5377: $nothide{join(':',split(/[\@]/,$user))}=1;
5378: } else {
5379: $nothide{$user}=1;
5380: }
1.470 www 5381: }
1.1219 raeburn 5382: my @possdoms = ($coursehash{'domain'});
5383: if ($coursehash{'checkforpriv'}) {
5384: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5385: }
1.351 www 5386: my %returnhash=();
5387: my %dumphash=
5388: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5389: my $now=time;
1.997 raeburn 5390: my %privileged;
1.1000 raeburn 5391: foreach my $entry (keys(%dumphash)) {
1.800 albertel 5392: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 5393: if (($tstart) && ($tstart<0)) { next; }
5394: if (($tend) && ($tend<$now)) { next; }
5395: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 5396: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 5397: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 5398: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 5399: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 5400: if ($role eq 'cr') { next; }
1.948 raeburn 5401: if ($codes) {
5402: if ($section) { $role .= ':'.$section; }
5403: if ($returnhash{$role}) {
5404: $returnhash{$role}.=','.$username.':'.$domain;
5405: } else {
5406: $returnhash{$role}=$username.':'.$domain;
5407: }
1.351 www 5408: } else {
1.988 raeburn 5409: my $key=&plaintext($role,$crstype);
1.973 bisitz 5410: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 5411: if ($returnhash{$key}) {
5412: $returnhash{$key}.=','.$username.':'.$domain;
5413: } else {
5414: $returnhash{$key}=$username.':'.$domain;
5415: }
1.351 www 5416: }
1.948 raeburn 5417: }
1.400 www 5418: return %returnhash;
5419: }
5420:
5421: sub get_my_roles {
1.937 raeburn 5422: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5423: unless (defined($uname)) { $uname=$env{'user.name'}; }
5424: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5425: my (%dumphash,%nothide);
1.1086 raeburn 5426: if ($context eq 'userroles') {
1.1166 raeburn 5427: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5428: } else {
1.1219 raeburn 5429: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5430: if ($hidepriv) {
5431: my %coursehash=&coursedescription($udom.'_'.$uname);
5432: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5433: if ($user !~ /:/) {
5434: $nothide{join(':',split(/[\@]/,$user))} = 1;
5435: } else {
5436: $nothide{$user} = 1;
5437: }
5438: }
5439: }
1.858 raeburn 5440: }
1.400 www 5441: my %returnhash=();
5442: my $now=time;
1.999 raeburn 5443: my %privileged;
1.800 albertel 5444: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5445: my ($role,$tend,$tstart);
5446: if ($context eq 'userroles') {
1.1149 raeburn 5447: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5448: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5449: } else {
5450: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5451: }
1.400 www 5452: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5453: my $status = 'active';
1.939 raeburn 5454: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5455: $status = 'previous';
5456: }
5457: if (($tstart) && ($now<$tstart)) {
5458: $status = 'future';
5459: }
5460: if (ref($types) eq 'ARRAY') {
5461: if (!grep(/^\Q$status\E$/,@{$types})) {
5462: next;
5463: }
5464: } else {
5465: if ($status ne 'active') {
5466: next;
5467: }
5468: }
1.867 raeburn 5469: my ($rolecode,$username,$domain,$section,$area);
5470: if ($context eq 'userroles') {
1.1186 raeburn 5471: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5472: (undef,$domain,$username,$section) = split(/\//,$area);
5473: } else {
5474: ($role,$username,$domain,$section) = split(/\:/,$entry);
5475: }
1.832 raeburn 5476: if (ref($roledoms) eq 'ARRAY') {
5477: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5478: next;
5479: }
5480: }
5481: if (ref($roles) eq 'ARRAY') {
5482: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5483: if ($role =~ /^cr\//) {
5484: if (!grep(/^cr$/,@{$roles})) {
5485: next;
5486: }
1.1104 raeburn 5487: } elsif ($role =~ /^gr\//) {
5488: if (!grep(/^gr$/,@{$roles})) {
5489: next;
5490: }
1.922 raeburn 5491: } else {
5492: next;
5493: }
1.832 raeburn 5494: }
1.867 raeburn 5495: }
1.937 raeburn 5496: if ($hidepriv) {
1.1219 raeburn 5497: my @privroles = ('dc','su');
1.999 raeburn 5498: if ($context eq 'userroles') {
1.1219 raeburn 5499: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5500: } else {
1.1219 raeburn 5501: my $possdoms = [$domain];
5502: if (ref($roledoms) eq 'ARRAY') {
5503: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5504: }
1.1219 raeburn 5505: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5506: if (!$nothide{$username.':'.$domain}) {
5507: next;
5508: }
5509: }
1.937 raeburn 5510: }
5511: }
1.933 raeburn 5512: if ($withsec) {
5513: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5514: $tstart.':'.$tend;
5515: } else {
5516: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5517: }
1.832 raeburn 5518: }
1.373 www 5519: return %returnhash;
1.399 www 5520: }
5521:
1.1333 raeburn 5522: sub get_all_adhocroles {
5523: my ($dom) = @_;
5524: my @roles_by_num = ();
5525: my %domdefaults = &get_domain_defaults($dom);
5526: my (%description,%access_in_dom,%access_info);
5527: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5528: my $count = 0;
5529: my %domcurrent = %{$domdefaults{'adhocroles'}};
5530: my %ordered;
5531: foreach my $role (sort(keys(%domcurrent))) {
5532: my ($order,$desc,$access_in_dom);
5533: if (ref($domcurrent{$role}) eq 'HASH') {
5534: $order = $domcurrent{$role}{'order'};
5535: $desc = $domcurrent{$role}{'desc'};
5536: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5537: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5538: }
5539: if ($order eq '') {
5540: $order = $count;
5541: }
5542: $ordered{$order} = $role;
5543: if ($desc ne '') {
5544: $description{$role} = $desc;
5545: } else {
5546: $description{$role}= $role;
5547: }
5548: $count++;
5549: }
5550: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5551: push(@roles_by_num,$ordered{$item});
5552: }
5553: }
5554: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5555: }
5556:
1.1332 raeburn 5557: sub get_my_adhocroles {
1.1333 raeburn 5558: my ($cid,$checkreg) = @_;
5559: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5560: if ($env{'request.course.id'} eq $cid) {
5561: $cdom = $env{'course.'.$cid.'.domain'};
5562: $cnum = $env{'course.'.$cid.'.num'};
5563: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5564: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5565: $cdom = $1;
5566: $cnum = $2;
1.1494 raeburn 5567: %info = &get('environment',['internal.coursecode'],
5568: $cdom,$cnum);
1.1333 raeburn 5569: }
5570: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5571: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5572: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5573: if ($rosterhash{$user} ne '') {
5574: my $type = (split(/:/,$rosterhash{$user}))[5];
5575: return ([],{}) if ($type eq 'auto');
5576: }
5577: }
5578: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 5579: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 5580: my $then=$env{'user.login.time'};
5581: my $update=$env{'user.update.time'};
1.1335 raeburn 5582: if (!$update) {
5583: $update = $then;
5584: }
5585: my @liveroles;
1.1334 raeburn 5586: foreach my $role ('dh','da') {
5587: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 5588: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 5589: my $limit = $update;
5590: if ($env{'request.role'} eq "$role./$cdom/") {
5591: $limit = $then;
5592: }
1.1335 raeburn 5593: my $activerole = 1;
5594: if ($tstart && $tstart>$limit) { $activerole = 0; }
5595: if ($tend && $tend <$limit) { $activerole = 0; }
5596: if ($activerole) {
5597: push(@liveroles,$role);
5598: }
1.1334 raeburn 5599: }
1.1332 raeburn 5600: }
1.1335 raeburn 5601: if (@liveroles) {
1.1332 raeburn 5602: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 5603: my ($accessref,$accessinfo,%access_in_dom);
5604: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5605: if (ref($roles_by_num) eq 'ARRAY') {
5606: if (@{$roles_by_num}) {
1.1332 raeburn 5607: my %settings;
5608: if ($env{'request.course.id'} eq $cid) {
5609: foreach my $envkey (keys(%env)) {
5610: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5611: $settings{$1} = $env{$envkey};
5612: }
5613: }
5614: } else {
5615: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5616: }
5617: my %setincrs;
5618: if ($settings{'internal.adhocaccess'}) {
5619: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5620: }
5621: my @statuses;
5622: if ($env{'environment.inststatus'}) {
5623: @statuses = split(/,/,$env{'environment.inststatus'});
5624: }
5625: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 5626: if (ref($accessref) eq 'HASH') {
5627: %access_in_dom = %{$accessref};
5628: }
5629: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 5630: my ($curraccess,@okstatus,@personnel);
5631: if ($setincrs{$role}) {
5632: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5633: if ($curraccess eq 'status') {
5634: @okstatus = split(/\&/,$rest);
5635: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5636: @personnel = split(/\&/,$rest);
5637: }
5638: } else {
5639: $curraccess = $access_in_dom{$role};
1.1333 raeburn 5640: if (ref($accessinfo) eq 'HASH') {
5641: if ($curraccess eq 'status') {
5642: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5643: @okstatus = @{$accessinfo->{$role}};
5644: }
5645: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5646: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5647: @personnel = @{$accessinfo->{$role}};
5648: }
1.1332 raeburn 5649: }
5650: }
5651: }
5652: if ($curraccess eq 'none') {
5653: next;
5654: } elsif ($curraccess eq 'all') {
5655: push(@possroles,$role);
1.1336 raeburn 5656: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 5657: if (grep(/^dh$/,@liveroles)) {
5658: push(@possroles,$role);
5659: } else {
5660: next;
5661: }
1.1336 raeburn 5662: } elsif ($curraccess eq 'da') {
1.1335 raeburn 5663: if (grep(/^da$/,@liveroles)) {
5664: push(@possroles,$role);
5665: } else {
5666: next;
5667: }
1.1332 raeburn 5668: } elsif ($curraccess eq 'status') {
5669: if (@okstatus) {
5670: if (!@statuses) {
5671: if (grep(/^default$/,@okstatus)) {
5672: push(@possroles,$role);
5673: }
5674: } else {
5675: foreach my $status (@okstatus) {
5676: if (grep(/^\Q$status\E$/,@statuses)) {
5677: push(@possroles,$role);
5678: last;
5679: }
5680: }
5681: }
5682: }
5683: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5684: if (grep(/^\Q$user\E$/,@personnel)) {
5685: if ($curraccess eq 'exc') {
5686: push(@possroles,$role);
5687: }
5688: } elsif ($curraccess eq 'inc') {
5689: push(@possroles,$role);
5690: }
5691: }
5692: }
5693: }
5694: }
5695: }
5696: }
5697: }
5698: }
1.1333 raeburn 5699: unless (ref($description) eq 'HASH') {
5700: if (ref($roles_by_num) eq 'ARRAY') {
5701: my %desc;
5702: map { $desc{$_} = $_; } (@{$roles_by_num});
5703: $description = \%desc;
5704: } else {
5705: $description = {};
5706: }
5707: }
5708: return (\@possroles,$description);
1.1332 raeburn 5709: }
5710:
1.399 www 5711: # ----------------------------------------------------- Frontpage Announcements
5712: #
5713: #
5714:
5715: sub postannounce {
5716: my ($server,$text)=@_;
1.844 albertel 5717: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5718: unless ($text=~/\w/) { $text=''; }
5719: return &reply('setannounce:'.&escape($text),$server);
5720: }
5721:
5722: sub getannounce {
1.448 albertel 5723:
1.1359 raeburn 5724: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5725: my $announcement='';
1.800 albertel 5726: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5727: close($fh);
1.399 www 5728: if ($announcement=~/\w/) {
5729: return
5730: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5731: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5732: } else {
5733: return '';
5734: }
5735: } else {
5736: return '';
5737: }
1.351 www 5738: }
1.353 www 5739:
5740: # ---------------------------------------------------------- Course ID routines
5741: # Deal with domain's nohist_courseid.db files
5742: #
5743:
5744: sub courseidput {
1.921 raeburn 5745: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5746: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5747: my $outcome;
5748: if ($caller eq 'timeonly') {
5749: my $cids = '';
5750: foreach my $item (keys(%$storehash)) {
5751: $cids.=&escape($item).'&';
5752: }
5753: $cids=~s/\&$//;
5754: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5755: $coursehome);
5756: } else {
5757: my $items = '';
5758: foreach my $item (keys(%$storehash)) {
5759: $items.= &escape($item).'='.
5760: &freeze_escape($$storehash{$item}).'&';
5761: }
5762: $items=~s/\&$//;
5763: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5764: $coursehome);
1.918 raeburn 5765: }
5766: if ($outcome eq 'unknown_cmd') {
5767: my $what;
5768: foreach my $cid (keys(%$storehash)) {
5769: $what .= &escape($cid).'=';
1.921 raeburn 5770: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5771: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5772: }
5773: $what =~ s/\:$/&/;
5774: }
5775: $what =~ s/\&$//;
5776: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5777: } else {
5778: return $outcome;
5779: }
1.353 www 5780: }
5781:
5782: sub courseiddump {
1.921 raeburn 5783: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5784: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5785: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 5786: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 5787: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5788: my $as_hash = 1;
5789: my %returnhash;
5790: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5791: my %libserv = &all_library();
5792: foreach my $tryserver (keys(%libserv)) {
5793: if ( ( $hostidflag == 1
5794: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5795: || (!defined($hostidflag)) ) {
5796:
1.918 raeburn 5797: if (($domfilter eq '') ||
5798: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 5799: my $rep;
5800: if (grep { $_ eq $tryserver } current_machine_ids()) {
5801: $rep = LONCAPA::Lond::dump_course_id_handler(
5802: join(":", (&host_domain($tryserver), $sincefilter,
5803: &escape($descfilter), &escape($instcodefilter),
5804: &escape($ownerfilter), &escape($coursefilter),
5805: &escape($typefilter), &escape($regexp_ok),
5806: $as_hash, &escape($selfenrollonly),
5807: &escape($catfilter), $showhidden, $caller,
5808: &escape($cloner), &escape($cc_clone), $cloneonly,
5809: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 5810: &escape($creationcontext),$domcloner,$hasuniquecode,
5811: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 5812: } else {
5813: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5814: $sincefilter.':'.&escape($descfilter).':'.
5815: &escape($instcodefilter).':'.&escape($ownerfilter).
5816: ':'.&escape($coursefilter).':'.&escape($typefilter).
5817: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5818: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5819: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5820: &escape($cc_clone).':'.$cloneonly.':'.
5821: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 5822: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5823: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 5824: }
5825:
1.918 raeburn 5826: my @pairs=split(/\&/,$rep);
5827: foreach my $item (@pairs) {
5828: my ($key,$value)=split(/\=/,$item,2);
5829: $key = &unescape($key);
5830: next if ($key =~ /^error: 2 /);
5831: my $result = &thaw_unescape($value);
5832: if (ref($result) eq 'HASH') {
5833: $returnhash{$key}=$result;
5834: } else {
1.921 raeburn 5835: my @responses = split(/:/,$value);
5836: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5837: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5838: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5839: }
1.1008 raeburn 5840: }
1.353 www 5841: }
5842: }
5843: }
5844: }
5845: return %returnhash;
5846: }
5847:
1.1055 raeburn 5848: sub courselastaccess {
5849: my ($cdom,$cnum,$hostidref) = @_;
5850: my %returnhash;
5851: if ($cdom && $cnum) {
5852: my $chome = &homeserver($cnum,$cdom);
5853: if ($chome ne 'no_host') {
5854: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5855: &extract_lastaccess(\%returnhash,$rep);
5856: }
5857: } else {
5858: if (!$cdom) { $cdom=''; }
5859: my %libserv = &all_library();
5860: foreach my $tryserver (keys(%libserv)) {
5861: if (ref($hostidref) eq 'ARRAY') {
5862: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5863: }
5864: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5865: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5866: &extract_lastaccess(\%returnhash,$rep);
5867: }
5868: }
5869: }
5870: return %returnhash;
5871: }
5872:
5873: sub extract_lastaccess {
5874: my ($returnhash,$rep) = @_;
5875: if (ref($returnhash) eq 'HASH') {
5876: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5877: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5878: $rep eq '') {
5879: my @pairs=split(/\&/,$rep);
5880: foreach my $item (@pairs) {
5881: my ($key,$value)=split(/\=/,$item,2);
5882: $key = &unescape($key);
5883: next if ($key =~ /^error: 2 /);
5884: $returnhash->{$key} = &thaw_unescape($value);
5885: }
5886: }
5887: }
5888: return;
5889: }
5890:
1.658 raeburn 5891: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5892:
5893: sub dcmailput {
1.685 raeburn 5894: my ($domain,$msgid,$message,$server)=@_;
1.1494 raeburn 5895: my $status = &critical(
1.740 www 5896: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5897: &escape($message),$server);
1.662 raeburn 5898: return $status;
5899: }
5900:
1.658 raeburn 5901: sub dcmaildump {
5902: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5903: my %returnhash=();
1.846 albertel 5904:
5905: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5906: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5907: &escape($enddate).':';
5908: my @esc_senders=map { &escape($_)} @$senders;
5909: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5910: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5911: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5912: if (($key) && ($value)) {
5913: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5914: }
5915: }
5916: }
5917: return %returnhash;
5918: }
1.662 raeburn 5919: # ---------------------------------------------------------- Domain roles
5920:
5921: sub get_domain_roles {
5922: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5923: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5924: $startdate = '.';
5925: }
1.1018 raeburn 5926: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5927: $enddate = '.';
5928: }
1.922 raeburn 5929: my $rolelist;
5930: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 5931: $rolelist = join('&',@{$roles});
1.922 raeburn 5932: }
1.662 raeburn 5933: my %personnel = ();
1.841 albertel 5934:
5935: my %servers = &get_servers($dom,'library');
5936: foreach my $tryserver (keys(%servers)) {
5937: %{$personnel{$tryserver}}=();
5938: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5939: &escape($startdate).':'.
5940: &escape($enddate).':'.
5941: &escape($rolelist), $tryserver))) {
5942: my ($key,$value) = split(/\=/,$line,2);
5943: if (($key) && ($value)) {
5944: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5945: }
5946: }
1.662 raeburn 5947: }
5948: return %personnel;
5949: }
1.658 raeburn 5950:
1.1332 raeburn 5951: sub get_active_domroles {
5952: my ($dom,$roles) = @_;
5953: return () unless (ref($roles) eq 'ARRAY');
5954: my $now = time;
5955: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5956: my %domroles;
5957: foreach my $server (keys(%dompersonnel)) {
5958: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5959: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5960: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5961: }
5962: }
5963: return %domroles;
5964: }
5965:
1.1057 www 5966: # ----------------------------------------------------------- Interval timing
1.149 www 5967:
1.1153 www 5968: {
5969: # Caches needed for speedup of navmaps
5970: # We don't want to cache this for very long at all (5 seconds at most)
5971: #
5972: # The user for whom we cache
5973: my $cachedkey='';
5974: # The cached times for this user
5975: my %cachedtimes=();
5976: # When this was last done
1.1282 raeburn 5977: my $cachedtime='';
1.1153 www 5978:
5979: sub load_all_first_access {
1.1308 raeburn 5980: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5981: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 5982: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5983: (!$ignorecache)) {
1.1154 raeburn 5984: return;
5985: }
5986: $cachedtime=time;
5987: $cachedkey=$uname.':'.$udom;
5988: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5989: }
5990:
1.504 albertel 5991: sub get_first_access {
1.1308 raeburn 5992: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5993: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5994: if ($argsymb) { $symb=$argsymb; }
5995: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5996: if ($argmap) { $map = $argmap; }
1.926 albertel 5997: if ($type eq 'course') {
5998: $res='course';
5999: } elsif ($type eq 'map') {
1.588 albertel 6000: $res=&symbread($map);
6001: } else {
6002: $res=$symb;
6003: }
1.1308 raeburn 6004: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 6005: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 6006: }
6007:
6008: sub set_first_access {
1.1162 raeburn 6009: my ($type,$interval)=@_;
1.790 albertel 6010: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 6011: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 6012: if ($type eq 'course') {
6013: $res='course';
6014: } elsif ($type eq 'map') {
1.588 albertel 6015: $res=&symbread($map);
6016: } else {
6017: $res=$symb;
6018: }
1.1153 www 6019: $cachedkey='';
1.1162 raeburn 6020: my $firstaccess=&get_first_access($type,$symb,$map);
1.1386 raeburn 6021: if ($firstaccess) {
6022: &logthis("First access time already set ($firstaccess) when attempting ".
1.1393 raeburn 6023: "to set new value (type: $type, extent: $res) for $uname:$udom ".
6024: "in $courseid");
1.1386 raeburn 6025: return 'already_set';
6026: } else {
1.1162 raeburn 6027: my $start = time;
6028: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
6029: $udom,$uname);
6030: if ($putres eq 'ok') {
6031: &put('timerinterval',{"$courseid\0$res"=>$interval},
6032: $udom,$uname);
6033: &appenv(
6034: {
6035: 'course.'.$courseid.'.firstaccess.'.$res => $start,
6036: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
6037: }
6038: );
1.1365 raeburn 6039: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
6040: $cachedtimes{"$courseid\0$res"} = $start;
6041: }
1.1386 raeburn 6042: } elsif ($putres ne 'refused') {
6043: &logthis("Result: $putres when attempting to set first access time ".
6044: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 6045: }
6046: return $putres;
1.505 albertel 6047: }
6048: return 'already_set';
1.504 albertel 6049: }
1.1153 www 6050: }
1.1282 raeburn 6051:
1.110 www 6052: # --------------------------------------------- Set Expire Date for Spreadsheet
6053:
6054: sub expirespread {
6055: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 6056: my $cid=$env{'request.course.id'};
1.110 www 6057: if ($cid) {
6058: my $now=time;
6059: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 6060: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
6061: $env{'course.'.$cid.'.num'}.
1.110 www 6062: ':nohist_expirationdates:'.
6063: &escape($key).'='.$now,
1.620 albertel 6064: $env{'course.'.$cid.'.home'})
1.110 www 6065: }
6066: return 'ok';
1.14 www 6067: }
6068:
1.109 www 6069: # ----------------------------------------------------- Devalidate Spreadsheets
6070:
6071: sub devalidate {
1.325 www 6072: my ($symb,$uname,$udom)=@_;
1.620 albertel 6073: my $cid=$env{'request.course.id'};
1.109 www 6074: if ($cid) {
1.391 matthew 6075: # delete the stored spreadsheets for
6076: # - the student level sheet of this user in course's homespace
6077: # - the assessment level sheet for this resource
6078: # for this user in user's homespace
1.553 albertel 6079: # - current conditional state info
1.325 www 6080: my $key=$uname.':'.$udom.':';
1.109 www 6081: my $status=
1.299 matthew 6082: &del('nohist_calculatedsheets',
1.391 matthew 6083: [$key.'studentcalc:'],
1.620 albertel 6084: $env{'course.'.$cid.'.domain'},
6085: $env{'course.'.$cid.'.num'})
1.133 albertel 6086: .' '.
6087: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 6088: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 6089: unless ($status eq 'ok ok') {
6090: &logthis('Could not devalidate spreadsheet '.
1.325 www 6091: $uname.' at '.$udom.' for '.
1.109 www 6092: $symb.': '.$status);
1.133 albertel 6093: }
1.553 albertel 6094: &delenv('user.state.'.$cid);
1.109 www 6095: }
6096: }
6097:
1.265 albertel 6098: sub get_scalar {
6099: my ($string,$end) = @_;
6100: my $value;
6101: if ($$string =~ s/^([^&]*?)($end)/$2/) {
6102: $value = $1;
6103: } elsif ($$string =~ s/^([^&]*?)&//) {
6104: $value = $1;
6105: }
6106: return &unescape($value);
6107: }
6108:
6109: sub array2str {
6110: my (@array) = @_;
6111: my $result=&arrayref2str(\@array);
6112: $result=~s/^__ARRAY_REF__//;
6113: $result=~s/__END_ARRAY_REF__$//;
6114: return $result;
6115: }
6116:
1.204 albertel 6117: sub arrayref2str {
6118: my ($arrayref) = @_;
1.265 albertel 6119: my $result='__ARRAY_REF__';
1.204 albertel 6120: foreach my $elem (@$arrayref) {
1.265 albertel 6121: if(ref($elem) eq 'ARRAY') {
6122: $result.=&arrayref2str($elem).'&';
6123: } elsif(ref($elem) eq 'HASH') {
6124: $result.=&hashref2str($elem).'&';
6125: } elsif(ref($elem)) {
6126: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 6127: } else {
6128: $result.=&escape($elem).'&';
6129: }
6130: }
6131: $result=~s/\&$//;
1.265 albertel 6132: $result .= '__END_ARRAY_REF__';
1.204 albertel 6133: return $result;
6134: }
6135:
1.168 albertel 6136: sub hash2str {
1.204 albertel 6137: my (%hash) = @_;
6138: my $result=&hashref2str(\%hash);
1.265 albertel 6139: $result=~s/^__HASH_REF__//;
6140: $result=~s/__END_HASH_REF__$//;
1.204 albertel 6141: return $result;
6142: }
6143:
6144: sub hashref2str {
6145: my ($hashref)=@_;
1.265 albertel 6146: my $result='__HASH_REF__';
1.800 albertel 6147: foreach my $key (sort(keys(%$hashref))) {
6148: if (ref($key) eq 'ARRAY') {
6149: $result.=&arrayref2str($key).'=';
6150: } elsif (ref($key) eq 'HASH') {
6151: $result.=&hashref2str($key).'=';
6152: } elsif (ref($key)) {
1.265 albertel 6153: $result.='=';
1.800 albertel 6154: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 6155: } else {
1.1132 raeburn 6156: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 6157: }
6158:
1.800 albertel 6159: if(ref($hashref->{$key}) eq 'ARRAY') {
6160: $result.=&arrayref2str($hashref->{$key}).'&';
6161: } elsif(ref($hashref->{$key}) eq 'HASH') {
6162: $result.=&hashref2str($hashref->{$key}).'&';
6163: } elsif(ref($hashref->{$key})) {
1.265 albertel 6164: $result.='&';
1.800 albertel 6165: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 6166: } else {
1.800 albertel 6167: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 6168: }
6169: }
1.168 albertel 6170: $result=~s/\&$//;
1.265 albertel 6171: $result .= '__END_HASH_REF__';
1.168 albertel 6172: return $result;
6173: }
6174:
6175: sub str2hash {
1.265 albertel 6176: my ($string)=@_;
6177: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
6178: return %$hash;
6179: }
6180:
6181: sub str2hashref {
1.168 albertel 6182: my ($string) = @_;
1.265 albertel 6183:
6184: my %hash;
6185:
6186: if($string !~ /^__HASH_REF__/) {
6187: if (! ($string eq '' || !defined($string))) {
6188: $hash{'error'}='Not hash reference';
6189: }
6190: return (\%hash, $string);
6191: }
6192:
6193: $string =~ s/^__HASH_REF__//;
6194:
6195: while($string !~ /^__END_HASH_REF__/) {
6196: #key
6197: my $key='';
6198: if($string =~ /^__HASH_REF__/) {
6199: ($key, $string)=&str2hashref($string);
6200: if(defined($key->{'error'})) {
6201: $hash{'error'}='Bad data';
6202: return (\%hash, $string);
6203: }
6204: } elsif($string =~ /^__ARRAY_REF__/) {
6205: ($key, $string)=&str2arrayref($string);
6206: if($key->[0] eq 'Array reference error') {
6207: $hash{'error'}='Bad data';
6208: return (\%hash, $string);
6209: }
6210: } else {
6211: $string =~ s/^(.*?)=//;
1.267 albertel 6212: $key=&unescape($1);
1.265 albertel 6213: }
6214: $string =~ s/^=//;
6215:
6216: #value
6217: my $value='';
6218: if($string =~ /^__HASH_REF__/) {
6219: ($value, $string)=&str2hashref($string);
6220: if(defined($value->{'error'})) {
6221: $hash{'error'}='Bad data';
6222: return (\%hash, $string);
6223: }
6224: } elsif($string =~ /^__ARRAY_REF__/) {
6225: ($value, $string)=&str2arrayref($string);
6226: if($value->[0] eq 'Array reference error') {
6227: $hash{'error'}='Bad data';
6228: return (\%hash, $string);
6229: }
6230: } else {
6231: $value=&get_scalar(\$string,'__END_HASH_REF__');
6232: }
6233: $string =~ s/^&//;
6234:
6235: $hash{$key}=$value;
1.204 albertel 6236: }
1.265 albertel 6237:
6238: $string =~ s/^__END_HASH_REF__//;
6239:
6240: return (\%hash, $string);
1.204 albertel 6241: }
6242:
6243: sub str2array {
1.265 albertel 6244: my ($string)=@_;
6245: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
6246: return @$array;
6247: }
6248:
6249: sub str2arrayref {
1.204 albertel 6250: my ($string) = @_;
1.265 albertel 6251: my @array;
6252:
6253: if($string !~ /^__ARRAY_REF__/) {
6254: if (! ($string eq '' || !defined($string))) {
6255: $array[0]='Array reference error';
6256: }
6257: return (\@array, $string);
6258: }
6259:
6260: $string =~ s/^__ARRAY_REF__//;
6261:
6262: while($string !~ /^__END_ARRAY_REF__/) {
6263: my $value='';
6264: if($string =~ /^__HASH_REF__/) {
6265: ($value, $string)=&str2hashref($string);
6266: if(defined($value->{'error'})) {
6267: $array[0] ='Array reference error';
6268: return (\@array, $string);
6269: }
6270: } elsif($string =~ /^__ARRAY_REF__/) {
6271: ($value, $string)=&str2arrayref($string);
6272: if($value->[0] eq 'Array reference error') {
6273: $array[0] ='Array reference error';
6274: return (\@array, $string);
6275: }
6276: } else {
6277: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6278: }
6279: $string =~ s/^&//;
6280:
6281: push(@array, $value);
1.191 harris41 6282: }
1.265 albertel 6283:
6284: $string =~ s/^__END_ARRAY_REF__//;
6285:
6286: return (\@array, $string);
1.168 albertel 6287: }
6288:
1.167 albertel 6289: # -------------------------------------------------------------------Temp Store
6290:
1.168 albertel 6291: sub tmpreset {
6292: my ($symb,$namespace,$domain,$stuname) = @_;
6293: if (!$symb) {
6294: $symb=&symbread();
1.620 albertel 6295: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6296: }
6297: $symb=escape($symb);
6298:
1.620 albertel 6299: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 6300: $namespace=~s/\//\_/g;
6301: $namespace=~s/\W//g;
6302:
1.620 albertel 6303: if (!$domain) { $domain=$env{'user.domain'}; }
6304: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6305: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6306: $stuname=&get_requestor_ip();
1.591 albertel 6307: }
1.1117 foxr 6308: my $path=LONCAPA::tempdir();
1.168 albertel 6309: my %hash;
6310: if (tie(%hash,'GDBM_File',
6311: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6312: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 6313: foreach my $key (keys(%hash)) {
1.180 albertel 6314: if ($key=~ /:$symb/) {
1.168 albertel 6315: delete($hash{$key});
6316: }
6317: }
6318: }
6319: }
6320:
1.167 albertel 6321: sub tmpstore {
1.168 albertel 6322: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6323:
6324: if (!$symb) {
6325: $symb=&symbread();
1.620 albertel 6326: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6327: }
6328: $symb=escape($symb);
6329:
6330: if (!$namespace) {
6331: # I don't think we would ever want to store this for a course.
6332: # it seems this will only be used if we don't have a course.
1.620 albertel 6333: #$namespace=$env{'request.course.id'};
1.168 albertel 6334: #if (!$namespace) {
1.620 albertel 6335: $namespace=$env{'request.state'};
1.168 albertel 6336: #}
6337: }
6338: $namespace=~s/\//\_/g;
6339: $namespace=~s/\W//g;
1.620 albertel 6340: if (!$domain) { $domain=$env{'user.domain'}; }
6341: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6342: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6343: $stuname=&get_requestor_ip();
1.591 albertel 6344: }
1.168 albertel 6345: my $now=time;
6346: my %hash;
1.1117 foxr 6347: my $path=LONCAPA::tempdir();
1.168 albertel 6348: if (tie(%hash,'GDBM_File',
6349: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6350: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6351: $hash{"version:$symb"}++;
6352: my $version=$hash{"version:$symb"};
6353: my $allkeys='';
6354: foreach my $key (keys(%$storehash)) {
6355: $allkeys.=$key.':';
1.591 albertel 6356: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6357: }
6358: $hash{"$version:$symb:timestamp"}=$now;
6359: $allkeys.='timestamp';
6360: $hash{"$version:keys:$symb"}=$allkeys;
6361: if (untie(%hash)) {
6362: return 'ok';
6363: } else {
6364: return "error:$!";
6365: }
6366: } else {
6367: return "error:$!";
6368: }
6369: }
1.167 albertel 6370:
1.168 albertel 6371: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6372:
1.168 albertel 6373: sub tmprestore {
6374: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6375:
1.168 albertel 6376: if (!$symb) {
6377: $symb=&symbread();
1.620 albertel 6378: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6379: }
6380: $symb=escape($symb);
6381:
1.620 albertel 6382: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6383:
1.620 albertel 6384: if (!$domain) { $domain=$env{'user.domain'}; }
6385: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6386: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6387: $stuname=&get_requestor_ip();
1.591 albertel 6388: }
1.168 albertel 6389: my %returnhash;
6390: $namespace=~s/\//\_/g;
6391: $namespace=~s/\W//g;
6392: my %hash;
1.1117 foxr 6393: my $path=LONCAPA::tempdir();
1.168 albertel 6394: if (tie(%hash,'GDBM_File',
6395: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6396: &GDBM_READER(),0640)) {
1.168 albertel 6397: my $version=$hash{"version:$symb"};
6398: $returnhash{'version'}=$version;
6399: my $scope;
6400: for ($scope=1;$scope<=$version;$scope++) {
6401: my $vkeys=$hash{"$scope:keys:$symb"};
6402: my @keys=split(/:/,$vkeys);
6403: my $key;
6404: $returnhash{"$scope:keys"}=$vkeys;
6405: foreach $key (@keys) {
1.591 albertel 6406: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6407: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6408: }
6409: }
1.168 albertel 6410: if (!(untie(%hash))) {
6411: return "error:$!";
6412: }
6413: } else {
6414: return "error:$!";
6415: }
6416: return %returnhash;
1.167 albertel 6417: }
6418:
1.9 www 6419: # ----------------------------------------------------------------------- Store
6420:
6421: sub store {
1.1269 raeburn 6422: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6423: my $home='';
6424:
1.168 albertel 6425: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6426:
1.213 www 6427: $symb=&symbclean($symb);
1.122 albertel 6428: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6429:
1.620 albertel 6430: if (!$domain) { $domain=$env{'user.domain'}; }
6431: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6432:
6433: &devalidate($symb,$stuname,$domain);
1.109 www 6434:
6435: $symb=escape($symb);
1.187 www 6436: if (!$namespace) {
1.620 albertel 6437: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6438: return '';
6439: }
6440: }
1.620 albertel 6441: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6442:
1.1434 raeburn 6443: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6444: $$storehash{'host'}=$perlvar{'lonHostID'};
6445:
1.12 www 6446: my $namevalue='';
1.800 albertel 6447: foreach my $key (keys(%$storehash)) {
6448: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6449: }
1.12 www 6450: $namevalue=~s/\&$//;
1.187 www 6451: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 6452: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6453: }
6454:
1.47 www 6455: # -------------------------------------------------------------- Critical Store
6456:
6457: sub cstore {
1.1269 raeburn 6458: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6459: my $home='';
6460:
1.168 albertel 6461: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6462:
1.213 www 6463: $symb=&symbclean($symb);
1.122 albertel 6464: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6465:
1.620 albertel 6466: if (!$domain) { $domain=$env{'user.domain'}; }
6467: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6468:
6469: &devalidate($symb,$stuname,$domain);
1.109 www 6470:
6471: $symb=escape($symb);
1.187 www 6472: if (!$namespace) {
1.620 albertel 6473: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6474: return '';
6475: }
6476: }
1.620 albertel 6477: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6478:
1.1434 raeburn 6479: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6480: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6481:
1.47 www 6482: my $namevalue='';
1.800 albertel 6483: foreach my $key (keys(%$storehash)) {
6484: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6485: }
1.47 www 6486: $namevalue=~s/\&$//;
1.187 www 6487: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6488: return critical
1.1269 raeburn 6489: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6490: }
6491:
1.9 www 6492: # --------------------------------------------------------------------- Restore
6493:
6494: sub restore {
1.124 www 6495: my ($symb,$namespace,$domain,$stuname) = @_;
6496: my $home='';
6497:
1.168 albertel 6498: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6499:
1.122 albertel 6500: if (!$symb) {
1.1224 raeburn 6501: return if ($namespace eq 'courserequests');
6502: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6503: } else {
1.1224 raeburn 6504: unless ($namespace eq 'courserequests') {
6505: $symb=&escape(&symbclean($symb));
6506: }
1.122 albertel 6507: }
1.188 www 6508: if (!$namespace) {
1.620 albertel 6509: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6510: return '';
6511: }
6512: }
1.620 albertel 6513: if (!$domain) { $domain=$env{'user.domain'}; }
6514: if (!$stuname) { $stuname=$env{'user.name'}; }
6515: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6516: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6517:
1.12 www 6518: my %returnhash=();
1.800 albertel 6519: foreach my $line (split(/\&/,$answer)) {
6520: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6521: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6522: }
1.75 www 6523: my $version;
6524: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6525: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6526: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6527: }
1.75 www 6528: }
1.13 www 6529: return %returnhash;
1.34 www 6530: }
6531:
6532: # ---------------------------------------------------------- Course Description
1.1118 foxr 6533: #
6534: #
1.34 www 6535:
6536: sub coursedescription {
1.731 albertel 6537: my ($courseid,$args)=@_;
1.34 www 6538: $courseid=~s/^\///;
1.49 www 6539: $courseid=~s/\_/\//g;
1.34 www 6540: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6541: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6542: my $normalid=$cdomain.'_'.$cnum;
6543: # need to always cache even if we get errors otherwise we keep
6544: # trying and trying and trying to get the course description.
6545: my %envhash=();
6546: my %returnhash=();
1.731 albertel 6547:
6548: my $expiretime=600;
6549: if ($env{'request.course.id'} eq $normalid) {
6550: $expiretime=120;
6551: }
6552:
6553: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6554: if (!$args->{'freshen_cache'}
6555: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6556: foreach my $key (keys(%env)) {
6557: next if ($key !~ /^\Q$prefix\E(.*)/);
6558: my ($setting) = $1;
6559: $returnhash{$setting} = $env{$key};
6560: }
6561: return %returnhash;
6562: }
6563:
1.1118 foxr 6564: # get the data again
6565:
1.731 albertel 6566: if (!$args->{'one_time'}) {
6567: $envhash{'course.'.$normalid.'.last_cache'}=time;
6568: }
1.811 albertel 6569:
1.34 www 6570: if ($chome ne 'no_host') {
1.302 albertel 6571: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6572: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6573: my $username = $env{'user.name'}; # Defult username
6574: if(defined $args->{'user'}) {
6575: $username = $args->{'user'};
6576: }
1.129 albertel 6577: $returnhash{'home'}= $chome;
6578: $returnhash{'domain'} = $cdomain;
6579: $returnhash{'num'} = $cnum;
1.741 raeburn 6580: if (!defined($returnhash{'type'})) {
6581: $returnhash{'type'} = 'Course';
6582: }
1.130 albertel 6583: while (my ($name,$value) = each %returnhash) {
1.53 www 6584: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6585: }
1.270 www 6586: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6587: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6588: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6589: $envhash{'course.'.$normalid.'.home'}=$chome;
6590: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6591: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6592: }
6593: }
1.731 albertel 6594: if (!$args->{'one_time'}) {
1.949 raeburn 6595: &appenv(\%envhash);
1.731 albertel 6596: }
1.302 albertel 6597: return %returnhash;
1.461 www 6598: }
6599:
1.1080 raeburn 6600: sub update_released_required {
6601: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6602: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6603: $cid = $env{'request.course.id'};
6604: $cdom = $env{'course.'.$cid.'.domain'};
6605: $cnum = $env{'course.'.$cid.'.num'};
6606: $chome = $env{'course.'.$cid.'.home'};
6607: }
6608: if ($needsrelease) {
6609: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6610: my $needsupdate;
6611: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6612: $needsupdate = 1;
6613: } else {
6614: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6615: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6616: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6617: $needsupdate = 1;
6618: }
6619: }
6620: if ($needsupdate) {
6621: my %needshash = (
6622: 'internal.releaserequired' => $needsrelease,
6623: );
6624: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6625: if ($putresult eq 'ok') {
6626: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6627: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6628: if (ref($crsinfo{$cid}) eq 'HASH') {
6629: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6630: &courseidput($cdom,\%crsinfo,$chome,'notime');
6631: }
6632: }
6633: }
6634: }
6635: return;
6636: }
6637:
1.461 www 6638: # -------------------------------------------------See if a user is privileged
6639:
6640: sub privileged {
1.1219 raeburn 6641: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6642: my $now = time;
1.1219 raeburn 6643: my $roles;
6644: if (ref($possroles) eq 'ARRAY') {
6645: $roles = $possroles;
6646: } else {
6647: $roles = ['dc','su'];
6648: }
6649: if (ref($possdomains) eq 'ARRAY') {
6650: my %privileged = &privileged_by_domain($possdomains,$roles);
6651: foreach my $dom (@{$possdomains}) {
6652: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6653: (ref($privileged{$dom}) eq 'HASH')) {
6654: foreach my $role (@{$roles}) {
6655: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6656: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6657: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6658: return 1 unless (($end && $end < $now) ||
6659: ($start && $start > $now));
6660: }
6661: }
6662: }
6663: }
6664: }
6665: } else {
6666: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6667: my $now = time;
1.1170 droeschl 6668:
1.1275 musolffc 6669: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6670: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 6671: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 6672: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 6673: or ($tstart && $tstart > $now);
1.1170 droeschl 6674: }
1.1219 raeburn 6675: }
6676: }
6677: return 0;
6678: }
1.1170 droeschl 6679:
1.1219 raeburn 6680: sub privileged_by_domain {
6681: my ($domains,$roles) = @_;
6682: my %privileged = ();
6683: my $cachetime = 60*60*24;
6684: my $now = time;
6685: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6686: return %privileged;
6687: }
6688: foreach my $dom (@{$domains}) {
6689: next if (ref($privileged{$dom}) eq 'HASH');
6690: my $needroles;
6691: foreach my $role (@{$roles}) {
6692: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6693: if (defined($cached)) {
6694: if (ref($result) eq 'HASH') {
6695: $privileged{$dom}{$role} = $result;
6696: }
6697: } else {
6698: $needroles = 1;
6699: }
6700: }
6701: if ($needroles) {
6702: my %dompersonnel = &get_domain_roles($dom,$roles);
6703: $privileged{$dom} = {};
6704: foreach my $server (keys(%dompersonnel)) {
6705: if (ref($dompersonnel{$server}) eq 'HASH') {
6706: foreach my $item (keys(%{$dompersonnel{$server}})) {
6707: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6708: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6709: next if ($end && $end < $now);
6710: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6711: $dompersonnel{$server}{$item};
6712: }
6713: }
6714: }
6715: if (ref($privileged{$dom}) eq 'HASH') {
6716: foreach my $role (@{$roles}) {
6717: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6718: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6719: } else {
6720: my %hash = ();
6721: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6722: }
6723: }
6724: }
6725: }
6726: }
6727: return %privileged;
1.9 www 6728: }
1.1 albertel 6729:
1.103 harris41 6730: # -------------------------------------------------------- Get user privileges
1.11 www 6731:
6732: sub rolesinit {
1.1169 droeschl 6733: my ($domain, $username) = @_;
6734: my %userroles = ('user.login.time' => time);
6735: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6736:
6737: # firstaccess and timerinterval are related to timed maps/resources.
6738: # also, blocking can be triggered by an activating timer
6739: # it's saved in the user's %env.
6740: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6741: my %timerinterval = &dump('timerinterval', $domain, $username);
6742: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6743: %timerintchk, %timerintenv);
6744:
1.1162 raeburn 6745: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6746: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6747: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6748: }
1.1169 droeschl 6749:
1.1162 raeburn 6750: foreach my $key (keys(%timerinterval)) {
6751: my ($cid,$rest) = split(/\0/,$key);
6752: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6753: }
1.1169 droeschl 6754:
1.11 www 6755: my %allroles=();
1.1162 raeburn 6756: my %allgroups=();
1.11 www 6757:
1.1274 raeburn 6758: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6759: my $role = $rolesdump{$area};
6760: $area =~ s/\_\w\w$//;
6761:
6762: my ($trole, $tend, $tstart, $group_privs);
6763:
6764: if ($role =~ /^cr/) {
6765: # Custom role, defined by a user
6766: # e.g., user.role.cr/msu/smith/mynewrole
6767: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6768: $trole = $1;
6769: ($tend, $tstart) = split('_', $2);
6770: } else {
6771: $trole = $role;
6772: }
6773: } elsif ($role =~ m|^gr/|) {
6774: # Role of member in a group, defined within a course/community
6775: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6776: ($trole, $tend, $tstart) = split(/_/, $role);
6777: next if $tstart eq '-1';
6778: ($trole, $group_privs) = split(/\//, $trole);
6779: $group_privs = &unescape($group_privs);
6780: } else {
6781: # Just a normal role, defined in roles.tab
6782: ($trole, $tend, $tstart) = split(/_/,$role);
6783: }
6784:
6785: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6786: $username);
6787: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6788:
6789: # role expired or not available yet?
6790: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6791: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6792:
6793: next if $area eq '' or $trole eq '';
6794:
6795: my $spec = "$trole.$area";
6796: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6797:
6798: if ($trole =~ /^cr\//) {
6799: # Custom role, defined by a user
6800: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6801: } elsif ($trole eq 'gr') {
6802: # Role of a member in a group, defined within a course/community
6803: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6804: next;
6805: } else {
6806: # Normal role, defined in roles.tab
6807: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6808: }
6809:
6810: my $cid = $tdomain.'_'.$trest;
6811: unless ($firstaccchk{$cid}) {
6812: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6813: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6814: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6815: $coursetimerstarts{$cid}{$item};
6816: }
6817: }
6818: $firstaccchk{$cid} = 1;
6819: }
6820: unless ($timerintchk{$cid}) {
6821: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6822: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6823: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6824: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6825: }
1.12 www 6826: }
1.1169 droeschl 6827: $timerintchk{$cid} = 1;
1.191 harris41 6828: }
1.11 www 6829: }
1.1169 droeschl 6830:
1.1341 raeburn 6831: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6832: \%allroles, \%allgroups);
1.1169 droeschl 6833: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 6834: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6835:
1.1162 raeburn 6836: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6837: }
6838:
1.567 raeburn 6839: sub set_arearole {
1.1215 raeburn 6840: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6841: unless ($nolog) {
1.567 raeburn 6842: # log the associated role with the area
1.1215 raeburn 6843: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6844: }
1.743 albertel 6845: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6846: }
6847:
6848: sub custom_roleprivs {
6849: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6850: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 6851: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6852: if (&hostname($homsvr) ne '') {
1.567 raeburn 6853: my ($rdummy,$roledef)=
6854: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6855: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6856: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6857: if (defined($syspriv)) {
1.1043 raeburn 6858: if ($trest =~ /^$match_community$/) {
6859: $syspriv =~ s/bre\&S//;
6860: }
1.567 raeburn 6861: $$allroles{'cm./'}.=':'.$syspriv;
6862: $$allroles{$spec.'./'}.=':'.$syspriv;
6863: }
6864: if ($tdomain ne '') {
6865: if (defined($dompriv)) {
6866: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6867: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6868: }
6869: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 6870: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6871: my $rolename = $1;
6872: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6873: }
1.567 raeburn 6874: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6875: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6876: }
6877: }
6878: }
6879: }
6880: }
6881:
1.1332 raeburn 6882: sub course_adhocrole_privs {
6883: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6884: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6885: if ($overrides{"internal.adhocpriv.$rolename"}) {
6886: my (%currprivs,%storeprivs);
6887: foreach my $item (split(/:/,$coursepriv)) {
6888: my ($priv,$restrict) = split(/\&/,$item);
6889: $currprivs{$priv} = $restrict;
6890: }
6891: my (%possadd,%possremove,%full);
6892: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6893: my ($priv,$restrict)=split(/\&/,$item);
6894: $full{$priv} = $restrict;
6895: }
6896: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1490 raeburn 6897: next if ($item eq '');
6898: my ($rule,$rest) = split(/=/,$item);
6899: next unless (($rule eq 'off') || ($rule eq 'on'));
6900: foreach my $priv (split(/:/,$rest)) {
6901: if ($priv ne '') {
6902: if ($rule eq 'off') {
6903: $possremove{$priv} = 1;
6904: } else {
6905: $possadd{$priv} = 1;
6906: }
6907: }
6908: }
6909: }
6910: foreach my $priv (sort(keys(%full))) {
6911: if (exists($currprivs{$priv})) {
6912: unless (exists($possremove{$priv})) {
6913: $storeprivs{$priv} = $currprivs{$priv};
6914: }
6915: } elsif (exists($possadd{$priv})) {
6916: $storeprivs{$priv} = $full{$priv};
6917: }
6918: }
6919: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6920: }
6921: return $coursepriv;
1.1332 raeburn 6922: }
6923:
1.678 raeburn 6924: sub group_roleprivs {
6925: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6926: my $access = 1;
6927: my $now = time;
6928: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6929: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6930: if ($access) {
1.811 albertel 6931: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6932: $$allgroups{$course}{$group} .=':'.$group_privs;
6933: }
6934: }
1.567 raeburn 6935:
6936: sub standard_roleprivs {
6937: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6938: if (defined($pr{$trole.':s'})) {
6939: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6940: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6941: }
6942: if ($tdomain ne '') {
6943: if (defined($pr{$trole.':d'})) {
6944: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6945: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6946: }
6947: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6948: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6949: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6950: }
6951: }
6952: }
6953:
6954: sub set_userprivs {
1.1064 raeburn 6955: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6956: my $author=0;
6957: my $adv=0;
1.1341 raeburn 6958: my $rar=0;
1.678 raeburn 6959: my %grouproles = ();
6960: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6961: my @groupkeys;
1.1000 raeburn 6962: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6963: push(@groupkeys,$role);
6964: }
6965: if (ref($groups_roles) eq 'HASH') {
6966: foreach my $key (keys(%{$groups_roles})) {
6967: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6968: push(@groupkeys,$key);
6969: }
6970: }
6971: }
6972: if (@groupkeys > 0) {
6973: foreach my $role (@groupkeys) {
6974: my ($trole,$area,$sec,$extendedarea);
6975: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6976: $trole = $1;
6977: $area = $2;
6978: $sec = $3;
6979: $extendedarea = $area.$sec;
6980: if (exists($$allgroups{$area})) {
6981: foreach my $group (keys(%{$$allgroups{$area}})) {
6982: my $spec = $trole.'.'.$extendedarea;
6983: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6984: $$allgroups{$area}{$group};
1.1064 raeburn 6985: }
1.678 raeburn 6986: }
6987: }
6988: }
6989: }
6990: }
1.800 albertel 6991: foreach my $group (keys(%grouproles)) {
6992: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6993: }
1.800 albertel 6994: foreach my $role (keys(%{$allroles})) {
6995: my %thesepriv;
1.941 raeburn 6996: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6997: foreach my $item (split(/:/,$$allroles{$role})) {
6998: if ($item ne '') {
6999: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 7000: if ($restrictions eq '') {
7001: $thesepriv{$privilege}='F';
7002: } elsif ($thesepriv{$privilege} ne 'F') {
7003: $thesepriv{$privilege}.=$restrictions;
7004: }
7005: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 7006: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 7007: }
7008: }
7009: my $thesestr='';
1.1104 raeburn 7010: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 7011: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
7012: }
7013: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 7014: }
1.1341 raeburn 7015: return ($author,$adv,$rar);
1.567 raeburn 7016: }
7017:
1.994 raeburn 7018: sub role_status {
1.1104 raeburn 7019: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 7020: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 7021: my ($one,$two) = split(m{\./},$rolekey,2);
7022: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 7023: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 7024: $$where = '/'.$two;
1.994 raeburn 7025: $$trolecode=$$role.'.'.$$where;
7026: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
7027: $$tstatus='is';
1.1104 raeburn 7028: if ($$tstart && $$tstart>$update) {
1.994 raeburn 7029: $$tstatus='future';
1.1034 raeburn 7030: if ($$tstart<$now) {
7031: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 7032: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 7033: my (%allroles,%allgroups,$group_privs,
7034: %groups_roles,@rolecodes);
1.1002 raeburn 7035: my %userroles = (
7036: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
7037: );
1.1064 raeburn 7038: @rolecodes = ('cm');
1.1002 raeburn 7039: my $spec=$$role.'.'.$$where;
7040: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
7041: if ($$role =~ /^cr\//) {
7042: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 7043: push(@rolecodes,'cr');
1.1002 raeburn 7044: } elsif ($$role eq 'gr') {
1.1064 raeburn 7045: push(@rolecodes,$$role);
1.1002 raeburn 7046: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
7047: $env{'user.name'});
1.1064 raeburn 7048: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 7049: (undef,my $group_privs) = split(/\//,$trole);
7050: $group_privs = &unescape($group_privs);
7051: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 7052: 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 7053: &get_groups_roles($tdomain,$trest,
7054: \%course_roles,\@rolecodes,
7055: \%groups_roles);
1.1002 raeburn 7056: } else {
1.1064 raeburn 7057: push(@rolecodes,$$role);
1.1002 raeburn 7058: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
7059: }
1.1341 raeburn 7060: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
7061: \%groups_roles);
1.1064 raeburn 7062: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 7063: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 7064: }
7065: }
1.1034 raeburn 7066: $$tstatus = 'is';
1.1002 raeburn 7067: }
1.994 raeburn 7068: }
7069: if ($$tend) {
1.1104 raeburn 7070: if ($$tend<$update) {
1.994 raeburn 7071: $$tstatus='expired';
7072: } elsif ($$tend<$now) {
7073: $$tstatus='will_not';
7074: }
7075: }
7076: }
7077: }
7078: }
7079:
1.1104 raeburn 7080: sub get_groups_roles {
7081: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
7082: return unless((ref($cdom_courseroles) eq 'HASH') &&
7083: (ref($rolecodes) eq 'ARRAY') &&
7084: (ref($groups_roles) eq 'HASH'));
7085: if (keys(%{$cdom_courseroles}) > 0) {
7086: my ($cnum) = ($rest =~ /^($match_courseid)/);
7087: if ($cdom ne '' && $cnum ne '') {
7088: foreach my $key (keys(%{$cdom_courseroles})) {
7089: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
7090: my $crsrole = $1;
7091: my $crssec = $2;
7092: if ($crsrole =~ /^cr/) {
7093: unless (grep(/^cr$/,@{$rolecodes})) {
7094: push(@{$rolecodes},'cr');
7095: }
7096: } else {
7097: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
7098: push(@{$rolecodes},$crsrole);
7099: }
7100: }
7101: my $rolekey = "$crsrole./$cdom/$cnum";
7102: if ($crssec ne '') {
7103: $rolekey .= "/$crssec";
7104: }
7105: $rolekey .= './';
7106: $groups_roles->{$rolekey} = $rolecodes;
7107: }
7108: }
7109: }
7110: }
7111: return;
7112: }
7113:
7114: sub delete_env_groupprivs {
7115: my ($where,$courseroles,$possroles) = @_;
7116: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
7117: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
7118: unless (ref($courseroles->{$udom}) eq 'HASH') {
7119: %{$courseroles->{$udom}} =
7120: &get_my_roles('','','userroles',['active'],
7121: $possroles,[$udom],1);
7122: }
7123: if (ref($courseroles->{$udom}) eq 'HASH') {
7124: foreach my $item (keys(%{$courseroles->{$udom}})) {
7125: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
7126: my $area = '/'.$cdom.'/'.$cnum;
7127: my $privkey = "user.priv.$crsrole.$area";
7128: if ($crssec ne '') {
7129: $privkey .= '/'.$crssec;
7130: }
7131: $privkey .= ".$area/$group";
7132: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
7133: }
7134: }
7135: return;
7136: }
7137:
1.994 raeburn 7138: sub check_adhoc_privs {
1.1329 raeburn 7139: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 7140: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 7141: if ($sec) {
7142: $cckey .= '/'.$sec;
7143: }
1.1185 raeburn 7144: my $setprivs;
1.994 raeburn 7145: if ($env{$cckey}) {
7146: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 7147: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 7148: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 7149: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7150: $setprivs = 1;
1.994 raeburn 7151: }
7152: } else {
1.1330 raeburn 7153: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7154: $setprivs = 1;
1.994 raeburn 7155: }
1.1185 raeburn 7156: return $setprivs;
1.994 raeburn 7157: }
7158:
7159: sub set_adhoc_privileges {
1.1326 raeburn 7160: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 7161: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 7162: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 7163: if ($sec ne '') {
7164: $area .= '/'.$sec;
7165: }
1.994 raeburn 7166: my $spec = $role.'.'.$area;
7167: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 7168: $env{'user.name'},1);
1.1326 raeburn 7169: my %rolehash = ();
1.1332 raeburn 7170: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
7171: my $rolename = $1;
1.1326 raeburn 7172: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 7173: my %domdef = &get_domain_defaults($dcdom);
7174: if (ref($domdef{'adhocroles'}) eq 'HASH') {
7175: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
7176: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
7177: }
7178: }
1.1326 raeburn 7179: } else {
7180: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
7181: }
1.1341 raeburn 7182: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 7183: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 7184: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402 raeburn 7185: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
7186: ($caller eq 'tiny')) {
1.1088 raeburn 7187: &appenv( {'request.role' => $spec,
7188: 'request.role.domain' => $dcdom,
1.1332 raeburn 7189: 'request.course.sec' => $sec,
1.1088 raeburn 7190: }
7191: );
7192: my $tadv=0;
7193: if (&allowed('adv') eq 'F') { $tadv=1; }
7194: &appenv({'request.role.adv' => $tadv});
7195: }
1.994 raeburn 7196: }
7197:
1.12 www 7198: # --------------------------------------------------------------- get interface
7199:
7200: sub get {
1.131 albertel 7201: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7202: my $items='';
1.800 albertel 7203: foreach my $item (@$storearr) {
7204: $items.=&escape($item).'&';
1.191 harris41 7205: }
1.12 www 7206: $items=~s/\&$//;
1.620 albertel 7207: if (!$udomain) { $udomain=$env{'user.domain'}; }
7208: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 7209: my $uhome=&homeserver($uname,$udomain);
7210:
1.133 albertel 7211: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7212: my @pairs=split(/\&/,$rep);
1.273 albertel 7213: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
7214: return @pairs;
7215: }
1.15 www 7216: my %returnhash=();
1.42 www 7217: my $i=0;
1.800 albertel 7218: foreach my $item (@$storearr) {
7219: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7220: $i++;
1.191 harris41 7221: }
1.15 www 7222: return %returnhash;
1.27 www 7223: }
7224:
7225: # --------------------------------------------------------------- del interface
7226:
7227: sub del {
1.133 albertel 7228: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 7229: my $items='';
1.800 albertel 7230: foreach my $item (@$storearr) {
7231: $items.=&escape($item).'&';
1.191 harris41 7232: }
1.984 neumanie 7233:
1.27 www 7234: $items=~s/\&$//;
1.620 albertel 7235: if (!$udomain) { $udomain=$env{'user.domain'}; }
7236: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7237: my $uhome=&homeserver($uname,$udomain);
7238: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7239: }
7240:
7241: # -------------------------------------------------------------- dump interface
7242:
1.1180 droeschl 7243: sub unserialize {
7244: my ($rep, $escapedkeys) = @_;
7245:
7246: return {} if $rep =~ /^error/;
7247:
7248: my %returnhash=();
1.1252 raeburn 7249: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 7250: my ($key, $value) = split(/=/, $item, 2);
7251: $key = unescape($key) unless $escapedkeys;
7252: next if $key =~ /^error: 2 /;
1.1252 raeburn 7253: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 7254: }
7255: #return %returnhash;
7256: return \%returnhash;
7257: }
7258:
7259: # see Lond::dump_with_regexp
7260: # if $escapedkeys hash keys won't get unescaped.
1.15 www 7261: sub dump {
1.1462 raeburn 7262: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755 albertel 7263: if (!$udomain) { $udomain=$env{'user.domain'}; }
7264: if (!$uname) { $uname=$env{'user.name'}; }
7265: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 7266:
1.1266 raeburn 7267: if ($regexp) {
7268: $regexp=&escape($regexp);
7269: } else {
7270: $regexp='.';
7271: }
1.1180 droeschl 7272: if (grep { $_ eq $uhome } current_machine_ids()) {
7273: # user is hosted on this machine
1.1266 raeburn 7274: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 7275: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 7276: return %{unserialize($reply, $escapedkeys)};
7277: }
1.1462 raeburn 7278: my $rep;
7279: if ($encrypt) {
7280: $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.1463 raeburn 7281: } else {
1.1462 raeburn 7282: $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7283: }
1.755 albertel 7284: my @pairs=split(/\&/,$rep);
7285: my %returnhash=();
1.1098 foxr 7286: if (!($rep =~ /^error/ )) {
7287: foreach my $item (@pairs) {
7288: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 7289: $key = unescape($key) unless $escapedkeys;
7290: #$key = &unescape($key);
1.1098 foxr 7291: next if ($key =~ /^error: 2 /);
7292: $returnhash{$key}=&thaw_unescape($value);
7293: }
1.755 albertel 7294: }
7295: return %returnhash;
1.407 www 7296: }
7297:
1.1098 foxr 7298:
1.717 albertel 7299: # --------------------------------------------------------- dumpstore interface
7300:
7301: sub dumpstore {
7302: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 7303: # same as dump but keys must be escaped. They may contain colon separated
7304: # lists of values that may themself contain colons (e.g. symbs).
7305: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 7306: }
7307:
1.407 www 7308: # -------------------------------------------------------------- keys interface
7309:
7310: sub getkeys {
7311: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 7312: if (!$udomain) { $udomain=$env{'user.domain'}; }
7313: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 7314: my $uhome=&homeserver($uname,$udomain);
7315: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7316: my @keyarray=();
1.800 albertel 7317: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 7318: next if ($key =~ /^error: 2 /);
1.800 albertel 7319: push(@keyarray,&unescape($key));
1.407 www 7320: }
7321: return @keyarray;
1.318 matthew 7322: }
7323:
1.319 matthew 7324: # --------------------------------------------------------------- currentdump
7325: sub currentdump {
1.328 matthew 7326: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 7327: $courseid = $env{'request.course.id'} if (! defined($courseid));
7328: $sdom = $env{'user.domain'} if (! defined($sdom));
7329: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 7330: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 7331: my $rep;
7332:
7333: if (grep { $_ eq $uhome } current_machine_ids()) {
7334: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7335: $courseid)));
7336: } else {
7337: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7338: }
7339:
1.318 matthew 7340: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7341: #
1.318 matthew 7342: my %returnhash=();
1.319 matthew 7343: #
1.1343 raeburn 7344: if ($rep eq 'unknown_cmd') {
1.319 matthew 7345: # an old lond will not know currentdump
7346: # Do a dump and make it look like a currentdump
1.822 albertel 7347: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7348: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7349: my %hash = @tmp;
7350: @tmp=();
1.424 matthew 7351: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7352: } else {
7353: my @pairs=split(/\&/,$rep);
1.800 albertel 7354: foreach my $pair (@pairs) {
7355: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7356: my ($symb,$param) = split(/:/,$key);
7357: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7358: &thaw_unescape($value);
1.319 matthew 7359: }
1.191 harris41 7360: }
1.12 www 7361: return %returnhash;
1.424 matthew 7362: }
7363:
7364: sub convert_dump_to_currentdump{
7365: my %hash = %{shift()};
7366: my %returnhash;
7367: # Code ripped from lond, essentially. The only difference
7368: # here is the unescaping done by lonnet::dump(). Conceivably
7369: # we might run in to problems with parameter names =~ /^v\./
7370: while (my ($key,$value) = each(%hash)) {
7371: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7372: $symb = &unescape($symb);
7373: $param = &unescape($param);
1.424 matthew 7374: next if ($v eq 'version' || $symb eq 'keys');
7375: next if (exists($returnhash{$symb}) &&
7376: exists($returnhash{$symb}->{$param}) &&
7377: $returnhash{$symb}->{'v.'.$param} > $v);
7378: $returnhash{$symb}->{$param}=$value;
7379: $returnhash{$symb}->{'v.'.$param}=$v;
7380: }
7381: #
7382: # Remove all of the keys in the hashes which keep track of
7383: # the version of the parameter.
7384: while (my ($symb,$param_hash) = each(%returnhash)) {
7385: # use a foreach because we are going to delete from the hash.
7386: foreach my $key (keys(%$param_hash)) {
7387: delete($param_hash->{$key}) if ($key =~ /^v\./);
7388: }
7389: }
7390: return \%returnhash;
1.12 www 7391: }
7392:
1.627 albertel 7393: # ------------------------------------------------------ critical inc interface
7394:
7395: sub cinc {
7396: return &inc(@_,'critical');
7397: }
7398:
1.449 matthew 7399: # --------------------------------------------------------------- inc interface
7400:
7401: sub inc {
1.627 albertel 7402: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7403: if (!$udomain) { $udomain=$env{'user.domain'}; }
7404: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7405: my $uhome=&homeserver($uname,$udomain);
7406: my $items='';
7407: if (! ref($store)) {
7408: # got a single value, so use that instead
7409: $items = &escape($store).'=&';
7410: } elsif (ref($store) eq 'SCALAR') {
7411: $items = &escape($$store).'=&';
7412: } elsif (ref($store) eq 'ARRAY') {
7413: $items = join('=&',map {&escape($_);} @{$store});
7414: } elsif (ref($store) eq 'HASH') {
7415: while (my($key,$value) = each(%{$store})) {
7416: $items.= &escape($key).'='.&escape($value).'&';
7417: }
7418: }
7419: $items=~s/\&$//;
1.627 albertel 7420: if ($critical) {
7421: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7422: } else {
7423: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7424: }
1.449 matthew 7425: }
7426:
1.12 www 7427: # --------------------------------------------------------------- put interface
7428:
7429: sub put {
1.1462 raeburn 7430: my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620 albertel 7431: if (!$udomain) { $udomain=$env{'user.domain'}; }
7432: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7433: my $uhome=&homeserver($uname,$udomain);
1.12 www 7434: my $items='';
1.800 albertel 7435: foreach my $item (keys(%$storehash)) {
7436: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7437: }
1.12 www 7438: $items=~s/\&$//;
1.1462 raeburn 7439: if ($encrypt) {
7440: return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
7441: } else {
7442: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7443: }
1.47 www 7444: }
7445:
1.631 albertel 7446: # ------------------------------------------------------------ newput interface
7447:
7448: sub newput {
7449: my ($namespace,$storehash,$udomain,$uname)=@_;
7450: if (!$udomain) { $udomain=$env{'user.domain'}; }
7451: if (!$uname) { $uname=$env{'user.name'}; }
7452: my $uhome=&homeserver($uname,$udomain);
7453: my $items='';
7454: foreach my $key (keys(%$storehash)) {
7455: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7456: }
7457: $items=~s/\&$//;
7458: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7459: }
7460:
7461: # --------------------------------------------------------- putstore interface
7462:
1.524 raeburn 7463: sub putstore {
1.1269 raeburn 7464: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7465: if (!$udomain) { $udomain=$env{'user.domain'}; }
7466: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7467: my $uhome=&homeserver($uname,$udomain);
7468: my $items='';
1.715 albertel 7469: foreach my $key (keys(%$storehash)) {
7470: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7471: }
1.715 albertel 7472: $items=~s/\&$//;
1.716 albertel 7473: my $esc_symb=&escape($symb);
7474: my $esc_v=&escape($version);
1.715 albertel 7475: my $reply =
1.716 albertel 7476: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7477: $uhome);
1.1269 raeburn 7478: if (($tolog) && ($reply eq 'ok')) {
7479: my $namevalue='';
7480: foreach my $key (keys(%{$storehash})) {
7481: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7482: }
1.1434 raeburn 7483: my $ip = &get_requestor_ip();
7484: $namevalue .= 'ip='.&escape($ip).
1.1269 raeburn 7485: '&host='.&escape($perlvar{'lonHostID'}).
7486: '&version='.$esc_v.
7487: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
1.1494 raeburn 7488: &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
1.1269 raeburn 7489: }
1.715 albertel 7490: if ($reply eq 'unknown_cmd') {
1.716 albertel 7491: # gfall back to way things use to be done
1.715 albertel 7492: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7493: $uname);
1.524 raeburn 7494: }
1.715 albertel 7495: return $reply;
7496: }
7497:
7498: sub old_putstore {
1.716 albertel 7499: my ($namespace,$symb,$version,$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 %newstorehash;
1.800 albertel 7504: foreach my $item (keys(%$storehash)) {
7505: my $key = $version.':'.&escape($symb).':'.$item;
7506: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7507: }
7508: my $items='';
7509: my %allitems = ();
1.800 albertel 7510: foreach my $item (keys(%newstorehash)) {
7511: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7512: my $key = $1.':keys:'.$2;
7513: $allitems{$key} .= $3.':';
7514: }
1.800 albertel 7515: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7516: }
1.800 albertel 7517: foreach my $item (keys(%allitems)) {
7518: $allitems{$item} =~ s/\:$//;
7519: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7520: }
7521: $items=~s/\&$//;
7522: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7523: }
7524:
1.47 www 7525: # ------------------------------------------------------ critical put interface
7526:
7527: sub cput {
1.134 albertel 7528: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7529: if (!$udomain) { $udomain=$env{'user.domain'}; }
7530: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7531: my $uhome=&homeserver($uname,$udomain);
1.47 www 7532: my $items='';
1.800 albertel 7533: foreach my $item (keys(%$storehash)) {
7534: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7535: }
1.47 www 7536: $items=~s/\&$//;
1.134 albertel 7537: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7538: }
7539:
7540: # -------------------------------------------------------------- eget interface
7541:
7542: sub eget {
1.133 albertel 7543: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7544: my $items='';
1.800 albertel 7545: foreach my $item (@$storearr) {
7546: $items.=&escape($item).'&';
1.191 harris41 7547: }
1.12 www 7548: $items=~s/\&$//;
1.620 albertel 7549: if (!$udomain) { $udomain=$env{'user.domain'}; }
7550: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7551: my $uhome=&homeserver($uname,$udomain);
7552: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7553: my @pairs=split(/\&/,$rep);
7554: my %returnhash=();
1.42 www 7555: my $i=0;
1.800 albertel 7556: foreach my $item (@$storearr) {
7557: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7558: $i++;
1.191 harris41 7559: }
1.12 www 7560: return %returnhash;
7561: }
7562:
1.667 albertel 7563: # ------------------------------------------------------------ tmpput interface
7564: sub tmpput {
1.802 raeburn 7565: my ($storehash,$server,$context)=@_;
1.667 albertel 7566: my $items='';
1.800 albertel 7567: foreach my $item (keys(%$storehash)) {
7568: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7569: }
7570: $items=~s/\&$//;
1.802 raeburn 7571: if (defined($context)) {
7572: $items .= ':'.&escape($context);
7573: }
1.667 albertel 7574: return &reply("tmpput:$items",$server);
7575: }
7576:
7577: # ------------------------------------------------------------ tmpget interface
7578: sub tmpget {
1.688 albertel 7579: my ($token,$server)=@_;
7580: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7581: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7582: my %returnhash;
1.1328 raeburn 7583: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7584: return %returnhash;
7585: }
1.667 albertel 7586: foreach my $item (split(/\&/,$rep)) {
7587: my ($key,$value)=split(/=/,$item);
7588: $returnhash{&unescape($key)}=&thaw_unescape($value);
7589: }
7590: return %returnhash;
7591: }
7592:
1.1113 raeburn 7593: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7594: sub tmpdel {
7595: my ($token,$server)=@_;
7596: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7597: return &reply("tmpdel:$token",$server);
7598: }
7599:
1.1198 raeburn 7600: # ------------------------------------------------------------ get_timebased_id
7601:
7602: sub get_timebased_id {
7603: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7604: $maxtries) = @_;
7605: my ($newid,$error,$dellock);
7606: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7607: return ('','ok','invalid call to get suffix');
7608: }
7609:
7610: # set defaults for any optional args for which values were not supplied
7611: if ($who eq '') {
7612: $who = $env{'user.name'}.':'.$env{'user.domain'};
7613: }
7614: if (!$locktries) {
7615: $locktries = 3;
7616: }
7617: if (!$maxtries) {
7618: $maxtries = 10;
7619: }
7620:
7621: if (($cdom eq '') || ($cnum eq '')) {
7622: if ($env{'request.course.id'}) {
7623: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7624: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7625: }
7626: if (($cdom eq '') || ($cnum eq '')) {
7627: return ('','ok','call to get suffix not in course context');
7628: }
7629: }
7630:
7631: # construct locking item
7632: my $lockhash = {
7633: $prefix."\0".'locked_'.$keyid => $who,
7634: };
7635: my $tries = 0;
7636:
7637: # attempt to get lock on nohist_$namespace file
1.1494 raeburn 7638: my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198 raeburn 7639: while (($gotlock ne 'ok') && $tries <$locktries) {
7640: $tries ++;
7641: sleep 1;
1.1494 raeburn 7642: $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198 raeburn 7643: }
7644:
7645: # attempt to get unique identifier, based on current timestamp
7646: if ($gotlock eq 'ok') {
1.1494 raeburn 7647: my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
1.1198 raeburn 7648: my $id = time;
7649: $newid = $id;
1.1268 raeburn 7650: if ($idtype eq 'addcode') {
7651: $newid .= &sixnum_code();
7652: }
1.1198 raeburn 7653: my $idtries = 0;
7654: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7655: if ($idtype eq 'concat') {
7656: $newid = $id.$idtries;
1.1268 raeburn 7657: } elsif ($idtype eq 'addcode') {
7658: $newid = $newid.&sixnum_code();
1.1198 raeburn 7659: } else {
7660: $newid ++;
7661: }
7662: $idtries ++;
7663: }
7664: if (!exists($inuse{$prefix."\0".$newid})) {
7665: my %new_item = (
7666: $prefix."\0".$newid => $who,
7667: );
1.1494 raeburn 7668: my $putresult = &put('nohist_'.$namespace,\%new_item,
1.1198 raeburn 7669: $cdom,$cnum);
7670: if ($putresult ne 'ok') {
7671: undef($newid);
7672: $error = 'error saving new item: '.$putresult;
7673: }
7674: } else {
1.1268 raeburn 7675: undef($newid);
1.1198 raeburn 7676: $error = ('error: no unique suffix available for the new item ');
7677: }
7678: # remove lock
7679: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7680: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7681: } else {
7682: $error = "error: could not obtain lockfile\n";
7683: $dellock = 'ok';
1.1276 raeburn 7684: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7685: $dellock = 'nolock';
7686: }
1.1198 raeburn 7687: }
7688: return ($newid,$dellock,$error);
7689: }
7690:
1.1268 raeburn 7691: sub sixnum_code {
7692: my $code;
7693: for (0..6) {
7694: $code .= int( rand(9) );
7695: }
7696: return $code;
7697: }
7698:
1.765 albertel 7699: # -------------------------------------------------- portfolio access checking
7700:
7701: sub portfolio_access {
1.1270 raeburn 7702: my ($requrl,$clientip) = @_;
1.765 albertel 7703: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 7704: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7705: if ($result) {
7706: my %setters;
7707: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1473 raeburn 7708: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7709: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
7710: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7711: return 'B';
7712: }
7713: } else {
1.1473 raeburn 7714: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7715: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7716: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7717: return 'B';
7718: }
7719: }
7720: }
1.765 albertel 7721: if ($result eq 'ok') {
1.766 albertel 7722: return 'F';
1.765 albertel 7723: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7724: return 'A';
1.765 albertel 7725: }
1.766 albertel 7726: return '';
1.765 albertel 7727: }
7728:
7729: sub get_portfolio_access {
1.1270 raeburn 7730: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7731:
7732: if (!ref($access_hash)) {
7733: my $current_perms = &get_portfile_permissions($udom,$unum);
7734: my %access_controls = &get_access_controls($current_perms,$group,
7735: $file_name);
7736: $access_hash = $access_controls{$file_name};
7737: }
7738:
1.1270 raeburn 7739: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7740: my $now = time;
7741: if (ref($access_hash) eq 'HASH') {
7742: foreach my $key (keys(%{$access_hash})) {
7743: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7744: if ($start > $now) {
7745: next;
7746: }
7747: if ($end && $end<$now) {
7748: next;
7749: }
7750: if ($scope eq 'public') {
7751: $public = $key;
7752: last;
7753: } elsif ($scope eq 'guest') {
7754: $guest = $key;
7755: } elsif ($scope eq 'domains') {
7756: push(@domains,$key);
7757: } elsif ($scope eq 'users') {
7758: push(@users,$key);
7759: } elsif ($scope eq 'course') {
7760: push(@courses,$key);
7761: } elsif ($scope eq 'group') {
7762: push(@groups,$key);
1.1270 raeburn 7763: } elsif ($scope eq 'ip') {
7764: push(@ips,$key);
1.765 albertel 7765: }
7766: }
7767: if ($public) {
7768: return 'ok';
1.1270 raeburn 7769: } elsif (@ips > 0) {
7770: my $allowed;
7771: foreach my $ipkey (@ips) {
7772: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7773: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7774: $allowed = 1;
7775: last;
7776: }
7777: }
7778: }
7779: if ($allowed) {
7780: return 'ok';
7781: }
1.765 albertel 7782: }
7783: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7784: if ($guest) {
7785: return $guest;
7786: }
7787: } else {
7788: if (@domains > 0) {
7789: foreach my $domkey (@domains) {
7790: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7791: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7792: return 'ok';
7793: }
7794: }
7795: }
7796: }
7797: if (@users > 0) {
7798: foreach my $userkey (@users) {
1.865 raeburn 7799: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7800: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7801: if (ref($item) eq 'HASH') {
7802: if (($item->{'uname'} eq $env{'user.name'}) &&
7803: ($item->{'udom'} eq $env{'user.domain'})) {
7804: return 'ok';
7805: }
7806: }
7807: }
7808: }
1.765 albertel 7809: }
7810: }
7811: my %roleshash;
7812: my @courses_and_groups = @courses;
7813: push(@courses_and_groups,@groups);
7814: if (@courses_and_groups > 0) {
7815: my (%allgroups,%allroles);
7816: my ($start,$end,$role,$sec,$group);
7817: foreach my $envkey (%env) {
1.1060 raeburn 7818: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7819: my $cid = $2.'_'.$3;
7820: if ($1 eq 'gr') {
7821: $group = $4;
7822: $allgroups{$cid}{$group} = $env{$envkey};
7823: } else {
7824: if ($4 eq '') {
7825: $sec = 'none';
7826: } else {
7827: $sec = $4;
7828: }
7829: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7830: }
1.811 albertel 7831: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7832: my $cid = $2.'_'.$3;
7833: if ($4 eq '') {
7834: $sec = 'none';
7835: } else {
7836: $sec = $4;
7837: }
7838: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7839: }
7840: }
7841: if (keys(%allroles) == 0) {
7842: return;
7843: }
7844: foreach my $key (@courses_and_groups) {
7845: my %content = %{$$access_hash{$key}};
7846: my $cnum = $content{'number'};
7847: my $cdom = $content{'domain'};
7848: my $cid = $cdom.'_'.$cnum;
7849: if (!exists($allroles{$cid})) {
7850: next;
7851: }
7852: foreach my $role_id (keys(%{$content{'roles'}})) {
7853: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7854: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7855: my @status = @{$content{'roles'}{$role_id}{'access'}};
7856: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7857: foreach my $role (keys(%{$allroles{$cid}})) {
7858: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7859: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7860: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7861: if (grep/^all$/,@sections) {
7862: return 'ok';
7863: } else {
7864: if (grep/^$sec$/,@sections) {
7865: return 'ok';
7866: }
7867: }
7868: }
7869: }
7870: if (keys(%{$allgroups{$cid}}) == 0) {
7871: if (grep/^none$/,@groups) {
7872: return 'ok';
7873: }
7874: } else {
7875: if (grep/^all$/,@groups) {
7876: return 'ok';
7877: }
7878: foreach my $group (keys(%{$allgroups{$cid}})) {
7879: if (grep/^$group$/,@groups) {
7880: return 'ok';
7881: }
7882: }
7883: }
7884: }
7885: }
7886: }
7887: }
7888: }
7889: if ($guest) {
7890: return $guest;
7891: }
7892: }
7893: }
7894: return;
7895: }
7896:
7897: sub course_group_datechecker {
7898: my ($dates,$now,$status) = @_;
7899: my ($start,$end) = split(/\./,$dates);
7900: if (!$start && !$end) {
7901: return 'ok';
7902: }
7903: if (grep/^active$/,@{$status}) {
7904: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7905: return 'ok';
7906: }
7907: }
7908: if (grep/^previous$/,@{$status}) {
7909: if ($end > $now ) {
7910: return 'ok';
7911: }
7912: }
7913: if (grep/^future$/,@{$status}) {
7914: if ($start > $now) {
7915: return 'ok';
7916: }
7917: }
7918: return;
7919: }
7920:
7921: sub parse_portfolio_url {
7922: my ($url) = @_;
7923:
7924: my ($type,$udom,$unum,$group,$file_name);
7925:
1.823 albertel 7926: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7927: $type = 1;
7928: $udom = $1;
7929: $unum = $2;
7930: $file_name = $3;
1.823 albertel 7931: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7932: $type = 2;
7933: $udom = $1;
7934: $unum = $2;
7935: $group = $3;
7936: $file_name = $3.'/'.$4;
7937: }
7938: if (wantarray) {
7939: return ($type,$udom,$unum,$file_name,$group);
7940: }
7941: return $type;
7942: }
7943:
7944: sub is_portfolio_url {
7945: my ($url) = @_;
7946: return scalar(&parse_portfolio_url($url));
7947: }
7948:
1.798 raeburn 7949: sub is_portfolio_file {
7950: my ($file) = @_;
1.820 raeburn 7951: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7952: return 1;
7953: }
7954: return;
7955: }
7956:
1.976 raeburn 7957: sub usertools_access {
1.1084 raeburn 7958: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7959: my ($access,%tools);
7960: if ($context eq '') {
7961: $context = 'tools';
7962: }
7963: if ($context eq 'requestcourses') {
7964: %tools = (
7965: official => 1,
7966: unofficial => 1,
1.1006 raeburn 7967: community => 1,
1.1246 raeburn 7968: textbook => 1,
1.1305 raeburn 7969: placement => 1,
1.1368 raeburn 7970: lti => 1,
1.985 raeburn 7971: );
1.1183 raeburn 7972: } elsif ($context eq 'requestauthor') {
7973: %tools = (
7974: requestauthor => 1,
7975: );
1.985 raeburn 7976: } else {
7977: %tools = (
7978: aboutme => 1,
7979: blog => 1,
1.1177 raeburn 7980: webdav => 1,
1.985 raeburn 7981: portfolio => 1,
1.1489 raeburn 7982: timezone => 1,
1.985 raeburn 7983: );
7984: }
1.976 raeburn 7985: return if (!defined($tools{$tool}));
7986:
1.1242 raeburn 7987: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7988: $udom = $env{'user.domain'};
7989: $uname = $env{'user.name'};
7990: }
7991:
1.978 raeburn 7992: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7993: if ($action ne 'reload') {
1.985 raeburn 7994: if ($context eq 'requestcourses') {
7995: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 7996: } elsif ($context eq 'requestauthor') {
7997: return $env{'environment.canrequest.author'};
1.985 raeburn 7998: } else {
7999: return $env{'environment.availabletools.'.$tool};
8000: }
8001: }
1.976 raeburn 8002: }
8003:
1.1183 raeburn 8004: my ($toolstatus,$inststatus,$envkey);
8005: if ($context eq 'requestauthor') {
8006: $envkey = $context;
8007: } else {
8008: $envkey = $context.'.'.$tool;
8009: }
1.976 raeburn 8010:
1.985 raeburn 8011: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8012: ($action ne 'reload')) {
1.1183 raeburn 8013: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 8014: $inststatus = $env{'environment.inststatus'};
8015: } else {
1.1084 raeburn 8016: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 8017: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 8018: $inststatus = $userenvref->{'inststatus'};
8019: } else {
1.1183 raeburn 8020: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
8021: $toolstatus = $userenv{$envkey};
1.1084 raeburn 8022: $inststatus = $userenv{'inststatus'};
8023: }
1.976 raeburn 8024: }
8025:
8026: if ($toolstatus ne '') {
8027: if ($toolstatus) {
8028: $access = 1;
8029: } else {
8030: $access = 0;
8031: }
8032: return $access;
8033: }
8034:
1.1084 raeburn 8035: my ($is_adv,%domdef);
8036: if (ref($is_advref) eq 'HASH') {
8037: $is_adv = $is_advref->{'is_adv'};
8038: } else {
8039: $is_adv = &is_advanced_user($udom,$uname);
8040: }
8041: if (ref($domdefref) eq 'HASH') {
8042: %domdef = %{$domdefref};
8043: } else {
8044: %domdef = &get_domain_defaults($udom);
8045: }
1.976 raeburn 8046: if (ref($domdef{$tool}) eq 'HASH') {
8047: if ($is_adv) {
8048: if ($domdef{$tool}{'_LC_adv'} ne '') {
8049: if ($domdef{$tool}{'_LC_adv'}) {
8050: $access = 1;
8051: } else {
8052: $access = 0;
8053: }
8054: return $access;
8055: }
8056: }
8057: if ($inststatus ne '') {
8058: my ($hasaccess,$hasnoaccess);
8059: foreach my $affiliation (split(/:/,$inststatus)) {
8060: if ($domdef{$tool}{$affiliation} ne '') {
8061: if ($domdef{$tool}{$affiliation}) {
8062: $hasaccess = 1;
8063: } else {
8064: $hasnoaccess = 1;
8065: }
8066: }
8067: }
8068: if ($hasaccess || $hasnoaccess) {
8069: if ($hasaccess) {
8070: $access = 1;
8071: } elsif ($hasnoaccess) {
8072: $access = 0;
8073: }
8074: return $access;
8075: }
8076: } else {
8077: if ($domdef{$tool}{'default'} ne '') {
8078: if ($domdef{$tool}{'default'}) {
8079: $access = 1;
8080: } elsif ($domdef{$tool}{'default'} == 0) {
8081: $access = 0;
8082: }
8083: return $access;
8084: }
8085: }
8086: } else {
1.1177 raeburn 8087: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 8088: $access = 1;
8089: } else {
8090: $access = 0;
8091: }
1.976 raeburn 8092: return $access;
8093: }
8094: }
8095:
1.1050 raeburn 8096: sub is_course_owner {
8097: my ($cdom,$cnum,$udom,$uname) = @_;
8098: if (($udom eq '') || ($uname eq '')) {
8099: $udom = $env{'user.domain'};
8100: $uname = $env{'user.name'};
8101: }
8102: unless (($udom eq '') || ($uname eq '')) {
8103: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
8104: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
8105: return 1;
8106: } else {
1.1494 raeburn 8107: my %courseinfo = &coursedescription($cdom.'/'.$cnum);
1.1050 raeburn 8108: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
8109: return 1;
8110: }
8111: }
8112: }
8113: }
8114: return;
8115: }
8116:
1.976 raeburn 8117: sub is_advanced_user {
8118: my ($udom,$uname) = @_;
1.1085 raeburn 8119: if ($udom ne '' && $uname ne '') {
8120: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 8121: if (wantarray) {
8122: return ($env{'user.adv'},$env{'user.author'});
8123: } else {
8124: return $env{'user.adv'};
8125: }
1.1085 raeburn 8126: }
8127: }
1.976 raeburn 8128: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
8129: my %allroles;
1.1128 raeburn 8130: my ($is_adv,$is_author);
1.976 raeburn 8131: foreach my $role (keys(%roleshash)) {
8132: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
8133: my $area = '/'.$tdomain.'/'.$trest;
8134: if ($sec ne '') {
8135: $area .= '/'.$sec;
8136: }
8137: if (($area ne '') && ($trole ne '')) {
8138: my $spec=$trole.'.'.$area;
8139: if ($trole =~ /^cr\//) {
8140: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
8141: } elsif ($trole ne 'gr') {
8142: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
8143: }
1.1128 raeburn 8144: if ($trole eq 'au') {
8145: $is_author = 1;
8146: }
1.976 raeburn 8147: }
8148: }
8149: foreach my $role (keys(%allroles)) {
8150: last if ($is_adv);
8151: foreach my $item (split(/:/,$allroles{$role})) {
8152: if ($item ne '') {
8153: my ($privilege,$restrictions)=split(/&/,$item);
8154: if ($privilege eq 'adv') {
8155: $is_adv = 1;
8156: last;
8157: }
8158: }
8159: }
8160: }
1.1128 raeburn 8161: if (wantarray) {
8162: return ($is_adv,$is_author);
8163: }
1.976 raeburn 8164: return $is_adv;
8165: }
1.798 raeburn 8166:
1.1035 raeburn 8167: sub check_can_request {
1.1368 raeburn 8168: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035 raeburn 8169: my $canreq = 0;
1.1368 raeburn 8170: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8171: $uname = $env{'user.name'};
8172: $udom = $env{'user.domain'};
8173: }
1.1035 raeburn 8174: my ($types,$typename) = &Apache::loncommon::course_types();
8175: my @options = ('approval','validate','autolimit');
8176: my $optregex = join('|',@options);
8177: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
1.1486 raeburn 8178: my %willtrust;
1.1035 raeburn 8179: foreach my $type (@{$types}) {
1.1368 raeburn 8180: if (&usertools_access($uname,$udom,$type,undef,
8181: 'requestcourses')) {
1.1035 raeburn 8182: $canreq ++;
1.1036 raeburn 8183: if (ref($request_domains) eq 'HASH') {
1.1368 raeburn 8184: push(@{$request_domains->{$type}},$udom);
1.1036 raeburn 8185: }
1.1368 raeburn 8186: if ($dom eq $udom) {
1.1035 raeburn 8187: $can_request->{$type} = 1;
8188: }
8189: }
1.1368 raeburn 8190: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
8191: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035 raeburn 8192: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
8193: if (@curr > 0) {
1.1036 raeburn 8194: foreach my $item (@curr) {
8195: if (ref($request_domains) eq 'HASH') {
8196: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
8197: if ($otherdom ne '') {
1.1486 raeburn 8198: unless (exists($willtrust{$otherdom})) {
8199: $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
8200: }
8201: if ($willtrust{$otherdom}) {
8202: if (ref($request_domains->{$type}) eq 'ARRAY') {
8203: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
8204: push(@{$request_domains->{$type}},$otherdom);
8205: }
8206: } else {
1.1036 raeburn 8207: push(@{$request_domains->{$type}},$otherdom);
8208: }
8209: }
8210: }
8211: }
8212: }
1.1368 raeburn 8213: unless ($dom eq $env{'user.domain'}) {
1.1036 raeburn 8214: $canreq ++;
1.1035 raeburn 8215: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
8216: $can_request->{$type} = 1;
8217: }
8218: }
8219: }
8220: }
8221: }
8222: }
8223: return $canreq;
8224: }
8225:
1.341 www 8226: # ---------------------------------------------- Custom access rule evaluation
8227:
8228: sub customaccess {
8229: my ($priv,$uri)=@_;
1.807 albertel 8230: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 8231: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 8232: $udom = &LONCAPA::clean_domain($udom);
8233: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 8234: my $access=0;
1.800 albertel 8235: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 8236: my ($effect,$realm,$role,$type)=split(/\:/,$right);
8237: if ($type eq 'user') {
8238: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 8239: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 8240: if ($tdom) {
8241: if ($tdom ne $env{'user.domain'}) { next; }
8242: }
1.896 albertel 8243: if ($tuname) {
8244: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 8245: }
8246: $access=($effect eq 'allow');
8247: last;
8248: }
8249: } else {
8250: if ($role) {
8251: if ($role ne $urole) { next; }
8252: }
8253: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8254: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8255: if ($tdom) {
8256: if ($tdom ne $udom) { next; }
8257: }
8258: if ($tcrs) {
8259: if ($tcrs ne $ucrs) { next; }
8260: }
8261: if ($tsec) {
8262: if ($tsec ne $usec) { next; }
8263: }
8264: $access=($effect eq 'allow');
8265: last;
8266: }
8267: if ($realm eq '' && $role eq '') {
8268: $access=($effect eq 'allow');
8269: }
1.402 bowersj2 8270: }
1.341 www 8271: }
8272: return $access;
8273: }
8274:
1.103 harris41 8275: # ------------------------------------------------- Check for a user privilege
1.12 www 8276:
8277: sub allowed {
1.1461 raeburn 8278: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705 albertel 8279: my $ver_orguri=$uri;
1.439 www 8280: $uri=&deversion($uri);
1.152 www 8281: my $orguri=$uri;
1.52 www 8282: $uri=&declutter($uri);
1.809 raeburn 8283:
1.810 raeburn 8284: if ($priv eq 'evb') {
1.1478 raeburn 8285: # Evade communication block restrictions for specified role in a course or domain
1.810 raeburn 8286: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8287: return $1;
8288: } else {
8289: return;
8290: }
8291: }
8292:
1.620 albertel 8293: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 8294: # Free bre access to adm and meta resources
1.1436 raeburn 8295: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$}))
1.769 albertel 8296: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8297: && ($priv eq 'bre')) {
1.14 www 8298: return 'F';
1.159 www 8299: }
8300:
1.545 banghart 8301: # Free bre access to user's own portfolio contents
1.714 raeburn 8302: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 8303: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 8304: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 8305: my %setters;
1.1473 raeburn 8306: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
8307: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
8308: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 8309: return 'B';
8310: } else {
8311: return 'F';
8312: }
1.545 banghart 8313: }
8314:
1.762 raeburn 8315: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 8316: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8317: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8318: if (exists($env{'request.course.id'})) {
8319: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8320: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8321: if (($domain eq $cdom) && ($name eq $cnum)) {
8322: my $courseprivid=$env{'request.course.id'};
8323: $courseprivid=~s/\_/\//;
8324: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8325: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8326: return $1;
1.762 raeburn 8327: } else {
8328: if ($env{'request.course.sec'}) {
8329: $courseprivid.='/'.$env{'request.course.sec'};
8330: }
8331: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8332: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8333: return $2;
8334: }
1.714 raeburn 8335: }
8336: }
8337: }
8338: }
8339:
1.159 www 8340: # Free bre to public access
8341:
8342: if ($priv eq 'bre') {
1.1362 raeburn 8343: my $copyright;
8344: unless ($uri =~ /ext\.tool/) {
8345: $copyright=&metadata($uri,'copyright');
8346: }
1.620 albertel 8347: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 8348: return 'F';
8349: }
1.238 www 8350: if ($copyright eq 'priv') {
8351: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8352: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 8353: return '';
8354: }
8355: }
8356: if ($copyright eq 'domain') {
8357: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8358: unless (($env{'user.domain'} eq $1) ||
8359: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8360: return '';
8361: }
1.262 matthew 8362: }
1.620 albertel 8363: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8364: # Library role, so allow browsing of resources in this domain.
8365: return 'F';
1.238 www 8366: }
1.341 www 8367: if ($copyright eq 'custom') {
8368: unless (&customaccess($priv,$uri)) { return ''; }
8369: }
1.14 www 8370: }
1.264 matthew 8371: # Domain coordinator is trying to create a course
1.620 albertel 8372: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8373: # uri is the requested domain in this case.
8374: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8375: # a role of dc for the domain in question.
1.620 albertel 8376: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8377: }
1.29 www 8378:
1.52 www 8379: my $thisallowed='';
8380: my $statecond=0;
8381: my $courseprivid='';
8382:
1.1039 raeburn 8383: my $ownaccess;
1.1043 raeburn 8384: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8385: if (($priv eq 'bro') && ($env{'user.author'})) {
8386: if ($uri eq '') {
8387: $ownaccess = 1;
8388: } else {
8389: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8390: my $udom = $env{'user.domain'};
8391: my $uname = $env{'user.name'};
8392: if ($uri =~ m{^\Q$udom\E/?$}) {
8393: $ownaccess = 1;
1.1040 raeburn 8394: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8395: unless ($uri =~ m{\.\./}) {
8396: $ownaccess = 1;
8397: }
8398: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8399: my $now = time;
8400: if ($uri =~ m{^([^/]+)/?$}) {
8401: my $adom = $1;
8402: foreach my $key (keys(%env)) {
1.1042 raeburn 8403: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452 raeburn 8404: my ($start,$end) = split(/\./,$env{$key});
8405: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8406: $ownaccess = 1;
8407: last;
8408: }
8409: }
8410: }
8411: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8412: my $adom = $1;
8413: my $aname = $2;
1.1042 raeburn 8414: foreach my $role ('ca','aa') {
8415: if ($env{"user.role.$role./$adom/$aname"}) {
8416: my ($start,$end) =
1.1452 raeburn 8417: split(/\./,$env{"user.role.$role./$adom/$aname"});
8418: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8419: $ownaccess = 1;
8420: last;
8421: }
1.1039 raeburn 8422: }
8423: }
8424: }
8425: }
8426: }
8427: }
8428: }
8429:
1.52 www 8430: # Course
8431:
1.620 albertel 8432: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8433: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8434: $thisallowed.=$1;
8435: }
1.52 www 8436: }
1.29 www 8437:
1.52 www 8438: # Domain
8439:
1.620 albertel 8440: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8441: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8442: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8443: $thisallowed.=$1;
8444: }
1.12 www 8445: }
1.52 www 8446:
1.1141 raeburn 8447: # User who is not author or co-author might still be able to edit
8448: # resource of an author in the domain (e.g., if Domain Coordinator).
8449: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8450: (&allowed('mdc',$env{'request.course.id'}))) {
8451: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8452: $thisallowed.=$1;
8453: }
8454: }
8455:
1.52 www 8456: # Course: uri itself is a course
1.66 www 8457: my $courseuri=$uri;
8458: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8459: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8460:
1.620 albertel 8461: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8462: =~/\Q$priv\E\&([^\:]*)/) {
1.1409 raeburn 8463: if ($priv eq 'mip') {
8464: my $rem = $1;
8465: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8466: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8467: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8468: if ($cdom ne '') {
1.1410 raeburn 8469: my %passwdconf = &get_passwdconf($cdom);
8470: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8471: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8472: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8473: my @inststatuses = split(':',$env{'environment.inststatus'});
8474: unless (@inststatuses) {
8475: @inststatuses = ('default');
8476: }
8477: foreach my $status (@inststatuses) {
8478: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8479: $thisallowed.=$rem;
8480: }
8481: }
8482: }
8483: }
1.1409 raeburn 8484: }
8485: }
8486: }
8487: } else {
8488: unless (($priv eq 'bro') && (!$ownaccess)) {
8489: $thisallowed.=$1;
8490: }
1.1039 raeburn 8491: }
1.12 www 8492: }
1.29 www 8493:
1.665 albertel 8494: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8495: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8496: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8497: $thisallowed='';
1.671 raeburn 8498: my ($match)=&is_on_map($uri);
8499: if ($match) {
8500: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8501: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 8502: my $value = $1;
1.1461 raeburn 8503: my $deeplinkblock;
8504: unless ($nodeeplinkcheck) {
8505: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8506: }
1.1402 raeburn 8507: if ($deeplinkblock) {
8508: $thisallowed='D';
8509: } elsif ($noblockcheck) {
1.1281 raeburn 8510: $thisallowed.=$value;
1.1162 raeburn 8511: } else {
1.1424 raeburn 8512: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8513: if (@blockers > 0) {
8514: $thisallowed = 'B';
8515: } else {
8516: $thisallowed.=$value;
8517: }
1.1162 raeburn 8518: }
1.671 raeburn 8519: }
8520: } else {
1.705 albertel 8521: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8522: if ($refuri) {
8523: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8524: $thisallowed='F';
1.671 raeburn 8525: } else {
8526: $refuri=&declutter($refuri);
8527: my ($match) = &is_on_map($refuri);
8528: if ($match) {
1.1461 raeburn 8529: my $deeplinkblock;
8530: unless ($nodeeplinkcheck) {
8531: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8532: }
1.1402 raeburn 8533: if ($deeplinkblock) {
8534: $thisallowed='D';
8535: } elsif ($noblockcheck) {
1.1281 raeburn 8536: $thisallowed='F';
1.1162 raeburn 8537: } else {
1.1426 raeburn 8538: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8539: if (@blockers > 0) {
8540: $thisallowed = 'B';
8541: } else {
8542: $thisallowed='F';
8543: }
1.1162 raeburn 8544: }
1.671 raeburn 8545: }
1.669 raeburn 8546: }
1.671 raeburn 8547: }
8548: }
1.314 www 8549: }
1.492 albertel 8550:
1.766 albertel 8551: if ($priv eq 'bre'
8552: && $thisallowed ne 'F'
8553: && $thisallowed ne '2'
8554: && &is_portfolio_url($uri)) {
1.1270 raeburn 8555: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8556: }
1.1250 raeburn 8557:
1.52 www 8558: # Full access at system, domain or course-wide level? Exit.
1.29 www 8559: if ($thisallowed=~/F/) {
8560: return 'F';
8561: }
8562:
1.52 www 8563: # If this is generating or modifying users, exit with special codes
1.29 www 8564:
1.643 www 8565: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8566: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8567: my ($audom,$auname)=split('/',$uri);
1.643 www 8568: # no author name given, so this just checks on the general right to make a co-author in this domain
8569: unless ($auname) { return $thisallowed; }
8570: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8571: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8572: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8573: ($audom ne $env{'request.role.domain'}))) { return ''; }
8574: }
1.52 www 8575: return $thisallowed;
8576: }
8577: #
1.103 harris41 8578: # Gathered so far: system, domain and course wide privileges
1.52 www 8579: #
8580: # Course: See if uri or referer is an individual resource that is part of
8581: # the course
8582:
1.620 albertel 8583: if ($env{'request.course.id'}) {
1.232 www 8584:
1.1409 raeburn 8585: # If this is modifying password (internal auth) domains must match for user and user's role.
8586:
8587: if ($priv eq 'mip') {
8588: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8589: return $thisallowed;
8590: } else {
8591: return '';
8592: }
8593: }
8594:
1.620 albertel 8595: $courseprivid=$env{'request.course.id'};
8596: if ($env{'request.course.sec'}) {
8597: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8598: }
8599: $courseprivid=~s/\_/\//;
8600: my $checkreferer=1;
1.232 www 8601: my ($match,$cond)=&is_on_map($uri);
8602: if ($match) {
8603: $statecond=$cond;
1.620 albertel 8604: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8605: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8606: my $value = $1;
8607: if ($priv eq 'bre') {
1.1461 raeburn 8608: my $deeplinkblock;
8609: unless ($nodeeplinkcheck) {
8610: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8611: }
1.1458 raeburn 8612: if ($deeplinkblock) {
8613: $thisallowed = 'D';
8614: } elsif ($noblockcheck) {
1.1281 raeburn 8615: $thisallowed.=$value;
1.1162 raeburn 8616: } else {
1.1424 raeburn 8617: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8618: if (@blockers > 0) {
8619: $thisallowed = 'B';
8620: } else {
8621: $thisallowed.=$value;
8622: }
1.1162 raeburn 8623: }
8624: } else {
8625: $thisallowed.=$value;
8626: }
1.52 www 8627: $checkreferer=0;
8628: }
1.29 www 8629: }
1.1424 raeburn 8630:
1.148 www 8631: if ($checkreferer) {
1.620 albertel 8632: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8633: unless ($refuri) {
1.800 albertel 8634: foreach my $key (keys(%env)) {
8635: if ($key=~/^httpref\..*\*/) {
8636: my $pattern=$key;
1.156 www 8637: $pattern=~s/^httpref\.\/res\///;
1.148 www 8638: $pattern=~s/\*/\[\^\/\]\+/g;
8639: $pattern=~s/\//\\\//g;
1.152 www 8640: if ($orguri=~/$pattern/) {
1.800 albertel 8641: $refuri=$env{$key};
1.148 www 8642: }
8643: }
1.191 harris41 8644: }
1.148 www 8645: }
1.232 www 8646:
1.148 www 8647: if ($refuri) {
1.152 www 8648: $refuri=&declutter($refuri);
1.232 www 8649: my ($match,$cond)=&is_on_map($refuri);
8650: if ($match) {
8651: my $refstatecond=$cond;
1.620 albertel 8652: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8653: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8654: my $value = $1;
8655: if ($priv eq 'bre') {
1.1461 raeburn 8656: my $deeplinkblock;
8657: unless ($nodeeplinkcheck) {
8658: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8659: }
1.1402 raeburn 8660: if ($deeplinkblock) {
8661: $thisallowed = 'D';
8662: } elsif ($noblockcheck) {
1.1281 raeburn 8663: $thisallowed.=$value;
1.1162 raeburn 8664: } else {
1.1426 raeburn 8665: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8666: if (@blockers > 0) {
8667: $thisallowed = 'B';
8668: } else {
8669: $thisallowed.=$value;
8670: }
1.1162 raeburn 8671: }
8672: } else {
8673: $thisallowed.=$value;
8674: }
1.53 www 8675: $uri=$refuri;
8676: $statecond=$refstatecond;
1.52 www 8677: }
8678: }
1.148 www 8679: }
1.29 www 8680: }
1.52 www 8681: }
1.29 www 8682:
1.52 www 8683: #
1.103 harris41 8684: # Gathered now: all privileges that could apply, and condition number
1.52 www 8685: #
8686: #
8687: # Full or no access?
8688: #
1.29 www 8689:
1.52 www 8690: if ($thisallowed=~/F/) {
8691: return 'F';
8692: }
1.29 www 8693:
1.52 www 8694: unless ($thisallowed) {
8695: return '';
8696: }
1.29 www 8697:
1.52 www 8698: # Restrictions exist, deal with them
8699: #
8700: # C:according to course preferences
8701: # R:according to resource settings
8702: # L:unless locked
8703: # X:according to user session state
8704: #
8705:
8706: # Possibly locked functionality, check all courses
1.1454 raeburn 8707: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 8708: # Locks might take effect only after 10 minutes cache expiration for other
1.1454 raeburn 8709: # courses, and 2 minutes for current course, in which user has st or ta role
8710: # which is neither expired nor a future role (unless current course).
1.52 www 8711:
1.1454 raeburn 8712: my ($needlockcheck,$now,$crsonly);
1.52 www 8713: if ($thisallowed=~/L/) {
1.1454 raeburn 8714: $now = time;
8715: if ($priv eq 'bre') {
8716: if ($uri ne '') {
8717: if ($orguri =~ m{^/+res/}) {
8718: if ($uri =~ m{^lib/templates/}) {
8719: if ($env{'request.course.id'}) {
8720: $crsonly = 1;
8721: $needlockcheck = 1;
8722: }
8723: } else {
8724: $needlockcheck = 1;
8725: }
8726: } elsif ($env{'request.course.id'}) {
8727: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8728: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8729: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8730: $crsonly = 1;
8731: }
8732: $needlockcheck = 1;
8733: }
8734: }
8735: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8736: $needlockcheck = 1;
8737: }
8738: }
8739: if ($needlockcheck) {
1.1453 raeburn 8740: foreach my $envkey (keys(%env)) {
1.54 www 8741: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8742: my $courseid=$2;
8743: my $roleid=$1.'.'.$2;
1.92 www 8744: $courseid=~s/^\///;
1.1453 raeburn 8745: unless ($env{'request.role'} eq $roleid) {
8746: my ($start,$end) = split(/\./,$env{$envkey});
8747: next unless (($now >= $start) && (!$end || $end > $now));
8748: }
1.54 www 8749: my $expiretime=600;
1.620 albertel 8750: if ($env{'request.role'} eq $roleid) {
1.54 www 8751: $expiretime=120;
8752: }
8753: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8754: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8755: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8756: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8757: }
1.620 albertel 8758: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8759: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8760: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8761: &log($env{'user.domain'},$env{'user.name'},
8762: $env{'user.home'},
1.57 www 8763: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8764: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8765: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8766: return '';
8767: }
8768: }
1.620 albertel 8769: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8770: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455 raeburn 8771: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 8772: &log($env{'user.domain'},$env{'user.name'},
8773: $env{'user.home'},
1.57 www 8774: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8775: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8776: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8777: return '';
8778: }
8779: }
8780: }
1.29 www 8781: }
1.52 www 8782: }
1.1424 raeburn 8783:
1.52 www 8784: #
8785: # Rest of the restrictions depend on selected course
8786: #
8787:
1.620 albertel 8788: unless ($env{'request.course.id'}) {
1.766 albertel 8789: if ($thisallowed eq 'A') {
8790: return 'A';
1.814 raeburn 8791: } elsif ($thisallowed eq 'B') {
8792: return 'B';
1.766 albertel 8793: } else {
8794: return '1';
8795: }
1.52 www 8796: }
1.29 www 8797:
1.52 www 8798: #
8799: # Now user is definitely in a course
8800: #
1.53 www 8801:
8802:
8803: # Course preferences
8804:
8805: if ($thisallowed=~/C/) {
1.620 albertel 8806: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8807: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8808: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8809: =~/\Q$rolecode\E/) {
1.1304 raeburn 8810: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8811: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8812: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8813: $env{'request.course.id'});
8814: }
1.237 www 8815: return '';
8816: }
8817:
1.620 albertel 8818: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8819: =~/\Q$unamedom\E/) {
1.1304 raeburn 8820: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8821: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8822: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8823: $env{'request.course.id'});
8824: }
1.54 www 8825: return '';
8826: }
1.53 www 8827: }
8828:
8829: # Resource preferences
8830:
8831: if ($thisallowed=~/R/) {
1.620 albertel 8832: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8833: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8834: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8835: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8836: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8837: }
8838: return '';
1.54 www 8839: }
1.53 www 8840: }
1.30 www 8841:
1.1461 raeburn 8842: # Restricted for deeplinked session?
8843:
8844: if ($env{'request.deeplink.login'}) {
8845: if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
8846: if (!$symb) { $symb=&symbread($uri,1); }
8847: if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
8848: return '';
8849: }
8850: }
8851: }
8852:
1.246 www 8853: # Restricted by state or randomout?
1.30 www 8854:
1.52 www 8855: if ($thisallowed=~/X/) {
1.620 albertel 8856: if ($env{'acc.randomout'}) {
1.579 albertel 8857: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8858: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8859: return '';
8860: }
1.247 www 8861: }
8862: if (&condval($statecond)) {
1.52 www 8863: return '2';
8864: } else {
8865: return '';
8866: }
8867: }
1.30 www 8868:
1.766 albertel 8869: if ($thisallowed eq 'A') {
8870: return 'A';
1.814 raeburn 8871: } elsif ($thisallowed eq 'B') {
8872: return 'B';
1.1402 raeburn 8873: } elsif ($thisallowed eq 'D') {
8874: return 'D';
1.766 albertel 8875: }
1.52 www 8876: return 'F';
1.232 www 8877: }
1.1162 raeburn 8878:
1.1192 raeburn 8879: # ------------------------------------------- Check construction space access
8880:
8881: sub constructaccess {
8882: my ($url,$setpriv)=@_;
8883:
8884: # We do not allow editing of previous versions of files
8885: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8886:
8887: # Get username and domain from URL
8888: my ($ownername,$ownerdomain,$ownerhome);
8889:
8890: ($ownerdomain,$ownername) =
1.1325 raeburn 8891: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 8892:
8893: # The URL does not really point to any authorspace, forget it
8894: unless (($ownername) && ($ownerdomain)) { return ''; }
8895:
8896: # Now we need to see if the user has access to the authorspace of
8897: # $ownername at $ownerdomain
8898:
8899: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8900: # Real author for this?
8901: $ownerhome = $env{'user.home'};
8902: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8903: return ($ownername,$ownerdomain,$ownerhome);
8904: }
8905: } else {
8906: # Co-author for this?
8907: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8908: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8909: $ownerhome = &homeserver($ownername,$ownerdomain);
8910: return ($ownername,$ownerdomain,$ownerhome);
8911: }
1.1312 raeburn 8912: if ($env{'request.course.id'}) {
8913: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
8914: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
8915: if (&allowed('mdc',$env{'request.course.id'})) {
8916: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
8917: return ($ownername,$ownerdomain,$ownerhome);
8918: }
8919: }
8920: }
1.1192 raeburn 8921: }
8922:
8923: # We don't have any access right now. If we are not possibly going to do anything about this,
8924: # we might as well leave
8925: unless ($setpriv) { return ''; }
8926:
8927: # Backdoor access?
8928: my $allowed=&allowed('eco',$ownerdomain);
8929: # Nope
8930: unless ($allowed) { return ''; }
8931: # Looks like we may have access, but could be locked by the owner of the construction space
8932: if ($allowed eq 'U') {
8933: my %blocked=&get('environment',['domcoord.author'],
8934: $ownerdomain,$ownername);
8935: # Is blocked by owner
8936: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8937: }
8938: if (($allowed eq 'F') || ($allowed eq 'U')) {
8939: # Grant temporary access
8940: my $then=$env{'user.login.time'};
1.1209 raeburn 8941: my $update=$env{'user.update.time'};
1.1192 raeburn 8942: if (!$update) { $update = $then; }
8943: my $refresh=$env{'user.refresh.time'};
8944: if (!$refresh) { $refresh = $update; }
8945: my $now = time;
8946: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8947: $now,'ca','constructaccess');
8948: $ownerhome = &homeserver($ownername,$ownerdomain);
8949: return($ownername,$ownerdomain,$ownerhome);
8950: }
8951: # No business here
8952: return '';
8953: }
8954:
1.1282 raeburn 8955: # ----------------------------------------------------------- Content Blocking
8956:
8957: {
8958: # Caches for faster Course Contents display where content blocking
8959: # is in operation (i.e., interval param set) for timed quiz.
8960: #
8961: # User for whom data are being temporarily cached.
8962: my $cacheduser='';
1.1424 raeburn 8963: # Course for which data are being temporarily cached.
8964: my $cachedcid='';
1.1282 raeburn 8965: # Cached blockers for this user (a hash of blocking items).
8966: my %cachedblockers=();
8967: # When the data were last cached.
8968: my $cachedlast='';
8969:
8970: sub load_all_blockers {
1.1427 raeburn 8971: my ($uname,$udom)=@_;
1.1282 raeburn 8972: if (($uname ne '') && ($udom ne '')) {
8973: if (($cacheduser eq $uname.':'.$udom) &&
1.1424 raeburn 8974: ($cachedcid eq $env{'request.course.id'}) &&
1.1427 raeburn 8975: (abs($cachedlast-time)<5)) {
1.1282 raeburn 8976: return;
8977: }
8978: }
8979: $cachedlast=time;
8980: $cacheduser=$uname.':'.$udom;
1.1424 raeburn 8981: $cachedcid=$env{'request.course.id'};
1.1427 raeburn 8982: %cachedblockers = &get_commblock_resources();
1.1424 raeburn 8983: return;
1.1282 raeburn 8984: }
8985:
1.1162 raeburn 8986: sub get_comm_blocks {
8987: my ($cdom,$cnum) = @_;
8988: if ($cdom eq '' || $cnum eq '') {
8989: return unless ($env{'request.course.id'});
8990: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8991: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8992: }
8993: my %commblocks;
8994: my $hashid=$cdom.'_'.$cnum;
8995: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8996: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8997: %commblocks = %{$blocksref};
8998: } else {
1.1494 raeburn 8999: %commblocks = &dump('comm_block',$cdom,$cnum);
1.1162 raeburn 9000: my $cachetime = 600;
9001: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
9002: }
9003: return %commblocks;
9004: }
9005:
1.1282 raeburn 9006: sub get_commblock_resources {
9007: my ($blocks) = @_;
9008: my %blockers = ();
9009: return %blockers unless ($env{'request.course.id'});
1.1470 raeburn 9010: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9011: if ($env{'request.course.sec'}) {
9012: $courseurl .= '/'.$env{'request.course.sec'};
9013: }
9014: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162 raeburn 9015: my %commblocks;
9016: if (ref($blocks) eq 'HASH') {
9017: %commblocks = %{$blocks};
9018: } else {
9019: %commblocks = &get_comm_blocks();
9020: }
1.1282 raeburn 9021: return %blockers unless (keys(%commblocks) > 0);
9022: my $navmap = Apache::lonnavmaps::navmap->new();
9023: return %blockers unless (ref($navmap));
1.1162 raeburn 9024: my $now = time;
9025: foreach my $block (keys(%commblocks)) {
9026: if ($block =~ /^(\d+)____(\d+)$/) {
9027: my ($start,$end) = ($1,$2);
9028: if ($start <= $now && $end >= $now) {
9029: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
9030: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
9031: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 9032: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9033: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 9034: }
9035: }
9036: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 9037: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9038: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 9039: }
9040: }
9041: }
9042: }
9043: }
9044: } elsif ($block =~ /^firstaccess____(.+)$/) {
9045: my $item = $1;
9046: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
9047: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1471 raeburn 9048: my (@interval,$mapname);
1.1282 raeburn 9049: my $type = 'map';
9050: if ($item eq 'course') {
9051: $type = 'course';
9052: @interval=&EXT("resource.0.interval");
9053: } else {
9054: if ($item =~ /___\d+___/) {
9055: $type = 'resource';
9056: @interval=&EXT("resource.0.interval",$item);
1.1162 raeburn 9057: } else {
1.1471 raeburn 9058: $mapname = &deversion($item);
9059: if (ref($navmap)) {
9060: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
9061: @interval = ($timelimit,'map');
1.1162 raeburn 9062: }
9063: }
1.1282 raeburn 9064: }
1.1310 raeburn 9065: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 9066: my $timelimit = $1;
1.1282 raeburn 9067: my $first_access;
9068: if ($type eq 'resource') {
9069: $first_access=&get_first_access($interval[1],$item);
9070: } elsif ($type eq 'map') {
9071: $first_access=&get_first_access($interval[1],undef,$item);
9072: } else {
9073: $first_access=&get_first_access($interval[1]);
9074: }
9075: if ($first_access) {
1.1292 raeburn 9076: my $timesup = $first_access+$timelimit;
1.1282 raeburn 9077: if ($timesup > $now) {
9078: my $activeblock;
1.1471 raeburn 9079: if ($type eq 'resource') {
9080: if (ref($navmap)) {
9081: my $res = $navmap->getBySymb($item);
9082: if ($res->answerable()) {
9083: $activeblock = 1;
9084: }
9085: }
9086: } elsif ($type eq 'map') {
9087: my $mapsymb = &symbread($mapname,1);
9088: if (($mapsymb) && (ref($navmap))) {
9089: my $mapres = $navmap->getBySymb($mapsymb);
9090: if (ref($mapres)) {
9091: my $first = $mapres->map_start();
9092: my $finish = $mapres->map_finish();
9093: my $it = $navmap->getIterator($first,$finish,undef,0,0);
9094: if (ref($it)) {
9095: my $res;
9096: while ($res = $it->next(undef,1)) {
9097: next unless (ref($res));
9098: my $symb = $res->symb();
9099: next if (($symb eq $mapsymb) || ($symb eq ''));
9100: @interval=&EXT("resource.0.interval",$symb);
9101: if ($interval[1] eq 'map') {
9102: if ($res->answerable()) {
9103: $activeblock = 1;
9104: last;
9105: }
9106: }
9107: }
9108: }
9109: }
1.1282 raeburn 9110: }
9111: }
9112: if ($activeblock) {
9113: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
9114: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9115: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
9116: }
9117: }
9118: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
9119: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9120: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 9121: }
1.1162 raeburn 9122: }
9123: }
9124: }
9125: }
9126: }
9127: }
9128: }
9129: }
9130: }
1.1282 raeburn 9131: return %blockers;
1.1162 raeburn 9132: }
9133:
1.1282 raeburn 9134: sub has_comm_blocking {
1.1427 raeburn 9135: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282 raeburn 9136: my @blockers;
9137: return unless ($env{'request.course.id'});
9138: return unless ($priv eq 'bre');
9139: return if ($env{'request.state'} eq 'construct');
1.1470 raeburn 9140: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9141: if ($env{'request.course.sec'}) {
9142: $courseurl .= '/'.$env{'request.course.sec'};
9143: }
9144: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1427 raeburn 9145: my %blockinfo;
9146: if (ref($blocks) eq 'HASH') {
9147: %blockinfo = &get_commblock_resources($blocks);
9148: } else {
9149: &load_all_blockers($env{'user.name'},$env{'user.domain'});
9150: %blockinfo = %cachedblockers;
9151: }
9152: return unless (keys(%blockinfo) > 0);
1.1282 raeburn 9153: my (%possibles,@symbs);
9154: if (!$symb) {
1.1427 raeburn 9155: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 9156: }
1.1282 raeburn 9157: if ($symb) {
9158: @symbs = ($symb);
9159: } elsif (keys(%possibles)) {
9160: @symbs = keys(%possibles);
9161: }
9162: my $noblock;
9163: foreach my $symb (@symbs) {
9164: last if ($noblock);
9165: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427 raeburn 9166: foreach my $block (keys(%blockinfo)) {
1.1282 raeburn 9167: if ($block =~ /^firstaccess____(.+)$/) {
9168: my $item = $1;
1.1424 raeburn 9169: unless ($blocked) {
9170: if (($item eq $map) || ($item eq $symb)) {
9171: $noblock = 1;
9172: last;
9173: }
1.1282 raeburn 9174: }
9175: }
1.1427 raeburn 9176: if (ref($blockinfo{$block}) eq 'HASH') {
9177: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
9178: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282 raeburn 9179: unless (grep(/^\Q$block\E$/,@blockers)) {
9180: push(@blockers,$block);
9181: }
9182: }
9183: }
1.1427 raeburn 9184: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
9185: if ($blockinfo{$block}{'maps'}{$map}) {
1.1424 raeburn 9186: unless (grep(/^\Q$block\E$/,@blockers)) {
9187: push(@blockers,$block);
9188: }
1.1282 raeburn 9189: }
9190: }
1.1162 raeburn 9191: }
9192: }
9193: }
1.1424 raeburn 9194: unless ($noblock) {
9195: return @blockers;
9196: }
9197: return;
1.1282 raeburn 9198: }
1.1162 raeburn 9199: }
9200:
1.1402 raeburn 9201: sub deeplink_check {
9202: my ($priv,$symb,$uri) = @_;
9203: return unless ($env{'request.course.id'});
9204: return unless ($priv eq 'bre');
9205: return if ($env{'request.state'} eq 'construct');
9206: return if ($env{'request.role.adv'});
9207: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9208: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9209: my (%possibles,@symbs);
9210: if (!$symb) {
9211: $symb = &symbread($uri,1,1,1,\%possibles);
9212: }
9213: if ($symb) {
9214: @symbs = ($symb);
9215: } elsif (keys(%possibles)) {
9216: @symbs = keys(%possibles);
9217: }
9218:
1.1461 raeburn 9219: my ($deeplink_symb,$allow);
9220: if ($env{'request.deeplink.login'}) {
9221: $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1.1402 raeburn 9222: }
9223: foreach my $symb (@symbs) {
9224: last if ($allow);
9225: my $deeplink = &EXT("resource.0.deeplink",$symb);
9226: if ($deeplink eq '') {
9227: $allow = 1;
9228: } else {
1.1463 raeburn 9229: my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
9230: if ($state ne 'only') {
1.1402 raeburn 9231: $allow = 1;
1.1463 raeburn 9232: } else {
9233: my $check_deeplink_entry;
9234: if ($protect ne 'none') {
9235: my ($acctype,$item) = split(/:/,$protect);
9236: if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
9237: if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
9238: $check_deeplink_entry = 1
9239: }
9240: } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
9241: if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
9242: $check_deeplink_entry = 1;
9243: }
9244: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
9245: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
9246: $check_deeplink_entry = 1;
9247: }
9248: }
9249: }
9250: if (($protect eq 'none') || ($check_deeplink_entry)) {
1.1402 raeburn 9251: if ($scope eq 'res') {
1.1461 raeburn 9252: if ($symb eq $deeplink_symb) {
1.1402 raeburn 9253: $allow = 1;
9254: }
1.1459 raeburn 9255: } elsif (($scope eq 'map') || ($scope eq 'rec')) {
1.1463 raeburn 9256: my ($map_from_symb,$map_from_login);
1.1461 raeburn 9257: $map_from_symb = &deversion((&decode_symb($symb))[0]);
9258: if ($deeplink_symb =~ /\.(page|sequence)$/) {
9259: $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
9260: } else {
9261: $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
9262: }
1.1459 raeburn 9263: if (($map_from_symb) && ($map_from_login)) {
9264: if ($map_from_symb eq $map_from_login) {
9265: $allow = 1;
9266: } elsif ($scope eq 'rec') {
9267: my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
9268: if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
9269: $allow = 1;
9270: }
9271: }
9272: }
1.1402 raeburn 9273: }
9274: }
9275: }
9276: }
9277: }
9278: return if ($allow);
9279: return 1;
9280: }
9281:
1.1282 raeburn 9282: # -------------------------------- Deversion and split uri into path an filename
9283:
1.1133 foxr 9284: #
1.1282 raeburn 9285: # Removes the version from a URI and
1.1133 foxr 9286: # splits it in to its filename and path to the filename.
9287: # Seems like File::Basename could have done this more clearly.
9288: # Parameters:
9289: # $uri - input URI
9290: # Returns:
9291: # Two element list consisting of
9292: # $pathname - the URI up to and excluding the trailing /
9293: # $filename - The part of the URI following the last /
9294: # NOTE:
9295: # Another realization of this is simply:
9296: # use File::Basename;
9297: # ...
9298: # $uri = shift;
9299: # $filename = basename($uri);
9300: # $path = dirname($uri);
9301: # return ($filename, $path);
9302: #
9303: # The implementation below is probably faster however.
9304: #
1.710 albertel 9305: sub split_uri_for_cond {
9306: my $uri=&deversion(&declutter(shift));
9307: my @uriparts=split(/\//,$uri);
9308: my $filename=pop(@uriparts);
9309: my $pathname=join('/',@uriparts);
9310: return ($pathname,$filename);
9311: }
1.232 www 9312: # --------------------------------------------------- Is a resource on the map?
9313:
9314: sub is_on_map {
1.710 albertel 9315: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 9316: #Trying to find the conditional for the file
1.620 albertel 9317: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 9318: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 9319: if ($match) {
1.289 bowersj2 9320: return (1,$1);
9321: } else {
1.434 www 9322: return (0,0);
1.289 bowersj2 9323: }
1.12 www 9324: }
9325:
1.427 www 9326: # --------------------------------------------------------- Get symb from alias
9327:
9328: sub get_symb_from_alias {
9329: my $symb=shift;
9330: my ($map,$resid,$url)=&decode_symb($symb);
9331: # Already is a symb
9332: if ($url) { return $symb; }
9333: # Must be an alias
9334: my $aliassymb='';
9335: my %bighash;
1.620 albertel 9336: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 9337: &GDBM_READER(),0640)) {
9338: my $rid=$bighash{'mapalias_'.$symb};
9339: if ($rid) {
9340: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 9341: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9342: $resid,$bighash{'src_'.$rid});
1.427 www 9343: }
9344: untie %bighash;
9345: }
9346: return $aliassymb;
9347: }
9348:
1.12 www 9349: # ----------------------------------------------------------------- Define Role
9350:
9351: sub definerole {
9352: if (allowed('mcr','/')) {
1.1326 raeburn 9353: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 9354: foreach my $role (split(':',$sysrole)) {
9355: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9356: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9357: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9358: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9359: return "refused:s:$crole&$cqual";
9360: }
9361: }
1.191 harris41 9362: }
1.800 albertel 9363: foreach my $role (split(':',$domrole)) {
9364: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9365: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9366: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9367: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 9368: return "refused:d:$crole&$cqual";
9369: }
9370: }
1.191 harris41 9371: }
1.800 albertel 9372: foreach my $role (split(':',$courole)) {
9373: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9374: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9375: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9376: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9377: return "refused:c:$crole&$cqual";
9378: }
9379: }
1.191 harris41 9380: }
1.1326 raeburn 9381: my $uhome;
9382: if (($uname ne '') && ($udom ne '')) {
9383: $uhome = &homeserver($uname,$udom);
9384: return $uhome if ($uhome eq 'no_host');
9385: } else {
9386: $uname = $env{'user.name'};
9387: $udom = $env{'user.domain'};
9388: $uhome = $env{'user.home'};
9389: }
1.620 albertel 9390: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 9391: "$udom:$uname:rolesdef_$rolename=".
1.21 www 9392: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 9393: return reply($command,$uhome);
1.12 www 9394: } else {
9395: return 'refused';
9396: }
1.105 harris41 9397: }
9398:
9399: # ---------------- Make a metadata query against the network of library servers
9400:
9401: sub metadata_query {
1.1237 raeburn 9402: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 9403: my %rhash;
1.845 albertel 9404: my %libserv = &all_library();
1.244 matthew 9405: my @server_list = (defined($server_array) ? @$server_array
9406: : keys(%libserv) );
9407: for my $server (@server_list) {
1.1237 raeburn 9408: my $domains = '';
9409: if (ref($domains_hash) eq 'HASH') {
9410: $domains = $domains_hash->{$server};
9411: }
1.118 harris41 9412: unless ($custom or $customshow) {
1.1237 raeburn 9413: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 9414: $rhash{$server}=$reply;
9415: }
9416: else {
9417: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 9418: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 9419: $server);
9420: $rhash{$server}=$reply;
9421: }
1.112 harris41 9422: }
1.118 harris41 9423: return \%rhash;
1.240 www 9424: }
9425:
9426: # ----------------------------------------- Send log queries and wait for reply
9427:
9428: sub log_query {
9429: my ($uname,$udom,$query,%filters)=@_;
9430: my $uhome=&homeserver($uname,$udom);
9431: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 9432: my $uhost=&hostname($uhome);
1.800 albertel 9433: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 9434: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9435: $uhome);
1.479 albertel 9436: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 9437: return get_query_reply($queryid);
9438: }
9439:
1.818 raeburn 9440: # -------------------------- Update MySQL table for portfolio file
9441:
9442: sub update_portfolio_table {
1.821 raeburn 9443: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 9444: if ($group ne '') {
9445: $file_name =~s /^\Q$group\E//;
9446: }
1.818 raeburn 9447: my $homeserver = &homeserver($uname,$udom);
9448: my $queryid=
1.821 raeburn 9449: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9450: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 9451: my $reply = &get_query_reply($queryid);
9452: return $reply;
9453: }
9454:
1.899 raeburn 9455: # -------------------------- Update MySQL allusers table
9456:
9457: sub update_allusers_table {
9458: my ($uname,$udom,$names) = @_;
9459: my $homeserver = &homeserver($uname,$udom);
9460: my $queryid=
9461: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9462: 'lastname='.&escape($names->{'lastname'}).'%%'.
9463: 'firstname='.&escape($names->{'firstname'}).'%%'.
9464: 'middlename='.&escape($names->{'middlename'}).'%%'.
9465: 'generation='.&escape($names->{'generation'}).'%%'.
9466: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9467: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 9468: return;
1.899 raeburn 9469: }
9470:
1.508 raeburn 9471: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 9472:
9473: sub fetch_enrollment_query {
1.511 raeburn 9474: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 9475: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 9476: my $maxtries = 1;
1.508 raeburn 9477: if ($context eq 'automated') {
9478: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 9479: $sleep = 2;
9480: $loopmax = 100;
1.547 raeburn 9481: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 9482: } else {
9483: $homeserver = &homeserver($cnum,$dom);
9484: }
1.838 albertel 9485: my $host=&hostname($homeserver);
1.506 raeburn 9486: my $cmd = '';
1.1000 raeburn 9487: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9488: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9489: }
9490: $cmd =~ s/%%$//;
9491: $cmd = &escape($cmd);
9492: my $query = 'fetchenrollment';
1.620 albertel 9493: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9494: unless ($queryid=~/^\Q$host\E\_/) {
9495: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9496: return 'error: '.$queryid;
9497: }
1.1317 raeburn 9498: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9499: my $tries = 1;
9500: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 9501: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9502: $tries ++;
9503: }
1.526 raeburn 9504: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9505: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9506: } else {
1.901 albertel 9507: my @responses = split(/:/,$reply);
1.1322 raeburn 9508: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9509: foreach my $line (@responses) {
9510: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9511: $$replyref{$key} = $value;
9512: }
9513: } else {
1.1117 foxr 9514: my $pathname = LONCAPA::tempdir();
1.800 albertel 9515: foreach my $line (@responses) {
9516: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9517: $$replyref{$key} = $value;
9518: if ($value > 0) {
1.800 albertel 9519: foreach my $item (@{$$affiliatesref{$key}}) {
9520: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9521: my $destname = $pathname.'/'.$filename;
9522: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9523: if ($xml_classlist =~ /^error/) {
9524: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9525: } else {
1.1359 raeburn 9526: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9527: print FILE &unescape($xml_classlist);
9528: close(FILE);
1.526 raeburn 9529: } else {
9530: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9531: }
9532: }
9533: }
9534: }
9535: }
9536: }
9537: return 'ok';
9538: }
9539: return 'error';
9540: }
9541:
1.242 www 9542: sub get_query_reply {
1.1471 raeburn 9543: my ($queryid,$sleep,$loopmax) = @_;
1.1317 raeburn 9544: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9545: $sleep = 0.2;
9546: }
9547: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9548: $loopmax = 100;
9549: }
1.1117 foxr 9550: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9551: my $reply='';
1.1317 raeburn 9552: for (1..$loopmax) {
9553: sleep($sleep);
1.240 www 9554: if (-e $replyfile.'.end') {
1.1359 raeburn 9555: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9556: $reply = join('',<$fh>);
9557: close($fh);
1.240 www 9558: } else { return 'error: reply_file_error'; }
1.242 www 9559: return &unescape($reply);
9560: }
1.240 www 9561: }
1.242 www 9562: return 'timeout:'.$queryid;
1.240 www 9563: }
9564:
9565: sub courselog_query {
1.241 www 9566: #
9567: # possible filters:
9568: # url: url or symb
9569: # username
9570: # domain
9571: # action: view, submit, grade
9572: # start: timestamp
9573: # end: timestamp
9574: #
1.240 www 9575: my (%filters)=@_;
1.620 albertel 9576: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9577: if ($filters{'url'}) {
9578: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9579: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9580: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9581: }
1.620 albertel 9582: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9583: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9584: return &log_query($cname,$cdom,'courselog',%filters);
9585: }
9586:
9587: sub userlog_query {
1.858 raeburn 9588: #
9589: # possible filters:
9590: # action: log check role
9591: # start: timestamp
9592: # end: timestamp
9593: #
1.240 www 9594: my ($uname,$udom,%filters)=@_;
9595: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9596: }
9597:
1.506 raeburn 9598: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9599:
9600: sub auto_run {
1.508 raeburn 9601: my ($cnum,$cdom) = @_;
1.876 raeburn 9602: my $response = 0;
9603: my $settings;
9604: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9605: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9606: $settings = $domconfig{'autoenroll'};
9607: if ($settings->{'run'} eq '1') {
9608: $response = 1;
9609: }
9610: } else {
1.934 raeburn 9611: my $homeserver;
9612: if (&is_course($cdom,$cnum)) {
9613: $homeserver = &homeserver($cnum,$cdom);
9614: } else {
9615: $homeserver = &domain($cdom,'primary');
9616: }
9617: if ($homeserver ne 'no_host') {
9618: $response = &reply('autorun:'.$cdom,$homeserver);
9619: }
1.876 raeburn 9620: }
1.506 raeburn 9621: return $response;
9622: }
1.776 albertel 9623:
1.506 raeburn 9624: sub auto_get_sections {
1.508 raeburn 9625: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9626: my $homeserver;
9627: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9628: $homeserver = &homeserver($cnum,$cdom);
9629: }
9630: if (!defined($homeserver)) {
9631: if ($cdom =~ /^$match_domain$/) {
9632: $homeserver = &domain($cdom,'primary');
9633: }
9634: }
9635: my @secs;
9636: if (defined($homeserver)) {
9637: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9638: unless ($response eq 'refused') {
9639: @secs = split(/:/,$response);
9640: }
1.506 raeburn 9641: }
9642: return @secs;
9643: }
1.776 albertel 9644:
1.506 raeburn 9645: sub auto_new_course {
1.1099 raeburn 9646: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9647: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9648: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9649: return $response;
9650: }
1.776 albertel 9651:
1.506 raeburn 9652: sub auto_validate_courseID {
1.508 raeburn 9653: my ($cnum,$cdom,$inst_course_id) = @_;
9654: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9655: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9656: return $response;
9657: }
1.776 albertel 9658:
1.1007 raeburn 9659: sub auto_validate_instcode {
1.1020 raeburn 9660: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9661: my ($homeserver,$response);
9662: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9663: $homeserver = &homeserver($cnum,$cdom);
9664: }
9665: if (!defined($homeserver)) {
9666: if ($cdom =~ /^$match_domain$/) {
9667: $homeserver = &domain($cdom,'primary');
9668: }
9669: }
1.1065 raeburn 9670: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9671: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 9672: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9673: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9674: }
9675:
1.1444 raeburn 9676: sub auto_validate_inst_crosslist {
9677: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9678: my ($homeserver,$response);
9679: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9680: $homeserver = &homeserver($cnum,$cdom);
9681: }
9682: if (!defined($homeserver)) {
9683: if ($cdom =~ /^$match_domain$/) {
9684: $homeserver = &domain($cdom,'primary');
9685: }
9686: }
9687: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9688: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9689: &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445 raeburn 9690: &escape($coowner),$homeserver);
1.1444 raeburn 9691: }
9692: return $response;
9693: }
9694:
1.506 raeburn 9695: sub auto_create_password {
1.873 raeburn 9696: my ($cnum,$cdom,$authparam,$udom) = @_;
9697: my ($homeserver,$response);
1.506 raeburn 9698: my $create_passwd = 0;
9699: my $authchk = '';
1.873 raeburn 9700: if ($udom =~ /^$match_domain$/) {
9701: $homeserver = &domain($udom,'primary');
9702: }
9703: if ($homeserver eq '') {
9704: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9705: $homeserver = &homeserver($cnum,$cdom);
9706: }
9707: }
9708: if ($homeserver eq '') {
9709: $authchk = 'nodomain';
1.506 raeburn 9710: } else {
1.873 raeburn 9711: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9712: if ($response eq 'refused') {
9713: $authchk = 'refused';
9714: } else {
1.901 albertel 9715: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9716: }
1.506 raeburn 9717: }
9718: return ($authparam,$create_passwd,$authchk);
9719: }
9720:
1.706 raeburn 9721: sub auto_photo_permission {
9722: my ($cnum,$cdom,$students) = @_;
9723: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9724: my ($outcome,$perm_reqd,$conditions) =
9725: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9726: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9727: return (undef,undef);
9728: }
1.706 raeburn 9729: return ($outcome,$perm_reqd,$conditions);
9730: }
9731:
9732: sub auto_checkphotos {
9733: my ($uname,$udom,$pid) = @_;
9734: my $homeserver = &homeserver($uname,$udom);
9735: my ($result,$resulttype);
9736: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9737: &escape($uname).':'.&escape($pid),
9738: $homeserver));
1.709 albertel 9739: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9740: return (undef,undef);
9741: }
1.706 raeburn 9742: if ($outcome) {
9743: ($result,$resulttype) = split(/:/,$outcome);
9744: }
9745: return ($result,$resulttype);
9746: }
9747:
9748: sub auto_photochoice {
9749: my ($cnum,$cdom) = @_;
9750: my $homeserver = &homeserver($cnum,$cdom);
9751: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9752: &escape($cdom),
9753: $homeserver)));
1.709 albertel 9754: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9755: return (undef,undef);
9756: }
1.706 raeburn 9757: return ($update,$comment);
9758: }
9759:
9760: sub auto_photoupdate {
9761: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9762: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9763: my $host=&hostname($homeserver);
1.706 raeburn 9764: my $cmd = '';
9765: my $maxtries = 1;
1.800 albertel 9766: foreach my $affiliate (keys(%{$affiliatesref})) {
9767: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9768: }
9769: $cmd =~ s/%%$//;
9770: $cmd = &escape($cmd);
9771: my $query = 'institutionalphotos';
9772: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9773: unless ($queryid=~/^\Q$host\E\_/) {
9774: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9775: return 'error: '.$queryid;
9776: }
9777: my $reply = &get_query_reply($queryid);
9778: my $tries = 1;
9779: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9780: $reply = &get_query_reply($queryid);
9781: $tries ++;
9782: }
9783: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9784: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9785: } else {
9786: my @responses = split(/:/,$reply);
9787: my $outcome = shift(@responses);
9788: foreach my $item (@responses) {
9789: my ($key,$value) = split(/=/,$item);
9790: $$photo{$key} = $value;
9791: }
9792: return $outcome;
9793: }
9794: return 'error';
9795: }
9796:
1.521 raeburn 9797: sub auto_instcode_format {
1.793 albertel 9798: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9799: $cat_order) = @_;
1.521 raeburn 9800: my $courses = '';
1.772 raeburn 9801: my @homeservers;
1.521 raeburn 9802: if ($caller eq 'global') {
1.841 albertel 9803: my %servers = &get_servers($codedom,'library');
9804: foreach my $tryserver (keys(%servers)) {
9805: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9806: push(@homeservers,$tryserver);
9807: }
1.584 raeburn 9808: }
1.1022 raeburn 9809: } elsif ($caller eq 'requests') {
9810: if ($codedom =~ /^$match_domain$/) {
9811: my $chome = &domain($codedom,'primary');
9812: unless ($chome eq 'no_host') {
9813: push(@homeservers,$chome);
9814: }
9815: }
1.521 raeburn 9816: } else {
1.772 raeburn 9817: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9818: }
1.793 albertel 9819: foreach my $code (keys(%{$instcodes})) {
9820: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9821: }
9822: chop($courses);
1.772 raeburn 9823: my $ok_response = 0;
9824: my $response;
9825: while (@homeservers > 0 && $ok_response == 0) {
9826: my $server = shift(@homeservers);
9827: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9828: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9829: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9830: split(/:/,$response);
1.772 raeburn 9831: %{$codes} = (%{$codes},&str2hash($codes_str));
9832: push(@{$codetitles},&str2array($codetitles_str));
9833: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9834: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9835: $ok_response = 1;
9836: }
9837: }
9838: if ($ok_response) {
1.521 raeburn 9839: return 'ok';
1.772 raeburn 9840: } else {
9841: return $response;
1.521 raeburn 9842: }
9843: }
9844:
1.792 raeburn 9845: sub auto_instcode_defaults {
9846: my ($domain,$returnhash,$code_order) = @_;
9847: my @homeservers;
1.841 albertel 9848:
9849: my %servers = &get_servers($domain,'library');
9850: foreach my $tryserver (keys(%servers)) {
9851: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9852: push(@homeservers,$tryserver);
9853: }
1.792 raeburn 9854: }
1.841 albertel 9855:
1.792 raeburn 9856: my $response;
1.841 albertel 9857: foreach my $server (@homeservers) {
1.792 raeburn 9858: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9859: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9860:
9861: foreach my $pair (split(/\&/,$response)) {
9862: my ($name,$value)=split(/\=/,$pair);
9863: if ($name eq 'code_order') {
9864: @{$code_order} = split(/\&/,&unescape($value));
9865: } else {
9866: $returnhash->{&unescape($name)}=&unescape($value);
9867: }
9868: }
9869: return 'ok';
1.792 raeburn 9870: }
1.841 albertel 9871:
9872: return $response;
1.1003 raeburn 9873: }
9874:
9875: sub auto_possible_instcodes {
1.1007 raeburn 9876: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9877: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9878: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9879: return;
9880: }
1.1003 raeburn 9881: my (@homeservers,$uhome);
9882: if (defined(&domain($domain,'primary'))) {
9883: $uhome=&domain($domain,'primary');
9884: push(@homeservers,&domain($domain,'primary'));
9885: } else {
9886: my %servers = &get_servers($domain,'library');
9887: foreach my $tryserver (keys(%servers)) {
9888: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9889: push(@homeservers,$tryserver);
9890: }
9891: }
9892: }
9893: my $response;
9894: foreach my $server (@homeservers) {
9895: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9896: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9897: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9898: split(':',$response);
9899: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9900: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9901: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9902: my ($name,$value)=split('=',$item);
9903: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9904: }
9905: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9906: my ($name,$value)=split('=',$item);
9907: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9908: }
9909: return 'ok';
9910: }
9911: return $response;
9912: }
1.792 raeburn 9913:
1.1010 raeburn 9914: sub auto_courserequest_checks {
9915: my ($dom) = @_;
1.1020 raeburn 9916: my ($homeserver,%validations);
9917: if ($dom =~ /^$match_domain$/) {
9918: $homeserver = &domain($dom,'primary');
9919: }
9920: unless ($homeserver eq 'no_host') {
9921: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9922: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9923: my @items = split(/&/,$response);
9924: foreach my $item (@items) {
9925: my ($key,$value) = split('=',$item);
9926: $validations{&unescape($key)} = &thaw_unescape($value);
9927: }
9928: }
9929: }
1.1010 raeburn 9930: return %validations;
9931: }
9932:
1.1020 raeburn 9933: sub auto_courserequest_validation {
1.1255 raeburn 9934: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9935: my ($homeserver,$response);
9936: if ($dom =~ /^$match_domain$/) {
9937: $homeserver = &domain($dom,'primary');
9938: }
1.1255 raeburn 9939: unless ($homeserver eq 'no_host') {
9940: my $customdata;
9941: if (ref($custominfo) eq 'HASH') {
9942: $customdata = &freeze_escape($custominfo);
9943: }
1.1020 raeburn 9944: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9945: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 9946: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9947: $customdata,$homeserver));
1.1020 raeburn 9948: }
9949: return $response;
9950: }
9951:
1.777 albertel 9952: sub auto_validate_class_sec {
1.918 raeburn 9953: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9954: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9955: my $ownerlist;
9956: if (ref($owners) eq 'ARRAY') {
9957: $ownerlist = join(',',@{$owners});
9958: } else {
9959: $ownerlist = $owners;
9960: }
1.773 raeburn 9961: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9962: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9963: return $response;
9964: }
9965:
1.1460 raeburn 9966: sub auto_instsec_reformat {
9967: my ($cdom,$action,$instsecref) = @_;
9968: return unless(($action eq 'clutter') || ($action eq 'declutter'));
9969: my @homeservers;
9970: if (defined(&domain($cdom,'primary'))) {
9971: push(@homeservers,&domain($cdom,'primary'));
9972: } else {
9973: my %servers = &get_servers($cdom,'library');
9974: foreach my $tryserver (keys(%servers)) {
9975: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9976: push(@homeservers,$tryserver);
9977: }
9978: }
9979: }
9980: my $response;
9981: my %reformatted = %{$instsecref};
9982: foreach my $server (@homeservers) {
9983: if (ref($instsecref) eq 'HASH') {
9984: my $info = &freeze_escape($instsecref);
9985: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
9986: $action.':'.$info,$server);
9987: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
9988: my @items = split(/&/,$response);
9989: foreach my $item (@items) {
9990: my ($key,$value) = split(/=/,$item);
9991: $reformatted{&unescape($key)} = &thaw_unescape($value);
9992: }
9993: }
9994: }
9995: return %reformatted;
9996: }
9997:
1.1367 raeburn 9998: sub auto_validate_instclasses {
9999: my ($cdom,$cnum,$owners,$classesref) = @_;
10000: my ($homeserver,%validations);
10001: $homeserver = &homeserver($cnum,$cdom);
10002: unless ($homeserver eq 'no_host') {
10003: my $ownerlist;
10004: if (ref($owners) eq 'ARRAY') {
10005: $ownerlist = join(',',@{$owners});
10006: } else {
10007: $ownerlist = $owners;
10008: }
10009: if (ref($classesref) eq 'HASH') {
10010: my $classes = &freeze_escape($classesref);
10011: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10012: ':'.$cdom.':'.$classes,$homeserver);
10013: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10014: my @items = split(/&/,$response);
10015: foreach my $item (@items) {
10016: my ($key,$value) = split('=',$item);
10017: $validations{&unescape($key)} = &thaw_unescape($value);
10018: }
10019: }
10020: }
10021: }
10022: return %validations;
10023: }
10024:
1.1248 raeburn 10025: sub auto_crsreq_update {
10026: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 10027: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 10028: my ($homeserver,%crsreqresponse);
10029: if ($cdom =~ /^$match_domain$/) {
10030: $homeserver = &domain($cdom,'primary');
10031: }
10032: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10033: my $info;
10034: if (ref($inbound) eq 'HASH') {
10035: $info = &freeze_escape($inbound);
10036: }
10037: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10038: ':'.&escape($action).':'.&escape($ownername).':'.
10039: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 10040: &escape($title).':'.&escape($code).':'.
10041: &escape($accessstart).':'.&escape($accessend).':'.$info,
10042: $homeserver);
1.1248 raeburn 10043: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10044: my @items = split(/&/,$response);
10045: foreach my $item (@items) {
10046: my ($key,$value) = split('=',$item);
10047: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10048: }
10049: }
10050: }
10051: return \%crsreqresponse;
10052: }
10053:
1.1305 raeburn 10054: sub auto_export_grades {
1.1309 raeburn 10055: my ($cdom,$cnum,$inforef,$gradesref) = @_;
10056: my ($homeserver,%exportresponse);
10057: if ($cdom =~ /^$match_domain$/) {
10058: $homeserver = &domain($cdom,'primary');
10059: }
10060: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10061: my $info;
10062: if (ref($inforef) eq 'HASH') {
10063: $info = &freeze_escape($inforef);
10064: }
10065: if (ref($gradesref) eq 'HASH') {
10066: my $grades = &freeze_escape($gradesref);
10067: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10068: $info.':'.$grades,$homeserver);
10069: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10070: my @items = split(/&/,$response);
10071: foreach my $item (@items) {
10072: my ($key,$value) = split('=',$item);
10073: $exportresponse{&unescape($key)} = &thaw_unescape($value);
10074: }
10075: }
10076: }
10077: }
10078: return \%exportresponse;
1.1305 raeburn 10079: }
10080:
1.1287 raeburn 10081: sub check_instcode_cloning {
10082: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10083: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10084: return;
10085: }
10086: my $canclone;
10087: if (@{$code_order} > 0) {
10088: my $instcoderegexp ='^';
10089: my @clonecodes = split(/\&/,$cloner);
10090: foreach my $item (@{$code_order}) {
10091: if (grep(/^\Q$item\E=/,@clonecodes)) {
10092: foreach my $pair (@clonecodes) {
10093: my ($key,$val) = split(/\=/,$pair,2);
10094: $val = &unescape($val);
10095: if ($key eq $item) {
10096: $instcoderegexp .= '('.$val.')';
10097: last;
10098: }
10099: }
10100: } else {
10101: $instcoderegexp .= $codedefaults->{$item};
10102: }
10103: }
10104: $instcoderegexp .= '$';
10105: my (@from,@to);
10106: eval {
10107: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10108: (@to) = ($clonetocode =~ /$instcoderegexp/);
10109: };
10110: if ((@from > 0) && (@to > 0)) {
10111: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10112: if (!@diffs) {
10113: $canclone = 1;
10114: }
10115: }
10116: }
10117: return $canclone;
10118: }
10119:
10120: sub default_instcode_cloning {
10121: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10122: my (%codedefaults,@code_order,$canclone);
10123: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10124: %codedefaults = %{$codedefaultsref};
10125: @code_order = @{$codeorderref};
10126: } elsif ($clonedom) {
10127: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10128: }
10129: if (($domdefclone) && (@code_order)) {
10130: my @clonecodes = split(/\+/,$domdefclone);
10131: my $instcoderegexp ='^';
10132: foreach my $item (@code_order) {
10133: if (grep(/^\Q$item\E$/,@clonecodes)) {
10134: $instcoderegexp .= '('.$codedefaults{$item}.')';
10135: } else {
10136: $instcoderegexp .= $codedefaults{$item};
10137: }
10138: }
10139: $instcoderegexp .= '$';
10140: my (@from,@to);
10141: eval {
10142: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10143: (@to) = ($clonetocode =~ /$instcoderegexp/);
10144: };
10145: if ((@from > 0) && (@to > 0)) {
10146: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10147: if (!@diffs) {
10148: $canclone = 1;
10149: }
10150: }
10151: }
10152: return $canclone;
10153: }
10154:
1.679 raeburn 10155: # ------------------------------------------------------- Course Group routines
10156:
10157: sub get_coursegroups {
1.809 raeburn 10158: my ($cdom,$cnum,$group,$namespace) = @_;
10159: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 10160: }
10161:
1.679 raeburn 10162: sub modify_coursegroup {
10163: my ($cdom,$cnum,$groupsettings) = @_;
10164: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10165: }
10166:
1.809 raeburn 10167: sub toggle_coursegroup_status {
10168: my ($cdom,$cnum,$group,$action) = @_;
10169: my ($from_namespace,$to_namespace);
10170: if ($action eq 'delete') {
10171: $from_namespace = 'coursegroups';
10172: $to_namespace = 'deleted_groups';
10173: } else {
10174: $from_namespace = 'deleted_groups';
10175: $to_namespace = 'coursegroups';
10176: }
10177: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 10178: if (my $tmp = &error(%curr_group)) {
10179: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10180: return ('read error',$tmp);
10181: } else {
10182: my %savedsettings = %curr_group;
1.809 raeburn 10183: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 10184: my $deloutcome;
10185: if ($result eq 'ok') {
1.809 raeburn 10186: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 10187: } else {
10188: return ('write error',$result);
10189: }
10190: if ($deloutcome eq 'ok') {
10191: return 'ok';
10192: } else {
10193: return ('delete error',$deloutcome);
10194: }
10195: }
10196: }
10197:
1.679 raeburn 10198: sub modify_group_roles {
1.957 raeburn 10199: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 10200: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10201: my $role = 'gr/'.&escape($userprivs);
10202: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 10203: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 10204: if ($result eq 'ok') {
10205: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10206: }
1.679 raeburn 10207: return $result;
10208: }
10209:
10210: sub modify_coursegroup_membership {
10211: my ($cdom,$cnum,$membership) = @_;
10212: my $result = &put('groupmembership',$membership,$cdom,$cnum);
10213: return $result;
10214: }
10215:
1.682 raeburn 10216: sub get_active_groups {
10217: my ($udom,$uname,$cdom,$cnum) = @_;
10218: my $now = time;
10219: my %groups = ();
10220: foreach my $key (keys(%env)) {
1.811 albertel 10221: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 10222: my ($start,$end) = split(/\./,$env{$key});
10223: if (($end!=0) && ($end<$now)) { next; }
10224: if (($start!=0) && ($start>$now)) { next; }
10225: if ($1 eq $cdom && $2 eq $cnum) {
10226: $groups{$3} = $env{$key} ;
10227: }
10228: }
10229: }
10230: return %groups;
10231: }
10232:
1.683 raeburn 10233: sub get_group_membership {
10234: my ($cdom,$cnum,$group) = @_;
10235: return(&dump('groupmembership',$cdom,$cnum,$group));
10236: }
10237:
10238: sub get_users_groups {
10239: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 10240: my @usersgroups;
1.683 raeburn 10241: my $cachetime=1800;
10242:
10243: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 10244: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10245: if (defined($cached)) {
1.734 albertel 10246: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 10247: } else {
10248: $grouplist = '';
1.816 raeburn 10249: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 10250: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 10251: my $access_end = $env{'course.'.$courseid.
10252: '.default_enrollment_end_date'};
10253: my $now = time;
10254: foreach my $key (keys(%roleshash)) {
10255: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10256: my $group = $1;
10257: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10258: my $start = $2;
10259: my $end = $1;
10260: if ($start == -1) { next; } # deleted from group
10261: if (($start!=0) && ($start>$now)) { next; }
10262: if (($end!=0) && ($end<$now)) {
10263: if ($access_end && $access_end < $now) {
10264: if ($access_end - $end < 86400) {
10265: push(@usersgroups,$group);
1.733 raeburn 10266: }
10267: }
1.817 raeburn 10268: next;
1.733 raeburn 10269: }
1.817 raeburn 10270: push(@usersgroups,$group);
1.683 raeburn 10271: }
10272: }
10273: }
1.817 raeburn 10274: @usersgroups = &sort_course_groups($courseid,@usersgroups);
10275: $grouplist = join(':',@usersgroups);
10276: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 10277: }
1.733 raeburn 10278: return @usersgroups;
1.683 raeburn 10279: }
10280:
10281: sub devalidate_getgroups_cache {
10282: my ($udom,$uname,$cdom,$cnum)=@_;
10283: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 10284:
1.683 raeburn 10285: my $hashid="$udom:$uname:$courseid";
10286: &devalidate_cache_new('getgroups',$hashid);
10287: }
10288:
1.12 www 10289: # ------------------------------------------------------------------ Plain Text
10290:
10291: sub plaintext {
1.988 raeburn 10292: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 10293: if ($short =~ m{^cr/}) {
1.758 albertel 10294: return (split('/',$short))[-1];
10295: }
1.742 raeburn 10296: if (!defined($cid)) {
10297: $cid = $env{'request.course.id'};
10298: }
10299: my %rolenames = (
1.1008 raeburn 10300: Course => 'std',
10301: Community => 'alt1',
1.1305 raeburn 10302: Placement => 'std',
1.742 raeburn 10303: );
1.1037 raeburn 10304: if ($cid ne '') {
10305: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10306: unless ($forcedefault) {
10307: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
10308: &Apache::lonlocal::mt_escape(\$roletext);
10309: return &Apache::lonlocal::mt($roletext);
10310: }
10311: }
10312: }
10313: if ((defined($type)) && (defined($rolenames{$type})) &&
10314: (defined($rolenames{$type})) &&
10315: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 10316: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 10317: } elsif ($cid ne '') {
10318: my $crstype = $env{'course.'.$cid.'.type'};
10319: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10320: (defined($prp{$short}{$rolenames{$crstype}}))) {
10321: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10322: }
1.742 raeburn 10323: }
1.1037 raeburn 10324: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 10325: }
10326:
10327: # ----------------------------------------------------------------- Assign Role
10328:
10329: sub assignrole {
1.957 raeburn 10330: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10331: $context)=@_;
1.21 www 10332: my $mrole;
10333: if ($role =~ /^cr\//) {
1.393 www 10334: my $cwosec=$url;
1.811 albertel 10335: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 10336: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 10337: my $refused = 1;
10338: if ($context eq 'requestcourses') {
10339: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10340: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10341: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10342: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10343: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10344: if ($crsenv{'internal.courseowner'} eq
10345: $env{'user.name'}.':'.$env{'user.domain'}) {
10346: $refused = '';
10347: }
10348: }
10349: }
10350: }
10351: }
10352: if ($refused) {
10353: &logthis('Refused custom assignrole: '.
10354: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10355: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10356: return 'refused';
10357: }
1.104 www 10358: }
1.21 www 10359: $mrole='cr';
1.678 raeburn 10360: } elsif ($role =~ /^gr\//) {
10361: my $cwogrp=$url;
1.811 albertel 10362: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 10363: unless (&allowed('mdg',$cwogrp)) {
10364: &logthis('Refused group assignrole: '.
10365: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10366: $env{'user.name'}.' at '.$env{'user.domain'});
10367: return 'refused';
10368: }
10369: $mrole='gr';
1.21 www 10370: } else {
1.82 www 10371: my $cwosec=$url;
1.811 albertel 10372: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 10373: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10374: my $refused;
10375: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10376: if (!(&allowed('c'.$role,$url))) {
10377: $refused = 1;
10378: }
10379: } else {
10380: $refused = 1;
10381: }
1.947 raeburn 10382: if ($refused) {
1.1045 raeburn 10383: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377 raeburn 10384: if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045 raeburn 10385: my %crsenv;
10386: if ($role eq 'cc' || $role eq 'co') {
10387: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10388: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10389: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10390: if ($crsenv{'internal.courseowner'} eq
10391: $env{'user.name'}.':'.$env{'user.domain'}) {
10392: $refused = '';
10393: }
10394: }
10395: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10396: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10397: if ($crsenv{'internal.courseowner'} eq
10398: $env{'user.name'}.':'.$env{'user.domain'}) {
10399: $refused = '';
10400: }
10401: }
10402: }
10403: }
1.1368 raeburn 10404: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10405: if ($role eq 'st') {
10406: $refused = '';
1.1377 raeburn 10407: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368 raeburn 10408: $refused = '';
10409: }
1.1017 raeburn 10410: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 10411: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 10412: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 10413: my $wrongcc;
10414: if ($cnum =~ /^$match_community$/) {
10415: $wrongcc = 1 if ($role eq 'cc');
10416: } else {
10417: $wrongcc = 1 if ($role eq 'co');
10418: }
10419: unless ($wrongcc) {
10420: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10421: if ($crsenv{'internal.courseowner'} eq
10422: $env{'user.name'}.':'.$env{'user.domain'}) {
10423: $refused = '';
10424: }
1.1017 raeburn 10425: }
10426: }
1.1183 raeburn 10427: } elsif ($context eq 'requestauthor') {
10428: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10429: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10430: if ($env{'environment.requestauthor'} eq 'automatic') {
10431: $refused = '';
10432: } else {
10433: my %domdefaults = &get_domain_defaults($udom);
10434: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10435: my $checkbystatus;
10436: if ($env{'user.adv'}) {
10437: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10438: if ($disposition eq 'automatic') {
10439: $refused = '';
10440: } elsif ($disposition eq '') {
10441: $checkbystatus = 1;
10442: }
10443: } else {
10444: $checkbystatus = 1;
10445: }
10446: if ($checkbystatus) {
10447: if ($env{'environment.inststatus'}) {
10448: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10449: foreach my $type (@inststatuses) {
10450: if (($type ne '') &&
10451: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10452: $refused = '';
10453: }
10454: }
10455: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10456: $refused = '';
10457: }
10458: }
10459: }
10460: }
10461: }
1.1017 raeburn 10462: }
10463: if ($refused) {
1.947 raeburn 10464: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10465: ' '.$role.' '.$end.' '.$start.' by '.
10466: $env{'user.name'}.' at '.$env{'user.domain'});
10467: return 'refused';
10468: }
1.932 raeburn 10469: }
1.1131 raeburn 10470: } elsif ($role eq 'au') {
10471: if ($url ne '/'.$udom.'/') {
10472: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10473: ' to assign author role for '.$uname.':'.$udom.
10474: ' in domain: '.$url.' refused (wrong domain).');
10475: return 'refused';
10476: }
1.104 www 10477: }
1.21 www 10478: $mrole=$role;
10479: }
1.620 albertel 10480: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 10481: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 10482: if ($end) { $command.='_'.$end; }
1.21 www 10483: if ($start) {
10484: if ($end) {
1.81 www 10485: $command.='_'.$start;
1.21 www 10486: } else {
1.81 www 10487: $command.='_0_'.$start;
1.21 www 10488: }
10489: }
1.739 raeburn 10490: my $origstart = $start;
10491: my $origend = $end;
1.957 raeburn 10492: my $delflag;
1.357 www 10493: # actually delete
10494: if ($deleteflag) {
1.373 www 10495: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 10496: # modify command to delete the role
1.620 albertel 10497: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 10498: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 10499: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 10500: # set start and finish to negative values for userrolelog
10501: $start=-1;
10502: $end=-1;
1.957 raeburn 10503: $delflag = 1;
1.357 www 10504: }
10505: }
10506: # send command
1.349 www 10507: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 10508: # log new user role if status is ok
1.349 www 10509: if ($answer eq 'ok') {
1.663 raeburn 10510: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 10511: if (($role eq 'cc') || ($role eq 'in') ||
10512: ($role eq 'ep') || ($role eq 'ad') ||
10513: ($role eq 'ta') || ($role eq 'st') ||
10514: ($role=~/^cr/) || ($role eq 'gr') ||
10515: ($role eq 'co')) {
1.1200 raeburn 10516: # for course roles, perform group memberships changes triggered by role change.
10517: unless ($role =~ /^gr/) {
10518: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10519: $origstart,$selfenroll,$context);
10520: }
1.1184 raeburn 10521: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10522: $selfenroll,$context);
10523: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 10524: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10525: ($role eq 'da')) {
1.1184 raeburn 10526: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10527: $context);
10528: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10529: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10530: $context);
10531: }
1.1053 raeburn 10532: if ($role eq 'cc') {
10533: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10534: }
1.349 www 10535: }
10536: return $answer;
1.169 harris41 10537: }
10538:
1.1053 raeburn 10539: sub autoupdate_coowners {
10540: my ($url,$end,$start,$uname,$udom) = @_;
10541: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10542: if (($cdom ne '') && ($cnum ne '')) {
10543: my $now = time;
10544: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10545: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10546: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10547: my $instcode = $coursehash{'internal.coursecode'};
1.1444 raeburn 10548: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 10549: if ($instcode ne '') {
1.1056 raeburn 10550: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10551: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10552: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10553: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444 raeburn 10554: unless ($result eq 'valid') {
10555: if ($xlists ne '') {
10556: foreach my $xlist (split(',',$xlists)) {
10557: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10558: $result =
1.1446 raeburn 10559: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10560: $inst_crosslist,$uname.':'.$udom);
10561: last if ($result eq 'valid');
1.1444 raeburn 10562: }
10563: }
10564: }
1.1056 raeburn 10565: if ($result eq 'valid') {
10566: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10567: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10568: push(@newcoowners,$coowner);
10569: }
10570: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10571: push(@newcoowners,$uname.':'.$udom);
10572: }
10573: @newcoowners = sort(@newcoowners);
10574: } else {
10575: push(@newcoowners,$uname.':'.$udom);
10576: }
1.1444 raeburn 10577: } elsif ($coursehash{'internal.co-owners'}) {
10578: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10579: unless ($coowner eq $uname.':'.$udom) {
10580: push(@newcoowners,$coowner);
1.1053 raeburn 10581: }
1.1444 raeburn 10582: }
10583: unless (@newcoowners > 0) {
10584: $delcoowners = 1;
10585: $coowners = '';
1.1053 raeburn 10586: }
10587: }
10588: if (@newcoowners || $delcoowners) {
10589: &store_coowners($cdom,$cnum,$coursehash{'home'},
10590: $delcoowners,@newcoowners);
10591: }
10592: }
10593: }
10594: }
10595: }
10596: }
10597: }
10598:
10599: sub store_coowners {
10600: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10601: my $cid = $cdom.'_'.$cnum;
10602: my ($coowners,$delresult,$putresult);
10603: if (@newcoowners) {
10604: $coowners = join(',',@newcoowners);
10605: my %coownershash = (
10606: 'internal.co-owners' => $coowners,
10607: );
10608: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10609: if ($putresult eq 'ok') {
10610: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10611: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10612: }
10613: }
10614: }
10615: if ($delcoowners) {
10616: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10617: if ($delresult eq 'ok') {
10618: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10619: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10620: }
10621: }
10622: }
10623: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10624: my %crsinfo =
1.1494 raeburn 10625: &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
1.1053 raeburn 10626: if (ref($crsinfo{$cid}) eq 'HASH') {
10627: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
1.1494 raeburn 10628: my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
1.1053 raeburn 10629: }
10630: }
10631: }
10632:
1.169 harris41 10633: # -------------------------------------------------- Modify user authentication
1.197 www 10634: # Overrides without validation
10635:
1.169 harris41 10636: sub modifyuserauth {
10637: my ($udom,$uname,$umode,$upass)=@_;
10638: my $uhome=&homeserver($uname,$udom);
1.1409 raeburn 10639: my $allowed;
10640: if (&allowed('mau',$udom)) {
10641: $allowed = 1;
10642: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10643: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10644: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10645: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10646: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10647: if (($cdom ne '') && ($cnum ne '')) {
10648: my $is_owner = &is_course_owner($cdom,$cnum);
10649: if ($is_owner) {
10650: $allowed = 1;
10651: }
10652: }
10653: }
10654: unless ($allowed) { return 'refused'; }
1.197 www 10655: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10656: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10657: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10658: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10659: &escape($upass),$uhome);
1.1434 raeburn 10660: my $ip = &get_requestor_ip();
1.620 albertel 10661: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10662: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434 raeburn 10663: '(Remote '.$ip.'): '.$reply);
1.197 www 10664: &log($udom,,$uname,$uhome,
1.620 albertel 10665: 'Authentication changed by '.$env{'user.domain'}.', '.
10666: $env{'user.name'}.', '.$umode.
1.1435 raeburn 10667: '(Remote '.$ip.'): '.$reply);
1.169 harris41 10668: unless ($reply eq 'ok') {
1.197 www 10669: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10670: return 'error: '.$reply;
10671: }
1.170 harris41 10672: return 'ok';
1.80 www 10673: }
10674:
1.81 www 10675: # --------------------------------------------------------------- Modify a user
1.80 www 10676:
1.81 www 10677: sub modifyuser {
1.206 matthew 10678: my ($udom, $uname, $uid,
10679: $umode, $upass, $first,
10680: $middle, $last, $gene,
1.1058 raeburn 10681: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10682: $udom= &LONCAPA::clean_domain($udom);
10683: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10684: my $showcandelete = 'none';
10685: if (ref($candelete) eq 'ARRAY') {
10686: if (@{$candelete} > 0) {
10687: $showcandelete = join(', ',@{$candelete});
10688: }
10689: }
1.81 www 10690: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10691: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10692: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10693: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10694: ' desiredhome not specified').
1.620 albertel 10695: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10696: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10697: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10698: my $newuser;
10699: if ($uhome eq 'no_host') {
10700: $newuser = 1;
1.1368 raeburn 10701: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10702: ($umode eq 'lti')) {
10703: return 'error: more information needed to create new user';
10704: }
1.1075 raeburn 10705: }
1.80 www 10706: # ----------------------------------------------------------------- Create User
1.406 albertel 10707: if (($uhome eq 'no_host') &&
1.1368 raeburn 10708: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80 www 10709: my $unhome='';
1.844 albertel 10710: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10711: $unhome = $desiredhome;
1.620 albertel 10712: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10713: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10714: } else { # load balancing routine for determining $unhome
1.81 www 10715: my $loadm=10000000;
1.841 albertel 10716: my %servers = &get_servers($udom,'library');
10717: foreach my $tryserver (keys(%servers)) {
10718: my $answer=reply('load',$tryserver);
10719: if (($answer=~/\d+/) && ($answer<$loadm)) {
10720: $loadm=$answer;
10721: $unhome=$tryserver;
10722: }
1.80 www 10723: }
10724: }
10725: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10726: return 'error: unable to find a home server for '.$uname.
10727: ' in domain '.$udom;
1.80 www 10728: }
10729: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10730: &escape($upass),$unhome);
10731: unless ($reply eq 'ok') {
10732: return 'error: '.$reply;
10733: }
1.230 stredwic 10734: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10735: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10736: return 'error: unable verify users home machine.';
1.80 www 10737: }
1.209 matthew 10738: } # End of creation of new user
1.80 www 10739: # ---------------------------------------------------------------------- Add ID
10740: if ($uid) {
10741: $uid=~tr/A-Z/a-z/;
10742: my %uidhash=&idrget($udom,$uname);
1.196 www 10743: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10744: && (!$forceid)) {
1.80 www 10745: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10746: return 'error: user id "'.$uid.'" does not match '.
10747: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10748: }
10749: } else {
1.1300 raeburn 10750: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 10751: }
10752: }
10753: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10754: my @tmp=&get('environment',
1.899 raeburn 10755: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10756: 'permanentemail','inststatus'],
1.134 albertel 10757: $udom,$uname);
1.1075 raeburn 10758: my (%names,%oldnames);
1.313 matthew 10759: if ($tmp[0] =~ m/^error:.*/) {
10760: %names=();
10761: } else {
10762: %names = @tmp;
1.1075 raeburn 10763: %oldnames = %names;
1.313 matthew 10764: }
1.388 www 10765: #
1.1058 raeburn 10766: # If name, email and/or uid are blank (e.g., because an uploaded file
10767: # of users did not contain them), do not overwrite existing values
10768: # unless field is in $candelete array ref.
10769: #
10770:
10771: my @fields = ('firstname','middlename','lastname','generation',
10772: 'permanentemail','id');
10773: my %newvalues;
10774: if (ref($candelete) eq 'ARRAY') {
10775: foreach my $field (@fields) {
10776: if (grep(/^\Q$field\E$/,@{$candelete})) {
10777: if ($field eq 'firstname') {
10778: $names{$field} = $first;
10779: } elsif ($field eq 'middlename') {
10780: $names{$field} = $middle;
10781: } elsif ($field eq 'lastname') {
10782: $names{$field} = $last;
10783: } elsif ($field eq 'generation') {
10784: $names{$field} = $gene;
10785: } elsif ($field eq 'permanentemail') {
10786: $names{$field} = $email;
10787: } elsif ($field eq 'id') {
10788: $names{$field} = $uid;
10789: }
10790: }
10791: }
10792: }
1.388 www 10793: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10794: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10795: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10796: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10797: if ($email) {
10798: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10799: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10800: }
1.899 raeburn 10801: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10802: if (defined($inststatus)) {
10803: $names{'inststatus'} = '';
10804: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10805: if (ref($usertypes) eq 'HASH') {
10806: my @okstatuses;
10807: foreach my $item (split(/:/,$inststatus)) {
10808: if (defined($usertypes->{$item})) {
10809: push(@okstatuses,$item);
10810: }
10811: }
10812: if (@okstatuses) {
10813: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10814: }
10815: }
10816: }
1.1075 raeburn 10817: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10818: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10819: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10820: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10821: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10822: } else {
10823: $logmsg .= ' during self creation';
10824: }
1.1075 raeburn 10825: my $changed;
10826: if ($newuser) {
10827: $changed = 1;
10828: } else {
10829: foreach my $field (@fields) {
10830: if ($names{$field} ne $oldnames{$field}) {
10831: $changed = 1;
10832: last;
10833: }
10834: }
10835: }
10836: unless ($changed) {
10837: $logmsg = 'No changes in user information needed for: '.$logmsg;
10838: &logthis($logmsg);
10839: return 'ok';
10840: }
10841: my $reply = &put('environment', \%names, $udom,$uname);
10842: if ($reply ne 'ok') {
10843: return 'error: '.$reply;
10844: }
1.1087 raeburn 10845: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
1.1494 raeburn 10846: &devalidate_cache_new('emailscache',$uname.':'.$udom);
1.1087 raeburn 10847: }
1.1075 raeburn 10848: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10849: &devalidate_cache_new('namescache',$uname.':'.$udom);
10850: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10851: &logthis($logmsg);
1.134 albertel 10852: return 'ok';
1.80 www 10853: }
10854:
1.81 www 10855: # -------------------------------------------------------------- Modify student
1.80 www 10856:
1.81 www 10857: sub modifystudent {
10858: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10859: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 10860: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10861: if (!$cid) {
1.620 albertel 10862: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10863: return 'not_in_class';
10864: }
1.80 www 10865: }
10866: # --------------------------------------------------------------- Make the user
1.81 www 10867: my $reply=&modifyuser
1.209 matthew 10868: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10869: $desiredhome,$email,$inststatus);
1.80 www 10870: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10871: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 10872: # student's environment
1.297 matthew 10873: $uid = undef if (!$forceid);
1.455 albertel 10874: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 10875: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 10876: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10877: return $reply;
10878: }
10879:
10880: sub modify_student_enrollment {
1.1216 raeburn 10881: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 10882: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10883: my ($cdom,$cnum,$chome);
10884: if (!$cid) {
1.620 albertel 10885: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10886: return 'not_in_class';
10887: }
1.620 albertel 10888: $cdom=$env{'course.'.$cid.'.domain'};
10889: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10890: } else {
10891: ($cdom,$cnum)=split(/_/,$cid);
10892: }
1.620 albertel 10893: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10894: if (!$chome) {
1.457 raeburn 10895: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10896: }
1.455 albertel 10897: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10898: # Make sure the user exists
1.81 www 10899: my $uhome=&homeserver($uname,$udom);
10900: if (($uhome eq '') || ($uhome eq 'no_host')) {
10901: return 'error: no such user';
10902: }
1.297 matthew 10903: # Get student data if we were not given enough information
10904: if (!defined($first) || $first eq '' ||
10905: !defined($last) || $last eq '' ||
10906: !defined($uid) || $uid eq '' ||
10907: !defined($middle) || $middle eq '' ||
10908: !defined($gene) || $gene eq '') {
1.294 matthew 10909: # They did not supply us with enough data to enroll the student, so
10910: # we need to pick up more information.
1.297 matthew 10911: my %tmp = &get('environment',
1.294 matthew 10912: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10913: ,$udom,$uname);
10914:
1.800 albertel 10915: #foreach my $key (keys(%tmp)) {
10916: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10917: #}
1.294 matthew 10918: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10919: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10920: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10921: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10922: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10923: }
1.556 albertel 10924: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10925: my $user = "$uname:$udom";
1.1494 raeburn 10926: my %old_entry = &get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10927: my $reply=cput('classlist',
1.1148 raeburn 10928: {$user =>
1.1314 raeburn 10929: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10930: $cdom,$cnum);
1.1148 raeburn 10931: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10932: &devalidate_getsection_cache($udom,$uname,$cid);
10933: } else {
1.81 www 10934: return 'error: '.$reply;
10935: }
1.297 matthew 10936: # Add student role to user
1.83 www 10937: my $uurl='/'.$cid;
1.81 www 10938: $uurl=~s/\_/\//g;
10939: if ($usec) {
10940: $uurl.='/'.$usec;
10941: }
1.1148 raeburn 10942: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10943: $selfenroll,$context);
10944: if ($result ne 'ok') {
10945: if ($old_entry{$user} ne '') {
10946: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10947: } else {
10948: $reply = &del('classlist',[$user],$cdom,$cnum);
10949: }
10950: }
10951: return $result;
1.21 www 10952: }
10953:
1.556 albertel 10954: sub format_name {
10955: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10956: my $name;
10957: if ($first ne 'lastname') {
10958: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10959: } else {
10960: if ($lastname=~/\S/) {
10961: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10962: $name=~s/\s+,/,/;
10963: } else {
10964: $name.= $firstname.' '.$middlename.' '.$generation;
10965: }
10966: }
10967: $name=~s/^\s+//;
10968: $name=~s/\s+$//;
10969: $name=~s/\s+/ /g;
10970: return $name;
10971: }
10972:
1.84 www 10973: # ------------------------------------------------- Write to course preferences
10974:
10975: sub writecoursepref {
10976: my ($courseid,%prefs)=@_;
10977: $courseid=~s/^\///;
10978: $courseid=~s/\_/\//g;
10979: my ($cdomain,$cnum)=split(/\//,$courseid);
10980: my $chome=homeserver($cnum,$cdomain);
10981: if (($chome eq '') || ($chome eq 'no_host')) {
10982: return 'error: no such course';
10983: }
10984: my $cstring='';
1.800 albertel 10985: foreach my $pref (keys(%prefs)) {
10986: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10987: }
1.84 www 10988: $cstring=~s/\&$//;
10989: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10990: }
10991:
10992: # ---------------------------------------------------------- Make/modify course
10993:
10994: sub createcourse {
1.741 raeburn 10995: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423 raeburn 10996: $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84 www 10997: $url=&declutter($url);
10998: my $cid='';
1.1028 raeburn 10999: if ($context eq 'requestcourses') {
11000: my $can_create = 0;
11001: my ($ownername,$ownerdom) = split(':',$course_owner);
11002: if ($udom eq $ownerdom) {
1.1423 raeburn 11003: my $reload;
11004: if (($callercontext eq 'auto') &&
11005: ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11006: $reload = 'reload';
11007: }
11008: if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028 raeburn 11009: $context)) {
11010: $can_create = 1;
11011: }
11012: } else {
11013: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11014: $category);
11015: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11016: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11017: if (@curr > 0) {
11018: my @options = qw(approval validate autolimit);
11019: my $optregex = join('|',@options);
11020: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11021: $can_create = 1;
11022: }
11023: }
11024: }
11025: }
11026: if ($can_create) {
11027: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11028: unless (&allowed('ccc',$udom)) {
11029: return 'refused';
11030: }
1.1017 raeburn 11031: }
11032: } else {
11033: return 'refused';
11034: }
1.1028 raeburn 11035: } elsif (!&allowed('ccc',$udom)) {
11036: return 'refused';
1.84 www 11037: }
1.1011 raeburn 11038: # --------------------------------------------------------------- Get Unique ID
11039: my $uname;
11040: if ($cnum =~ /^$match_courseid$/) {
11041: my $chome=&homeserver($cnum,$udom,'true');
11042: if (($chome eq '') || ($chome eq 'no_host')) {
11043: $uname = $cnum;
11044: } else {
1.1038 raeburn 11045: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 11046: }
11047: } else {
1.1038 raeburn 11048: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 11049: }
11050: return $uname if ($uname =~ /^error/);
11051: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 11052: if (!defined($course_server)) {
11053: if (defined(&domain($udom,'primary'))) {
11054: $course_server = &domain($udom,'primary');
11055: } else {
11056: $course_server = $env{'user.home'};
11057: }
11058: }
11059: my %host_servers =
1.1494 raeburn 11060: &get_servers($udom,'library');
1.1052 raeburn 11061: unless ($host_servers{$course_server}) {
11062: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 11063: }
1.84 www 11064: # ------------------------------------------------------------- Make the course
11065: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 11066: $course_server);
1.84 www 11067: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 11068: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 11069: if (($uhome eq '') || ($uhome eq 'no_host')) {
11070: return 'error: no such course';
11071: }
1.271 www 11072: # ----------------------------------------------------------------- Course made
1.516 raeburn 11073: # log existence
1.1029 raeburn 11074: my $now = time;
1.918 raeburn 11075: my $newcourse = {
11076: $udom.'_'.$uname => {
1.921 raeburn 11077: description => $description,
11078: inst_code => $inst_code,
11079: owner => $course_owner,
11080: type => $crstype,
1.1029 raeburn 11081: creator => $env{'user.name'}.':'.
11082: $env{'user.domain'},
11083: created => $now,
11084: context => $context,
1.918 raeburn 11085: },
11086: };
1.921 raeburn 11087: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 11088: # set toplevel url
1.271 www 11089: my $topurl=$url;
11090: unless ($nonstandard) {
11091: # ------------------------------------------ For standard courses, make top url
11092: my $mapurl=&clutter($url);
1.278 www 11093: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 11094: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 11095: <map>
11096: <resource id="1" type="start"></resource>
11097: <resource id="2" src="$mapurl"></resource>
11098: <resource id="3" type="finish"></resource>
11099: <link index="1" from="1" to="2"></link>
11100: <link index="2" from="2" to="3"></link>
11101: </map>
11102: ENDINITMAP
11103: $topurl=&declutter(
1.638 albertel 11104: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 11105: );
11106: }
11107: # ----------------------------------------------------------- Write preferences
1.84 www 11108: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 11109: ('description' => $description,
11110: 'url' => $topurl,
11111: 'internal.creator' => $env{'user.name'}.':'.
11112: $env{'user.domain'},
11113: 'internal.created' => $now,
11114: 'internal.creationcontext' => $context)
11115: );
1.84 www 11116: return '/'.$udom.'/'.$uname;
11117: }
11118:
1.1011 raeburn 11119: # ------------------------------------------------------------------- Create ID
11120: sub generate_coursenum {
1.1038 raeburn 11121: my ($udom,$crstype) = @_;
1.1011 raeburn 11122: my $domdesc = &domain($udom);
11123: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 11124: my $first;
11125: if ($crstype eq 'Community') {
11126: $first = '0';
11127: } else {
11128: $first = int(1+rand(9));
11129: }
11130: my $uname=$first.
1.1011 raeburn 11131: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11132: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11133: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11134: # ----------------------------------------------- Make sure that does not exist
11135: my $uhome=&homeserver($uname,$udom,'true');
11136: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 11137: if ($crstype eq 'Community') {
11138: $first = '0';
11139: } else {
11140: $first = int(1+rand(9));
11141: }
11142: $uname=$first.
1.1011 raeburn 11143: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11144: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11145: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11146: $uhome=&homeserver($uname,$udom,'true');
11147: unless (($uhome eq '') || ($uhome eq 'no_host')) {
11148: return 'error: unable to generate unique course-ID';
11149: }
11150: }
11151: return $uname;
11152: }
11153:
1.813 albertel 11154: sub is_course {
1.1167 droeschl 11155: my ($cdom, $cnum) = scalar(@_) == 1 ?
11156: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
11157:
1.1381 raeburn 11158: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11159: my $uhome=&homeserver($cnum,$cdom);
11160: my $iscourse;
11161: if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382 raeburn 11162: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381 raeburn 11163: } else {
11164: my $hashid = $cdom.':'.$cnum;
11165: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11166: unless (defined($cached)) {
11167: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11168: $cnum,undef,undef,'.');
11169: $iscourse = 0;
11170: if (exists($courses{$cdom.'_'.$cnum})) {
11171: $iscourse = 1;
11172: }
11173: &do_cache_new('iscourse',$hashid,$iscourse,3600);
11174: }
11175: }
11176: return unless ($iscourse);
1.1167 droeschl 11177: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 11178: }
11179:
1.1015 raeburn 11180: sub store_userdata {
11181: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 11182: my $result;
1.1016 raeburn 11183: if ($datakey ne '') {
1.1013 raeburn 11184: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 11185: if ($udom eq '' || $uname eq '') {
11186: $udom = $env{'user.domain'};
11187: $uname = $env{'user.name'};
11188: }
11189: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 11190: if (($uhome eq '') || ($uhome eq 'no_host')) {
11191: $result = 'error: no_host';
11192: } else {
1.1434 raeburn 11193: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 11194: $storehash->{'host'} = $perlvar{'lonHostID'};
11195:
11196: my $namevalue='';
11197: foreach my $key (keys(%{$storehash})) {
11198: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11199: }
11200: $namevalue=~s/\&$//;
1.1224 raeburn 11201: unless ($namespace eq 'courserequests') {
11202: $datakey = &escape($datakey);
11203: }
1.1105 raeburn 11204: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
11205: $namevalue,$uhome);
1.1013 raeburn 11206: }
11207: } else {
11208: $result = 'error: data to store was not a hash reference';
11209: }
11210: } else {
11211: $result= 'error: invalid requestkey';
11212: }
11213: return $result;
11214: }
11215:
1.21 www 11216: # ---------------------------------------------------------- Assign Custom Role
11217:
11218: sub assigncustomrole {
1.957 raeburn 11219: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11220: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 11221: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 11222: }
11223:
11224: # ----------------------------------------------------------------- Revoke Role
11225:
11226: sub revokerole {
1.957 raeburn 11227: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11228: my $now=time;
1.965 raeburn 11229: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 11230: }
11231:
11232: # ---------------------------------------------------------- Revoke Custom Role
11233:
11234: sub revokecustomrole {
1.957 raeburn 11235: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11236: my $now=time;
1.357 www 11237: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 11238: $deleteflag,$selfenroll,$context);
1.17 www 11239: }
11240:
1.533 banghart 11241: # ------------------------------------------------------------ Disk usage
1.535 albertel 11242: sub diskusage {
1.955 raeburn 11243: my ($udom,$uname,$directorypath,$getpropath)=@_;
11244: $directorypath =~ s/\/$//;
11245: my $listing=&reply('du2:'.&escape($directorypath).':'
11246: .&escape($getpropath).':'.&escape($uname).':'
11247: .&escape($udom),homeserver($uname,$udom));
11248: if ($listing eq 'unknown_cmd') {
11249: if ($getpropath) {
11250: $directorypath = &propath($udom,$uname).'/'.$directorypath;
11251: }
11252: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11253: }
1.514 albertel 11254: return $listing;
1.512 banghart 11255: }
11256:
1.566 banghart 11257: sub is_locked {
1.1096 raeburn 11258: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 11259: my @check;
11260: my $is_locked;
1.1093 raeburn 11261: push (@check,$file_name);
1.613 albertel 11262: my %locked = &get('file_permissions',\@check,
1.620 albertel 11263: $env{'user.domain'},$env{'user.name'});
1.615 albertel 11264: my ($tmp)=keys(%locked);
11265: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 11266:
1.566 banghart 11267: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 11268: $is_locked = 'false';
11269: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 11270: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 11271: $is_locked = 'true';
1.1096 raeburn 11272: if (ref($which) eq 'ARRAY') {
11273: push(@{$which},$entry);
11274: } else {
11275: last;
11276: }
1.745 raeburn 11277: }
11278: }
1.566 banghart 11279: } else {
11280: $is_locked = 'false';
11281: }
1.1093 raeburn 11282: return $is_locked;
1.566 banghart 11283: }
11284:
1.759 albertel 11285: sub declutter_portfile {
11286: my ($file) = @_;
1.833 albertel 11287: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 11288: return $file;
11289: }
11290:
1.559 banghart 11291: # ------------------------------------------------------------- Mark as Read Only
11292:
11293: sub mark_as_readonly {
11294: my ($domain,$user,$files,$what) = @_;
1.613 albertel 11295: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11296: my ($tmp)=keys(%current_permissions);
11297: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 11298: foreach my $file (@{$files}) {
1.759 albertel 11299: $file = &declutter_portfile($file);
1.561 banghart 11300: push(@{$current_permissions{$file}},$what);
1.559 banghart 11301: }
1.613 albertel 11302: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11303: return;
11304: }
11305:
1.572 banghart 11306: # ------------------------------------------------------------Save Selected Files
11307:
11308: sub save_selected_files {
11309: my ($user, $path, @files) = @_;
11310: my $filename = $user."savedfiles";
1.573 banghart 11311: my @other_files = &files_not_in_path($user, $path);
1.1359 raeburn 11312: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 11313: foreach my $file (@files) {
1.620 albertel 11314: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 11315: }
11316: foreach my $file (@other_files) {
1.574 banghart 11317: print (OUT $file."\n");
1.572 banghart 11318: }
1.574 banghart 11319: close (OUT);
1.572 banghart 11320: return 'ok';
11321: }
11322:
1.574 banghart 11323: sub clear_selected_files {
11324: my ($user) = @_;
11325: my $filename = $user."savedfiles";
1.1359 raeburn 11326: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 11327: print (OUT undef);
11328: close (OUT);
11329: return ("ok");
11330: }
11331:
1.572 banghart 11332: sub files_in_path {
11333: my ($user, $path) = @_;
11334: my $filename = $user."savedfiles";
11335: my %return_files;
1.1359 raeburn 11336: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 11337: while (my $line_in = <IN>) {
1.574 banghart 11338: chomp ($line_in);
11339: my @paths_and_file = split (m!/!, $line_in);
11340: my $file_part = pop (@paths_and_file);
11341: my $path_part = join ('/', @paths_and_file);
1.573 banghart 11342: $path_part.='/';
11343: my $path_and_file = $path_part.$file_part;
11344: if ($path_part eq $path) {
11345: $return_files{$file_part}= 'selected';
11346: }
11347: }
1.574 banghart 11348: close (IN);
11349: return (\%return_files);
1.572 banghart 11350: }
11351:
11352: # called in portfolio select mode, to show files selected NOT in current directory
11353: sub files_not_in_path {
11354: my ($user, $path) = @_;
11355: my $filename = $user."savedfiles";
11356: my @return_files;
11357: my $path_part;
1.1359 raeburn 11358: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 11359: while (my $line = <IN>) {
1.572 banghart 11360: #ok, I know it's clunky, but I want it to work
1.800 albertel 11361: my @paths_and_file = split(m|/|, $line);
11362: my $file_part = pop(@paths_and_file);
11363: chomp($file_part);
11364: my $path_part = join('/', @paths_and_file);
1.572 banghart 11365: $path_part .= '/';
11366: my $path_and_file = $path_part.$file_part;
11367: if ($path_part ne $path) {
1.800 albertel 11368: push(@return_files, ($path_and_file));
1.572 banghart 11369: }
11370: }
1.800 albertel 11371: close(OUT);
1.574 banghart 11372: return (@return_files);
1.572 banghart 11373: }
11374:
1.1273 raeburn 11375: #------------------------------Submitted/Handedback Portfolio Files Versioning
11376:
11377: sub portfiles_versioning {
11378: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11379: my $portfolio_root = '/userfiles/portfolio';
11380: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11381: foreach my $file (@{$portfiles}) {
11382: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11383: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11384: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11385: my $getpropath = 1;
11386: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11387: $stu_name,$getpropath);
11388: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11389: my $new_answer =
11390: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11391: if ($new_answer ne 'problem getting file') {
11392: push(@{$versioned_portfiles}, $directory.$new_answer);
11393: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11394: [$symb,$env{'request.course.id'},'graded']);
11395: }
11396: }
11397: }
11398:
11399: sub get_next_version {
11400: my ($answer_name, $answer_ext, $dir_list) = @_;
11401: my $version;
11402: if (ref($dir_list) eq 'ARRAY') {
11403: foreach my $row (@{$dir_list}) {
11404: my ($file) = split(/\&/,$row,2);
11405: my ($file_name,$file_version,$file_ext) =
11406: &file_name_version_ext($file);
11407: if (($file_name eq $answer_name) &&
11408: ($file_ext eq $answer_ext)) {
11409: # gets here if filename and extension match,
11410: # regardless of version
11411: if ($file_version ne '') {
11412: # a versioned file is found so save it for later
11413: if ($file_version > $version) {
11414: $version = $file_version;
11415: }
11416: }
11417: }
11418: }
11419: }
11420: $version ++;
11421: return($version);
11422: }
11423:
11424: sub version_selected_portfile {
11425: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11426: my ($answer_name,$answer_ver,$answer_ext) =
11427: &file_name_version_ext($file_name);
11428: my $new_answer;
11429: $env{'form.copy'} =
11430: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11431: if($env{'form.copy'} eq '-1') {
11432: $new_answer = 'problem getting file';
11433: } else {
11434: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11435: my $copy_result =
11436: &finishuserfileupload($stu_name,$domain,'copy',
11437: '/portfolio'.$directory.$new_answer);
11438: }
11439: undef($env{'form.copy'});
11440: return ($new_answer);
11441: }
11442:
11443: sub file_name_version_ext {
11444: my ($file)=@_;
11445: my @file_parts = split(/\./, $file);
11446: my ($name,$version,$ext);
11447: if (@file_parts > 1) {
11448: $ext=pop(@file_parts);
11449: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11450: $version=pop(@file_parts);
11451: }
11452: $name=join('.',@file_parts);
11453: } else {
11454: $name=join('.',@file_parts);
11455: }
11456: return($name,$version,$ext);
11457: }
11458:
1.745 raeburn 11459: #----------------------------------------------Get portfolio file permissions
1.629 banghart 11460:
1.745 raeburn 11461: sub get_portfile_permissions {
11462: my ($domain,$user) = @_;
1.613 albertel 11463: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11464: my ($tmp)=keys(%current_permissions);
11465: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11466: return \%current_permissions;
11467: }
11468:
11469: #---------------------------------------------Get portfolio file access controls
11470:
1.749 raeburn 11471: sub get_access_controls {
1.745 raeburn 11472: my ($current_permissions,$group,$file) = @_;
1.769 albertel 11473: my %access;
11474: my $real_file = $file;
11475: $file =~ s/\.meta$//;
1.745 raeburn 11476: if (defined($file)) {
1.749 raeburn 11477: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11478: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 11479: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 11480: }
11481: }
1.745 raeburn 11482: } else {
1.749 raeburn 11483: foreach my $key (keys(%{$current_permissions})) {
11484: if ($key =~ /\0accesscontrol$/) {
11485: if (defined($group)) {
11486: if ($key !~ m-^\Q$group\E/-) {
11487: next;
11488: }
11489: }
11490: my ($fullpath) = split(/\0/,$key);
11491: if (ref($$current_permissions{$key}) eq 'HASH') {
11492: foreach my $control (keys(%{$$current_permissions{$key}})) {
11493: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11494: }
11495: }
11496: }
11497: }
11498: }
11499: return %access;
11500: }
11501:
11502: sub modify_access_controls {
11503: my ($file_name,$changes,$domain,$user)=@_;
11504: my ($outcome,$deloutcome);
11505: my %store_permissions;
11506: my %new_values;
11507: my %new_control;
11508: my %translation;
11509: my @deletions = ();
11510: my $now = time;
11511: if (exists($$changes{'activate'})) {
11512: if (ref($$changes{'activate'}) eq 'HASH') {
11513: my @newitems = sort(keys(%{$$changes{'activate'}}));
11514: my $numnew = scalar(@newitems);
11515: for (my $i=0; $i<$numnew; $i++) {
11516: my $newkey = $newitems[$i];
11517: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 11518: if ($newkey =~ /^\d+:/) {
11519: $newkey =~ s/^(\d+)/$newid/;
11520: $translation{$1} = $newid;
11521: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11522: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11523: $translation{$1} = $newid;
11524: }
1.749 raeburn 11525: $new_values{$file_name."\0".$newkey} =
11526: $$changes{'activate'}{$newitems[$i]};
11527: $new_control{$newkey} = $now;
11528: }
11529: }
11530: }
11531: my %todelete;
11532: my %changed_items;
11533: foreach my $action ('delete','update') {
11534: if (exists($$changes{$action})) {
11535: if (ref($$changes{$action}) eq 'HASH') {
11536: foreach my $key (keys(%{$$changes{$action}})) {
11537: my ($itemnum) = ($key =~ /^([^:]+):/);
11538: if ($action eq 'delete') {
11539: $todelete{$itemnum} = 1;
11540: } else {
11541: $changed_items{$itemnum} = $key;
11542: }
11543: }
1.745 raeburn 11544: }
11545: }
1.749 raeburn 11546: }
11547: # get lock on access controls for file.
11548: my $lockhash = {
11549: $file_name."\0".'locked_access_records' => $env{'user.name'}.
11550: ':'.$env{'user.domain'},
11551: };
11552: my $tries = 0;
11553: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11554:
1.1288 damieng 11555: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 11556: $tries ++;
1.1289 damieng 11557: sleep(0.1);
1.749 raeburn 11558: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11559: }
11560: if ($gotlock eq 'ok') {
11561: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11562: my ($tmp)=keys(%curr_permissions);
11563: if ($tmp=~/^error:/) { undef(%curr_permissions); }
11564: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11565: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11566: if (ref($curr_controls) eq 'HASH') {
11567: foreach my $control_item (keys(%{$curr_controls})) {
11568: my ($itemnum) = ($control_item =~ /^([^:]+):/);
11569: if (defined($todelete{$itemnum})) {
11570: push(@deletions,$file_name."\0".$control_item);
11571: } else {
11572: if (defined($changed_items{$itemnum})) {
11573: $new_control{$changed_items{$itemnum}} = $now;
11574: push(@deletions,$file_name."\0".$control_item);
11575: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11576: } else {
11577: $new_control{$control_item} = $$curr_controls{$control_item};
11578: }
11579: }
1.745 raeburn 11580: }
11581: }
11582: }
1.970 raeburn 11583: my ($group);
11584: if (&is_course($domain,$user)) {
11585: ($group,my $file) = split(/\//,$file_name,2);
11586: }
1.749 raeburn 11587: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11588: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11589: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11590: # remove lock
11591: my @del_lock = ($file_name."\0".'locked_access_records');
11592: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11593: my $sqlresult =
1.970 raeburn 11594: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11595: $group);
1.749 raeburn 11596: } else {
11597: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11598: }
1.749 raeburn 11599: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11600: }
11601:
1.827 raeburn 11602: sub make_public_indefinitely {
1.1271 raeburn 11603: my (@requrl) = @_;
11604: return &automated_portfile_access('public',\@requrl);
11605: }
11606:
11607: sub automated_portfile_access {
11608: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 11609: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11610: return 'invalid';
11611: }
1.1271 raeburn 11612: my %urls;
11613: if (ref($addsref) eq 'ARRAY') {
11614: foreach my $requrl (@{$addsref}) {
11615: if (&is_portfolio_url($requrl)) {
11616: unless (exists($urls{$requrl})) {
11617: $urls{$requrl} = 'add';
11618: }
11619: }
11620: }
11621: }
11622: if (ref($delsref) eq 'ARRAY') {
11623: foreach my $requrl (@{$delsref}) {
11624: if (&is_portfolio_url($requrl)) {
11625: unless (exists($urls{$requrl})) {
11626: $urls{$requrl} = 'delete';
11627: }
11628: }
11629: }
11630: }
11631: unless (keys(%urls)) {
11632: return 'invalid';
11633: }
11634: my $ip;
11635: if ($accesstype eq 'ip') {
11636: if (ref($info) eq 'HASH') {
11637: if ($info->{'ip'} ne '') {
11638: $ip = $info->{'ip'};
11639: }
11640: }
11641: if ($ip eq '') {
11642: return 'invalid';
11643: }
11644: }
11645: my $errors;
1.827 raeburn 11646: my $now = time;
1.1271 raeburn 11647: my %current_perms;
11648: foreach my $requrl (sort(keys(%urls))) {
11649: my $action;
11650: if ($urls{$requrl} eq 'add') {
11651: $action = 'activate';
11652: } else {
11653: $action = 'none';
11654: }
11655: my $aclnum = 0;
1.827 raeburn 11656: my (undef,$udom,$unum,$file_name,$group) =
11657: &parse_portfolio_url($requrl);
1.1271 raeburn 11658: unless (exists($current_perms{$unum.':'.$udom})) {
11659: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11660: }
11661: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 11662: $group,$file_name);
11663: foreach my $key (keys(%{$access_controls{$file_name}})) {
11664: my ($num,$scope,$end,$start) =
11665: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 11666: if ($scope eq $accesstype) {
11667: if (($start <= $now) && ($end == 0)) {
11668: if ($accesstype eq 'ip') {
11669: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11670: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11671: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11672: if ($urls{$requrl} eq 'add') {
11673: $action = 'none';
11674: last;
11675: } else {
11676: $action = 'delete';
11677: $aclnum = $num;
11678: last;
11679: }
11680: }
11681: }
11682: }
11683: } elsif ($accesstype eq 'public') {
11684: if ($urls{$requrl} eq 'add') {
11685: $action = 'none';
11686: last;
11687: } else {
11688: $action = 'delete';
11689: $aclnum = $num;
11690: last;
11691: }
11692: }
11693: } elsif ($accesstype eq 'public') {
1.827 raeburn 11694: $action = 'update';
11695: $aclnum = $num;
1.1271 raeburn 11696: last;
1.827 raeburn 11697: }
11698: }
11699: }
11700: if ($action eq 'none') {
1.1271 raeburn 11701: next;
1.827 raeburn 11702: } else {
11703: my %changes;
11704: my $newend = 0;
11705: my $newstart = $now;
1.1271 raeburn 11706: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 11707: $changes{$action}{$newkey} = {
1.1271 raeburn 11708: type => $accesstype,
1.827 raeburn 11709: time => {
11710: start => $newstart,
11711: end => $newend,
11712: },
11713: };
1.1271 raeburn 11714: if ($accesstype eq 'ip') {
11715: $changes{$action}{$newkey}{'ip'} = [$ip];
11716: }
1.827 raeburn 11717: my ($outcome,$deloutcome,$new_values,$translation) =
11718: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 11719: unless ($outcome eq 'ok') {
11720: $errors .= $outcome.' ';
11721: }
1.827 raeburn 11722: }
1.1271 raeburn 11723: }
11724: if ($errors) {
11725: $errors =~ s/\s$//;
11726: return $errors;
1.827 raeburn 11727: } else {
1.1271 raeburn 11728: return 'ok';
1.827 raeburn 11729: }
11730: }
11731:
1.745 raeburn 11732: #------------------------------------------------------Get Marked as Read Only
11733:
11734: sub get_marked_as_readonly {
11735: my ($domain,$user,$what,$group) = @_;
11736: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11737: my @readonly_files;
1.629 banghart 11738: my $cmp1=$what;
11739: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11740: while (my ($file_name,$value) = each(%{$current_permissions})) {
11741: if (defined($group)) {
11742: if ($file_name !~ m-^\Q$group\E/-) {
11743: next;
11744: }
11745: }
1.561 banghart 11746: if (ref($value) eq "ARRAY"){
11747: foreach my $stored_what (@{$value}) {
1.629 banghart 11748: my $cmp2=$stored_what;
1.759 albertel 11749: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11750: $cmp2=join('',@{$stored_what});
1.745 raeburn 11751: }
1.629 banghart 11752: if ($cmp1 eq $cmp2) {
1.561 banghart 11753: push(@readonly_files, $file_name);
1.745 raeburn 11754: last;
1.563 banghart 11755: } elsif (!defined($what)) {
11756: push(@readonly_files, $file_name);
1.745 raeburn 11757: last;
1.561 banghart 11758: }
11759: }
1.745 raeburn 11760: }
1.561 banghart 11761: }
11762: return @readonly_files;
11763: }
1.577 banghart 11764: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11765:
1.577 banghart 11766: sub get_marked_as_readonly_hash {
1.745 raeburn 11767: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11768: my %readonly_files;
1.745 raeburn 11769: while (my ($file_name,$value) = each(%{$current_permissions})) {
11770: if (defined($group)) {
11771: if ($file_name !~ m-^\Q$group\E/-) {
11772: next;
11773: }
11774: }
1.577 banghart 11775: if (ref($value) eq "ARRAY"){
11776: foreach my $stored_what (@{$value}) {
1.745 raeburn 11777: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11778: foreach my $lock_descriptor(@{$stored_what}) {
11779: if ($lock_descriptor eq 'graded') {
11780: $readonly_files{$file_name} = 'graded';
11781: } elsif ($lock_descriptor eq 'handback') {
11782: $readonly_files{$file_name} = 'handback';
11783: } else {
11784: if (!exists($readonly_files{$file_name})) {
11785: $readonly_files{$file_name} = 'locked';
11786: }
11787: }
1.745 raeburn 11788: }
1.750 banghart 11789: }
1.577 banghart 11790: }
11791: }
11792: }
11793: return %readonly_files;
11794: }
1.559 banghart 11795: # ------------------------------------------------------------ Unmark as Read Only
11796:
11797: sub unmark_as_readonly {
1.629 banghart 11798: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11799: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11800: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11801: $file_name = &declutter_portfile($file_name);
1.634 albertel 11802: my $symb_crs = $what;
11803: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11804: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11805: my ($tmp)=keys(%current_permissions);
11806: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11807: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11808: foreach my $file (@readonly_files) {
1.759 albertel 11809: my $clean_file = &declutter_portfile($file);
11810: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11811: my $current_locks = $current_permissions{$file};
1.563 banghart 11812: my @new_locks;
11813: my @del_keys;
11814: if (ref($current_locks) eq "ARRAY"){
11815: foreach my $locker (@{$current_locks}) {
1.632 albertel 11816: my $compare=$locker;
1.749 raeburn 11817: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11818: $compare=join('',@{$locker});
1.746 raeburn 11819: if ($compare ne $symb_crs) {
11820: push(@new_locks, $locker);
11821: }
1.563 banghart 11822: }
11823: }
1.650 albertel 11824: if (scalar(@new_locks) > 0) {
1.563 banghart 11825: $current_permissions{$file} = \@new_locks;
11826: } else {
11827: push(@del_keys, $file);
1.613 albertel 11828: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11829: delete($current_permissions{$file});
1.563 banghart 11830: }
11831: }
1.561 banghart 11832: }
1.613 albertel 11833: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11834: return;
11835: }
1.512 banghart 11836:
1.17 www 11837: # ------------------------------------------------------------ Directory lister
11838:
11839: sub dirlist {
1.955 raeburn 11840: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11841: $uri=~s/^\///;
11842: $uri=~s/\/$//;
1.253 stredwic 11843: my ($udom, $uname);
1.955 raeburn 11844: if ($getuserdir) {
1.253 stredwic 11845: $udom = $userdomain;
11846: $uname = $username;
1.955 raeburn 11847: } else {
11848: (undef,$udom,$uname)=split(/\//,$uri);
11849: if(defined($userdomain)) {
11850: $udom = $userdomain;
11851: }
11852: if(defined($username)) {
11853: $uname = $username;
11854: }
1.253 stredwic 11855: }
1.955 raeburn 11856: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11857:
1.955 raeburn 11858: $dirRoot = $perlvar{'lonDocRoot'};
11859: if (defined($getpropath)) {
11860: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11861: $dirRoot =~ s/\/$//;
1.955 raeburn 11862: } elsif (defined($getuserdir)) {
11863: my $subdir=$uname.'__';
11864: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11865: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11866: ."/$udom/$subdir/$uname";
11867: } elsif (defined($alternateRoot)) {
11868: $dirRoot = $alternateRoot;
1.751 banghart 11869: }
1.253 stredwic 11870:
11871: if($udom) {
11872: if($uname) {
1.1135 raeburn 11873: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11874: if ($uhome eq 'no_host') {
11875: return ([],'no_host');
11876: }
1.955 raeburn 11877: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11878: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11879: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11880: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11881: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11882: } else {
11883: @listing_results = map { &unescape($_); } split(/:/,$listing);
11884: }
1.605 matthew 11885: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11886: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11887: @listing_results = split(/:/,$listing);
11888: } else {
11889: @listing_results = map { &unescape($_); } split(/:/,$listing);
11890: }
1.1135 raeburn 11891: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11892: ($listing eq 'rejected') || ($listing eq 'refused') ||
11893: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11894: return ([],$listing);
11895: } else {
11896: return (\@listing_results);
1.1135 raeburn 11897: }
1.955 raeburn 11898: } elsif(!$alternateRoot) {
1.1136 raeburn 11899: my (%allusers,%listerror);
1.841 albertel 11900: my %servers = &get_servers($udom,'library');
1.955 raeburn 11901: foreach my $tryserver (keys(%servers)) {
11902: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11903: &escape($udom),$tryserver);
11904: if ($listing eq 'unknown_cmd') {
11905: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11906: $udom, $tryserver);
11907: } else {
11908: @listing_results = map { &unescape($_); } split(/:/,$listing);
11909: }
1.841 albertel 11910: if ($listing eq 'unknown_cmd') {
11911: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11912: $udom, $tryserver);
11913: @listing_results = split(/:/,$listing);
11914: } else {
11915: @listing_results =
11916: map { &unescape($_); } split(/:/,$listing);
11917: }
1.1136 raeburn 11918: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11919: ($listing eq 'rejected') || ($listing eq 'refused') ||
11920: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11921: $listerror{$tryserver} = $listing;
11922: } else {
1.841 albertel 11923: foreach my $line (@listing_results) {
11924: my ($entry) = split(/&/,$line,2);
11925: $allusers{$entry} = 1;
11926: }
11927: }
1.253 stredwic 11928: }
1.1136 raeburn 11929: my @alluserslist=();
1.800 albertel 11930: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11931: push(@alluserslist,$user.'&user');
1.253 stredwic 11932: }
1.1318 droeschl 11933:
11934: if (!%listerror) {
11935: # no errors
11936: return (\@alluserslist);
11937: } elsif (scalar(keys(%servers)) == 1) {
11938: # one library server, one error
11939: my ($key) = keys(%listerror);
11940: return (\@alluserslist, $listerror{$key});
11941: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11942: # con_lost indicates that we might miss data from at least one
11943: # library server
11944: return (\@alluserslist, 'con_lost');
11945: } else {
11946: # multiple library servers and no con_lost -> data should be
11947: # complete.
11948: return (\@alluserslist);
11949: }
11950:
1.253 stredwic 11951: } else {
1.1136 raeburn 11952: return ([],'missing username');
1.253 stredwic 11953: }
1.955 raeburn 11954: } elsif(!defined($getpropath)) {
1.1136 raeburn 11955: my $path = $perlvar{'lonDocRoot'}.'/res/';
11956: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11957: return (\@all_domains);
1.955 raeburn 11958: } else {
1.1136 raeburn 11959: return ([],'missing domain');
1.275 stredwic 11960: }
11961: }
11962:
11963: # --------------------------------------------- GetFileTimestamp
11964: # This function utilizes dirlist and returns the date stamp for
11965: # when it was last modified. It will also return an error of -1
11966: # if an error occurs
11967:
11968: sub GetFileTimestamp {
1.955 raeburn 11969: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11970: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11971: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11972: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11973: undef,$getuserdir);
11974: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11975: return -1;
11976: }
11977: if (ref($fileref) eq 'ARRAY') {
11978: my @stats = split('&',$fileref->[0]);
1.375 matthew 11979: # @stats contains first the filename, then the stat output
11980: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11981: } else {
11982: return -1;
1.253 stredwic 11983: }
1.26 www 11984: }
11985:
1.712 albertel 11986: sub stat_file {
11987: my ($uri) = @_;
1.787 albertel 11988: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11989:
1.955 raeburn 11990: my ($udom,$uname,$file);
1.712 albertel 11991: if ($uri =~ m-^/(uploaded|editupload)/-) {
11992: ($udom,$uname,$file) =
1.811 albertel 11993: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11994: $file = 'userfiles/'.$file;
11995: }
11996: if ($uri =~ m-^/res/-) {
11997: ($udom,$uname) =
1.807 albertel 11998: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11999: $file = $uri;
12000: }
12001:
12002: if (!$udom || !$uname || !$file) {
12003: # unable to handle the uri
12004: return ();
12005: }
1.956 raeburn 12006: my $getpropath;
12007: if ($file =~ /^userfiles\//) {
12008: $getpropath = 1;
12009: }
1.1136 raeburn 12010: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12011: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12012: return ();
12013: } else {
12014: if (ref($listref) eq 'ARRAY') {
12015: my @stats = split('&',$listref->[0]);
12016: shift(@stats); #filename is first
12017: return @stats;
12018: }
1.712 albertel 12019: }
12020: return ();
12021: }
12022:
1.1313 raeburn 12023: # --------------------------------------------------------- recursedirs
12024: # Recursive function to traverse either a specific user's Authoring Space
12025: # or corresponding Published Resource Space, and populate the hash ref:
12026: # $dirhashref with URLs of all directories, and if $filehashref hash
12027: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
12028: # or .rights files in resource space, and .meta, .save, .log, and .bak
12029: # files in Authoring Space.
12030: #
12031: # Inputs:
12032: #
12033: # $is_home - true if current server is home server for user's space
12034: # $context - either: priv, or res respectively for Authoring or Resource Space.
12035: # $docroot - Document root (i.e., /home/httpd/html
12036: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12037: # $relpath - Current path (relative to top level).
12038: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12039: # $filehashref - reference to hash to populate with URLs of files (Optional)
12040: #
12041: # Returns: nothing
12042: #
12043: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12044: #
12045: # Currently used by interface/londocs.pm to create linked select boxes for
12046: # directory and filename to import a Course "Author" resource into a course, and
12047: # also to create linked select boxes for Authoring Space and Directory to choose
12048: # save location for creation of a new "standard" problem from the Course Editor.
12049: #
12050:
12051: sub recursedirs {
12052: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
12053: return unless (ref($dirhashref) eq 'HASH');
12054: my $currpath = $docroot.$toppath;
12055: if ($relpath) {
12056: $currpath .= "/$relpath";
12057: }
12058: my $savefile;
12059: if (ref($filehashref)) {
12060: $savefile = 1;
12061: }
12062: if ($is_home) {
12063: if (opendir(my $dirh,$currpath)) {
12064: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12065: next if ($item eq '');
12066: if (-d "$currpath/$item") {
12067: my $newpath;
12068: if ($relpath) {
12069: $newpath = "$relpath/$item";
12070: } else {
12071: $newpath = $item;
12072: }
12073: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12074: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
12075: } elsif ($savefile) {
12076: if ($context eq 'priv') {
12077: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
12078: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12079: }
12080: } else {
12081: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
12082: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12083: }
12084: }
12085: }
12086: }
12087: closedir($dirh);
12088: }
12089: } else {
12090: my ($dirlistref,$listerror) =
12091: &dirlist($toppath.$relpath);
12092: my @dir_lines;
12093: my $dirptr=16384;
12094: if (ref($dirlistref) eq 'ARRAY') {
12095: foreach my $dir_line (sort
12096: {
12097: my ($afile)=split('&',$a,2);
12098: my ($bfile)=split('&',$b,2);
12099: return (lc($afile) cmp lc($bfile));
12100: } (@{$dirlistref})) {
12101: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12102: split(/\&/,$dir_line,16);
12103: $item =~ s/\s+$//;
12104: next if (($item =~ /^\.\.?$/) || ($obs));
12105: if ($dirptr&$testdir) {
12106: my $newpath;
12107: if ($relpath) {
12108: $newpath = "$relpath/$item";
12109: } else {
12110: $relpath = '/';
12111: $newpath = $item;
12112: }
12113: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12114: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
12115: } elsif ($savefile) {
12116: if ($context eq 'priv') {
12117: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
12118: $filehashref->{$relpath}{$item} = 1;
12119: }
12120: } else {
12121: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
12122: $filehashref->{$relpath}{$item} = 1;
12123: }
12124: }
12125: }
12126: }
12127: }
12128: }
12129: return;
12130: }
12131:
1.26 www 12132: # -------------------------------------------------------- Value of a Condition
12133:
1.713 albertel 12134: # gets the value of a specific preevaluated condition
12135: # stored in the string $env{user.state.<cid>}
12136: # or looks up a condition reference in the bighash and if if hasn't
12137: # already been evaluated recurses into docondval to get the value of
12138: # the condition, then memoizing it to
12139: # $env{user.state.<cid>.<condition>}
1.40 www 12140: sub directcondval {
12141: my $number=shift;
1.620 albertel 12142: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 12143: &Apache::lonuserstate::evalstate();
12144: }
1.713 albertel 12145: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12146: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12147: } elsif ($number =~ /^_/) {
12148: my $sub_condition;
12149: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12150: &GDBM_READER(),0640)) {
12151: $sub_condition=$bighash{'conditions'.$number};
12152: untie(%bighash);
12153: }
12154: my $value = &docondval($sub_condition);
1.949 raeburn 12155: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 12156: return $value;
12157: }
1.620 albertel 12158: if ($env{'user.state.'.$env{'request.course.id'}}) {
12159: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 12160: } else {
12161: return 2;
12162: }
12163: }
12164:
1.713 albertel 12165: # get the collection of conditions for this resource
1.26 www 12166: sub condval {
12167: my $condidx=shift;
1.54 www 12168: my $allpathcond='';
1.713 albertel 12169: foreach my $cond (split(/\|/,$condidx)) {
12170: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12171: $allpathcond.=
12172: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12173: }
1.191 harris41 12174: }
1.54 www 12175: $allpathcond=~s/\|$//;
1.713 albertel 12176: return &docondval($allpathcond);
12177: }
12178:
12179: #evaluates an expression of conditions
12180: sub docondval {
12181: my ($allpathcond) = @_;
12182: my $result=0;
12183: if ($env{'request.course.id'}
12184: && defined($allpathcond)) {
12185: my $operand='|';
12186: my @stack;
12187: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12188: if ($chunk eq '(') {
12189: push @stack,($operand,$result);
12190: } elsif ($chunk eq ')') {
12191: my $before=pop @stack;
12192: if (pop @stack eq '&') {
12193: $result=$result>$before?$before:$result;
12194: } else {
12195: $result=$result>$before?$result:$before;
12196: }
12197: } elsif (($chunk eq '&') || ($chunk eq '|')) {
12198: $operand=$chunk;
12199: } else {
12200: my $new=directcondval($chunk);
12201: if ($operand eq '&') {
12202: $result=$result>$new?$new:$result;
12203: } else {
12204: $result=$result>$new?$result:$new;
12205: }
12206: }
12207: }
1.26 www 12208: }
12209: return $result;
1.421 albertel 12210: }
12211:
12212: # ---------------------------------------------------- Devalidate courseresdata
12213:
12214: sub devalidatecourseresdata {
12215: my ($coursenum,$coursedomain)=@_;
12216: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12217: &devalidate_cache_new('courseres',$hashid);
1.28 www 12218: }
12219:
1.763 www 12220:
1.200 www 12221: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 12222: #
12223: # Parameters:
12224: # $coursenum - Number of the course.
12225: # $coursedomain - Domain at which the course was created.
12226: # Returns:
12227: # A hash of the course parameters along (I think) with timestamps
12228: # and version info.
1.877 foxr 12229:
1.624 albertel 12230: sub get_courseresdata {
12231: my ($coursenum,$coursedomain)=@_;
1.200 www 12232: my $coursehom=&homeserver($coursenum,$coursedomain);
12233: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12234: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 12235: my %dumpreply;
1.417 albertel 12236: unless (defined($cached)) {
1.624 albertel 12237: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 12238: $result=\%dumpreply;
1.251 albertel 12239: my ($tmp) = keys(%dumpreply);
12240: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 12241: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 12242: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12243: return $tmp;
1.416 albertel 12244: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 12245: $result=undef;
1.599 albertel 12246: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 12247: }
12248: }
1.624 albertel 12249: return $result;
12250: }
12251:
1.633 albertel 12252: sub devalidateuserresdata {
12253: my ($uname,$udom)=@_;
12254: my $hashid="$udom:$uname";
12255: &devalidate_cache_new('userres',$hashid);
12256: }
12257:
1.624 albertel 12258: sub get_userresdata {
12259: my ($uname,$udom)=@_;
12260: #most student don\'t have any data set, check if there is some data
12261: if (&EXT_cache_status($udom,$uname)) { return undef; }
12262:
12263: my $hashid="$udom:$uname";
12264: my ($result,$cached)=&is_cached_new('userres',$hashid);
12265: if (!defined($cached)) {
12266: my %resourcedata=&dump('resourcedata',$udom,$uname);
12267: $result=\%resourcedata;
12268: &do_cache_new('userres',$hashid,$result,600);
12269: }
12270: my ($tmp)=keys(%$result);
12271: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12272: return $result;
12273: }
12274: #error 2 occurs when the .db doesn't exist
12275: if ($tmp!~/error: 2 /) {
1.1294 raeburn 12276: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12277: &logthis("<font color=\"blue\">WARNING:".
12278: " Trying to get resource data for ".
12279: $uname." at ".$udom.": ".
12280: $tmp."</font>");
12281: }
1.624 albertel 12282: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 12283: #&EXT_cache_set($udom,$uname);
12284: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 12285: undef($tmp); # not really an error so don't send it back
1.624 albertel 12286: }
12287: return $tmp;
12288: }
1.879 foxr 12289: #----------------------------------------------- resdata - return resource data
12290: # Purpose:
12291: # Return resource data for either users or for a course.
12292: # Parameters:
12293: # $name - Course/user name.
12294: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 12295: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 12296: # $mapp - decluttered URL of enclosing map
12297: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
12298: # $recurseup - Ref to array of map URLs, starting with map containing
12299: # $mapp up through hierarchy of nested maps to top level map.
12300: # $courseid - CourseID (first part of param identifier).
12301: # $modifier - Middle part of param identifier.
12302: # $what - Last part of param identifier.
1.879 foxr 12303: # @which - Array of names of resources desired.
12304: # Returns:
12305: # The value of the first reasource in @which that is found in the
12306: # resource hash.
12307: # Exceptional Conditions:
12308: # If the $type passed in is not valid (not the string 'course' or
12309: # 'user', an undefined reference is returned.
12310: # If none of the resources are found, an undef is returned
1.624 albertel 12311: sub resdata {
1.1301 raeburn 12312: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12313: $modifier,$what,@which)=@_;
1.624 albertel 12314: my $result;
12315: if ($type eq 'course') {
12316: $result=&get_courseresdata($name,$domain);
12317: } elsif ($type eq 'user') {
12318: $result=&get_userresdata($name,$domain);
12319: }
12320: if (!ref($result)) { return $result; }
1.251 albertel 12321: foreach my $item (@which) {
1.1301 raeburn 12322: if ($item->[1] eq 'course') {
12323: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12324: unless ($$recursed) {
1.1302 raeburn 12325: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 12326: $$recursed = 1;
12327: }
12328: foreach my $item (@${recurseup}) {
12329: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12330: last if (defined($result->{$norecursechk}));
12331: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12332: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12333: }
12334: }
12335: }
12336: if (defined($result->{$item->[0]})) {
1.927 albertel 12337: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 12338: }
1.250 albertel 12339: }
1.291 albertel 12340: return undef;
1.200 www 12341: }
12342:
1.1360 raeburn 12343: sub get_domain_lti {
12344: my ($cdom,$context) = @_;
1.1483 raeburn 12345: my ($name,$cachename,%lti);
1.1360 raeburn 12346: if ($context eq 'consumer') {
12347: $name = 'ltitools';
12348: } elsif ($context eq 'provider') {
12349: $name = 'lti';
1.1483 raeburn 12350: } elsif ($context eq 'linkprot') {
12351: $name = 'ltisec';
1.1360 raeburn 12352: } else {
12353: return %lti;
12354: }
1.1483 raeburn 12355:
12356: if ($context eq 'linkprot') {
12357: $cachename = $context;
12358: } else {
12359: $cachename = $name;
12360: }
12361:
12362: my ($result,$cached)=&is_cached_new($cachename,$cdom);
1.1298 raeburn 12363: if (defined($cached)) {
12364: if (ref($result) eq 'HASH') {
1.1360 raeburn 12365: %lti = %{$result};
1.1298 raeburn 12366: }
12367: } else {
1.1360 raeburn 12368: my %domconfig = &get_dom('configuration',[$name],$cdom);
12369: if (ref($domconfig{$name}) eq 'HASH') {
1.1483 raeburn 12370: if ($context eq 'linkprot') {
12371: if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12372: %lti = %{$domconfig{$name}{'linkprot'}};
12373: }
12374: } else {
12375: %lti = %{$domconfig{$name}};
12376: }
12377: if (($context eq 'consumer') && (keys(%lti))) {
12378: my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
12379: if (ref($encdomconfig{$name}) eq 'HASH') {
12380: foreach my $id (keys(%lti)) {
12381: if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12382: foreach my $item ('key','secret') {
12383: $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12384: }
1.1344 raeburn 12385: }
12386: }
12387: }
12388: }
1.1298 raeburn 12389: }
12390: my $cachetime = 24*60*60;
1.1483 raeburn 12391: &do_cache_new($cachename,$cdom,\%lti,$cachetime);
1.1298 raeburn 12392: }
1.1360 raeburn 12393: return %lti;
1.1298 raeburn 12394: }
12395:
1.1463 raeburn 12396: sub get_course_lti {
12397: my ($cnum,$cdom) = @_;
12398: my $hashid=$cdom.'_'.$cnum;
12399: my %courselti;
12400: my ($result,$cached)=&is_cached_new('courselti',$hashid);
12401: if (defined($cached)) {
12402: if (ref($result) eq 'HASH') {
12403: %courselti = %{$result};
12404: }
12405: } else {
12406: %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
12407: my $cachetime = 24*60*60;
12408: &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
12409: }
12410: return %courselti;
12411: }
12412:
1.1479 raeburn 12413: sub courselti_itemid {
12414: my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12415: my ($chome,$itemid);
12416: $chome = &homeserver($cnum,$cdom);
12417: return if ($chome eq 'no_host');
12418: if (ref($params) eq 'HASH') {
12419: my $rep;
12420: if (grep { $_ eq $chome } current_machine_ids()) {
12421: $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12422: } else {
12423: my $escurl = &escape($url);
12424: my $escmethod = &escape($method);
12425: my $items = &freeze_escape($params);
12426: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12427: }
12428: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12429: ($rep eq 'unknown_cmd')) {
12430: $itemid = $rep;
12431: }
12432: }
12433: return $itemid;
12434: }
12435:
12436: sub domainlti_itemid {
12437: my ($cdom,$url,$method,$params,$context) = @_;
12438: my ($primary_id,$itemid);
12439: $primary_id = &domain($cdom,'primary');
12440: return if ($primary_id eq '');
12441: if (ref($params) eq 'HASH') {
12442: my $rep;
12443: if (grep { $_ eq $primary_id } current_machine_ids()) {
12444: $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12445: } else {
12446: my $cnum = '';
12447: my $escurl = &escape($url);
12448: my $escmethod = &escape($method);
12449: my $items = &freeze_escape($params);
12450: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12451: }
12452: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12453: ($rep eq 'unknown_cmd')) {
12454: $itemid = $rep;
12455: }
12456: }
12457: return $itemid;
12458: }
12459:
1.1496 raeburn 12460: sub count_supptools {
12461: my ($cnum,$cdom,$ignorecache,$reload)=@_;
12462: my $hashid=$cnum.':'.$cdom;
12463: my ($numexttools,$cached);
12464: unless ($ignorecache) {
12465: ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
12466: }
12467: unless (defined($cached)) {
12468: my $chome=&homeserver($cnum,$cdom);
12469: $numexttools = 0;
12470: unless ($chome eq 'no_host') {
12471: my ($supplemental) = &get_supplemental($cnum,$cdom,$reload);
12472: if (ref($supplemental) eq 'HASH') {
12473: if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12474: foreach my $key (keys(%{$supplemental->{'ids'}})) {
12475: if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
12476: $numexttools ++;
12477: }
12478: }
12479: }
12480: }
12481: }
12482: &do_cache_new('supptools',$hashid,$numexttools,600);
12483: }
12484: return $numexttools;
12485: }
12486:
12487: sub has_unhidden_suppfiles {
1.1498 raeburn 12488: my ($cnum,$cdom,$ignorecache,$possdel)=@_;
1.1236 raeburn 12489: my $hashid=$cnum.':'.$cdom;
1.1496 raeburn 12490: my ($showsupp,$cached);
1.1236 raeburn 12491: unless ($ignorecache) {
1.1496 raeburn 12492: ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
1.1236 raeburn 12493: }
12494: unless (defined($cached)) {
12495: my $chome=&homeserver($cnum,$cdom);
12496: unless ($chome eq 'no_host') {
1.1497 raeburn 12497: my ($supplemental) = &get_supplemental($cnum,$cdom,$ignorecache,$possdel);
1.1496 raeburn 12498: if (ref($supplemental) eq 'HASH') {
12499: if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12500: foreach my $key (keys(%{$supplemental->{'ids'}})) {
12501: next if ($key =~ /\.sequence$/);
12502: if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
12503: foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
12504: unless ($supplemental->{'hidden'}->{$id}) {
12505: $showsupp = 1;
12506: last;
12507: }
12508: }
12509: }
12510: last if ($showsupp);
12511: }
12512: }
12513: }
1.1236 raeburn 12514: }
1.1496 raeburn 12515: &do_cache_new('showsupp',$hashid,$showsupp,600);
1.1236 raeburn 12516: }
1.1496 raeburn 12517: return $showsupp;
12518: }
12519:
12520: sub get_supplemental {
12521: my ($cnum,$cdom,$ignorecache,$possdel)=@_;
12522: my $hashid=$cnum.':'.$cdom;
12523: my ($supplemental,$cached,$set_httprefs);
12524: unless ($ignorecache) {
12525: ($supplemental,$cached) = &is_cached_new('supplemental',$hashid);
12526: }
12527: unless (defined($cached)) {
12528: my $chome=&homeserver($cnum,$cdom);
12529: unless ($chome eq 'no_host') {
1.1499 ! raeburn 12530: my @order = @LONCAPA::map::order;
! 12531: my @resources = @LONCAPA::map::resources;
! 12532: my @resparms = @LONCAPA::map::resparms;
! 12533: my @zombies = @LONCAPA::map::zombies;
1.1496 raeburn 12534: my ($errors,%ids,%hidden);
12535: $errors =
12536: &Apache::loncommon::recurse_supplemental($cnum,$cdom,
12537: 'supplemental.sequence',
12538: $errors,$possdel,\%ids,\%hidden);
1.1499 ! raeburn 12539: @LONCAPA::map::order = @order;
! 12540: @LONCAPA::map::resources = @resources;
! 12541: @LONCAPA::map::resparms = @resparms;
! 12542: @LONCAPA::map::zombies = @zombies;
1.1496 raeburn 12543: $set_httprefs = 1;
12544: if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
12545: &Apache::lonnet::appenv({'request.course.suppupdated' => time});
12546: }
12547: $supplemental = {
12548: ids => \%ids,
12549: hidden => \%hidden,
12550: };
12551: &do_cache_new('supplemental',$hashid,$supplemental,600);
12552: }
12553: }
12554: return ($supplemental,$set_httprefs);
1.1236 raeburn 12555: }
12556:
1.379 matthew 12557: #
12558: # EXT resource caching routines
12559: #
12560:
1.1302 raeburn 12561: {
12562: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12563: #
12564: # The course for which we cache
12565: my $cachedmapkey='';
12566: # The cached recursive maps for this course
12567: my %cachedmaps=();
12568: # When this was last done
12569: my $cachedmaptime='';
12570:
1.379 matthew 12571: sub clear_EXT_cache_status {
1.383 albertel 12572: &delenv('cache.EXT.');
1.379 matthew 12573: }
12574:
12575: sub EXT_cache_status {
12576: my ($target_domain,$target_user) = @_;
1.383 albertel 12577: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 12578: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 12579: # We know already the user has no data
12580: return 1;
12581: } else {
12582: return 0;
12583: }
12584: }
12585:
12586: sub EXT_cache_set {
12587: my ($target_domain,$target_user) = @_;
1.383 albertel 12588: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 12589: #&appenv({$cachename => time});
1.379 matthew 12590: }
12591:
1.28 www 12592: # --------------------------------------------------------- Value of a Variable
1.58 www 12593: sub EXT {
1.715 albertel 12594:
1.1461 raeburn 12595: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
1.68 www 12596: unless ($varname) { return ''; }
1.218 albertel 12597: #get real user name/domain, courseid and symb
12598: my $courseid;
1.359 albertel 12599: my $publicuser;
1.427 www 12600: if ($symbparm) {
12601: $symbparm=&get_symb_from_alias($symbparm);
12602: }
1.218 albertel 12603: if (!($uname && $udom)) {
1.790 albertel 12604: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 12605: if (!$symbparm) { $symbparm=$cursymb; }
12606: } else {
1.620 albertel 12607: $courseid=$env{'request.course.id'};
1.218 albertel 12608: }
1.48 www 12609: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12610: my $rest;
1.320 albertel 12611: if (defined($therest[0])) {
1.48 www 12612: $rest=join('.',@therest);
12613: } else {
12614: $rest='';
12615: }
1.320 albertel 12616:
1.57 www 12617: my $qualifierrest=$qualifier;
12618: if ($rest) { $qualifierrest.='.'.$rest; }
12619: my $spacequalifierrest=$space;
12620: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 12621: if ($realm eq 'user') {
1.48 www 12622: # --------------------------------------------------------------- user.resource
12623: if ($space eq 'resource') {
1.651 albertel 12624: if ( (defined($Apache::lonhomework::parsing_a_problem)
12625: || defined($Apache::lonhomework::parsing_a_task))
12626: &&
1.1469 raeburn 12627: ($symbparm eq &symbread()) ) {
1.744 albertel 12628: # if we are in the middle of processing the resource the
12629: # get the value we are planning on committing
12630: if (defined($Apache::lonhomework::results{$qualifierrest})) {
12631: return $Apache::lonhomework::results{$qualifierrest};
12632: } else {
12633: return $Apache::lonhomework::history{$qualifierrest};
12634: }
1.335 albertel 12635: } else {
1.359 albertel 12636: my %restored;
1.620 albertel 12637: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 12638: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12639: } else {
12640: %restored=&restore($symbparm,$courseid,$udom,$uname);
12641: }
1.335 albertel 12642: return $restored{$qualifierrest};
12643: }
1.48 www 12644: # ----------------------------------------------------------------- user.access
12645: } elsif ($space eq 'access') {
1.218 albertel 12646: # FIXME - not supporting calls for a specific user
1.48 www 12647: return &allowed($qualifier,$rest);
12648: # ------------------------------------------ user.preferences, user.environment
12649: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 12650: if (($uname eq $env{'user.name'}) &&
12651: ($udom eq $env{'user.domain'})) {
12652: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 12653: } else {
1.359 albertel 12654: my %returnhash;
12655: if (!$publicuser) {
12656: %returnhash=&userenvironment($udom,$uname,
12657: $qualifierrest);
12658: }
1.218 albertel 12659: return $returnhash{$qualifierrest};
12660: }
1.48 www 12661: # ----------------------------------------------------------------- user.course
12662: } elsif ($space eq 'course') {
1.218 albertel 12663: # FIXME - not supporting calls for a specific user
1.620 albertel 12664: return $env{join('.',('request.course',$qualifier))};
1.48 www 12665: # ------------------------------------------------------------------- user.role
12666: } elsif ($space eq 'role') {
1.218 albertel 12667: # FIXME - not supporting calls for a specific user
1.620 albertel 12668: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 12669: if ($qualifier eq 'value') {
12670: return $role;
12671: } elsif ($qualifier eq 'extent') {
12672: return $where;
12673: }
12674: # ----------------------------------------------------------------- user.domain
12675: } elsif ($space eq 'domain') {
1.218 albertel 12676: return $udom;
1.48 www 12677: # ------------------------------------------------------------------- user.name
12678: } elsif ($space eq 'name') {
1.218 albertel 12679: return $uname;
1.48 www 12680: # ---------------------------------------------------- Any other user namespace
1.29 www 12681: } else {
1.359 albertel 12682: my %reply;
12683: if (!$publicuser) {
12684: %reply=&get($space,[$qualifierrest],$udom,$uname);
12685: }
12686: return $reply{$qualifierrest};
1.48 www 12687: }
1.236 www 12688: } elsif ($realm eq 'query') {
12689: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 12690: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12691: [$spacequalifierrest]);
1.620 albertel 12692: return $env{'form.'.$spacequalifierrest};
1.236 www 12693: } elsif ($realm eq 'request') {
1.48 www 12694: # ------------------------------------------------------------- request.browser
12695: if ($space eq 'browser') {
1.1145 bisitz 12696: return $env{'browser.'.$qualifier};
1.57 www 12697: # ------------------------------------------------------------ request.filename
12698: } else {
1.620 albertel 12699: return $env{'request.'.$spacequalifierrest};
1.29 www 12700: }
1.28 www 12701: } elsif ($realm eq 'course') {
1.48 www 12702: # ---------------------------------------------------------- course.description
1.620 albertel 12703: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 12704: } elsif ($realm eq 'resource') {
1.165 www 12705:
1.620 albertel 12706: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 12707: if (!$symbparm) { $symbparm=&symbread(); }
12708: }
1.693 albertel 12709:
1.1232 raeburn 12710: if ($qualifier eq '') {
12711: if ($space eq 'title') {
12712: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12713: return &gettitle($symbparm);
12714: }
1.693 albertel 12715:
1.1232 raeburn 12716: if ($space eq 'map') {
12717: my ($map) = &decode_symb($symbparm);
12718: return &symbread($map);
12719: }
12720: if ($space eq 'maptitle') {
12721: my ($map) = &decode_symb($symbparm);
12722: return &gettitle($map);
12723: }
12724: if ($space eq 'filename') {
12725: if ($symbparm) {
12726: return &clutter((&decode_symb($symbparm))[2]);
12727: }
12728: return &hreflocation('',$env{'request.filename'});
1.905 albertel 12729: }
1.1232 raeburn 12730:
1.1233 raeburn 12731: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12732: if ($space eq 'visibleparts') {
12733: my $navmap = Apache::lonnavmaps::navmap->new();
12734: my $item;
12735: if (ref($navmap)) {
12736: my $res = $navmap->getBySymb($symbparm);
12737: my $parts = $res->parts();
12738: if (ref($parts) eq 'ARRAY') {
12739: $item = join(',',@{$parts});
12740: }
12741: undef($navmap);
1.1232 raeburn 12742: }
1.1233 raeburn 12743: return $item;
1.1232 raeburn 12744: }
12745: }
12746: }
1.693 albertel 12747:
1.1301 raeburn 12748: my ($section, $group, @groups, @recurseup, $recursed);
1.1461 raeburn 12749: if (ref($recurseupref) eq 'ARRAY') {
12750: @recurseup = @{$recurseupref};
12751: $recursed = 1;
12752: }
1.1301 raeburn 12753: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 12754: if (($courseid eq '') && ($cid)) {
12755: $courseid = $cid;
12756: }
12757: if (($symbparm && $courseid) &&
12758: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 12759:
1.218 albertel 12760: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 12761:
1.60 www 12762: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 12763: my $symbp=$symbparm;
1.1301 raeburn 12764: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 12765: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 12766: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 12767: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 12768: if (($env{'user.name'} eq $uname) &&
12769: ($env{'user.domain'} eq $udom)) {
12770: $section=$env{'request.course.sec'};
1.733 raeburn 12771: @groups = split(/:/,$env{'request.course.groups'});
12772: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 12773: } else {
1.539 albertel 12774: if (! defined($usection)) {
1.551 albertel 12775: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 12776: } else {
12777: $section = $usection;
12778: }
1.733 raeburn 12779: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 12780: }
12781:
12782: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12783: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 12784: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 12785: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12786:
1.593 albertel 12787: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 12788: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 12789: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 12790: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 12791:
1.60 www 12792: # ----------------------------------------------------------- first, check user
1.624 albertel 12793:
1.1301 raeburn 12794: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12795: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 12796: ([$courselevelr,'resource'],
12797: [$courselevelm,'map' ],
1.1301 raeburn 12798: [$courseleveli,'map' ],
1.927 albertel 12799: [$courselevel, 'course' ]));
1.931 albertel 12800: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 12801:
1.594 albertel 12802: # ------------------------------------------------ second, check some of course
1.684 raeburn 12803: my $coursereply;
1.691 raeburn 12804: if (@groups > 0) {
12805: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 12806: $recurseparm,$mapparm,$spacequalifierrest,
12807: $mapp,\$recursed,\@recurseup);
12808: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 12809: }
1.96 www 12810:
1.684 raeburn 12811: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 12812: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12813: 'course',$mapp,\$recursed,\@recurseup,
12814: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 12815: ([$seclevelr, 'resource'],
12816: [$seclevelm, 'map' ],
1.1301 raeburn 12817: [$secleveli, 'map' ],
1.927 albertel 12818: [$seclevel, 'course' ],
12819: [$courselevelr,'resource']));
12820: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 12821:
1.60 www 12822: # ------------------------------------------------------ third, check map parms
1.218 albertel 12823: my %parmhash=();
12824: my $thisparm='';
12825: if (tie(%parmhash,'GDBM_File',
1.620 albertel 12826: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 12827: &GDBM_READER(),0640)) {
1.218 albertel 12828: $thisparm=$parmhash{$symbparm};
12829: untie(%parmhash);
12830: }
1.927 albertel 12831: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 12832: }
1.594 albertel 12833: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 12834:
12835: my $what = $spacequalifierrest;
12836: $what=~s/\./\_/;
1.282 albertel 12837: my $filename;
12838: if (!$symbparm) { $symbparm=&symbread(); }
12839: if ($symbparm) {
1.409 www 12840: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 12841: } else {
1.620 albertel 12842: $filename=$env{'request.filename'};
1.282 albertel 12843: }
1.1362 raeburn 12844: my $toolsymb;
12845: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12846: $toolsymb = $symbparm;
12847: }
12848: my $metadata=&metadata($filename,$what,$toolsymb);
1.927 albertel 12849: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362 raeburn 12850: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927 albertel 12851: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 12852:
1.1301 raeburn 12853: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 12854: if ($symbparm && defined($courseid) &&
1.620 albertel 12855: $courseid eq $env{'request.course.id'}) {
1.624 albertel 12856: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12857: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12858: 'course',$mapp,\$recursed,\@recurseup,
12859: $courseid,'.',$spacequalifierrest,
1.927 albertel 12860: ([$courselevelm,'map' ],
1.1301 raeburn 12861: [$courseleveli,'map' ],
1.927 albertel 12862: [$courselevel, 'course']));
12863: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 12864: }
1.145 www 12865: # ------------------------------------------------------------------ Cascade up
1.218 albertel 12866: unless ($space eq '0') {
1.336 albertel 12867: my @parts=split(/_/,$space);
12868: my $id=pop(@parts);
12869: my $part=join('_',@parts);
12870: if ($part eq '') { $part='0'; }
1.927 albertel 12871: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 12872: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 12873: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 12874: }
1.395 albertel 12875: if ($recurse) { return undef; }
1.1362 raeburn 12876: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927 albertel 12877: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 12878: # ---------------------------------------------------- Any other user namespace
12879: } elsif ($realm eq 'environment') {
12880: # ----------------------------------------------------------------- environment
1.620 albertel 12881: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12882: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 12883: } else {
1.770 albertel 12884: if ($uname eq 'anonymous' && $udom eq '') {
12885: return '';
12886: }
1.219 albertel 12887: my %returnhash=&userenvironment($udom,$uname,
12888: $spacequalifierrest);
12889: return $returnhash{$spacequalifierrest};
12890: }
1.28 www 12891: } elsif ($realm eq 'system') {
1.48 www 12892: # ----------------------------------------------------------------- system.time
12893: if ($space eq 'time') {
12894: return time;
12895: }
1.696 albertel 12896: } elsif ($realm eq 'server') {
12897: # ----------------------------------------------------------------- system.time
12898: if ($space eq 'name') {
12899: return $ENV{'SERVER_NAME'};
12900: }
1.1415 raeburn 12901: } elsif ($realm eq 'client') {
12902: if ($space eq 'remote_addr') {
1.1441 raeburn 12903: return &get_requestor_ip();
1.1415 raeburn 12904: }
1.28 www 12905: }
1.48 www 12906: return '';
1.61 www 12907: }
12908:
1.927 albertel 12909: sub get_reply {
12910: my ($reply_value) = @_;
1.940 raeburn 12911: if (ref($reply_value) eq 'ARRAY') {
12912: if (wantarray) {
12913: return @$reply_value;
12914: }
12915: return $reply_value->[0];
12916: } else {
12917: return $reply_value;
1.927 albertel 12918: }
12919: }
12920:
1.691 raeburn 12921: sub check_group_parms {
1.1301 raeburn 12922: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12923: $recursed,$recurseupref) = @_;
12924: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12925: [$what,'course']);
12926: my $coursereply;
1.691 raeburn 12927: foreach my $group (@{$groups}) {
1.1301 raeburn 12928: my @groupitems = ();
1.691 raeburn 12929: foreach my $level (@levels) {
1.927 albertel 12930: my $item = $courseid.'.['.$group.'].'.$level->[0];
12931: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 12932: }
1.1301 raeburn 12933: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12934: $env{'course.'.$courseid.'.domain'},
12935: 'course',$mapp,$recursed,$recurseupref,
12936: $courseid,'.['.$group.'].',$what,
12937: @groupitems);
12938: last if (defined($coursereply));
1.691 raeburn 12939: }
12940: return $coursereply;
12941: }
12942:
1.1301 raeburn 12943: sub get_map_hierarchy {
1.1302 raeburn 12944: my ($mapname,$courseid) = @_;
12945: my @recurseup = ();
1.1301 raeburn 12946: if ($mapname) {
1.1302 raeburn 12947: if (($cachedmapkey eq $courseid) &&
12948: (abs($cachedmaptime-time)<5)) {
12949: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12950: return @{$cachedmaps{$mapname}};
12951: }
12952: }
1.1301 raeburn 12953: my $navmap = Apache::lonnavmaps::navmap->new();
12954: if (ref($navmap)) {
12955: @recurseup = $navmap->recurseup_maps($mapname);
12956: undef($navmap);
1.1302 raeburn 12957: $cachedmaps{$mapname} = \@recurseup;
12958: $cachedmaptime=time;
12959: $cachedmapkey=$courseid;
1.1301 raeburn 12960: }
12961: }
12962: return @recurseup;
12963: }
12964:
1.1302 raeburn 12965: }
12966:
1.691 raeburn 12967: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 12968: my ($courseid,@groups) = @_;
12969: @groups = sort(@groups);
1.691 raeburn 12970: return @groups;
12971: }
12972:
1.395 albertel 12973: sub packages_tab_default {
1.1362 raeburn 12974: my ($uri,$varname,$toolsymb)=@_;
1.395 albertel 12975: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 12976:
12977: my (@extension,@specifics,$do_default);
1.1362 raeburn 12978: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395 albertel 12979: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 12980: if ($pack_type eq 'default') {
12981: $do_default=1;
12982: } elsif ($pack_type eq 'extension') {
12983: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 12984: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 12985: # only look at packages defaults for packages that this id is
1.738 albertel 12986: push(@specifics,[$package,$pack_type,$pack_part]);
12987: }
12988: }
12989: # first look for a package that matches the requested part id
12990: foreach my $package (@specifics) {
12991: my (undef,$pack_type,$pack_part)=@{$package};
12992: next if ($pack_part ne $part);
12993: if (defined($packagetab{"$pack_type&$name&default"})) {
12994: return $packagetab{"$pack_type&$name&default"};
12995: }
12996: }
12997: # look for any possible matching non extension_ package
12998: foreach my $package (@specifics) {
12999: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 13000: if (defined($packagetab{"$pack_type&$name&default"})) {
13001: return $packagetab{"$pack_type&$name&default"};
13002: }
1.585 albertel 13003: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 13004: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13005: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 13006: }
13007: }
1.738 albertel 13008: # look for any posible extension_ match
13009: foreach my $package (@extension) {
13010: my ($package,$pack_type)=@{$package};
13011: if (defined($packagetab{"$pack_type&$name&default"})) {
13012: return $packagetab{"$pack_type&$name&default"};
13013: }
13014: if (defined($packagetab{$package."&$name&default"})) {
13015: return $packagetab{$package."&$name&default"};
13016: }
13017: }
13018: # look for a global default setting
13019: if ($do_default && defined($packagetab{"default&$name&default"})) {
13020: return $packagetab{"default&$name&default"};
13021: }
1.395 albertel 13022: return undef;
13023: }
13024:
1.334 albertel 13025: sub add_prefix_and_part {
13026: my ($prefix,$part)=@_;
13027: my $keyroot;
13028: if (defined($prefix) && $prefix !~ /^__/) {
13029: # prefix that has a part already
13030: $keyroot=$prefix;
13031: } elsif (defined($prefix)) {
13032: # prefix that is missing a part
13033: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13034: } else {
13035: # no prefix at all
13036: if (defined($part)) { $keyroot='_'.$part; }
13037: }
13038: return $keyroot;
13039: }
13040:
1.71 www 13041: # ---------------------------------------------------------------- Get metadata
13042:
1.599 albertel 13043: my %metaentry;
1.1070 www 13044: my %importedpartids;
1.1369 raeburn 13045: my %importedrespids;
1.71 www 13046: sub metadata {
1.1362 raeburn 13047: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71 www 13048: $uri=&declutter($uri);
1.288 albertel 13049: # if it is a non metadata possible uri return quickly
1.529 albertel 13050: if (($uri eq '') ||
13051: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 13052: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 13053: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 13054: return undef;
13055: }
1.1261 raeburn 13056: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 13057: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 13058: return undef;
1.288 albertel 13059: }
1.73 www 13060: my $filename=$uri;
13061: $uri=~s/\.meta$//;
1.172 www 13062: #
13063: # Is the metadata already cached?
1.177 www 13064: # Look at timestamp of caching
1.172 www 13065: # Everything is cached by the main uri, libraries are never directly cached
13066: #
1.428 albertel 13067: if (!defined($liburi)) {
1.599 albertel 13068: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 13069: if (defined($cached)) { return $result->{':'.$what}; }
13070: }
1.1362 raeburn 13071:
13072: #
13073: # If the uri is for an external tool the file from
13074: # which metadata should be retrieved depends on whether
13075: # the tool had been configured to be gradable (set in the Course
13076: # Editor or Resource Editor).
13077: #
13078: # If a valid symb has been included as the third arg in the call
13079: # to &metadata() that can be used to retrieve the value of
13080: # parameter_0_gradable set for the resource, and included in the
13081: # uploaded map containing the tool. The value is retrieved via
13082: # &EXT(), if a valid symb is available. Otherwise the value of
13083: # gradable in the exttool_$marker.db file for the tool instance
1.1364 raeburn 13084: # is retrieved via &get().
13085: #
13086: # When lonuserstate::traceroute() calls lonnet::EXT() for
13087: # hiddenresource and encrypturl (during course initialization)
13088: # the map-level parameter for resource.0.gradable included in the
13089: # uploaded map containing the tool will not yet have been stored
13090: # in the user_course_parms.db file for the user's session, so in
13091: # this case fall back to retrieving gradable status from the
13092: # exttool_$marker.db file.
1.1362 raeburn 13093: #
13094: # In order to avoid an infinite loop, &metadata() will return
13095: # before a call to &EXT(), if the uri is for an external tool
13096: # and the $what for which metadata is being requested is
13097: # parameter_0_gradable or 0_gradable.
13098: #
13099:
13100: if ($uri =~ /ext\.tool$/) {
13101: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13102: return;
13103: } else {
13104: my ($checked,$use_passback);
13105: if ($toolsymb ne '') {
13106: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364 raeburn 13107: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362 raeburn 13108: $checked = 1;
13109: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13110: $use_passback = 1;
13111: }
13112: }
13113: }
13114: unless ($checked) {
13115: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13116: $marker=~s/\D//g;
1.1363 raeburn 13117: if ($marker) {
1.1362 raeburn 13118: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13119: $use_passback = $toolsettings{'gradable'};
13120: }
13121: }
13122: if ($use_passback) {
13123: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13124: } else {
13125: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13126: }
13127: }
13128: }
13129:
1.428 albertel 13130: {
1.1069 www 13131: # Imported parts would go here
1.1369 raeburn 13132: my @origfiletagids=();
1.1069 www 13133: my $importedparts=0;
1.1369 raeburn 13134:
13135: # Imported responseids would go here
13136: my $importedresponses=0;
1.172 www 13137: #
13138: # Is this a recursive call for a library?
13139: #
1.599 albertel 13140: # if (! exists($metacache{$uri})) {
13141: # $metacache{$uri}={};
13142: # }
1.924 albertel 13143: my $cachetime = 60*60;
1.171 www 13144: if ($liburi) {
13145: $liburi=&declutter($liburi);
13146: $filename=$liburi;
1.401 bowersj2 13147: } else {
1.599 albertel 13148: &devalidate_cache_new('meta',$uri);
13149: undef(%metaentry);
1.401 bowersj2 13150: }
1.140 www 13151: my %metathesekeys=();
1.73 www 13152: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 13153: my $metastring;
1.1140 www 13154: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 13155: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 13156: $metastring =
1.929 albertel 13157: &Apache::lonnet::ssi_body($which,
1.924 albertel 13158: ('grade_target' => 'meta'));
13159: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 13160: } elsif (($uri !~ m -^(editupload)/-) &&
13161: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 13162: my $file=&filelocation('',&clutter($filename));
1.599 albertel 13163: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 13164: $metastring=&getfile($file);
1.489 albertel 13165: }
1.208 albertel 13166: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 13167: my $token;
1.140 www 13168: undef %metathesekeys;
1.71 www 13169: while ($token=$parser->get_token) {
1.339 albertel 13170: if ($token->[0] eq 'S') {
13171: if (defined($token->[2]->{'package'})) {
1.172 www 13172: #
13173: # This is a package - get package info
13174: #
1.339 albertel 13175: my $package=$token->[2]->{'package'};
13176: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13177: if (defined($token->[2]->{'id'})) {
13178: $keyroot.='_'.$token->[2]->{'id'};
13179: }
1.599 albertel 13180: if ($metaentry{':packages'}) {
13181: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 13182: } else {
1.599 albertel 13183: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 13184: }
1.736 albertel 13185: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 13186: my $part=$keyroot;
13187: $part=~s/^\_//;
1.736 albertel 13188: if ($pack_entry=~/^\Q$package\E\&/ ||
13189: $pack_entry=~/^\Q$package\E_0\&/) {
13190: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 13191: # ignore package.tab specified default values
13192: # here &package_tab_default() will fetch those
13193: if ($subp eq 'default') { next; }
1.736 albertel 13194: my $value=$packagetab{$pack_entry};
1.432 albertel 13195: my $unikey;
13196: if ($pack =~ /_0$/) {
13197: $unikey='parameter_0_'.$name;
13198: $part=0;
13199: } else {
13200: $unikey='parameter'.$keyroot.'_'.$name;
13201: }
1.339 albertel 13202: if ($subp eq 'display') {
13203: $value.=' [Part: '.$part.']';
13204: }
1.599 albertel 13205: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 13206: $metathesekeys{$unikey}=1;
1.599 albertel 13207: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13208: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 13209: }
1.599 albertel 13210: if (defined($metaentry{':'.$unikey.'.default'})) {
13211: $metaentry{':'.$unikey}=
13212: $metaentry{':'.$unikey.'.default'};
1.356 albertel 13213: }
1.339 albertel 13214: }
13215: }
13216: } else {
1.172 www 13217: #
13218: # This is not a package - some other kind of start tag
1.339 albertel 13219: #
13220: my $entry=$token->[1];
1.1068 www 13221: my $unikey='';
1.175 www 13222:
1.339 albertel 13223: if ($entry eq 'import') {
1.175 www 13224: #
13225: # Importing a library here
1.339 albertel 13226: #
1.1067 www 13227: my $location=$parser->get_text('/import');
13228: my $dir=$filename;
13229: $dir=~s|[^/]*$||;
13230: $location=&filelocation($dir,$location);
1.1369 raeburn 13231:
13232: my $importid=$token->[2]->{'id'};
1.1068 www 13233: my $importmode=$token->[2]->{'importmode'};
1.1369 raeburn 13234: #
13235: # Check metadata for imported file to
13236: # see if it contained response items
13237: #
1.1372 raeburn 13238: my ($origfile,@libfilekeys);
1.1370 raeburn 13239: my %currmetaentry = %metaentry;
1.1372 raeburn 13240: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13241: $depthcount+1));
13242: if (grep(/^responseorder$/,@libfilekeys)) {
13243: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13244: undef,$depthcount+1);
13245: if ($libresponseorder ne '') {
13246: if ($#origfiletagids<0) {
13247: undef(%importedrespids);
13248: undef(%importedpartids);
13249: }
1.1373 raeburn 13250: my @respids = split(/\s*,\s*/,$libresponseorder);
13251: if (@respids) {
13252: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13253: }
13254: if ($importedrespids{$importid} ne '') {
1.1372 raeburn 13255: $importedresponses = 1;
1.1369 raeburn 13256: # We need to get the original file and the imported file to get the response order correct
13257: # Load and inspect original file
1.1372 raeburn 13258: if ($#origfiletagids<0) {
13259: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13260: $origfile=&getfile($origfilelocation);
13261: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13262: }
1.1369 raeburn 13263: }
13264: }
13265: }
1.1370 raeburn 13266: # Do not overwrite contents of %metaentry hash for resource itself with
13267: # hash populated for imported library file
13268: %metaentry = %currmetaentry;
13269: undef(%currmetaentry);
1.1374 raeburn 13270: if ($importmode eq 'part') {
1.1068 www 13271: # Import as part(s)
1.1069 www 13272: $importedparts=1;
13273: # We need to get the original file and the imported file to get the part order correct
13274: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369 raeburn 13275: # Load and inspect original file if we didn't do that already
13276: if ($#origfiletagids<0) {
13277: undef(%importedrespids);
13278: undef(%importedpartids);
13279: if ($origfile eq '') {
13280: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13281: $origfile=&getfile($origfilelocation);
13282: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13283: }
1.1070 www 13284: }
1.1372 raeburn 13285: my @impfilepartids;
13286: # If <partorder> tag is included in metadata for the imported file
13287: # get the parts in the imported file from that.
13288: if (grep(/^partorder$/,@libfilekeys)) {
13289: %currmetaentry = %metaentry;
13290: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13291: $depthcount+1);
13292: %metaentry = %currmetaentry;
13293: undef(%currmetaentry);
13294: if ($libpartorder ne '') {
13295: @impfilepartids=split(/\s*,\s*/,$libpartorder);
13296: }
13297: } else {
13298: # If no <partorder> tag available, load and inspect imported file
13299: my $impfile=&getfile($location);
13300: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13301: }
1.1069 www 13302: if ($#impfilepartids>=0) {
13303: # This problem had parts
1.1070 www 13304: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 13305: } else {
13306: # Importing by turning a single problem into a problem part
13307: # It gets the import-tags ID as part-ID
13308: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 13309: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 13310: }
1.1068 www 13311: } else {
1.1374 raeburn 13312: # Import as problem or as normal import
13313: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13314: unless ($importmode eq 'problem') {
1.1068 www 13315: # Normal import
1.1374 raeburn 13316: if (defined($token->[2]->{'id'})) {
13317: $unikey.='_'.$token->[2]->{'id'};
13318: }
13319: }
13320: # Check metadata for imported file to
13321: # see if it contained parts
13322: if (grep(/^partorder$/,@libfilekeys)) {
13323: %currmetaentry = %metaentry;
13324: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13325: $depthcount+1);
13326: %metaentry = %currmetaentry;
13327: undef(%currmetaentry);
13328: if ($libpartorder ne '') {
13329: $importedparts = 1;
13330: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13331: }
13332: }
1.1067 www 13333: }
1.339 albertel 13334: if ($depthcount<20) {
1.736 albertel 13335: my $metadata =
1.1362 raeburn 13336: &metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736 albertel 13337: $depthcount+1);
13338: foreach my $meta (split(',',$metadata)) {
13339: $metaentry{':'.$meta}=$metaentry{':'.$meta};
13340: $metathesekeys{$meta}=1;
1.339 albertel 13341: }
1.1068 www 13342: }
1.1067 www 13343: } else {
13344: #
13345: # Not importing, some other kind of non-package, non-library start tag
13346: #
13347: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13348: if (defined($token->[2]->{'id'})) {
13349: $unikey.='_'.$token->[2]->{'id'};
13350: }
1.339 albertel 13351: if (defined($token->[2]->{'name'})) {
13352: $unikey.='_'.$token->[2]->{'name'};
13353: }
13354: $metathesekeys{$unikey}=1;
1.736 albertel 13355: foreach my $param (@{$token->[3]}) {
13356: $metaentry{':'.$unikey.'.'.$param} =
13357: $token->[2]->{$param};
1.339 albertel 13358: }
13359: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 13360: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 13361: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13362: # only ws inside the tag, and not in default, so use default
13363: # as value
1.599 albertel 13364: $metaentry{':'.$unikey}=$default;
1.908 albertel 13365: } elsif ( $internaltext =~ /\S/ ) {
13366: # something interesting inside the tag
13367: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 13368: } else {
1.908 albertel 13369: # no interesting values, don't set a default
1.339 albertel 13370: }
1.172 www 13371: # end of not-a-package not-a-library import
1.339 albertel 13372: }
1.172 www 13373: # end of not-a-package start tag
1.339 albertel 13374: }
1.172 www 13375: # the next is the end of "start tag"
1.339 albertel 13376: }
13377: }
1.483 albertel 13378: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 13379: $extension = lc($extension);
13380: if ($extension eq 'htm') { $extension='html'; }
13381:
1.737 albertel 13382: foreach my $key (keys(%packagetab)) {
1.483 albertel 13383: #no specific packages #how's our extension
13384: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 13385: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 13386: \%metathesekeys);
13387: }
1.883 albertel 13388:
13389: if (!exists($metaentry{':packages'})
13390: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 13391: foreach my $key (keys(%packagetab)) {
1.483 albertel 13392: #no specific packages well let's get default then
13393: if ($key!~/^default&/) { next; }
1.488 albertel 13394: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 13395: \%metathesekeys);
13396: }
13397: }
1.338 www 13398: # are there custom rights to evaluate
1.599 albertel 13399: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 13400:
1.338 www 13401: #
13402: # Importing a rights file here
1.339 albertel 13403: #
13404: unless ($depthcount) {
1.599 albertel 13405: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 13406: my $dir=$filename;
13407: $dir=~s|[^/]*$||;
13408: $location=&filelocation($dir,$location);
1.736 albertel 13409: my $rights_metadata =
1.1362 raeburn 13410: &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736 albertel 13411: $depthcount+1);
13412: foreach my $rights (split(',',$rights_metadata)) {
13413: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13414: $metathesekeys{$rights}=1;
1.339 albertel 13415: }
13416: }
13417: }
1.737 albertel 13418: # uniqifiy package listing
13419: my %seen;
13420: my @uniq_packages =
13421: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13422: $metaentry{':packages'} = join(',',@uniq_packages);
13423:
1.1369 raeburn 13424: if (($importedresponses) || ($importedparts)) {
13425: if ($importedparts) {
1.1070 www 13426: # We had imported parts and need to rebuild partorder
1.1369 raeburn 13427: $metaentry{':partorder'}='';
13428: $metathesekeys{'partorder'}=1;
13429: }
13430: if ($importedresponses) {
13431: # We had imported responses and need to rebuil responseorder
13432: $metaentry{':responseorder'}='';
13433: $metathesekeys{'responseorder'}=1;
13434: }
13435: for (my $index=0;$index<$#origfiletagids;$index+=2) {
13436: my $origid = $origfiletagids[$index+1];
13437: if ($origfiletagids[$index] eq 'part') {
13438: # Original part, part of the problem
13439: if ($importedparts) {
13440: $metaentry{':partorder'}.=','.$origid;
13441: }
13442: } elsif ($origfiletagids[$index] eq 'import') {
13443: if ($importedparts) {
13444: # We have imported parts at this position
1.1373 raeburn 13445: if ($importedpartids{$origid} ne '') {
13446: $metaentry{':partorder'}.=','.$importedpartids{$origid};
13447: }
1.1369 raeburn 13448: }
13449: if ($importedresponses) {
13450: # We have imported responses at this position
1.1373 raeburn 13451: if ($importedrespids{$origid} ne '') {
13452: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369 raeburn 13453: }
13454: }
13455: } else {
13456: # Original response item, part of the problem
13457: if ($importedresponses) {
13458: $metaentry{':responseorder'}.=','.$origid;
13459: }
13460: }
13461: }
13462: if ($importedparts) {
13463: $metaentry{':partorder'}=~s/^\,//;
13464: }
13465: if ($importedresponses) {
13466: $metaentry{':responseorder'}=~s/^\,//;
13467: }
1.1070 www 13468: }
1.737 albertel 13469: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 13470: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 13471: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371 raeburn 13472: unless ($liburi) {
13473: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13474: }
1.177 www 13475: # this is the end of "was not already recently cached
1.71 www 13476: }
1.599 albertel 13477: return $metaentry{':'.$what};
1.261 albertel 13478: }
13479:
1.488 albertel 13480: sub metadata_create_package_def {
1.483 albertel 13481: my ($uri,$key,$package,$metathesekeys)=@_;
13482: my ($pack,$name,$subp)=split(/\&/,$key);
13483: if ($subp eq 'default') { next; }
13484:
1.599 albertel 13485: if (defined($metaentry{':packages'})) {
13486: $metaentry{':packages'}.=','.$package;
1.483 albertel 13487: } else {
1.599 albertel 13488: $metaentry{':packages'}=$package;
1.483 albertel 13489: }
13490: my $value=$packagetab{$key};
13491: my $unikey;
13492: $unikey='parameter_0_'.$name;
1.599 albertel 13493: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 13494: $$metathesekeys{$unikey}=1;
1.599 albertel 13495: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13496: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 13497: }
1.599 albertel 13498: if (defined($metaentry{':'.$unikey.'.default'})) {
13499: $metaentry{':'.$unikey}=
13500: $metaentry{':'.$unikey.'.default'};
1.483 albertel 13501: }
13502: }
13503:
1.261 albertel 13504: sub metadata_generate_part0 {
13505: my ($metadata,$metacache,$uri) = @_;
13506: my %allnames;
1.737 albertel 13507: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 13508: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 13509: my $part=$$metacache{':'.$metakey.'.part'};
13510: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 13511: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 13512: $allnames{$name}=$part;
13513: }
13514: }
13515: }
13516: foreach my $name (keys(%allnames)) {
13517: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 13518: my $key=":parameter_0_$name";
1.261 albertel 13519: $$metacache{"$key.part"}='0';
13520: $$metacache{"$key.name"}=$name;
1.428 albertel 13521: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 13522: $allnames{$name}.'_'.$name.
13523: '.type'};
1.428 albertel 13524: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 13525: '.display'};
1.644 www 13526: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 13527: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 13528: $$metacache{"$key.display"}=$olddis;
13529: }
1.71 www 13530: }
13531:
1.764 albertel 13532: # ------------------------------------------------------ Devalidate title cache
13533:
13534: sub devalidate_title_cache {
13535: my ($url)=@_;
13536: if (!$env{'request.course.id'}) { return; }
13537: my $symb=&symbread($url);
13538: if (!$symb) { return; }
13539: my $key=$env{'request.course.id'}."\0".$symb;
13540: &devalidate_cache_new('title',$key);
13541: }
13542:
1.1014 droeschl 13543: # ------------------------------------------------- Get the title of a course
13544:
13545: sub current_course_title {
13546: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13547: }
1.301 www 13548: # ------------------------------------------------- Get the title of a resource
13549:
13550: sub gettitle {
13551: my $urlsymb=shift;
13552: my $symb=&symbread($urlsymb);
1.534 albertel 13553: if ($symb) {
1.620 albertel 13554: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 13555: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 13556: if (defined($cached)) {
13557: return $result;
13558: }
1.534 albertel 13559: my ($map,$resid,$url)=&decode_symb($symb);
13560: my $title='';
1.907 albertel 13561: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13562: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13563: } else {
13564: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13565: &GDBM_READER(),0640)) {
13566: my $mapid=$bighash{'map_pc_'.&clutter($map)};
13567: $title=$bighash{'title_'.$mapid.'.'.$resid};
13568: untie(%bighash);
13569: }
1.534 albertel 13570: }
13571: $title=~s/\&colon\;/\:/gs;
13572: if ($title) {
1.1159 www 13573: # Remember both $symb and $title for dynamic metadata
13574: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 13575: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 13576: # Cache this title and then return it
1.599 albertel 13577: return &do_cache_new('title',$key,$title,600);
1.534 albertel 13578: }
13579: $urlsymb=$url;
13580: }
13581: my $title=&metadata($urlsymb,'title');
13582: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
13583: return $title;
1.301 www 13584: }
1.613 albertel 13585:
1.614 albertel 13586: sub get_slot {
13587: my ($which,$cnum,$cdom)=@_;
13588: if (!$cnum || !$cdom) {
1.790 albertel 13589: (undef,my $courseid)=&whichuser();
1.620 albertel 13590: $cdom=$env{'course.'.$courseid.'.domain'};
13591: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 13592: }
1.703 albertel 13593: my $key=join("\0",'slots',$cdom,$cnum,$which);
13594: my %slotinfo;
13595: if (exists($remembered{$key})) {
13596: $slotinfo{$which} = $remembered{$key};
13597: } else {
13598: %slotinfo=&get('slots',[$which],$cdom,$cnum);
13599: &Apache::lonhomework::showhash(%slotinfo);
13600: my ($tmp)=keys(%slotinfo);
13601: if ($tmp=~/^error:/) { return (); }
13602: $remembered{$key} = $slotinfo{$which};
13603: }
1.616 albertel 13604: if (ref($slotinfo{$which}) eq 'HASH') {
13605: return %{$slotinfo{$which}};
13606: }
13607: return $slotinfo{$which};
1.614 albertel 13608: }
1.1150 raeburn 13609:
13610: sub get_reservable_slots {
13611: my ($cnum,$cdom,$uname,$udom) = @_;
13612: my $now = time;
13613: my $reservable_info;
13614: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13615: if (exists($remembered{$key})) {
13616: $reservable_info = $remembered{$key};
13617: } else {
13618: my %resv;
13619: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13620: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13621: $reservable_info = \%resv;
13622: $remembered{$key} = $reservable_info;
13623: }
13624: return $reservable_info;
13625: }
13626:
13627: sub get_course_slots {
13628: my ($cnum,$cdom) = @_;
13629: my $hashid=$cnum.':'.$cdom;
1.1494 raeburn 13630: my ($result,$cached) = &is_cached_new('allslots',$hashid);
1.1150 raeburn 13631: if (defined($cached)) {
13632: if (ref($result) eq 'HASH') {
13633: return %{$result};
13634: }
13635: } else {
1.1494 raeburn 13636: my %slots=&dump('slots',$cdom,$cnum);
1.1150 raeburn 13637: my ($tmp) = keys(%slots);
13638: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 13639: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 13640: return %slots;
13641: }
13642: }
13643: return;
13644: }
13645:
13646: sub devalidate_slots_cache {
13647: my ($cnum,$cdom)=@_;
13648: my $hashid=$cnum.':'.$cdom;
13649: &devalidate_cache_new('allslots',$hashid);
13650: }
13651:
1.1181 raeburn 13652: sub get_coursechange {
13653: my ($cdom,$cnum) = @_;
13654: if ($cdom eq '' || $cnum eq '') {
13655: return unless ($env{'request.course.id'});
13656: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13657: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13658: }
13659: my $hashid=$cdom.'_'.$cnum;
13660: my ($change,$cached)=&is_cached_new('crschange',$hashid);
13661: if ((defined($cached)) && ($change ne '')) {
13662: return $change;
13663: } else {
13664: my %crshash;
13665: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13666: if ($crshash{'internal.contentchange'} eq '') {
13667: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13668: if ($change eq '') {
13669: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13670: $change = $crshash{'internal.created'};
13671: }
13672: } else {
13673: $change = $crshash{'internal.contentchange'};
13674: }
13675: my $cachetime = 600;
13676: &do_cache_new('crschange',$hashid,$change,$cachetime);
13677: }
13678: return $change;
13679: }
13680:
13681: sub devalidate_coursechange_cache {
1.1496 raeburn 13682: my ($cdom,$cnum)=@_;
13683: my $hashid=$cdom.'_'.$cnum;
1.1181 raeburn 13684: &devalidate_cache_new('crschange',$hashid);
13685: }
13686:
1.1496 raeburn 13687: sub get_suppchange {
13688: my ($cdom,$cnum) = @_;
13689: if ($cdom eq '' || $cnum eq '') {
13690: return unless ($env{'request.course.id'});
13691: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13692: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13693: }
13694: my $hashid=$cdom.'_'.$cnum;
13695: my ($change,$cached)=&is_cached_new('suppchange',$hashid);
13696: if ((defined($cached)) && ($change ne '')) {
13697: return $change;
13698: } else {
13699: my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
13700: if ($crshash{'internal.supplementalchange'} eq '') {
13701: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13702: if ($change eq '') {
13703: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13704: $change = $crshash{'internal.created'};
13705: }
13706: } else {
13707: $change = $crshash{'internal.supplementalchange'};
13708: }
13709: my $cachetime = 600;
13710: &do_cache_new('suppchange',$hashid,$change,$cachetime);
13711: }
13712: return $change;
13713: }
13714:
13715: sub devalidate_suppchange_cache {
13716: my ($cdom,$cnum)=@_;
13717: my $hashid=$cdom.'_'.$cnum;
13718: &devalidate_cache_new('suppchange',$hashid);
13719: }
13720:
1.1497 raeburn 13721: sub update_supp_caches {
13722: my ($cdom,$cnum) = @_;
13723: my %servers = &internet_dom_servers($cdom);
13724: my @ids=¤t_machine_ids();
13725: foreach my $server (keys(%servers)) {
13726: next if (grep(/^\Q$server\E$/,@ids));
13727: my $hashid=$cnum.':'.$cdom;
13728: my $cachekey = &escape('showsupp').':'.&escape($hashid);
13729: &remote_devalidate_cache($server,[$cachekey]);
13730: }
13731: &has_unhidden_suppfiles($cnum,$cdom,1,1);
13732: &count_supptools($cnum,$cdom,1);
13733: my $now = time;
13734: if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
13735: &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
13736: }
13737: &put('environment',{'internal.supplementalchange' => $now},
13738: $cdom,$cnum);
13739: &Apache::lonnet::appenv(
13740: {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
13741: &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
13742: }
13743:
1.31 www 13744: # ------------------------------------------------- Update symbolic store links
13745:
13746: sub symblist {
13747: my ($mapname,%newhash)=@_;
1.438 www 13748: $mapname=&deversion(&declutter($mapname));
1.31 www 13749: my %hash;
1.620 albertel 13750: if (($env{'request.course.fn'}) && (%newhash)) {
13751: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 13752: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 13753: foreach my $url (keys(%newhash)) {
1.711 albertel 13754: next if ($url eq 'last_known'
13755: && $env{'form.no_update_last_known'});
13756: $hash{declutter($url)}=&encode_symb($mapname,
13757: $newhash{$url}->[1],
13758: $newhash{$url}->[0]);
1.191 harris41 13759: }
1.31 www 13760: if (untie(%hash)) {
13761: return 'ok';
13762: }
13763: }
13764: }
13765: return 'error';
1.212 www 13766: }
13767:
13768: # --------------------------------------------------------------- Verify a symb
13769:
13770: sub symbverify {
1.1190 raeburn 13771: my ($symb,$thisurl,$encstate)=@_;
1.510 www 13772: my $thisfn=$thisurl;
1.439 www 13773: $thisfn=&declutter($thisfn);
1.215 www 13774: # direct jump to resource in page or to a sequence - will construct own symbs
13775: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13776: # check URL part
1.409 www 13777: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 13778:
1.431 www 13779: unless ($url eq $thisfn) { return 0; }
1.213 www 13780:
1.216 www 13781: $symb=&symbclean($symb);
1.510 www 13782: $thisurl=&deversion($thisurl);
1.439 www 13783: $thisfn=&deversion($thisfn);
1.213 www 13784:
13785: my %bighash;
13786: my $okay=0;
1.431 www 13787:
1.620 albertel 13788: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13789: &GDBM_READER(),0640)) {
1.1032 raeburn 13790: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13791: $thisurl =~ s/\?.+$//;
1.1204 raeburn 13792: if ($map =~ m{^uploaded/.+\.page$}) {
13793: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13794: $thisurl =~ s{^\Qhttp://https://\E}{https://};
13795: }
13796: }
13797: my $ids;
1.1419 raeburn 13798: if ($map =~ m{^uploaded/.+\.page$}) {
13799: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204 raeburn 13800: } else {
13801: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 13802: }
1.1102 raeburn 13803: unless ($ids) {
13804: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
13805: $ids=$bighash{$idkey};
1.216 www 13806: }
13807: if ($ids) {
13808: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 13809: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 13810: $symb =~ s/\?.+$//;
1.1202 raeburn 13811: }
1.800 albertel 13812: foreach my $id (split(/\,/,$ids)) {
13813: my ($mapid,$resid)=split(/\./,$id);
1.216 www 13814: if (
13815: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 13816: eq $symb) {
13817: if (ref($encstate)) {
13818: $$encstate = $bighash{'encrypted_'.$id};
13819: }
1.620 albertel 13820: if (($env{'request.role.adv'}) ||
1.1101 raeburn 13821: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13822: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 13823: $okay=1;
1.1202 raeburn 13824: last;
1.582 albertel 13825: }
13826: }
1.216 www 13827: }
13828: }
1.213 www 13829: untie(%bighash);
13830: }
13831: return $okay;
1.31 www 13832: }
13833:
1.210 www 13834: # --------------------------------------------------------------- Clean-up symb
13835:
13836: sub symbclean {
13837: my $symb=shift;
1.568 albertel 13838: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 13839: # remove version from map
13840: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 13841:
1.210 www 13842: # remove version from URL
13843: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 13844:
1.507 www 13845: # remove wrapper
13846:
1.510 www 13847: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 13848: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 13849: return $symb;
1.409 www 13850: }
13851:
13852: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 13853:
13854: sub encode_symb {
13855: my ($map,$resid,$url)=@_;
13856: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13857: }
1.409 www 13858:
13859: sub decode_symb {
1.568 albertel 13860: my $symb=shift;
13861: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13862: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 13863: return (&fixversion($map),$resid,&fixversion($url));
13864: }
13865:
13866: sub fixversion {
13867: my $fn=shift;
1.609 banghart 13868: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 13869: my %bighash;
13870: my $uri=&clutter($fn);
1.620 albertel 13871: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 13872: # is this cached?
1.599 albertel 13873: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 13874: if (defined($cached)) { return $result; }
13875: # unfortunately not cached, or expired
1.620 albertel 13876: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 13877: &GDBM_READER(),0640)) {
13878: if ($bighash{'version_'.$uri}) {
13879: my $version=$bighash{'version_'.$uri};
1.444 www 13880: unless (($version eq 'mostrecent') ||
13881: ($version==&getversion($uri))) {
1.440 www 13882: $uri=~s/\.(\w+)$/\.$version\.$1/;
13883: }
13884: }
13885: untie %bighash;
1.413 www 13886: }
1.599 albertel 13887: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 13888: }
13889:
13890: sub deversion {
13891: my $url=shift;
13892: $url=~s/\.\d+\.(\w+)$/\.$1/;
13893: return $url;
1.210 www 13894: }
13895:
1.31 www 13896: # ------------------------------------------------------ Return symb list entry
13897:
13898: sub symbread {
1.1424 raeburn 13899: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427 raeburn 13900: $ignoresymbdb,$noenccheck)=@_;
1.1265 raeburn 13901: my $cache_str='request.symbread.cached.'.$thisfn;
1.1427 raeburn 13902: if (defined($env{$cache_str})) {
1.1424 raeburn 13903: unless (ref($possibles) eq 'HASH') {
13904: if ($ignorecachednull) {
13905: return $env{$cache_str} unless ($env{$cache_str} eq '');
13906: } else {
13907: return $env{$cache_str};
13908: }
1.1282 raeburn 13909: }
13910: }
1.242 www 13911: # no filename provided? try from environment
1.1265 raeburn 13912: unless ($thisfn) {
1.620 albertel 13913: if ($env{'request.symb'}) {
1.1427 raeburn 13914: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 13915: }
1.620 albertel 13916: $thisfn=$env{'request.filename'};
1.44 www 13917: }
1.569 albertel 13918: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 13919: # is that filename actually a symb? Verify, clean, and return
13920: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 13921: if (&symbverify($thisfn,$1)) {
1.1427 raeburn 13922: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 13923: }
1.242 www 13924: }
1.44 www 13925: $thisfn=declutter($thisfn);
1.31 www 13926: my %hash;
1.37 www 13927: my %bighash;
13928: my $syval='';
1.620 albertel 13929: if (($env{'request.course.fn'}) && ($thisfn)) {
1.1427 raeburn 13930: unless ($ignoresymbdb) {
1.1424 raeburn 13931: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13932: &GDBM_READER(),0640)) {
1.1487 raeburn 13933: $syval=$hash{$thisfn};
1.1424 raeburn 13934: untie(%hash);
13935: }
1.1427 raeburn 13936: if ($syval && $checkforblock) {
13937: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424 raeburn 13938: if (@blockers) {
13939: $syval='';
13940: }
13941: }
1.37 www 13942: }
13943: # ---------------------------------------------------------- There was an entry
13944: if ($syval) {
1.601 albertel 13945: #unless ($syval=~/\_\d+$/) {
1.620 albertel 13946: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 13947: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13948: #return $env{$cache_str}='';
1.601 albertel 13949: #}
13950: #$syval.=$1;
13951: #}
1.37 www 13952: } else {
13953: # ------------------------------------------------------- Was not in symb table
1.620 albertel 13954: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13955: &GDBM_READER(),0640)) {
1.37 www 13956: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 13957: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 13958: unless ($ids) {
13959: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 13960: }
13961: unless ($ids) {
13962: # alias?
13963: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 13964: }
1.37 www 13965: if ($ids) {
13966: # ------------------------------------------------------------------- Has ID(s)
13967: my @possibilities=split(/\,/,$ids);
1.39 www 13968: if ($#possibilities==0) {
13969: # ----------------------------------------------- There is only one possibility
1.37 www 13970: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 13971: $syval=&encode_symb($bighash{'map_id_'.$mapid},
13972: $resid,$thisfn);
1.1282 raeburn 13973: if (ref($possibles) eq 'HASH') {
1.1424 raeburn 13974: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13975: $possibles->{$syval} = 1;
13976: }
1.1282 raeburn 13977: }
13978: if ($checkforblock) {
1.1424 raeburn 13979: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426 raeburn 13980: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424 raeburn 13981: if (@blockers) {
13982: $syval = '';
1.1425 raeburn 13983: untie(%bighash);
13984: return $env{$cache_str}='';
1.1424 raeburn 13985: }
1.1282 raeburn 13986: }
13987: }
13988: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 13989: # ------------------------------------------ There is more than one possibility
13990: my $realpossible=0;
1.800 albertel 13991: foreach my $id (@possibilities) {
13992: my $file=$bighash{'src_'.$id};
1.1282 raeburn 13993: my $canaccess;
13994: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13995: $canaccess = 1;
13996: } else {
13997: $canaccess = &allowed('bre',$file);
13998: }
13999: if ($canaccess) {
14000: my ($mapid,$resid)=split(/\./,$id);
14001: if ($bighash{'map_type_'.$mapid} ne 'page') {
14002: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14003: $resid,$thisfn);
1.1424 raeburn 14004: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426 raeburn 14005: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282 raeburn 14006: if ($checkforblock) {
1.1426 raeburn 14007: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424 raeburn 14008: if (@blockers > 0) {
14009: $syval = '';
14010: } else {
1.1282 raeburn 14011: $syval = $poss_syval;
14012: $realpossible++;
14013: }
14014: } else {
14015: $syval = $poss_syval;
14016: $realpossible++;
14017: }
1.1424 raeburn 14018: if ($syval) {
14019: if (ref($possibles) eq 'HASH') {
14020: $possibles->{$syval} = 1;
14021: }
14022: }
1.1282 raeburn 14023: }
1.39 www 14024: }
1.191 harris41 14025: }
1.39 www 14026: if ($realpossible!=1) { $syval=''; }
1.249 www 14027: } else {
14028: $syval='';
1.37 www 14029: }
14030: }
1.1282 raeburn 14031: untie(%bighash);
1.481 raeburn 14032: }
1.31 www 14033: }
1.62 www 14034: if ($syval) {
1.1427 raeburn 14035: return $env{$cache_str}=$syval;
1.62 www 14036: }
1.31 www 14037: }
1.949 raeburn 14038: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 14039: return $env{$cache_str}='';
1.31 www 14040: }
14041:
14042: # ---------------------------------------------------------- Return random seed
14043:
1.32 www 14044: sub numval {
14045: my $txt=shift;
14046: $txt=~tr/A-J/0-9/;
14047: $txt=~tr/a-j/0-9/;
14048: $txt=~tr/K-T/0-9/;
14049: $txt=~tr/k-t/0-9/;
14050: $txt=~tr/U-Z/0-5/;
14051: $txt=~tr/u-z/0-5/;
14052: $txt=~s/\D//g;
1.564 albertel 14053: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 14054: return int($txt);
1.368 albertel 14055: }
14056:
1.484 albertel 14057: sub numval2 {
14058: my $txt=shift;
14059: $txt=~tr/A-J/0-9/;
14060: $txt=~tr/a-j/0-9/;
14061: $txt=~tr/K-T/0-9/;
14062: $txt=~tr/k-t/0-9/;
14063: $txt=~tr/U-Z/0-5/;
14064: $txt=~tr/u-z/0-5/;
14065: $txt=~s/\D//g;
14066: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14067: my $total;
14068: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 14069: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 14070: return int($total);
14071: }
14072:
1.575 albertel 14073: sub numval3 {
14074: use integer;
14075: my $txt=shift;
14076: $txt=~tr/A-J/0-9/;
14077: $txt=~tr/a-j/0-9/;
14078: $txt=~tr/K-T/0-9/;
14079: $txt=~tr/k-t/0-9/;
14080: $txt=~tr/U-Z/0-5/;
14081: $txt=~tr/u-z/0-5/;
14082: $txt=~s/\D//g;
14083: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14084: my $total;
14085: foreach my $val (@txts) { $total+=$val; }
14086: if ($_64bit) { $total=(($total<<32)>>32); }
14087: return $total;
14088: }
14089:
1.675 albertel 14090: sub digest {
14091: my ($data)=@_;
14092: my $digest=&Digest::MD5::md5($data);
14093: my ($a,$b,$c,$d)=unpack("iiii",$digest);
14094: my ($e,$f);
14095: {
14096: use integer;
14097: $e=($a+$b);
14098: $f=($c+$d);
14099: if ($_64bit) {
14100: $e=(($e<<32)>>32);
14101: $f=(($f<<32)>>32);
14102: }
14103: }
14104: if (wantarray) {
14105: return ($e,$f);
14106: } else {
14107: my $g;
14108: {
14109: use integer;
14110: $g=($e+$f);
14111: if ($_64bit) {
14112: $g=(($g<<32)>>32);
14113: }
14114: }
14115: return $g;
14116: }
14117: }
14118:
1.368 albertel 14119: sub latest_rnd_algorithm_id {
1.675 albertel 14120: return '64bit5';
1.366 albertel 14121: }
1.32 www 14122:
1.503 albertel 14123: sub get_rand_alg {
14124: my ($courseid)=@_;
1.790 albertel 14125: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 14126: if ($courseid) {
1.620 albertel 14127: return $env{"course.$courseid.rndseed"};
1.503 albertel 14128: }
14129: return &latest_rnd_algorithm_id();
14130: }
14131:
1.562 albertel 14132: sub validCODE {
14133: my ($CODE)=@_;
14134: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14135: return 0;
14136: }
14137:
1.491 albertel 14138: sub getCODE {
1.620 albertel 14139: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 14140: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14141: defined($Apache::lonhomework::parsing_a_task) ) &&
14142: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 14143: return $Apache::lonhomework::history{'resource.CODE'};
14144: }
14145: return undef;
14146: }
1.1133 foxr 14147: #
14148: # Determines the random seed for a specific context:
14149: #
14150: # parameters:
14151: # symb - in course context the symb for the seed.
14152: # course_id - The course id of the form domain_coursenum.
14153: # domain - Domain for the user.
14154: # course - Course for the user.
14155: # cenv - environment of the course.
14156: #
14157: # NOTE:
14158: # All parameters are picked out of the environment if missing
14159: # or not defined.
14160: # If a symb cannot be determined the current time is used instead.
14161: #
14162: # For a given well defined symb, courside, domain, username,
14163: # and course environment, the seed is reproducible.
14164: #
1.31 www 14165: sub rndseed {
1.1133 foxr 14166: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 14167: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 14168: if (!defined($symb)) {
1.366 albertel 14169: unless ($symb=$wsymb) { return time; }
14170: }
1.1146 foxr 14171: if (!defined $courseid) {
14172: $courseid=$wcourseid;
14173: }
14174: if (!defined $domain) { $domain=$wdomain; }
14175: if (!defined $username) { $username=$wusername }
1.1133 foxr 14176:
14177: my $which;
14178: if (defined($cenv->{'rndseed'})) {
14179: $which = $cenv->{'rndseed'};
14180: } else {
14181: $which =&get_rand_alg($courseid);
14182: }
1.491 albertel 14183: if (defined(&getCODE())) {
1.1133 foxr 14184:
1.675 albertel 14185: if ($which eq '64bit5') {
14186: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14187: } elsif ($which eq '64bit4') {
1.575 albertel 14188: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14189: } else {
14190: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14191: }
1.675 albertel 14192: } elsif ($which eq '64bit5') {
14193: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 14194: } elsif ($which eq '64bit4') {
14195: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 14196: } elsif ($which eq '64bit3') {
14197: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 14198: } elsif ($which eq '64bit2') {
14199: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 14200: } elsif ($which eq '64bit') {
14201: return &rndseed_64bit($symb,$courseid,$domain,$username);
14202: }
14203: return &rndseed_32bit($symb,$courseid,$domain,$username);
14204: }
14205:
14206: sub rndseed_32bit {
14207: my ($symb,$courseid,$domain,$username)=@_;
14208: {
14209: use integer;
14210: my $symbchck=unpack("%32C*",$symb) << 27;
14211: my $symbseed=numval($symb) << 22;
14212: my $namechck=unpack("%32C*",$username) << 17;
14213: my $nameseed=numval($username) << 12;
14214: my $domainseed=unpack("%32C*",$domain) << 7;
14215: my $courseseed=unpack("%32C*",$courseid);
14216: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 14217: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14218: #&logthis("rndseed :$num:$symb");
1.564 albertel 14219: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 14220: return $num;
14221: }
14222: }
14223:
14224: sub rndseed_64bit {
14225: my ($symb,$courseid,$domain,$username)=@_;
14226: {
14227: use integer;
14228: my $symbchck=unpack("%32S*",$symb) << 21;
14229: my $symbseed=numval($symb) << 10;
14230: my $namechck=unpack("%32S*",$username);
14231:
14232: my $nameseed=numval($username) << 21;
14233: my $domainseed=unpack("%32S*",$domain) << 10;
14234: my $courseseed=unpack("%32S*",$courseid);
14235:
14236: my $num1=$symbchck+$symbseed+$namechck;
14237: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14238: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14239: #&logthis("rndseed :$num:$symb");
1.564 albertel 14240: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 14241: return "$num1,$num2";
1.155 albertel 14242: }
1.366 albertel 14243: }
14244:
1.443 albertel 14245: sub rndseed_64bit2 {
14246: my ($symb,$courseid,$domain,$username)=@_;
14247: {
14248: use integer;
14249: # strings need to be an even # of cahracters long, it it is odd the
14250: # last characters gets thrown away
14251: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14252: my $symbseed=numval($symb) << 10;
14253: my $namechck=unpack("%32S*",$username.' ');
14254:
14255: my $nameseed=numval($username) << 21;
1.501 albertel 14256: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14257: my $courseseed=unpack("%32S*",$courseid.' ');
14258:
14259: my $num1=$symbchck+$symbseed+$namechck;
14260: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14261: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14262: #&logthis("rndseed :$num:$symb");
1.803 albertel 14263: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 14264: return "$num1,$num2";
14265: }
14266: }
14267:
14268: sub rndseed_64bit3 {
14269: my ($symb,$courseid,$domain,$username)=@_;
14270: {
14271: use integer;
14272: # strings need to be an even # of cahracters long, it it is odd the
14273: # last characters gets thrown away
14274: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14275: my $symbseed=numval2($symb) << 10;
14276: my $namechck=unpack("%32S*",$username.' ');
14277:
14278: my $nameseed=numval2($username) << 21;
1.443 albertel 14279: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14280: my $courseseed=unpack("%32S*",$courseid.' ');
14281:
14282: my $num1=$symbchck+$symbseed+$namechck;
14283: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14284: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14285: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 14286: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14287:
1.503 albertel 14288: return "$num1:$num2";
1.443 albertel 14289: }
14290: }
14291:
1.575 albertel 14292: sub rndseed_64bit4 {
14293: my ($symb,$courseid,$domain,$username)=@_;
14294: {
14295: use integer;
14296: # strings need to be an even # of cahracters long, it it is odd the
14297: # last characters gets thrown away
14298: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14299: my $symbseed=numval3($symb) << 10;
14300: my $namechck=unpack("%32S*",$username.' ');
14301:
14302: my $nameseed=numval3($username) << 21;
14303: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14304: my $courseseed=unpack("%32S*",$courseid.' ');
14305:
14306: my $num1=$symbchck+$symbseed+$namechck;
14307: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14308: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14309: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 14310: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14311:
1.575 albertel 14312: return "$num1:$num2";
14313: }
14314: }
14315:
1.675 albertel 14316: sub rndseed_64bit5 {
14317: my ($symb,$courseid,$domain,$username)=@_;
14318: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14319: return "$num1:$num2";
14320: }
14321:
1.366 albertel 14322: sub rndseed_CODE_64bit {
14323: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 14324: {
1.366 albertel 14325: use integer;
1.443 albertel 14326: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 14327: my $symbseed=numval2($symb);
1.491 albertel 14328: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14329: my $CODEseed=numval(&getCODE());
1.443 albertel 14330: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 14331: my $num1=$symbseed+$CODEchck;
14332: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14333: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14334: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 14335: if ($_64bit) { $num1=(($num1<<32)>>32); }
14336: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 14337: return "$num1:$num2";
1.366 albertel 14338: }
14339: }
14340:
1.575 albertel 14341: sub rndseed_CODE_64bit4 {
14342: my ($symb,$courseid,$domain,$username)=@_;
14343: {
14344: use integer;
14345: my $symbchck=unpack("%32S*",$symb.' ') << 16;
14346: my $symbseed=numval3($symb);
14347: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14348: my $CODEseed=numval3(&getCODE());
14349: my $courseseed=unpack("%32S*",$courseid.' ');
14350: my $num1=$symbseed+$CODEchck;
14351: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14352: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14353: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 14354: if ($_64bit) { $num1=(($num1<<32)>>32); }
14355: if ($_64bit) { $num2=(($num2<<32)>>32); }
14356: return "$num1:$num2";
14357: }
14358: }
14359:
1.675 albertel 14360: sub rndseed_CODE_64bit5 {
14361: my ($symb,$courseid,$domain,$username)=@_;
14362: my $code = &getCODE();
14363: my ($num1,$num2)=&digest("$symb,$courseid,$code");
14364: return "$num1:$num2";
14365: }
14366:
1.366 albertel 14367: sub setup_random_from_rndseed {
14368: my ($rndseed)=@_;
1.503 albertel 14369: if ($rndseed =~/([,:])/) {
1.1262 raeburn 14370: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14371: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14372: &Math::Random::random_set_seed_from_phrase($rndseed);
14373: } else {
14374: &Math::Random::random_set_seed($num1,$num2);
14375: }
1.366 albertel 14376: } else {
14377: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 14378: }
1.36 albertel 14379: }
14380:
1.474 albertel 14381: sub latest_receipt_algorithm_id {
1.835 albertel 14382: return 'receipt3';
1.474 albertel 14383: }
14384:
1.480 www 14385: sub recunique {
14386: my $fucourseid=shift;
14387: my $unique;
1.835 albertel 14388: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14389: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14390: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 14391: } else {
14392: $unique=$perlvar{'lonReceipt'};
14393: }
14394: return unpack("%32C*",$unique);
14395: }
14396:
14397: sub recprefix {
14398: my $fucourseid=shift;
14399: my $prefix;
1.835 albertel 14400: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14401: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14402: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 14403: } else {
14404: $prefix=$perlvar{'lonHostID'};
14405: }
14406: return unpack("%32C*",$prefix);
14407: }
14408:
1.76 www 14409: sub ireceipt {
1.474 albertel 14410: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 14411:
14412: my $return =&recprefix($fucourseid).'-';
14413:
14414: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14415: $env{'request.state'} eq 'construct') {
14416: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14417: return $return;
14418: }
14419:
1.76 www 14420: my $cuname=unpack("%32C*",$funame);
14421: my $cudom=unpack("%32C*",$fudom);
14422: my $cucourseid=unpack("%32C*",$fucourseid);
14423: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 14424: my $cunique=&recunique($fucourseid);
1.474 albertel 14425: my $cpart=unpack("%32S*",$part);
1.835 albertel 14426: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14427:
1.790 albertel 14428: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 14429:
14430: $return.= ($cunique%$cuname+
14431: $cunique%$cudom+
14432: $cusymb%$cuname+
14433: $cusymb%$cudom+
14434: $cucourseid%$cuname+
14435: $cucourseid%$cudom+
14436: $cpart%$cuname+
14437: $cpart%$cudom);
14438: } else {
14439: $return.= ($cunique%$cuname+
14440: $cunique%$cudom+
14441: $cusymb%$cuname+
14442: $cusymb%$cudom+
14443: $cucourseid%$cuname+
14444: $cucourseid%$cudom);
14445: }
14446: return $return;
1.76 www 14447: }
14448:
14449: sub receipt {
1.474 albertel 14450: my ($part)=@_;
1.790 albertel 14451: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 14452: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 14453: }
1.260 ng 14454:
1.790 albertel 14455: sub whichuser {
14456: my ($passedsymb)=@_;
14457: my ($symb,$courseid,$domain,$name,$publicuser);
14458: if (defined($env{'form.grade_symb'})) {
14459: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14460: my $allowed=&allowed('vgr',$tmp_courseid);
14461: if (!$allowed &&
14462: exists($env{'request.course.sec'}) &&
14463: $env{'request.course.sec'} !~ /^\s*$/) {
14464: $allowed=&allowed('vgr',$tmp_courseid.
14465: '/'.$env{'request.course.sec'});
14466: }
14467: if ($allowed) {
14468: ($symb)=&get_env_multiple('form.grade_symb');
14469: $courseid=$tmp_courseid;
14470: ($domain)=&get_env_multiple('form.grade_domain');
14471: ($name)=&get_env_multiple('form.grade_username');
14472: return ($symb,$courseid,$domain,$name,$publicuser);
14473: }
14474: }
14475: if (!$passedsymb) {
14476: $symb=&symbread();
14477: } else {
14478: $symb=$passedsymb;
14479: }
14480: $courseid=$env{'request.course.id'};
14481: $domain=$env{'user.domain'};
14482: $name=$env{'user.name'};
14483: if ($name eq 'public' && $domain eq 'public') {
14484: if (!defined($env{'form.username'})) {
14485: $env{'form.username'}.=time.rand(10000000);
14486: }
14487: $name.=$env{'form.username'};
14488: }
14489: return ($symb,$courseid,$domain,$name,$publicuser);
14490:
14491: }
14492:
1.36 albertel 14493: # ------------------------------------------------------------ Serves up a file
1.472 albertel 14494: # returns either the contents of the file or
14495: # -1 if the file doesn't exist
1.481 raeburn 14496: #
14497: # if the target is a file that was uploaded via DOCS,
14498: # a check will be made to see if a current copy exists on the local server,
14499: # if it does this will be served, otherwise a copy will be retrieved from
14500: # the home server for the course and stored in /home/httpd/html/userfiles on
14501: # the local server.
1.472 albertel 14502:
1.36 albertel 14503: sub getfile {
1.538 albertel 14504: my ($file) = @_;
1.609 banghart 14505: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 14506: &repcopy($file);
14507: return &readfile($file);
14508: }
14509:
14510: sub repcopy_userfile {
14511: my ($file)=@_;
1.1142 raeburn 14512: my $londocroot = $perlvar{'lonDocRoot'};
14513: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 14514: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 14515: my ($cdom,$cnum,$filename) =
1.811 albertel 14516: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 14517: my $uri="/uploaded/$cdom/$cnum/$filename";
14518: if (-e "$file") {
1.828 www 14519: # we already have a local copy, check it out
1.538 albertel 14520: my @fileinfo = stat($file);
1.828 www 14521: my $rtncode;
14522: my $info;
1.538 albertel 14523: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 14524: if ($lwpresp ne 'ok') {
1.828 www 14525: # there is no such file anymore, even though we had a local copy
1.482 albertel 14526: if ($rtncode eq '404') {
1.538 albertel 14527: unlink($file);
1.482 albertel 14528: }
14529: return -1;
14530: }
14531: if ($info < $fileinfo[9]) {
1.828 www 14532: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 14533: return 'ok';
1.828 www 14534: } else {
14535: # the file is outdated, get rid of it
14536: unlink($file);
1.482 albertel 14537: }
1.828 www 14538: }
14539: # one way or the other, at this point, we don't have the file
14540: # construct the correct path for the file
14541: my @parts = ($cdom,$cnum);
14542: if ($filename =~ m|^(.+)/[^/]+$|) {
14543: push @parts, split(/\//,$1);
14544: }
14545: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14546: foreach my $part (@parts) {
14547: $path .= '/'.$part;
14548: if (!-e $path) {
14549: mkdir($path,0770);
1.482 albertel 14550: }
14551: }
1.828 www 14552: # now the path exists for sure
14553: # get a user agent
14554: my $transferfile=$file.'.in.transfer';
14555: # FIXME: this should flock
14556: if (-e $transferfile) { return 'ok'; }
14557: my $request;
14558: $uri=~s/^\///;
1.980 raeburn 14559: my $homeserver = &homeserver($cnum,$cdom);
1.1398 raeburn 14560: my $hostname = &hostname($homeserver);
1.980 raeburn 14561: my $protocol = $protocol{$homeserver};
14562: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14563: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345 raeburn 14564: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828 www 14565: # did it work?
14566: if ($response->is_error()) {
14567: unlink($transferfile);
14568: &logthis("Userfile repcopy failed for $uri");
14569: return -1;
14570: }
14571: # worked, rename the transfer file
14572: rename($transferfile,$file);
1.607 raeburn 14573: return 'ok';
1.481 raeburn 14574: }
14575:
1.517 albertel 14576: sub tokenwrapper {
14577: my $uri=shift;
1.980 raeburn 14578: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 14579: $uri=~s|^/||;
1.620 albertel 14580: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 14581: my $token=$1;
1.552 albertel 14582: my (undef,$udom,$uname,$file)=split('/',$uri,4);
14583: if ($udom && $uname && $file) {
14584: $file=~s|(\?\.*)*$||;
1.949 raeburn 14585: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 14586: my $homeserver = &homeserver($uname,$udom);
1.1397 raeburn 14587: my $hostname = &hostname($homeserver);
1.980 raeburn 14588: my $protocol = $protocol{$homeserver};
14589: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14590: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 14591: (($uri=~/\?/)?'&':'?').'token='.$token.
14592: '&tokenissued='.$perlvar{'lonHostID'};
14593: } else {
14594: return '/adm/notfound.html';
14595: }
14596: }
14597:
1.828 www 14598: # call with reqtype HEAD: get last modification time
14599: # call with reqtype GET: get the file contents
14600: # Do not call this with reqtype GET for large files! It loads everything into memory
14601: #
1.481 raeburn 14602: sub getuploaded {
14603: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14604: $uri=~s/^\///;
1.980 raeburn 14605: my $homeserver = &homeserver($cnum,$cdom);
1.1397 raeburn 14606: my $hostname = &hostname($homeserver);
1.980 raeburn 14607: my $protocol = $protocol{$homeserver};
14608: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14609: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 14610: my $request=new HTTP::Request($reqtype,$uri);
1.1345 raeburn 14611: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481 raeburn 14612: $$rtncode = $response->code;
1.482 albertel 14613: if (! $response->is_success()) {
14614: return 'failed';
14615: }
14616: if ($reqtype eq 'HEAD') {
1.486 www 14617: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 14618: } elsif ($reqtype eq 'GET') {
14619: $$info = $response->content;
1.472 albertel 14620: }
1.482 albertel 14621: return 'ok';
1.36 albertel 14622: }
14623:
1.481 raeburn 14624: sub readfile {
14625: my $file = shift;
14626: if ( (! -e $file ) || ($file eq '') ) { return -1; };
14627: my $fh;
1.1359 raeburn 14628: open($fh,"<",$file);
1.481 raeburn 14629: my $a='';
1.800 albertel 14630: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 14631: return $a;
14632: }
14633:
1.36 albertel 14634: sub filelocation {
1.590 banghart 14635: my ($dir,$file) = @_;
14636: my $location;
14637: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 14638:
14639: if ($file =~ m-^/adm/-) {
14640: $file=~s-^/adm/wrapper/-/-;
14641: $file=~s-^/adm/coursedocs/showdoc/-/-;
14642: }
1.882 albertel 14643:
1.1139 www 14644: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 14645: $location = $file;
1.609 banghart 14646: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 14647: my ($udom,$uname,$filename)=
1.811 albertel 14648: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 14649: my $home=&homeserver($uname,$udom);
14650: my $is_me=0;
14651: my @ids=¤t_machine_ids();
14652: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14653: if ($is_me) {
1.1117 foxr 14654: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 14655: } else {
14656: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14657: $udom.'/'.$uname.'/'.$filename;
14658: }
1.882 albertel 14659: } elsif ($file =~ m-^/adm/-) {
14660: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 14661: } else {
14662: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 14663: $file=~s:^/(res|priv)/:/:;
14664: my $space=$1;
1.590 banghart 14665: if ( !( $file =~ m:^/:) ) {
14666: $location = $dir. '/'.$file;
14667: } else {
1.1142 raeburn 14668: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 14669: }
1.59 albertel 14670: }
1.590 banghart 14671: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 14672: while ($location=~m{/\.\./}) {
14673: if ($location =~ m{/[^/]+/\.\./}) {
14674: $location=~ s{/[^/]+/\.\./}{/}g;
14675: } else {
14676: $location=~ s{/\.\./}{/}g;
14677: }
14678: } #remove dir/..
1.590 banghart 14679: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14680: return $location;
1.46 www 14681: }
1.36 albertel 14682:
1.46 www 14683: sub hreflocation {
14684: my ($dir,$file)=@_;
1.980 raeburn 14685: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 14686: $file=filelocation($dir,$file);
1.700 albertel 14687: } elsif ($file=~m-^/adm/-) {
14688: $file=~s-^/adm/wrapper/-/-;
14689: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 14690: }
14691: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14692: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14693: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 14694: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14695: {/uploaded/$1/$2/}x;
1.46 www 14696: }
1.913 albertel 14697: if ($file=~ m{^/userfiles/}) {
14698: $file =~ s{^/userfiles/}{/uploaded/};
14699: }
1.462 albertel 14700: return $file;
1.465 albertel 14701: }
14702:
1.1139 www 14703:
14704:
14705:
14706:
1.465 albertel 14707: sub current_machine_domains {
1.853 albertel 14708: return &machine_domains(&hostname($perlvar{'lonHostID'}));
14709: }
14710:
14711: sub machine_domains {
14712: my ($hostname) = @_;
1.465 albertel 14713: my @domains;
1.838 albertel 14714: my %hostname = &all_hostnames();
1.465 albertel 14715: while( my($id, $name) = each(%hostname)) {
1.467 matthew 14716: # &logthis("-$id-$name-$hostname-");
1.465 albertel 14717: if ($hostname eq $name) {
1.844 albertel 14718: push(@domains,&host_domain($id));
1.465 albertel 14719: }
14720: }
14721: return @domains;
14722: }
14723:
14724: sub current_machine_ids {
1.853 albertel 14725: return &machine_ids(&hostname($perlvar{'lonHostID'}));
14726: }
14727:
14728: sub machine_ids {
14729: my ($hostname) = @_;
14730: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 14731: my @ids;
1.888 albertel 14732: my %name_to_host = &all_names();
1.889 albertel 14733: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14734: return @{ $name_to_host{$hostname} };
14735: }
14736: return;
1.31 www 14737: }
14738:
1.824 raeburn 14739: sub additional_machine_domains {
14740: my @domains;
1.1466 raeburn 14741: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14742: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14743: while (my $line = <$fh>) {
14744: chomp($line);
14745: $line =~ s/\s//g;
14746: push(@domains,$line);
14747: }
14748: close($fh);
14749: }
1.824 raeburn 14750: }
14751: return @domains;
14752: }
14753:
14754: sub default_login_domain {
14755: my $domain = $perlvar{'lonDefDomain'};
14756: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14757: foreach my $posdom (¤t_machine_domains(),
14758: &additional_machine_domains()) {
14759: if (lc($posdom) eq lc($testdomain)) {
14760: $domain=$posdom;
14761: last;
14762: }
14763: }
14764: return $domain;
14765: }
14766:
1.1414 raeburn 14767: sub shared_institution {
1.1439 raeburn 14768: my ($dom,$lonhost) = @_;
14769: if ($lonhost eq '') {
14770: $lonhost = $perlvar{'lonHostID'};
14771: }
1.1414 raeburn 14772: my $same_intdom;
1.1439 raeburn 14773: my $hostintdom = &internet_dom($lonhost);
1.1414 raeburn 14774: if ($hostintdom ne '') {
14775: my %iphost = &get_iphost();
14776: my $primary_id = &domain($dom,'primary');
14777: my $primary_ip = &get_host_ip($primary_id);
14778: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14779: foreach my $id (@{$iphost{$primary_ip}}) {
14780: my $intdom = &internet_dom($id);
14781: if ($intdom eq $hostintdom) {
14782: $same_intdom = 1;
14783: last;
14784: }
14785: }
14786: }
14787: }
14788: return $same_intdom;
14789: }
14790:
1.1398 raeburn 14791: sub uses_sts {
14792: my ($ignore_cache) = @_;
14793: my $lonhost = $perlvar{'lonHostID'};
14794: my $hostname = &hostname($lonhost);
14795: my $sts_on;
14796: if ($protocol{$lonhost} eq 'https') {
14797: my $cachetime = 12*3600;
14798: if (!$ignore_cache) {
14799: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14800: if (defined($cached)) {
14801: return $sts_on;
14802: }
14803: }
14804: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14805: my $request=new HTTP::Request('HEAD',$url);
14806: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14807: if ($response->is_success) {
14808: my $has_sts = $response->header('Strict-Transport-Security');
14809: if ($has_sts eq '') {
14810: $sts_on = 0;
14811: } else {
14812: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14813: my $maxage = $1;
14814: if ($maxage) {
14815: $sts_on = 1;
14816: } else {
14817: $sts_on = 0;
14818: }
14819: } else {
14820: $sts_on = 0;
14821: }
14822: }
14823: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14824: }
14825: }
14826: return;
14827: }
14828:
1.1449 raeburn 14829: sub waf_allssl {
14830: my ($host_name) = @_;
14831: my $alias = &get_proxy_alias();
14832: if ($host_name eq '') {
14833: $host_name = $ENV{'SERVER_NAME'};
14834: }
14835: if (($host_name ne '') && ($alias eq $host_name)) {
14836: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14837: my %defdomdefaults = &get_domain_defaults($serverhomedom);
14838: if ($defdomdefaults{'waf_sslopt'}) {
14839: return $defdomdefaults{'waf_sslopt'};
14840: }
14841: }
14842: return;
14843: }
14844:
1.1434 raeburn 14845: sub get_requestor_ip {
14846: my ($r,$nolookup,$noproxy) = @_;
14847: my $from_ip;
14848: if (ref($r)) {
1.1447 raeburn 14849: if ($r->can('useragent_ip')) {
14850: if ($noproxy && $r->can('client_ip')) {
14851: $from_ip = $r->client_ip();
14852: } else {
14853: $from_ip = $r->useragent_ip();
14854: }
14855: } elsif ($r->connection->can('remote_ip')) {
14856: $from_ip = $r->connection->remote_ip();
14857: } else {
14858: $from_ip = $r->get_remote_host($nolookup);
14859: }
1.1434 raeburn 14860: } else {
14861: $from_ip = $ENV{'REMOTE_ADDR'};
14862: }
14863: return $from_ip if ($noproxy);
14864: # Who controls proxy settings for server
14865: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14866: my $proxyinfo = &get_proxy_settings($dom_in_use);
14867: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437 raeburn 14868: if ($proxyinfo->{'vpnint'}) {
14869: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434 raeburn 14870: return $from_ip;
14871: }
14872: }
14873: if ($proxyinfo->{'trusted'}) {
14874: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14875: my $ipheader = $proxyinfo->{'ipheader'};
14876: my ($ip,$xfor);
14877: if (ref($r)) {
14878: if ($ipheader) {
14879: $ip = $r->headers_in->{$ipheader};
14880: }
14881: $xfor = $r->headers_in->{'X-Forwarded-For'};
14882: } else {
14883: if ($ipheader) {
14884: $ip = $ENV{'HTTP_'.uc($ipheader)};
14885: }
14886: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14887: }
14888: if (($ip eq '') && ($xfor ne '')) {
14889: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14890: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14891: $ip = $poss_ip;
1.1435 raeburn 14892: last;
1.1434 raeburn 14893: }
14894: }
14895: }
14896: if ($ip ne '') {
14897: return $ip;
14898: }
14899: }
14900: }
14901: }
14902: return $from_ip;
14903: }
14904:
14905: sub get_proxy_settings {
14906: my ($dom_in_use) = @_;
1.1494 raeburn 14907: my %domdefaults = &get_domain_defaults($dom_in_use);
1.1434 raeburn 14908: my $proxyinfo = {
14909: ipheader => $domdefaults{'waf_ipheader'},
14910: trusted => $domdefaults{'waf_trusted'},
1.1437 raeburn 14911: vpnint => $domdefaults{'waf_vpnint'},
1.1438 raeburn 14912: vpnext => $domdefaults{'waf_vpnext'},
1.1449 raeburn 14913: sslopt => $domdefaults{'waf_sslopt'},
1.1434 raeburn 14914: };
14915: return $proxyinfo;
14916: }
14917:
14918: sub ip_match {
14919: my ($ip,$pattern_str) = @_;
14920: $ip=Net::CIDR::cidrvalidate($ip);
14921: if ($ip) {
14922: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14923: }
14924: return;
14925: }
14926:
14927: sub get_proxy_alias {
1.1450 raeburn 14928: my ($lonid) = @_;
14929: if ($lonid eq '') {
14930: $lonid = $perlvar{'lonHostID'};
14931: }
14932: if (!defined(&hostname($lonid))) {
14933: return;
14934: }
14935: if ($lonid ne '') {
14936: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434 raeburn 14937: if ($cached) {
14938: return $alias;
14939: }
1.1494 raeburn 14940: my $dom = &host_domain($lonid);
1.1434 raeburn 14941: if ($dom ne '') {
14942: my $cachetime = 60*60*24;
14943: my %domconfig =
1.1494 raeburn 14944: &get_dom('configuration',['wafproxy'],$dom);
1.1437 raeburn 14945: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14946: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450 raeburn 14947: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
14948: }
14949: }
14950: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
14951: }
14952: }
14953: return;
14954: }
14955:
14956: sub use_proxy_alias {
14957: my ($r,$lonid) = @_;
14958: my $alias = &get_proxy_alias($lonid);
14959: if ($alias) {
14960: my $dom = &host_domain($lonid);
14961: if ($dom ne '') {
1.1467 raeburn 14962: my $proxyinfo = &get_proxy_settings($dom);
1.1450 raeburn 14963: my ($vpnint,$remote_ip);
14964: if (ref($proxyinfo) eq 'HASH') {
14965: $vpnint = $proxyinfo->{'vpnint'};
14966: if ($vpnint) {
14967: $remote_ip = &get_requestor_ip($r,1,1);
1.1434 raeburn 14968: }
14969: }
1.1450 raeburn 14970: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14971: return $alias;
14972: }
1.1434 raeburn 14973: }
14974: }
14975: return;
14976: }
14977:
1.1474 raeburn 14978: sub alias_sso {
1.1467 raeburn 14979: my ($lonid) = @_;
14980: if ($lonid eq '') {
14981: $lonid = $perlvar{'lonHostID'};
14982: }
14983: if (!defined(&hostname($lonid))) {
14984: return;
14985: }
14986: if ($lonid ne '') {
14987: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
14988: if ($cached) {
14989: return $use_alias;
14990: }
1.1494 raeburn 14991: my $dom = &host_domain($lonid);
1.1467 raeburn 14992: if ($dom ne '') {
14993: my $cachetime = 60*60*24;
14994: my %domconfig =
1.1494 raeburn 14995: &get_dom('configuration',['wafproxy'],$dom);
1.1467 raeburn 14996: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14997: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
14998: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
14999: }
15000: }
15001: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15002: }
15003: }
15004: return;
15005: }
15006:
1.1465 raeburn 15007: sub get_saml_landing {
15008: my ($lonid) = @_;
15009: if ($lonid eq '') {
15010: my $defdom = &default_login_domain();
15011: my @hosts = ¤t_machine_ids();
15012: if (@hosts > 1) {
15013: foreach my $hostid (@hosts) {
15014: if (&host_domain($hostid) eq $defdom) {
15015: $lonid = $hostid;
15016: last;
15017: }
15018: }
15019: } else {
15020: $lonid = $perlvar{'lonHostID'};
15021: }
15022: if ($lonid) {
1.1494 raeburn 15023: unless (&host_domain($lonid) eq $defdom) {
1.1465 raeburn 15024: return;
15025: }
15026: } else {
15027: return;
15028: }
15029: } elsif (!defined(&hostname($lonid))) {
15030: return;
15031: }
15032: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15033: if ($cached) {
15034: return $landing;
15035: }
1.1494 raeburn 15036: my $dom = &host_domain($lonid);
1.1465 raeburn 15037: if ($dom ne '') {
15038: my $cachetime = 60*60*24;
15039: my %domconfig =
1.1494 raeburn 15040: &get_dom('configuration',['login'],$dom);
1.1465 raeburn 15041: if (ref($domconfig{'login'}) eq 'HASH') {
15042: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15043: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15044: $landing = 1;
15045: }
15046: }
15047: }
15048: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15049: }
15050: return;
15051: }
15052:
1.31 www 15053: # ------------------------------------------------------------- Declutters URLs
15054:
15055: sub declutter {
15056: my $thisfn=shift;
1.569 albertel 15057: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 15058: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15059: $thisfn=~s{^/home/httpd/html}{};
15060: }
1.31 www 15061: $thisfn=~s/^\///;
1.697 albertel 15062: $thisfn=~s|^adm/wrapper/||;
15063: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 15064: $thisfn=~s/^res\///;
1.1172 bisitz 15065: $thisfn=~s/^priv\///;
1.1032 raeburn 15066: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15067: $thisfn=~s/\?.+$//;
15068: }
1.268 www 15069: return $thisfn;
15070: }
15071:
15072: # ------------------------------------------------------------- Clutter up URLs
15073:
15074: sub clutter {
15075: my $thisfn='/'.&declutter(shift);
1.887 albertel 15076: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 15077: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 15078: $thisfn='/res'.$thisfn;
15079: }
1.1031 raeburn 15080: if ($thisfn !~m|^/adm|) {
15081: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 15082: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 15083: } else {
15084: my ($ext) = ($thisfn =~ /\.(\w+)$/);
15085: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 15086: if ($embstyle eq 'ssi'
15087: || ($embstyle eq 'hdn')
15088: || ($embstyle eq 'rat')
15089: || ($embstyle eq 'prv')
15090: || ($embstyle eq 'ign')) {
15091: #do nothing with these
15092: } elsif (($embstyle eq 'img')
1.695 albertel 15093: || ($embstyle eq 'emb')
15094: || ($embstyle eq 'wrp')) {
15095: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 15096: } elsif ($embstyle eq 'unk'
15097: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 15098: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 15099: } else {
1.718 www 15100: # &logthis("Got a blank emb style");
1.695 albertel 15101: }
1.694 albertel 15102: }
1.1343 raeburn 15103: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 15104: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 15105: }
1.31 www 15106: return $thisfn;
1.12 www 15107: }
15108:
1.787 albertel 15109: sub clutter_with_no_wrapper {
15110: my $uri = &clutter(shift);
15111: if ($uri =~ m-^/adm/-) {
15112: $uri =~ s-^/adm/wrapper/-/-;
15113: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
15114: }
15115: return $uri;
15116: }
15117:
1.557 albertel 15118: sub freeze_escape {
15119: my ($value)=@_;
15120: if (ref($value)) {
15121: $value=&nfreeze($value);
15122: return '__FROZEN__'.&escape($value);
15123: }
15124: return &escape($value);
15125: }
15126:
1.11 www 15127:
1.557 albertel 15128: sub thaw_unescape {
15129: my ($value)=@_;
15130: if ($value =~ /^__FROZEN__/) {
15131: substr($value,0,10,undef);
15132: $value=&unescape($value);
15133: return &thaw($value);
15134: }
15135: return &unescape($value);
15136: }
15137:
1.436 albertel 15138: sub correct_line_ends {
15139: my ($result)=@_;
15140: $$result =~s/\r\n/\n/mg;
15141: $$result =~s/\r/\n/mg;
1.415 albertel 15142: }
1.1 albertel 15143: # ================================================================ Main Program
15144:
1.184 www 15145: sub goodbye {
1.204 albertel 15146: &logthis("Starting Shut down");
1.443 albertel 15147: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 15148: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 15149: #converted
1.599 albertel 15150: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 15151: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15152: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15153: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 15154: #1.1 only
1.870 albertel 15155: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15156: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15157: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15158: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15159: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 15160: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15161: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 15162: &flushcourselogs();
15163: &logthis("Shutting down");
15164: }
15165:
1.852 albertel 15166: sub get_dns {
1.1210 raeburn 15167: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 15168: if (!$ignore_cache) {
15169: my ($content,$cached)=
1.1494 raeburn 15170: &is_cached_new('dns',$url);
1.869 albertel 15171: if ($cached) {
1.1210 raeburn 15172: &$func($content,$hashref);
1.869 albertel 15173: return;
15174: }
15175: }
15176:
15177: my %alldns;
1.1379 raeburn 15178: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15179: foreach my $dns (<$config>) {
15180: next if ($dns !~ /^\^(\S*)/x);
15181: my $line = $1;
15182: my ($host,$protocol) = split(/:/,$line);
15183: if ($protocol ne 'https') {
15184: $protocol = 'http';
15185: }
15186: $alldns{$host} = $protocol;
1.979 raeburn 15187: }
1.1379 raeburn 15188: close($config);
1.869 albertel 15189: }
15190: while (%alldns) {
1.1263 raeburn 15191: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456 raeburn 15192: my ($contents,@content);
15193: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15194: my $command = (split('/',$url))[3];
15195: my ($dir,$file) = &parse_getdns_url($command,$url);
15196: delete($alldns{$dns});
15197: next if (($dir eq '') || ($file eq ''));
15198: if (open(my $config,'<',"$dir/$file")) {
1.1457 raeburn 15199: @content = <$config>;
1.1456 raeburn 15200: close($config);
15201: }
15202: if ($url eq '/adm/dns/loncapaCRL') {
15203: $contents = join('',@content);
15204: }
15205: } else {
15206: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15207: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15208: delete($alldns{$dns});
15209: next if ($response->is_error());
15210: if ($url eq '/adm/dns/loncapaCRL') {
15211: $contents = $response->content;
15212: } else {
15213: @content = split("\n",$response->content);
15214: }
15215: }
1.1379 raeburn 15216: if ($url eq '/adm/dns/loncapaCRL') {
1.1456 raeburn 15217: return &$func($contents);
1.1379 raeburn 15218: } else {
15219: unless ($nocache) {
15220: &do_cache_new('dns',$url,\@content,30*24*60*60);
15221: }
15222: &$func(\@content,$hashref);
15223: return;
15224: }
15225: }
15226: my $which = (split('/',$url,4))[3];
15227: if ($which eq 'loncapaCRL') {
15228: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15229: if (-e $diskfile) {
15230: &logthis("unable to contact DNS, on disk file $diskfile not updated");
15231: } else {
15232: &logthis("unable to contact DNS, no on disk file $diskfile available");
15233: }
15234: } else {
15235: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15236: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15237: my @content = <$config>;
15238: close($config);
15239: &$func(\@content,$hashref);
15240: }
1.852 albertel 15241: }
1.1210 raeburn 15242: return;
15243: }
15244:
15245: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 15246: sub parse_dns_checksums_tab {
1.1210 raeburn 15247: my ($lines,$hashref) = @_;
1.1264 raeburn 15248: my $lonhost = $perlvar{'lonHostID'};
1.1494 raeburn 15249: my $machine_dom = &host_domain($lonhost);
1.1210 raeburn 15250: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 15251: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15252: my $webconfdir = '/etc/httpd/conf';
15253: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15254: $webconfdir = '/etc/apache2';
15255: } elsif ($distro =~ /^sles(\d+)$/) {
15256: if ($1 >= 10) {
15257: $webconfdir = '/etc/apache2';
15258: }
15259: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15260: if ($1 >= 10.0) {
15261: $webconfdir = '/etc/apache2';
15262: }
15263: }
1.1210 raeburn 15264: my ($release,$timestamp) = split(/\-/,$loncaparev);
15265: my (%chksum,%revnum);
15266: if (ref($lines) eq 'ARRAY') {
15267: chomp(@{$lines});
1.1238 raeburn 15268: my $version = shift(@{$lines});
15269: if ($version eq $release) {
1.1210 raeburn 15270: foreach my $line (@{$lines}) {
1.1238 raeburn 15271: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 15272: if ($file =~ m{^/etc/httpd/conf}) {
15273: if ($webconfdir eq '/etc/apache2') {
15274: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15275: }
15276: }
1.1238 raeburn 15277: $chksum{$file} = $shasum;
15278: $revnum{$file} = $version;
1.1210 raeburn 15279: }
15280: if (ref($hashref) eq 'HASH') {
15281: %{$hashref} = (
15282: sums => \%chksum,
15283: versions => \%revnum,
15284: );
15285: }
15286: }
15287: }
1.869 albertel 15288: return;
1.852 albertel 15289: }
1.1210 raeburn 15290:
15291: sub fetch_dns_checksums {
1.1238 raeburn 15292: my %checksums;
1.1494 raeburn 15293: my $machine_dom = &host_domain($perlvar{'lonHostID'});
1.1260 raeburn 15294: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 15295: my ($release,$timestamp) = split(/\-/,$loncaparev);
15296: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 15297: \%checksums);
1.1210 raeburn 15298: return \%checksums;
15299: }
15300:
1.1379 raeburn 15301: sub fetch_crl_pemfile {
15302: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15303: }
15304:
15305: sub save_crl_pem {
1.1456 raeburn 15306: my ($content) = @_;
1.1380 raeburn 15307: my ($msg,$hadchanges);
1.1456 raeburn 15308: if ($content ne '') {
1.1379 raeburn 15309: my $now = time;
15310: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15311: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15312: if (open(my $fh,'>',"$tmpcrl")) {
1.1456 raeburn 15313: print $fh $content;
1.1379 raeburn 15314: close($fh);
15315: if (-e $lonca) {
15316: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15317: my $check = <PIPE>;
15318: close(PIPE);
15319: chomp($check);
15320: if ($check eq 'verify OK') {
15321: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380 raeburn 15322: my $backup;
1.1379 raeburn 15323: if (-e $dest) {
1.1380 raeburn 15324: if (&File::Copy::move($dest,"$dest.bak")) {
15325: $backup = 'ok';
15326: }
1.1379 raeburn 15327: }
15328: if (&File::Copy::move($tmpcrl,$dest)) {
15329: $msg = 'ok';
1.1380 raeburn 15330: if ($backup) {
15331: my (%oldnums,%newnums);
15332: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15333: while (<PIPE>) {
15334: $oldnums{(split(/:/))[1]} = 1;
15335: }
15336: close(PIPE);
15337: }
15338: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15339: while(<PIPE>) {
15340: $newnums{(split(/:/))[1]} = 1;
15341: }
15342: close(PIPE);
15343: }
15344: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15345: unless (exists($oldnums{$key})) {
15346: $hadchanges = 1;
15347: last;
15348: }
15349: }
15350: unless ($hadchanges) {
15351: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15352: unless (exists($newnums{$key})) {
15353: $hadchanges = 1;
15354: last;
15355: }
15356: }
15357: }
15358: }
1.1379 raeburn 15359: }
15360: } else {
15361: unlink($tmpcrl);
15362: }
15363: } else {
15364: unlink($tmpcrl);
15365: }
15366: } else {
15367: unlink($tmpcrl);
15368: }
15369: }
15370: }
1.1380 raeburn 15371: return ($msg,$hadchanges);
1.1379 raeburn 15372: }
15373:
1.1456 raeburn 15374: sub parse_getdns_url {
15375: my ($command,$url) = @_;
15376: my $dir = $perlvar{'lonTabDir'};
15377: my $file;
15378: if ($command eq 'hosts') {
15379: $file = 'dns_hosts.tab';
15380: } elsif ($command eq 'domain') {
15381: $file = 'dns_domain.tab';
15382: } elsif ($command eq 'checksums') {
15383: my $version = (split('/',$url))[4];
15384: $file = "dns_checksums/$version.tab",
15385: } elsif ($command eq 'loncapaCRL') {
15386: $dir = $perlvar{'lonCertificateDirectory'};
15387: $file = $perlvar{'lonnetCertRevocationList'};
15388: }
15389: return ($dir,$file);
15390: }
15391:
1.327 albertel 15392: # ------------------------------------------------------------ Read domain file
15393: {
1.852 albertel 15394: my $loaded;
1.846 albertel 15395: my %domain;
15396:
1.852 albertel 15397: sub parse_domain_tab {
15398: my ($lines) = @_;
15399: foreach my $line (@$lines) {
15400: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 15401:
1.846 albertel 15402: chomp($line);
1.852 albertel 15403: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 15404: my %this_domain;
15405: foreach my $field ('description', 'auth_def', 'auth_arg_def',
15406: 'lang_def', 'city', 'longi', 'lati',
15407: 'primary') {
15408: $this_domain{$field} = shift(@elements);
15409: }
15410: $domain{$name} = \%this_domain;
1.852 albertel 15411: }
15412: }
1.864 albertel 15413:
15414: sub reset_domain_info {
15415: undef($loaded);
15416: undef(%domain);
15417: }
15418:
1.852 albertel 15419: sub load_domain_tab {
1.1293 raeburn 15420: my ($ignore_cache,$nocache) = @_;
15421: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 15422: my $fh;
1.1359 raeburn 15423: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 15424: my @lines = <$fh>;
15425: &parse_domain_tab(\@lines);
1.448 albertel 15426: }
1.852 albertel 15427: close($fh);
15428: $loaded = 1;
1.327 albertel 15429: }
1.846 albertel 15430:
15431: sub domain {
1.852 albertel 15432: &load_domain_tab() if (!$loaded);
15433:
1.846 albertel 15434: my ($name,$what) = @_;
15435: return if ( !exists($domain{$name}) );
15436:
15437: if (!$what) {
15438: return $domain{$name}{'description'};
15439: }
15440: return $domain{$name}{$what};
15441: }
1.974 raeburn 15442:
15443: sub domain_info {
15444: &load_domain_tab() if (!$loaded);
15445: return %domain;
15446: }
15447:
1.327 albertel 15448: }
15449:
15450:
1.1 albertel 15451: # ------------------------------------------------------------- Read hosts file
15452: {
1.838 albertel 15453: my %hostname;
1.844 albertel 15454: my %hostdom;
1.845 albertel 15455: my %libserv;
1.852 albertel 15456: my $loaded;
1.888 albertel 15457: my %name_to_host;
1.1074 raeburn 15458: my %internetdom;
1.1107 raeburn 15459: my %LC_dns_serv;
1.852 albertel 15460:
15461: sub parse_hosts_tab {
15462: my ($file) = @_;
15463: foreach my $configline (@$file) {
15464: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 15465: chomp($configline);
15466: if ($configline =~ /^\^/) {
15467: if ($configline =~ /^\^([\w.\-]+)/) {
15468: $LC_dns_serv{$1} = 1;
15469: }
15470: next;
15471: }
1.1074 raeburn 15472: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 15473: $name=~s/\s//g;
15474: if ($id && $domain && $role && $name) {
1.1351 raeburn 15475: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15476: my $curr = $hostname{$id};
15477: my $skip;
15478: if (ref($name_to_host{$curr}) eq 'ARRAY') {
15479: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15480: $skip = 1;
15481: } else {
15482: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15483: }
15484: }
15485: unless ($skip) {
15486: push(@{$name_to_host{$name}},$id);
15487: }
15488: } else {
15489: push(@{$name_to_host{$name}},$id);
15490: }
1.852 albertel 15491: $hostname{$id}=$name;
15492: $hostdom{$id}=$domain;
15493: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 15494: if (defined($protocol)) {
15495: if ($protocol eq 'https') {
15496: $protocol{$id} = $protocol;
15497: } else {
15498: $protocol{$id} = 'http';
15499: }
1.968 raeburn 15500: } else {
1.969 raeburn 15501: $protocol{$id} = 'http';
1.968 raeburn 15502: }
1.1074 raeburn 15503: if (defined($intdom)) {
15504: $internetdom{$id} = $intdom;
15505: }
1.852 albertel 15506: }
15507: }
15508: }
1.864 albertel 15509:
15510: sub reset_hosts_info {
1.897 albertel 15511: &purge_remembered();
1.864 albertel 15512: &reset_domain_info();
15513: &reset_hosts_ip_info();
1.1339 raeburn 15514: undef(%internetdom);
1.892 albertel 15515: undef(%name_to_host);
1.864 albertel 15516: undef(%hostname);
15517: undef(%hostdom);
15518: undef(%libserv);
15519: undef($loaded);
15520: }
1.1 albertel 15521:
1.852 albertel 15522: sub load_hosts_tab {
1.1293 raeburn 15523: my ($ignore_cache,$nocache) = @_;
15524: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359 raeburn 15525: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 15526: my @config = <$config>;
15527: &parse_hosts_tab(\@config);
15528: close($config);
15529: $loaded=1;
1.1 albertel 15530: }
1.852 albertel 15531:
1.838 albertel 15532: sub hostname {
1.852 albertel 15533: &load_hosts_tab() if (!$loaded);
15534:
1.838 albertel 15535: my ($lonid) = @_;
15536: return $hostname{$lonid};
15537: }
1.845 albertel 15538:
1.838 albertel 15539: sub all_hostnames {
1.852 albertel 15540: &load_hosts_tab() if (!$loaded);
15541:
1.838 albertel 15542: return %hostname;
15543: }
1.845 albertel 15544:
1.888 albertel 15545: sub all_names {
1.1293 raeburn 15546: my ($ignore_cache,$nocache) = @_;
15547: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 15548:
15549: return %name_to_host;
15550: }
15551:
1.974 raeburn 15552: sub all_host_domain {
15553: &load_hosts_tab() if (!$loaded);
15554: return %hostdom;
15555: }
15556:
1.1339 raeburn 15557: sub all_host_intdom {
15558: &load_hosts_tab() if (!$loaded);
15559: return %internetdom;
15560: }
15561:
1.845 albertel 15562: sub is_library {
1.852 albertel 15563: &load_hosts_tab() if (!$loaded);
15564:
1.845 albertel 15565: return exists($libserv{$_[0]});
15566: }
15567:
15568: sub all_library {
1.852 albertel 15569: &load_hosts_tab() if (!$loaded);
15570:
1.845 albertel 15571: return %libserv;
15572: }
15573:
1.1062 droeschl 15574: sub unique_library {
15575: #2x reverse removes all hostnames that appear more than once
15576: my %unique = reverse &all_library();
15577: return reverse %unique;
15578: }
15579:
1.841 albertel 15580: sub get_servers {
1.852 albertel 15581: &load_hosts_tab() if (!$loaded);
15582:
1.841 albertel 15583: my ($domain,$type) = @_;
15584: my %possible_hosts = ($type eq 'library') ? %libserv
15585: : %hostname;
15586: my %result;
1.842 albertel 15587: if (ref($domain) eq 'ARRAY') {
15588: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 15589: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 15590: $result{$host} = $hostname;
15591: }
15592: }
15593: } else {
15594: while ( my ($host,$hostname) = each(%possible_hosts)) {
15595: if ($hostdom{$host} eq $domain) {
15596: $result{$host} = $hostname;
15597: }
1.841 albertel 15598: }
15599: }
15600: return %result;
15601: }
1.845 albertel 15602:
1.1062 droeschl 15603: sub get_unique_servers {
15604: my %unique = reverse &get_servers(@_);
15605: return reverse %unique;
15606: }
15607:
1.844 albertel 15608: sub host_domain {
1.852 albertel 15609: &load_hosts_tab() if (!$loaded);
15610:
1.844 albertel 15611: my ($lonid) = @_;
15612: return $hostdom{$lonid};
15613: }
15614:
1.841 albertel 15615: sub all_domains {
1.852 albertel 15616: &load_hosts_tab() if (!$loaded);
15617:
1.841 albertel 15618: my %seen;
15619: my @uniq = grep(!$seen{$_}++, values(%hostdom));
15620: return @uniq;
15621: }
1.1074 raeburn 15622:
15623: sub internet_dom {
15624: &load_hosts_tab() if (!$loaded);
15625:
15626: my ($lonid) = @_;
15627: return $internetdom{$lonid};
15628: }
1.1107 raeburn 15629:
15630: sub is_LC_dns {
15631: &load_hosts_tab() if (!$loaded);
15632:
15633: my ($hostname) = @_;
15634: return exists($LC_dns_serv{$hostname});
15635: }
15636:
1.1 albertel 15637: }
15638:
1.847 albertel 15639: {
15640: my %iphost;
1.856 albertel 15641: my %name_to_ip;
15642: my %lonid_to_ip;
1.869 albertel 15643:
1.847 albertel 15644: sub get_hosts_from_ip {
15645: my ($ip) = @_;
15646: my %iphosts = &get_iphost();
15647: if (ref($iphosts{$ip})) {
15648: return @{$iphosts{$ip}};
15649: }
15650: return;
1.839 albertel 15651: }
1.864 albertel 15652:
15653: sub reset_hosts_ip_info {
15654: undef(%iphost);
15655: undef(%name_to_ip);
15656: undef(%lonid_to_ip);
15657: }
1.856 albertel 15658:
15659: sub get_host_ip {
15660: my ($lonid) = @_;
15661: if (exists($lonid_to_ip{$lonid})) {
15662: return $lonid_to_ip{$lonid};
15663: }
15664: my $name=&hostname($lonid);
15665: my $ip = gethostbyname($name);
15666: return if (!$ip || length($ip) ne 4);
15667: $ip=inet_ntoa($ip);
15668: $name_to_ip{$name} = $ip;
15669: $lonid_to_ip{$lonid} = $ip;
15670: return $ip;
15671: }
1.847 albertel 15672:
15673: sub get_iphost {
1.1293 raeburn 15674: my ($ignore_cache,$nocache) = @_;
1.894 albertel 15675:
1.869 albertel 15676: if (!$ignore_cache) {
15677: if (%iphost) {
15678: return %iphost;
15679: }
15680: my ($ip_info,$cached)=
1.1494 raeburn 15681: &is_cached_new('iphost','iphost');
1.869 albertel 15682: if ($cached) {
15683: %iphost = %{$ip_info->[0]};
15684: %name_to_ip = %{$ip_info->[1]};
15685: %lonid_to_ip = %{$ip_info->[2]};
15686: return %iphost;
15687: }
15688: }
1.894 albertel 15689:
15690: # get yesterday's info for fallback
15691: my %old_name_to_ip;
15692: my ($ip_info,$cached)=
1.1495 raeburn 15693: &is_cached_new('iphost','iphost');
1.894 albertel 15694: if ($cached) {
15695: %old_name_to_ip = %{$ip_info->[1]};
15696: }
15697:
1.1293 raeburn 15698: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 15699: foreach my $name (keys(%name_to_host)) {
1.847 albertel 15700: my $ip;
15701: if (!exists($name_to_ip{$name})) {
15702: $ip = gethostbyname($name);
15703: if (!$ip || length($ip) ne 4) {
1.894 albertel 15704: if (defined($old_name_to_ip{$name})) {
15705: $ip = $old_name_to_ip{$name};
15706: &logthis("Can't find $name defaulting to old $ip");
15707: } else {
15708: &logthis("Name $name no IP found");
15709: next;
15710: }
15711: } else {
15712: $ip=inet_ntoa($ip);
1.847 albertel 15713: }
15714: $name_to_ip{$name} = $ip;
15715: } else {
15716: $ip = $name_to_ip{$name};
1.653 albertel 15717: }
1.888 albertel 15718: foreach my $id (@{ $name_to_host{$name} }) {
15719: $lonid_to_ip{$id} = $ip;
15720: }
15721: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 15722: }
1.1293 raeburn 15723: unless ($nocache) {
15724: &do_cache_new('iphost','iphost',
15725: [\%iphost,\%name_to_ip,\%lonid_to_ip],
15726: 48*60*60);
15727: }
1.869 albertel 15728:
1.847 albertel 15729: return %iphost;
1.598 albertel 15730: }
15731:
1.992 raeburn 15732: #
15733: # Given a DNS returns the loncapa host name for that DNS
15734: #
15735: sub host_from_dns {
15736: my ($dns) = @_;
15737: my @hosts;
15738: my $ip;
15739:
1.993 raeburn 15740: if (exists($name_to_ip{$dns})) {
1.992 raeburn 15741: $ip = $name_to_ip{$dns};
15742: }
15743: if (!$ip) {
15744: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15745: if (length($ip) == 4) {
15746: $ip = &IO::Socket::inet_ntoa($ip);
15747: }
15748: }
15749: if ($ip) {
15750: @hosts = get_hosts_from_ip($ip);
15751: return $hosts[0];
15752: }
15753: return undef;
1.986 foxr 15754: }
1.992 raeburn 15755:
1.1074 raeburn 15756: sub get_internet_names {
15757: my ($lonid) = @_;
15758: return if ($lonid eq '');
15759: my ($idnref,$cached)=
1.1494 raeburn 15760: &is_cached_new('internetnames',$lonid);
1.1074 raeburn 15761: if ($cached) {
15762: return $idnref;
15763: }
15764: my $ip = &get_host_ip($lonid);
15765: my @hosts = &get_hosts_from_ip($ip);
15766: my %iphost = &get_iphost();
15767: my (@idns,%seen);
15768: foreach my $id (@hosts) {
15769: my $dom = &host_domain($id);
15770: my $prim_id = &domain($dom,'primary');
15771: my $prim_ip = &get_host_ip($prim_id);
15772: next if ($seen{$prim_ip});
15773: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15774: foreach my $id (@{$iphost{$prim_ip}}) {
15775: my $intdom = &internet_dom($id);
15776: unless (grep(/^\Q$intdom\E$/,@idns)) {
15777: push(@idns,$intdom);
15778: }
15779: }
15780: }
15781: $seen{$prim_ip} = 1;
15782: }
1.1219 raeburn 15783: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 15784: }
15785:
1.986 foxr 15786: }
15787:
1.1079 raeburn 15788: sub all_loncaparevs {
1.1249 raeburn 15789: 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 15790: }
15791:
1.1227 raeburn 15792: # ---------------------------------------------------------- Read loncaparev table
15793: {
15794: sub load_loncaparevs {
15795: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359 raeburn 15796: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227 raeburn 15797: while (my $configline=<$config>) {
15798: chomp($configline);
15799: my ($hostid,$loncaparev)=split(/:/,$configline);
15800: $loncaparevs{$hostid}=$loncaparev;
15801: }
15802: close($config);
15803: }
15804: }
15805: }
15806: }
15807:
15808: # ---------------------------------------------------------- Read serverhostID table
15809: {
15810: sub load_serverhomeIDs {
15811: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359 raeburn 15812: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227 raeburn 15813: while (my $configline=<$config>) {
15814: chomp($configline);
15815: my ($name,$id)=split(/:/,$configline);
15816: $serverhomeIDs{$name}=$id;
15817: }
15818: close($config);
15819: }
15820: }
15821: }
15822: }
15823:
15824:
1.862 albertel 15825: BEGIN {
15826:
15827: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15828: unless ($readit) {
15829: {
15830: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15831: %perlvar = (%perlvar,%{$configvars});
15832: }
15833:
15834:
1.1 albertel 15835: # ------------------------------------------------------ Read spare server file
15836: {
1.1359 raeburn 15837: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 15838:
15839: while (my $configline=<$config>) {
15840: chomp($configline);
1.284 matthew 15841: if ($configline) {
1.784 albertel 15842: my ($host,$type) = split(':',$configline,2);
1.785 albertel 15843: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 15844: push(@{ $spareid{$type} }, $host);
1.1 albertel 15845: }
15846: }
1.448 albertel 15847: close($config);
1.1 albertel 15848: }
1.11 www 15849: # ------------------------------------------------------------ Read permissions
15850: {
1.1359 raeburn 15851: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 15852:
15853: while (my $configline=<$config>) {
1.448 albertel 15854: chomp($configline);
15855: if ($configline) {
15856: my ($role,$perm)=split(/ /,$configline);
15857: if ($perm ne '') { $pr{$role}=$perm; }
15858: }
1.11 www 15859: }
1.448 albertel 15860: close($config);
1.11 www 15861: }
15862:
15863: # -------------------------------------------- Read plain texts for permissions
15864: {
1.1359 raeburn 15865: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 15866:
15867: while (my $configline=<$config>) {
1.448 albertel 15868: chomp($configline);
15869: if ($configline) {
1.742 raeburn 15870: my ($short,@plain)=split(/:/,$configline);
15871: %{$prp{$short}} = ();
15872: if (@plain > 0) {
15873: $prp{$short}{'std'} = $plain[0];
15874: for (my $i=1; $i<@plain; $i++) {
15875: $prp{$short}{'alt'.$i} = $plain[$i];
15876: }
15877: }
1.448 albertel 15878: }
1.135 www 15879: }
1.448 albertel 15880: close($config);
1.135 www 15881: }
15882:
15883: # ---------------------------------------------------------- Read package table
15884: {
1.1359 raeburn 15885: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 15886:
15887: while (my $configline=<$config>) {
1.483 albertel 15888: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 15889: chomp($configline);
15890: my ($short,$plain)=split(/:/,$configline);
15891: my ($pack,$name)=split(/\&/,$short);
15892: if ($plain ne '') {
15893: $packagetab{$pack.'&'.$name.'&name'}=$name;
15894: $packagetab{$short}=$plain;
15895: }
1.11 www 15896: }
1.448 albertel 15897: close($config);
1.329 matthew 15898: }
15899:
1.1073 raeburn 15900: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 15901:
15902: &load_loncaparevs();
1.1073 raeburn 15903:
1.1074 raeburn 15904: # ---------------------------------------------------------- Read serverhostID table
15905:
1.1227 raeburn 15906: &load_serverhomeIDs();
15907:
15908: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 15909: {
15910: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15911: if (-e $file) {
15912: my $parser = HTML::LCParser->new($file);
15913: while (my $token = $parser->get_token()) {
15914: if ($token->[0] eq 'S') {
15915: my $item = $token->[1];
15916: my $name = $token->[2]{'name'};
15917: my $value = $token->[2]{'value'};
1.1285 raeburn 15918: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 15919: my $namematch = $token->[2]{'namematch'};
15920: if ($item eq 'parameter') {
15921: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15922: my $release = $parser->get_text();
15923: $release =~ s/(^\s*|\s*$ )//gx;
15924: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15925: }
15926: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 15927: my $release = $parser->get_text();
15928: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 15929: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 15930: }
15931: }
15932: }
15933: }
1.1073 raeburn 15934: }
15935:
1.1138 raeburn 15936: # ---------------------------------------------------------- Read managers table
15937: {
15938: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359 raeburn 15939: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 15940: while (my $configline=<$config>) {
15941: chomp($configline);
15942: next if ($configline =~ /^\#/);
15943: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15944: $managerstab{$configline} = 1;
15945: }
15946: }
15947: close($config);
15948: }
15949: }
15950: }
15951:
1.329 matthew 15952: # ------------- set up temporary directory
15953: {
1.1117 foxr 15954: $tmpdir = LONCAPA::tempdir();
1.329 matthew 15955:
1.11 www 15956: }
15957:
1.1405 raeburn 15958: # ------------- set default texengine (domain default overrides this)
15959: {
15960: $deftex = LONCAPA::texengine();
15961: }
15962:
1.1416 raeburn 15963: # ------------- set default minimum length for passwords for internal auth users
15964: {
15965: $passwdmin = LONCAPA::passwd_min();
15966: }
15967:
1.794 albertel 15968: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
15969: 'compress_threshold'=> 20_000,
15970: });
1.185 www 15971:
1.281 www 15972: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 15973: $dumpcount=0;
1.958 www 15974: $locknum=0;
1.22 www 15975:
1.163 harris41 15976: &logtouch();
1.672 albertel 15977: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 15978: $readit=1;
1.564 albertel 15979: {
15980: use integer;
15981: my $test=(2**32)+1;
1.568 albertel 15982: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 15983: &logthis(" Detected 64bit platform ($_64bit)");
15984: }
1.195 www 15985: }
1.1 albertel 15986: }
1.179 www 15987:
1.1 albertel 15988: 1;
1.191 harris41 15989: __END__
15990:
1.243 albertel 15991: =pod
15992:
1.191 harris41 15993: =head1 NAME
15994:
1.243 albertel 15995: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 15996:
15997: =head1 SYNOPSIS
15998:
1.243 albertel 15999: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 16000:
16001: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16002:
1.243 albertel 16003: Common parameters:
16004:
16005: =over 4
16006:
16007: =item *
16008:
16009: $uname : an internal username (if $cname expecting a course Id specifically)
16010:
16011: =item *
16012:
16013: $udom : a domain (if $cdom expecting a course's domain specifically)
16014:
16015: =item *
16016:
16017: $symb : a resource instance identifier
16018:
16019: =item *
16020:
16021: $namespace : the name of a .db file that contains the data needed or
16022: being set.
16023:
16024: =back
16025:
1.394 bowersj2 16026: =head1 OVERVIEW
1.191 harris41 16027:
1.394 bowersj2 16028: lonnet provides subroutines which interact with the
16029: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16030: about classes, users, and resources.
1.243 albertel 16031:
16032: For many of these objects you can also use this to store data about
16033: them or modify them in various ways.
1.191 harris41 16034:
1.394 bowersj2 16035: =head2 Symbs
1.191 harris41 16036:
1.394 bowersj2 16037: To identify a specific instance of a resource, LON-CAPA uses symbols
16038: or "symbs"X<symb>. These identifiers are built from the URL of the
16039: map, the resource number of the resource in the map, and the URL of
16040: the resource itself. The latter is somewhat redundant, but might help
16041: if maps change.
16042:
16043: An example is
16044:
16045: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16046:
16047: The respective map entry is
16048:
16049: <resource id="19" src="/res/msu/korte/tests/part12.problem"
16050: title="Problem 2">
16051: </resource>
16052:
16053: Symbs are used by the random number generator, as well as to store and
16054: restore data specific to a certain instance of for example a problem.
16055:
16056: =head2 Storing And Retrieving Data
16057:
16058: X<store()>X<cstore()>X<restore()>Three of the most important functions
16059: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16060: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16061: is is the non-critical message twin of cstore. These functions are for
16062: handlers to store a perl hash to a user's permanent data space in an
16063: easy manner, and to retrieve it again on another call. It is expected
16064: that a handler would use this once at the beginning to retrieve data,
16065: and then again once at the end to send only the new data back.
16066:
16067: The data is stored in the user's data directory on the user's
16068: homeserver under the ID of the course.
16069:
16070: The hash that is returned by restore will have all of the previous
16071: value for all of the elements of the hash.
16072:
16073: Example:
16074:
16075: #creating a hash
16076: my %hash;
16077: $hash{'foo'}='bar';
16078:
16079: #storing it
16080: &Apache::lonnet::cstore(\%hash);
16081:
16082: #changing a value
16083: $hash{'foo'}='notbar';
16084:
16085: #adding a new value
16086: $hash{'bar'}='foo';
16087: &Apache::lonnet::cstore(\%hash);
16088:
16089: #retrieving the hash
16090: my %history=&Apache::lonnet::restore();
16091:
16092: #print the hash
16093: foreach my $key (sort(keys(%history))) {
16094: print("\%history{$key} = $history{$key}");
16095: }
16096:
16097: Will print out:
1.191 harris41 16098:
1.394 bowersj2 16099: %history{1:foo} = bar
16100: %history{1:keys} = foo:timestamp
16101: %history{1:timestamp} = 990455579
16102: %history{2:bar} = foo
16103: %history{2:foo} = notbar
16104: %history{2:keys} = foo:bar:timestamp
16105: %history{2:timestamp} = 990455580
16106: %history{bar} = foo
16107: %history{foo} = notbar
16108: %history{timestamp} = 990455580
16109: %history{version} = 2
16110:
16111: Note that the special hash entries C<keys>, C<version> and
16112: C<timestamp> were added to the hash. C<version> will be equal to the
16113: total number of versions of the data that have been stored. The
16114: C<timestamp> attribute will be the UNIX time the hash was
16115: stored. C<keys> is available in every historical section to list which
16116: keys were added or changed at a specific historical revision of a
16117: hash.
16118:
16119: B<Warning>: do not store the hash that restore returns directly. This
16120: will cause a mess since it will restore the historical keys as if the
16121: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 16122:
1.394 bowersj2 16123: Calling convention:
1.191 harris41 16124:
1.1225 raeburn 16125: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 16126: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 16127:
1.394 bowersj2 16128: For more detailed information, see lonnet specific documentation.
1.191 harris41 16129:
1.394 bowersj2 16130: =head1 RETURN MESSAGES
1.191 harris41 16131:
1.394 bowersj2 16132: =over 4
1.191 harris41 16133:
1.394 bowersj2 16134: =item * B<con_lost>: unable to contact remote host
1.191 harris41 16135:
1.394 bowersj2 16136: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16137: when the connection is brought back up
1.191 harris41 16138:
1.394 bowersj2 16139: =item * B<con_failed>: unable to contact remote host and unable to save message
16140: for later delivery
1.191 harris41 16141:
1.967 bisitz 16142: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 16143:
1.394 bowersj2 16144: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 16145: that was requested
1.191 harris41 16146:
1.243 albertel 16147: =back
1.191 harris41 16148:
1.243 albertel 16149: =head1 PUBLIC SUBROUTINES
1.191 harris41 16150:
1.243 albertel 16151: =head2 Session Environment Functions
1.191 harris41 16152:
1.243 albertel 16153: =over 4
1.191 harris41 16154:
1.394 bowersj2 16155: =item *
16156: X<appenv()>
1.949 raeburn 16157: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 16158: the user envirnoment file, and will be restored for each access this
1.620 albertel 16159: user makes during this session, also modifies the %env for the current
1.949 raeburn 16160: process. Optional rolesarrayref - if defined contains a reference to an array
16161: of roles which are exempt from the restriction on modifying user.role entries
16162: in the user's environment.db and in %env.
1.191 harris41 16163:
16164: =item *
1.394 bowersj2 16165: X<delenv()>
1.987 raeburn 16166: B<delenv($delthis,$regexp)>: removes all items from the session
16167: environment file that begin with $delthis. If the
16168: optional second arg - $regexp - is true, $delthis is treated as a
16169: regular expression, otherwise \Q$delthis\E is used.
16170: The values are also deleted from the current processes %env.
1.191 harris41 16171:
1.795 albertel 16172: =item * get_env_multiple($name)
16173:
16174: gets $name from the %env hash, it seemlessly handles the cases where multiple
16175: values may be defined and end up as an array ref.
16176:
16177: returns an array of values
16178:
1.243 albertel 16179: =back
16180:
16181: =head2 User Information
1.191 harris41 16182:
1.243 albertel 16183: =over 4
1.191 harris41 16184:
16185: =item *
1.394 bowersj2 16186: X<queryauthenticate()>
16187: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 16188: authentication scheme
16189:
16190: =item *
1.394 bowersj2 16191: X<authenticate()>
1.1073 raeburn 16192: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 16193: authenticate user from domain's lib servers (first use the current
16194: one). C<$upass> should be the users password.
1.1073 raeburn 16195: $checkdefauth is optional (value is 1 if a check should be made to
16196: authenticate user using default authentication method, and allow
16197: account creation if username does not have account in the domain).
16198: $clientcancheckhost is optional (value is 1 if checking whether the
16199: server can host will occur on the client side in lonauth.pm).
1.191 harris41 16200:
16201: =item *
1.394 bowersj2 16202: X<homeserver()>
16203: B<homeserver($uname,$udom)>: find the server which has
16204: the user's directory and files (there must be only one), this caches
16205: the answer, and also caches if there is a borken connection.
1.191 harris41 16206:
16207: =item *
1.394 bowersj2 16208: X<idget()>
1.1300 raeburn 16209: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
16210: a list of student/employee IDs or clicker IDs
16211: (student/employee IDs are a unique resource in a domain, there must be
16212: only 1 ID per username, and only 1 username per ID in a specific domain).
16213: clickerIDs are not necessarily unique, as students might share clickers.
16214: (returns hash: id=>name,id=>name)
1.191 harris41 16215:
16216: =item *
1.394 bowersj2 16217: X<idrget()>
16218: B<idrget($udom,@unames)>: find the IDs behind a list of
16219: usernames (returns hash: name=>id,name=>id)
1.191 harris41 16220:
16221: =item *
1.394 bowersj2 16222: X<idput()>
1.1300 raeburn 16223: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
16224: names and associated student/employee IDs or clicker IDs.
16225:
16226: =item *
16227: X<iddel()>
16228: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
16229: student/employee ID or clicker ID username look-ups from domain.
16230: The homeserver ($uhome) and namespace ($namespace) are optional.
16231: If no $uhome is provided, it will be determined usig &homeserver()
16232: for each user. If no $namespace is provided, the default is ids.
16233:
16234: =item *
16235: X<updateclickers()>
16236: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
16237: clicker ID-to-username look-ups in clickers.db on library server.
16238: Permitted actions are add or del (i.e., add or delete). The
16239: clickers.db contains clickerID as keys (escaped), and each corresponding
16240: value is an escaped comma-separated list of usernames (for whom the
16241: library server is the homeserver), who registered that particular ID.
16242: If $critical is true, the update will be sent via &critical, otherwise
16243: &reply() will be used.
1.191 harris41 16244:
16245: =item *
1.394 bowersj2 16246: X<rolesinit()>
1.1169 droeschl 16247: B<rolesinit($udom,$username)>: get user privileges.
16248: returns user role, first access and timer interval hashes
1.243 albertel 16249:
16250: =item *
1.1171 droeschl 16251: X<privileged()>
16252: B<privileged($username,$domain)>: returns a true if user has a
16253: privileged and active role (i.e. su or dc), false otherwise.
16254:
16255: =item *
1.551 albertel 16256: X<getsection()>
16257: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 16258: course $cname, return section name/number or '' for "not in course"
16259: and '-1' for "no section"
16260:
16261: =item *
1.394 bowersj2 16262: X<userenvironment()>
16263: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 16264: passed in @what from the requested user's environment, returns a hash
16265:
1.858 raeburn 16266: =item *
16267: X<userlog_query()>
1.859 albertel 16268: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16269: activity.log file. %filters defines filters applied when parsing the
16270: log file. These can be start or end timestamps, or the type of action
16271: - log to look for Login or Logout events, check for Checkin or
16272: Checkout, role for role selection. The response is in the form
16273: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
16274: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 16275:
1.243 albertel 16276: =back
16277:
16278: =head2 User Roles
16279:
16280: =over 4
16281:
16282: =item *
16283:
1.1284 raeburn 16284: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
16285: returns codes for allowed actions.
16286:
16287: The first argument is required, all others are optional.
16288:
16289: $priv is the privilege being checked.
16290: $uri contains additional information about what is being checked for access (e.g.,
16291: URL, course ID etc.).
16292: $symb is the unique resource instance identifier in a course; if needed,
16293: but not provided, it will be retrieved via a call to &symbread().
16294: $role is the role for which a priv is being checked (only used if priv is evb).
16295: $clientip is the user's IP address (only used when checking for access to portfolio
16296: files).
16297: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
16298: prevents recursive calls to &allowed.
16299:
1.243 albertel 16300: F: full access
16301: U,I,K: authentication modes (cxx only)
16302: '': forbidden
16303: 1: user needs to choose course
16304: 2: browse allowed
1.766 albertel 16305: A: passphrase authentication needed
1.1284 raeburn 16306: B: access temporarily blocked because of a blocking event in a course.
1.1402 raeburn 16307: D: access blocked because access is required via session initiated via deep-link
1.243 albertel 16308:
16309: =item *
16310:
1.1192 raeburn 16311: constructaccess($url,$setpriv) : check for access to construction space URL
16312:
16313: See if the owner domain and name in the URL match those in the
16314: expected environment. If so, return three element list
16315: ($ownername,$ownerdomain,$ownerhome).
16316:
16317: Otherwise return the null string.
16318:
16319: If second argument 'setpriv' is true, it assigns the privileges,
16320: and returns the same three element list, unless the owner has
16321: blocked "ad hoc" Domain Coordinator access to the Author Space,
16322: in which case the null string is returned.
16323:
16324: =item *
16325:
1.1326 raeburn 16326: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16327: define a custom role rolename set privileges in format of lonTabs/roles.tab
16328: for system, domain, and course level. $uname and $udom are optional (current
16329: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 16330:
16331: =item *
16332:
1.988 raeburn 16333: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
16334: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 16335: $type is Course (default) or Community.
1.988 raeburn 16336: If $forcedefault evaluates to true, text returned will be default
16337: text for $type. Otherwise, if this is a course, the text returned
16338: will be a custom name for the role (if defined in the course's
16339: environment). If no custom name is defined the default is returned.
16340:
1.832 raeburn 16341: =item *
16342:
1.1219 raeburn 16343: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 16344: All arguments are optional. Returns a hash of a roles, either for
16345: co-author/assistant author roles for a user's Construction Space
1.906 albertel 16346: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 16347: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16348: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16349: For each key, value is set to colon-separated start and end times for
16350: the role. If no username and domain are specified, will default to
1.934 raeburn 16351: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 16352: of role statuses (active, future or previous), roles
16353: (e.g., cc,in, st etc.) and domains of the roles which can be used
16354: to restrict the list of roles reported. If no array ref is
16355: provided for types, will default to return only active roles.
1.834 albertel 16356:
1.1195 raeburn 16357: =item *
16358:
16359: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 16360: user: $uname:$udom has a role in the course: $cdom_$cnum.
16361:
16362: Additional optional arguments are: $type (if role checking is to be restricted
16363: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 16364: available roles) or future (roles available in the future), and
16365: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 16366: have active Domain Coordinator role in course's domain or in additional
16367: domains (specified in 'Domains to check for privileged users' in course
16368: environment -- set via: Course Settings -> Classlists and staff listing).
16369:
16370: =item *
16371:
16372: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16373: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16374: $possdomains and $possroles are optional array refs -- to domains to check and
16375: roles to check. If $possdomains is not specified, a dump will be done of the
16376: users' roles.db to check for a dc or su role in any domain. This can be
16377: time consuming if &privileged is called repeatedly (e.g., when displaying a
16378: classlist), so in such cases, supplying a $possdomains array is preferred, as
16379: this then allows &privileged_by_domain() to be used, which caches the identity
16380: of privileged users, eliminating the need for repeated calls to &dump().
16381:
16382: =item *
16383:
16384: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16385: where the outer hash keys are domains specified in the $possdomains array ref,
16386: next inner hash keys are privileged roles specified in the $roles array ref,
16387: and the innermost hash contains key = value pairs for username:domain = end:start
16388: for active or future "privileged" users with that role in that domain. To avoid
16389: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16390: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 16391:
1.243 albertel 16392: =back
16393:
16394: =head2 User Modification
16395:
16396: =over 4
16397:
16398: =item *
16399:
1.957 raeburn 16400: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 16401: user for the level given by URL. Optional start and end dates (leave empty
16402: string or zero for "no date")
1.191 harris41 16403:
16404: =item *
16405:
1.243 albertel 16406: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16407: change a users, password, possible return values are: ok,
16408: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16409: refused
1.191 harris41 16410:
16411: =item *
16412:
1.243 albertel 16413: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 16414:
16415: =item *
16416:
1.1058 raeburn 16417: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16418: $forceid,$desiredhome,$email,$inststatus,$candelete) :
16419:
16420: will update user information (firstname,middlename,lastname,generation,
16421: permanentemail), and if forceid is true, student/employee ID also.
16422: A user's institutional affiliation(s) can also be updated.
16423: User information fields will not be overwritten with empty entries
16424: unless the field is included in the $candelete array reference.
16425: This array is included when a single user is modified via "Manage Users",
16426: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 16427:
16428: =item *
16429:
1.286 matthew 16430: modifystudent
16431:
1.957 raeburn 16432: modify a student's enrollment and identification information.
1.1235 raeburn 16433: The course id is resolved based on the current user's environment.
16434: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 16435: associated with a course.
16436:
1.297 matthew 16437: This call is essentially a wrapper for lonnet::modifyuser and
16438: lonnet::modify_student_enrollment
1.286 matthew 16439:
16440: Inputs:
16441:
16442: =over 4
16443:
1.957 raeburn 16444: =item B<$udom> Student's loncapa domain
1.286 matthew 16445:
1.957 raeburn 16446: =item B<$uname> Student's loncapa login name
1.286 matthew 16447:
1.964 bisitz 16448: =item B<$uid> Student/Employee ID
1.286 matthew 16449:
1.957 raeburn 16450: =item B<$umode> Student's authentication mode
1.286 matthew 16451:
1.957 raeburn 16452: =item B<$upass> Student's password
1.286 matthew 16453:
1.957 raeburn 16454: =item B<$first> Student's first name
1.286 matthew 16455:
1.957 raeburn 16456: =item B<$middle> Student's middle name
1.286 matthew 16457:
1.957 raeburn 16458: =item B<$last> Student's last name
1.286 matthew 16459:
1.957 raeburn 16460: =item B<$gene> Student's generation
1.286 matthew 16461:
1.957 raeburn 16462: =item B<$usec> Student's section in course
1.286 matthew 16463:
16464: =item B<$end> Unix time of the roles expiration
16465:
16466: =item B<$start> Unix time of the roles start date
16467:
16468: =item B<$forceid> If defined, allow $uid to be changed
16469:
16470: =item B<$desiredhome> server to use as home server for student
16471:
1.957 raeburn 16472: =item B<$email> Student's permanent e-mail address
16473:
16474: =item B<$type> Type of enrollment (auto or manual)
16475:
1.963 raeburn 16476: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
16477:
16478: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 16479:
1.963 raeburn 16480: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 16481:
1.963 raeburn 16482: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 16483:
1.1216 raeburn 16484: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16485:
16486: =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 16487:
1.286 matthew 16488: =back
1.297 matthew 16489:
16490: =item *
16491:
16492: modify_student_enrollment
16493:
1.1235 raeburn 16494: Change a student's enrollment status in a class. The environment variable
1.297 matthew 16495: 'role.request.course' must be defined for this function to proceed.
16496:
16497: Inputs:
16498:
16499: =over 4
16500:
1.1235 raeburn 16501: =item $udom, student's domain
1.297 matthew 16502:
1.1235 raeburn 16503: =item $uname, student's name
1.297 matthew 16504:
1.1235 raeburn 16505: =item $uid, student's user id
1.297 matthew 16506:
1.1235 raeburn 16507: =item $first, student's first name
1.297 matthew 16508:
16509: =item $middle
16510:
16511: =item $last
16512:
16513: =item $gene
16514:
16515: =item $usec
16516:
16517: =item $end
16518:
16519: =item $start
16520:
1.957 raeburn 16521: =item $type
16522:
16523: =item $locktype
16524:
16525: =item $cid
16526:
16527: =item $selfenroll
16528:
16529: =item $context
16530:
1.1216 raeburn 16531: =item $credits, number of credits student will earn from this class
16532:
1.1314 raeburn 16533: =item $instsec, institutional course section code for student
16534:
1.297 matthew 16535: =back
16536:
1.191 harris41 16537:
16538: =item *
16539:
1.243 albertel 16540: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16541: custom role; give a custom role to a user for the level given by URL. Specify
16542: name and domain of role author, and role name
1.191 harris41 16543:
16544: =item *
16545:
1.243 albertel 16546: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 16547:
16548: =item *
16549:
1.243 albertel 16550: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16551:
16552: =back
16553:
16554: =head2 Course Infomation
16555:
16556: =over 4
1.191 harris41 16557:
16558: =item *
16559:
1.1118 foxr 16560: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 16561: specified course id, including all environment settings for the
16562: course, the description of the course will be in the hash under the
16563: key 'description'
1.191 harris41 16564:
1.1118 foxr 16565: $options is an optional parameter that if supplied is a hash reference that controls
16566: what how this function works. It has the following key/values:
16567:
16568: =over 4
16569:
16570: =item freshen_cache
16571:
16572: If defined, and the environment cache for the course is valid, it is
16573: returned in the returned hash.
16574:
16575: =item one_time
16576:
16577: If defined, the last cache time is set to _now_
16578:
16579: =item user
16580:
16581: If defined, the supplied username is used instead of the current user.
16582:
16583:
16584: =back
16585:
1.191 harris41 16586: =item *
16587:
1.624 albertel 16588: resdata($name,$domain,$type,@which) : request for current parameter
16589: setting for a specific $type, where $type is either 'course' or 'user',
16590: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 16591: answers for 10 minutes.
1.243 albertel 16592:
1.877 foxr 16593: =item *
16594:
16595: get_courseresdata($courseid, $domain) : dump the entire course resource
16596: data base, returning a hash that is keyed by the resource name and has
16597: values that are the resource value. I believe that the timestamps and
16598: versions are also returned.
16599:
1.243 albertel 16600: =back
16601:
16602: =head2 Course Modification
16603:
16604: =over 4
1.191 harris41 16605:
16606: =item *
16607:
1.243 albertel 16608: writecoursepref($courseid,%prefs) : write preferences (environment
16609: database) for a course
1.191 harris41 16610:
16611: =item *
16612:
1.1011 raeburn 16613: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16614:
16615: =item *
16616:
1.1038 raeburn 16617: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 16618:
1.1167 droeschl 16619: =item *
16620:
16621: is_course($courseid), is_course($cdom, $cnum)
16622:
16623: Accepts either a combined $courseid (in the form of domain_courseid) or the
16624: two component version $cdom, $cnum. It checks if the specified course exists.
16625:
16626: Returns:
16627: undef if the course doesn't exist, otherwise
16628: in scalar context the combined courseid.
16629: in list context the two components of the course identifier, domain and
16630: courseid.
16631:
1.243 albertel 16632: =back
16633:
1.1401 raeburn 16634: =head2 Bubblesheet Configuration
16635:
16636: =over 4
16637:
16638: =item *
16639:
16640: get_scantron_config($which)
16641:
16642: $which - the name of the configuration to parse from the file.
16643:
16644: Parses and returns the bubblesheet configuration line selected as a
16645: hash of configuration file fields.
16646:
16647:
16648: Returns:
16649: If the named configuration is not in the file, an empty
16650: hash is returned.
16651:
16652: a hash with the fields
16653: name - internal name for the this configuration setup
16654: description - text to display to operator that describes this config
16655: CODElocation - if 0 or the string 'none'
16656: - no CODE exists for this config
16657: if -1 || the string 'letter'
16658: - a CODE exists for this config and is
16659: a string of letters
16660: Unsupported value (but planned for future support)
16661: if a positive integer
16662: - The CODE exists as the first n items from
16663: the question section of the form
16664: if the string 'number'
16665: - The CODE exists for this config and is
16666: a string of numbers
16667: CODEstart - (only matter if a CODE exists) column in the line where
16668: the CODE starts
16669: CODElength - length of the CODE
16670: IDstart - column where the student/employee ID starts
16671: IDlength - length of the student/employee ID info
16672: Qstart - column where the information from the bubbled
16673: 'questions' start
16674: Qlength - number of columns comprising a single bubble line from
16675: the sheet. (usually either 1 or 10)
16676: Qon - either a single character representing the character used
16677: to signal a bubble was chosen in the positional setup, or
16678: the string 'letter' if the letter of the chosen bubble is
16679: in the final, or 'number' if a number representing the
16680: chosen bubble is in the file (1->A 0->J)
16681: Qoff - the character used to represent that a bubble was
16682: left blank
16683: PaperID - if the scanning process generates a unique number for each
16684: sheet scanned the column that this ID number starts in
16685: PaperIDlength - number of columns that comprise the unique ID number
16686: for the sheet of paper
16687: FirstName - column that the first name starts in
16688: FirstNameLength - number of columns that the first name spans
16689: LastName - column that the last name starts in
16690: LastNameLength - number of columns that the last name spans
16691: BubblesPerRow - number of bubbles available in each row used to
16692: bubble an answer. (If not specified, 10 assumed).
16693:
16694:
16695: =item *
16696:
16697: get_scantronformat_file($cdom)
16698:
16699: $cdom - the course's domain (optional); if not supplied, uses
16700: domain for current $env{'request.course.id'}.
16701:
16702: Returns an array containing lines from the scantron format file for
16703: the domain of the course.
16704:
16705: If a url for a custom.tab file is listed in domain's configuration.db,
16706: lines are from this file.
16707:
16708: Otherwise, if a default.tab has been published in RES space by the
16709: domainconfig user, lines are from this file.
16710:
16711: Otherwise, fall back to getting lines from the legacy file on the
16712: local server: /home/httpd/lonTabs/default_scantronformat.tab
16713:
16714: =back
16715:
1.243 albertel 16716: =head2 Resource Subroutines
16717:
16718: =over 4
1.191 harris41 16719:
16720: =item *
16721:
1.243 albertel 16722: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 16723:
16724: =item *
16725:
1.243 albertel 16726: repcopy($filename) : subscribes to the requested file, and attempts to
16727: replicate from the owning library server, Might return
1.607 raeburn 16728: 'unavailable', 'not_found', 'forbidden', 'ok', or
16729: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 16730: resource. Expects the local filesystem pathname
16731: (/home/httpd/html/res/....)
16732:
16733: =back
16734:
16735: =head2 Resource Information
16736:
16737: =over 4
1.191 harris41 16738:
16739: =item *
16740:
1.1228 raeburn 16741: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
16742: and returns the value of a variety of different possible values,
16743: $varname should be a request string, and the other parameters can be
16744: used to specify who and what one is asking about. Ordinarily, $cid
16745: does not need to be specified, as it is retrived from
16746: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16747: within lonuserstate::loadmap() when initializing a course, before
16748: $env{'request.course.id'} has been set, so it needs to be provided
16749: in that one case.
1.243 albertel 16750:
16751: Possible values for $varname are environment.lastname (or other item
16752: from the envirnment hash), user.name (or someother aspect about the
16753: user), resource.0.maxtries (or some other part and parameter of a
16754: resource)
1.204 albertel 16755:
16756: =item *
16757:
1.243 albertel 16758: directcondval($number) : get current value of a condition; reads from a state
16759: string
1.204 albertel 16760:
16761: =item *
16762:
1.243 albertel 16763: condval($condidx) : value of condition index based on state
1.204 albertel 16764:
16765: =item *
16766:
1.1362 raeburn 16767: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243 albertel 16768: resource's metadata, $what should be either a specific key, or either
16769: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362 raeburn 16770: packages that this resource currently uses, the last 3 arguments are
16771: only used internally for recursive metadata.
16772:
16773: the toolsymb is only used where the uri is for an external tool (for which
16774: the uri as well as the symb are guaranteed to be unique).
1.243 albertel 16775:
1.1371 raeburn 16776: this function automatically caches all requests except any made recursively
16777: to retrieve a list of metadata keys for an imported library file ($liburi is
16778: defined).
1.191 harris41 16779:
16780: =item *
16781:
1.243 albertel 16782: metadata_query($query,$custom,$customshow) : make a metadata query against the
16783: network of library servers; returns file handle of where SQL and regex results
16784: will be stored for query
1.191 harris41 16785:
16786: =item *
16787:
1.1282 raeburn 16788: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
16789: return symbolic list entry (all arguments optional).
16790:
16791: Args: filename is the filename (including path) for the file for which a symb
16792: is required; donotrecurse, if true will prevent calls to allowed() being made
16793: to check access status if more than one resource was found in the bighash
16794: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
16795: a randompick); ignorecachednull, if true will prevent a symb of '' being
16796: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16797: cause possible symbs to be checked to determine if they are subject to content
16798: blocking, if so they will not be included as possible symbs; possibles is a
16799: ref to a hash, which, as a side effect, will be populated with all possible
16800: symbs (content blocking not tested).
16801:
1.243 albertel 16802: returns the data handle
1.191 harris41 16803:
16804: =item *
16805:
1.1190 raeburn 16806: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16807: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 16808: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 16809: on failure, user must be in a course, as it assumes the existence of
16810: the course initial hash, and uses $env('request.course.id'}. The third
16811: arg is an optional reference to a scalar. If this arg is passed in the
16812: call to symbverify, it will be set to 1 if the symb has been set to be
16813: encrypted; otherwise it will be null.
1.191 harris41 16814:
16815: =item *
16816:
1.243 albertel 16817: symbclean($symb) : removes versions numbers from a symb, returns the
16818: cleaned symb
1.191 harris41 16819:
16820: =item *
16821:
1.243 albertel 16822: is_on_map($uri) : checks if the $uri is somewhere on the current
16823: course map, user must be in a course for it to work.
1.191 harris41 16824:
16825: =item *
16826:
1.243 albertel 16827: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 16828:
16829: =item *
16830:
1.243 albertel 16831: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16832: a random seed, all arguments are optional, if they aren't sent it uses the
16833: environment to derive them. Note: if symb isn't sent and it can't get one
16834: from &symbread it will use the current time as its return value
1.191 harris41 16835:
16836: =item *
16837:
1.243 albertel 16838: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16839: unfakeable, receipt
1.191 harris41 16840:
16841: =item *
16842:
1.620 albertel 16843: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 16844:
16845: =item *
16846:
1.243 albertel 16847: countacc($url) : count the number of accesses to a given URL
1.191 harris41 16848:
16849: =item *
16850:
1.243 albertel 16851: 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 16852:
16853: =item *
16854:
1.243 albertel 16855: 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 16856:
16857: =item *
16858:
1.243 albertel 16859: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 16860:
16861: =item *
16862:
1.243 albertel 16863: devalidate($symb) : devalidate temporary spreadsheet calculations,
16864: forcing spreadsheet to reevaluate the resource scores next time.
16865:
1.1195 raeburn 16866: =item *
16867:
1.1196 raeburn 16868: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16869: when viewing in course context.
1.1195 raeburn 16870:
1.1196 raeburn 16871: input: six args -- filename (decluttered), course number, course domain,
16872: url, symb (if registered) and group (if this is a
16873: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 16874:
1.1196 raeburn 16875: output: array of five scalars --
1.1195 raeburn 16876: $cfile -- url for file editing if editable on current server
16877: $home -- homeserver of resource (i.e., for author if published,
16878: or course if uploaded.).
16879: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 16880: $forceedit -- 1 if icon/link should be to go to edit mode
16881: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 16882:
16883: =item *
16884:
16885: is_course_upload($file,$cnum,$cdom)
16886:
16887: Used in course context to determine if current file was uploaded to
16888: the course (i.e., would be found in /userfiles/docs on the course's
16889: homeserver.
16890:
16891: input: 3 args -- filename (decluttered), course number and course domain.
16892: output: boolean -- 1 if file was uploaded.
16893:
1.243 albertel 16894: =back
16895:
16896: =head2 Storing/Retreiving Data
16897:
16898: =over 4
1.191 harris41 16899:
16900: =item *
16901:
1.1269 raeburn 16902: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16903: permanently for this url; hashref needs to be given and should be a \%hashname;
16904: the remaining args aren't required and if they aren't passed or are '' they will
16905: be derived from the env (with the exception of $laststore, which is an
16906: optional arg used when a user's submission is stored in grading).
16907: $laststore is $version=$timestamp, where $version is the most recent version
16908: number retrieved for the corresponding $symb in the $namespace db file, and
16909: $timestamp is the timestamp for that transaction (UNIX time).
16910: $laststore is currently only passed when cstore() is called by
16911: structuretags::finalize_storage().
1.191 harris41 16912:
16913: =item *
16914:
1.1269 raeburn 16915: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16916: but uses critical subroutine
1.191 harris41 16917:
16918: =item *
16919:
1.243 albertel 16920: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16921: all args are optional
1.191 harris41 16922:
16923: =item *
16924:
1.717 albertel 16925: dumpstore($namespace,$udom,$uname,$regexp,$range) :
16926: dumps the complete (or key matching regexp) namespace into a hash
16927: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16928: normally &store()ed into
16929:
16930: $range should be either an integer '100' (give me the first 100
16931: matching records)
16932: or be two integers sperated by a - with no spaces
16933: '30-50' (give me the 30th through the 50th matching
16934: records)
16935:
16936:
16937: =item *
16938:
1.1269 raeburn 16939: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 16940: replaces a &store() version of data with a replacement set of data
16941: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 16942: reference. If $tolog is true, the transaction is logged in the courselog
16943: with an action=PUTSTORE.
1.717 albertel 16944:
16945: =item *
16946:
1.243 albertel 16947: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16948: works very similar to store/cstore, but all data is stored in a
16949: temporary location and can be reset using tmpreset, $storehash should
16950: be a hash reference, returns nothing on success
1.191 harris41 16951:
16952: =item *
16953:
1.243 albertel 16954: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16955: similar to restore, but all data is stored in a temporary location and
16956: can be reset using tmpreset. Returns a hash of values on success,
16957: error string otherwise.
1.191 harris41 16958:
16959: =item *
16960:
1.243 albertel 16961: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16962: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 16963:
16964: =item *
16965:
1.243 albertel 16966: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16967: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 16968:
16969: =item *
16970:
1.243 albertel 16971: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16972: namesp ($udom and $uname are optional)
1.191 harris41 16973:
16974: =item *
16975:
1.702 albertel 16976: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 16977: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 16978: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 16979:
1.702 albertel 16980: $range should be either an integer '100' (give me the first 100
16981: matching records)
16982: or be two integers sperated by a - with no spaces
16983: '30-50' (give me the 30th through the 50th matching
16984: records)
1.449 matthew 16985: =item *
16986:
16987: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16988: $store can be a scalar, an array reference, or if the amount to be
16989: incremented is > 1, a hash reference.
16990:
16991: ($udom and $uname are optional)
1.191 harris41 16992:
16993: =item *
16994:
1.243 albertel 16995: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16996: ($udom and $uname are optional)
1.191 harris41 16997:
16998: =item *
16999:
1.243 albertel 17000: cput($namespace,$storehash,$udom,$uname) : critical put
17001: ($udom and $uname are optional)
1.191 harris41 17002:
17003: =item *
17004:
1.748 albertel 17005: newput($namespace,$storehash,$udom,$uname) :
17006:
17007: Attempts to store the items in the $storehash, but only if they don't
17008: currently exist, if this succeeds you can be certain that you have
17009: successfully created a new key value pair in the $namespace db.
17010:
17011:
17012: Args:
17013: $namespace: name of database to store values to
17014: $storehash: hashref to store to the db
17015: $udom: (optional) domain of user containing the db
17016: $uname: (optional) name of user caontaining the db
17017:
17018: Returns:
17019: 'ok' -> succeeded in storing all keys of $storehash
17020: 'key_exists: <key>' -> failed to anything out of $storehash, as at
17021: least <key> already existed in the db (other
17022: requested keys may also already exist)
1.967 bisitz 17023: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 17024: 'con_lost' -> unable to contact request server
17025: 'refused' -> action was not allowed by remote machine
17026:
17027:
17028: =item *
17029:
1.243 albertel 17030: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17031: reference filled in from namesp (encrypts the return communication)
17032: ($udom and $uname are optional)
1.191 harris41 17033:
17034: =item *
17035:
1.243 albertel 17036: log($udom,$name,$home,$message) : write to permanent log for user; use
17037: critical subroutine
17038:
1.806 raeburn 17039: =item *
17040:
1.860 raeburn 17041: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17042: array reference filled in from namespace found in domain level on either
17043: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 17044:
17045: =item *
17046:
1.860 raeburn 17047: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
17048: domain level either on specified domain server ($uhome) or primary domain
17049: server ($udom and $uhome are optional)
1.806 raeburn 17050:
1.943 raeburn 17051: =item *
17052:
1.1240 raeburn 17053: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
17054: for: authentication, language, quotas, timezone, date locale, and portal URL in
17055: the target domain.
17056:
17057: May also include additional key => value pairs for the following groups:
17058:
17059: =over
17060:
17061: =item
17062: disk quotas (MB allocated by default to portfolios and authoring spaces).
17063:
17064: =over
17065:
17066: =item defaultquota, authorquota
17067:
17068: =back
17069:
17070: =item
17071: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17072: portfolio for users).
17073:
17074: =over
17075:
17076: =item
17077: aboutme, blog, webdav, portfolio
17078:
17079: =back
17080:
17081: =item
17082: requestcourses: ability to request courses, and how requests are processed.
17083:
17084: =over
17085:
17086: =item
1.1305 raeburn 17087: official, unofficial, community, textbook, placement
1.1240 raeburn 17088:
17089: =back
17090:
17091: =item
17092: inststatus: types of institutional affiliation, and order in which they are displayed.
17093:
17094: =over
17095:
17096: =item
1.1256 raeburn 17097: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 17098:
17099: =back
17100:
17101: =item
17102: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17103: for course's uploaded content.
17104:
17105: =over
17106:
17107: =item
1.1246 raeburn 17108: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 17109: communityquota, textbookquota, placementquota
1.1240 raeburn 17110:
17111: =back
17112:
17113: =item
17114: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17115: on your servers.
17116:
17117: =over
17118:
17119: =item
17120: remotesessions, hostedsessions
17121:
17122: =back
17123:
17124: =back
17125:
17126: In cases where a domain coordinator has never used the "Set Domain Configuration"
17127: utility to create a configuration.db file on a domain's primary library server
17128: only the following domain defaults: auth_def, auth_arg_def, lang_def
17129: -- corresponding values are authentication type (internal, krb4, krb5,
17130: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
17131: will be available. Values are retrieved from cache (if current), unless the
17132: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17133: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17134:
17135: Typical usage:
1.943 raeburn 17136:
1.1240 raeburn 17137: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 17138:
1.243 albertel 17139: =back
17140:
17141: =head2 Network Status Functions
17142:
17143: =over 4
1.191 harris41 17144:
17145: =item *
17146:
1.1137 raeburn 17147: dirlist() : return directory list based on URI (first arg).
17148:
17149: Inputs: 1 required, 5 optional.
17150:
17151: =over
17152:
17153: =item
17154: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17155:
17156: =item
17157: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
17158:
17159: =item
17160: $username - username of user/course to be listed. Extracted from $uri if absent.
17161:
17162: =item
17163: $getpropath - boolean: 1 if prepend path using &propath().
17164:
17165: =item
17166: $getuserdir - boolean: 1 if prepend path for "userfiles".
17167:
17168: =item
17169: $alternateRoot - path to prepend in place of path from $uri.
17170:
17171: =back
17172:
17173: Returns: Array of up to two items.
17174:
17175: =over
17176:
17177: a reference to an array of files/subdirectories
17178:
17179: =over
17180:
17181: Each element in the array of files/subdirectories is a & separated list of
17182: item name and the result of running stat on the item. If dirlist was requested
17183: for a file instead of a directory, the item name will be ''. For a directory
17184: listing, if the item is a metadata file, the element will end &N&M
17185: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17186: default copyright set (1).
17187:
17188: =back
17189:
17190: a scalar containing error condition (if encountered).
17191:
17192: =over
17193:
17194: =item
17195: no_host (no homeserver identified for $username:$domain).
17196:
17197: =item
17198: no_such_host (server contacted for listing not identified as valid host).
17199:
17200: =item
17201: con_lost (connection to remote server failed).
17202:
17203: =item
17204: refused (invalid $username:$domain received on lond side).
17205:
17206: =item
17207: no_such_dir (directory at specified path on lond side does not exist).
17208:
17209: =item
17210: empty (directory at specified path on lond side is empty).
17211:
17212: =over
17213:
17214: This is currently not encountered because the &ls3, &ls2,
17215: &ls (_handler) routines on the lond side do not filter out
17216: . and .. from a directory listing.
17217:
17218: =back
17219:
17220: =back
17221:
17222: =back
1.191 harris41 17223:
17224: =item *
17225:
1.243 albertel 17226: spareserver() : find server with least workload from spare.tab
17227:
1.986 foxr 17228:
17229: =item *
17230:
17231: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17232: if there is no corresponding loncapa host.
17233:
1.243 albertel 17234: =back
17235:
1.986 foxr 17236:
1.243 albertel 17237: =head2 Apache Request
17238:
17239: =over 4
1.191 harris41 17240:
17241: =item *
17242:
1.243 albertel 17243: ssi($url,%hash) : server side include, does a complete request cycle on url to
17244: localhost, posts hash
17245:
17246: =back
17247:
17248: =head2 Data to String to Data
17249:
17250: =over 4
1.191 harris41 17251:
17252: =item *
17253:
1.243 albertel 17254: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17255: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 17256:
17257: =item *
17258:
1.243 albertel 17259: hashref2str($hashref) : convert a hashref into a string complete with
17260: escaping and '=' and '&' separators, supports elements that are
17261: arrayrefs and hashrefs
1.191 harris41 17262:
17263: =item *
17264:
1.243 albertel 17265: arrayref2str($arrayref) : convert an arrayref into a string complete
17266: with escaping and '&' separators, supports elements that are arrayrefs
17267: and hashrefs
1.191 harris41 17268:
17269: =item *
17270:
1.243 albertel 17271: str2hash($string) : convert string to hash using unescaping and
17272: splitting on '=' and '&', supports elements that are arrayrefs and
17273: hashrefs
1.191 harris41 17274:
17275: =item *
17276:
1.243 albertel 17277: str2array($string) : convert string to hash using unescaping and
17278: splitting on '&', supports elements that are arrayrefs and hashrefs
17279:
17280: =back
17281:
17282: =head2 Logging Routines
17283:
17284:
17285: These routines allow one to make log messages in the lonnet.log and
17286: lonnet.perm logfiles.
1.191 harris41 17287:
1.1119 foxr 17288: =over 4
17289:
1.191 harris41 17290: =item *
17291:
1.243 albertel 17292: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 17293:
17294: =item *
17295:
1.243 albertel 17296: logthis() : append message to the normal lonnet.log file, it gets
17297: preiodically rolled over and deleted.
1.191 harris41 17298:
17299: =item *
17300:
1.243 albertel 17301: logperm() : append a permanent message to lonnet.perm.log, this log
17302: file never gets deleted by any automated portion of the system, only
17303: messages of critical importance should go in here.
17304:
1.1119 foxr 17305:
1.243 albertel 17306: =back
17307:
17308: =head2 General File Helper Routines
17309:
17310: =over 4
1.191 harris41 17311:
17312: =item *
17313:
1.481 raeburn 17314: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17315: (a) files in /uploaded
17316: (i) If a local copy of the file exists -
17317: compares modification date of local copy with last-modified date for
17318: definitive version stored on home server for course. If local copy is
17319: stale, requests a new version from the home server and stores it.
17320: If the original has been removed from the home server, then local copy
17321: is unlinked.
17322: (ii) If local copy does not exist -
17323: requests the file from the home server and stores it.
17324:
17325: If $caller is 'uploadrep':
17326: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17327: for request for files originally uploaded via DOCS.
17328: - returns 'ok' if fresh local copy now available, -1 otherwise.
17329:
17330: Otherwise:
17331: This indicates a call from the content generation phase of the request.
17332: - returns the entire contents of the file or -1.
17333:
17334: (b) files in /res
17335: - returns the entire contents of a file or -1;
17336: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 17337:
1.712 albertel 17338:
17339: =item *
17340:
17341: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17342: reference
17343:
17344: returns either a stat() list of data about the file or an empty list
17345: if the file doesn't exist or couldn't find out about it (connection
17346: problems or user unknown)
17347:
1.191 harris41 17348: =item *
17349:
1.243 albertel 17350: filelocation($dir,$file) : returns file system location of a file
17351: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17352: directory that relative $file lookups are to looked in ($dir of /a/dir
17353: and a file of ../bob will become /a/bob)
1.191 harris41 17354:
17355: =item *
17356:
17357: hreflocation($dir,$file) : returns file system location or a URL; same as
17358: filelocation except for hrefs
17359:
17360: =item *
17361:
1.1261 raeburn 17362: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17363: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 17364:
1.243 albertel 17365: =back
17366:
1.608 albertel 17367: =head2 Usererfile file routines (/uploaded*)
17368:
17369: =over 4
17370:
17371: =item *
17372:
17373: userfileupload(): main rotine for putting a file in a user or course's
17374: filespace, arguments are,
17375:
1.620 albertel 17376: formname - required - this is the name of the element in $env where the
1.608 albertel 17377: filename, and the contents of the file to create/modifed exist
1.620 albertel 17378: the filename is in $env{'form.'.$formname.'.filename'} and the
17379: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 17380: context - if coursedoc, store the file in the course of the active role
17381: of the current user;
17382: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17383: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 17384: subdir - required - subdirectory to put the file in under ../userfiles/
17385: if undefined, it will be placed in "unknown"
17386:
17387: (This routine calls clean_filename() to remove any dangerous
17388: characters from the filename, and then calls finuserfileupload() to
17389: complete the transaction)
17390:
17391: returns either the url of the uploaded file (/uploaded/....) if successful
17392: and /adm/notfound.html if unsuccessful
17393:
17394: =item *
17395:
17396: clean_filename(): routine for cleaing a filename up for storage in
17397: userfile space, argument is:
17398:
17399: filename - proposed filename
17400:
17401: returns: the new clean filename
17402:
17403: =item *
17404:
1.1090 raeburn 17405: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 17406: userspace, probably shouldn't be called directly
17407:
17408: docuname: username or courseid of destination for the file
17409: docudom: domain of user/course of destination for the file
17410: formname: same as for userfileupload()
1.1090 raeburn 17411: fname: filename (including subdirectories) for the file
17412: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401 raeburn 17413: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 17414: allfiles: reference to hash used to store objects found by parser
17415: codebase: reference to hash used for codebases of java objects found by parser
17416: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17417: thumbheight: height (pixels) of thumbnail to be created for uploaded image
17418: resizewidth: width to be used to resize image using resizeImage from ImageMagick
17419: resizeheight: height to be used to resize image using resizeImage from ImageMagick
17420: context: if 'overwrite', will move the uploaded file from its temporary location to
17421: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 17422: mimetype: reference to scalar to accommodate mime type determined
17423: from File::MMagic if $parser = parse.
1.608 albertel 17424:
17425: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 17426: and /adm/notfound.html if unsuccessful (or an error message if context
17427: was 'overwrite').
17428:
1.608 albertel 17429:
17430: =item *
17431:
17432: renameuserfile(): renames an existing userfile to a new name
17433:
17434: Args:
17435: docuname: username or courseid of destination for the file
17436: docudom: domain of user/course of destination for the file
17437: old: current file name (including any subdirs under userfiles)
17438: new: desired file name (including any subdirs under userfiles)
17439:
17440: =item *
17441:
17442: mkdiruserfile(): creates a directory is a userfiles dir
17443:
17444: Args:
17445: docuname: username or courseid of destination for the file
17446: docudom: domain of user/course of destination for the file
17447: dir: dir to create (including any subdirs under userfiles)
17448:
17449: =item *
17450:
17451: removeuserfile(): removes a file that exists in userfiles
17452:
17453: Args:
17454: docuname: username or courseid of destination for the file
17455: docudom: domain of user/course of destination for the file
17456: fname: filname to delete (including any subdirs under userfiles)
17457:
17458: =item *
17459:
17460: removeuploadedurl(): convience function for removeuserfile()
17461:
17462: Args:
17463: url: a full /uploaded/... url to delete
17464:
1.747 albertel 17465: =item *
17466:
17467: get_portfile_permissions():
17468: Args:
17469: domain: domain of user or course contain the portfolio files
17470: user: name of user or num of course contain the portfolio files
17471: Returns:
17472: hashref of a dump of the proper file_permissions.db
17473:
17474:
17475: =item *
17476:
17477: get_access_controls():
17478:
17479: Args:
17480: current_permissions: the hash ref returned from get_portfile_permissions()
17481: group: (optional) the group you want the files associated with
17482: file: (optional) the file you want access info on
17483:
17484: Returns:
1.749 raeburn 17485: a hash (keys are file names) of hashes containing
17486: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17487: values are XML containing access control settings (see below)
1.747 albertel 17488:
17489: Internal notes:
17490:
1.749 raeburn 17491: access controls are stored in file_permissions.db as key=value pairs.
17492: key -> path to file/file_name\0uniqueID:scope_end_start
17493: where scope -> public,guest,course,group,domains or users.
17494: end -> UNIX time for end of access (0 -> no end date)
17495: start -> UNIX time for start of access
17496:
17497: value -> XML description of access control
17498: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17499: <start></start>
17500: <end></end>
17501:
17502: <password></password> for scope type = guest
17503:
17504: <domain></domain> for scope type = course or group
17505: <number></number>
17506: <roles id="">
17507: <role></role>
17508: <access></access>
17509: <section></section>
17510: <group></group>
17511: </roles>
17512:
17513: <dom></dom> for scope type = domains
17514:
17515: <users> for scope type = users
17516: <user>
17517: <uname></uname>
17518: <udom></udom>
17519: </user>
17520: </users>
17521: </scope>
17522:
17523: Access data is also aggregated for each file in an additional key=value pair:
17524: key -> path to file/file_name\0accesscontrol
17525: value -> reference to hash
17526: hash contains key = value pairs
17527: where key = uniqueID:scope_end_start
17528: value = UNIX time record was last updated
17529:
17530: Used to improve speed of look-ups of access controls for each file.
17531:
17532: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17533:
1.1198 raeburn 17534: =item *
17535:
1.749 raeburn 17536: modify_access_controls():
17537:
17538: Modifies access controls for a portfolio file
17539: Args
17540: 1. file name
17541: 2. reference to hash of required changes,
17542: 3. domain
17543: 4. username
17544: where domain,username are the domain of the portfolio owner
17545: (either a user or a course)
17546:
17547: Returns:
17548: 1. result of additions or updates ('ok' or 'error', with error message).
17549: 2. result of deletions ('ok' or 'error', with error message).
17550: 3. reference to hash of any new or updated access controls.
17551: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17552: key = integer (inbound ID)
1.1198 raeburn 17553: value = uniqueID
17554:
17555: =item *
17556:
17557: get_timebased_id():
17558:
17559: Attempts to get a unique timestamp-based suffix for use with items added to a
17560: course via the Course Editor (e.g., folders, composite pages,
17561: group bulletin boards).
17562:
17563: Args: (first three required; six others optional)
17564:
17565: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17566: docssequence, or name of group
17567:
17568: 2. keyid (alphanumeric): name of temporary locking key in hash,
17569: e.g., num, boardids
17570:
17571: 3. namespace: name of gdbm file used to store suffixes already assigned;
17572: file will be named nohist_namespace.db
17573:
17574: 4. cdom: domain of course; default is current course domain from %env
17575:
17576: 5. cnum: course number; default is current course number from %env
17577:
17578: 6. idtype: set to concat if an additional digit is to be appended to the
17579: unix timestamp to form the suffix, if the plain timestamp is already
17580: in use. Default is to not do this, but simply increment the unix
17581: timestamp by 1 until a unique key is obtained.
17582:
17583: 7. who: holder of locking key; defaults to user:domain for user.
17584:
17585: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
17586: retrying); default is 3.
17587:
17588: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
17589:
17590: Returns:
17591:
17592: 1. suffix obtained (numeric)
17593:
17594: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17595:
17596: 3. error: contains (localized) error message if an error occurred.
17597:
1.747 albertel 17598:
1.608 albertel 17599: =back
17600:
1.243 albertel 17601: =head2 HTTP Helper Routines
17602:
17603: =over 4
17604:
1.191 harris41 17605: =item *
17606:
17607: escape() : unpack non-word characters into CGI-compatible hex codes
17608:
17609: =item *
17610:
17611: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17612:
1.243 albertel 17613: =back
17614:
17615: =head1 PRIVATE SUBROUTINES
17616:
17617: =head2 Underlying communication routines (Shouldn't call)
17618:
17619: =over 4
17620:
17621: =item *
17622:
17623: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17624:
17625: =item *
17626:
17627: reply() : uses subreply to send a message to remote machine, logs all failures
17628:
17629: =item *
17630:
17631: critical() : passes a critical message to another server; if cannot
17632: get through then place message in connection buffer directory and
17633: returns con_delayed, if incapable of saving message, returns
17634: con_failed
17635:
17636: =item *
17637:
17638: reconlonc() : tries to reconnect lonc client processes.
17639:
17640: =back
17641:
17642: =head2 Resource Access Logging
17643:
17644: =over 4
17645:
17646: =item *
17647:
17648: flushcourselogs() : flush (save) buffer logs and access logs
17649:
17650: =item *
17651:
17652: courselog($what) : save message for course in hash
17653:
17654: =item *
17655:
17656: courseacclog($what) : save message for course using &courselog(). Perform
17657: special processing for specific resource types (problems, exams, quizzes, etc).
17658:
1.191 harris41 17659: =item *
17660:
17661: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17662: as a PerlChildExitHandler
1.243 albertel 17663:
17664: =back
17665:
17666: =head2 Other
17667:
17668: =over 4
17669:
17670: =item *
17671:
17672: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 17673:
17674: =back
17675:
17676: =cut
1.877 foxr 17677:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>