Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1483
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1483 ! raeburn 4: # $Id: lonnet.pm,v 1.1482 2022/02/16 00:06:12 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 '')) {
988: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
989: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
990: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
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.1451 raeburn 1026: my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
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 =
1214: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
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);
1326: if (!$uhome) {
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");
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.1073 raeburn 1381: sub can_host_session {
1.1074 raeburn 1382: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1383: my $canhost = 1;
1.1074 raeburn 1384: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1385: if (ref($remotesessions) eq 'HASH') {
1386: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1387: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1388: $canhost = 0;
1389: } else {
1390: $canhost = 1;
1391: }
1392: }
1393: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1394: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1395: $canhost = 1;
1396: } else {
1397: $canhost = 0;
1398: }
1399: }
1400: if ($canhost) {
1401: if ($remotesessions->{'version'} ne '') {
1402: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1403: if ($reqmajor ne '' && $reqminor ne '') {
1404: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1405: my $major = $1;
1406: my $minor = $2;
1407: if (($major < $reqmajor ) ||
1408: (($major == $reqmajor) && ($minor < $reqminor))) {
1409: $canhost = 0;
1410: }
1411: } else {
1412: $canhost = 0;
1413: }
1414: }
1415: }
1416: }
1417: }
1418: if ($canhost) {
1419: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1420: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1421: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1422: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1423: if (($uint_dom ne '') &&
1424: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1425: $canhost = 0;
1426: } else {
1427: $canhost = 1;
1428: }
1429: }
1430: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1431: if (($uint_dom ne '') &&
1432: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1433: $canhost = 1;
1434: } else {
1435: $canhost = 0;
1436: }
1437: }
1438: }
1439: }
1440: return $canhost;
1441: }
1442:
1.1083 raeburn 1443: sub spare_can_host {
1444: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1445: my $canhost=1;
1.1279 raeburn 1446: my $try_server_hostname = &hostname($try_server);
1447: my $serverhomeID = &get_server_homeID($try_server_hostname);
1448: my $serverhomedom = &host_domain($serverhomeID);
1449: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1450: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1451: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1452: $canhost = 0;
1453: }
1454: }
1.1439 raeburn 1455: if ($canhost) {
1456: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1457: if ($defdomdefaults{'offloadoth'}{$try_server}) {
1458: unless (&shared_institution($udom,$try_server)) {
1459: $canhost = 0;
1460: }
1461: }
1462: }
1463: }
1.1279 raeburn 1464: if (($canhost) && ($uint_dom)) {
1465: my @intdoms;
1466: my $internet_names = &get_internet_names($try_server);
1467: if (ref($internet_names) eq 'ARRAY') {
1468: @intdoms = @{$internet_names};
1469: }
1470: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1471: my $remoterev = &get_server_loncaparev(undef,$try_server);
1472: $canhost = &can_host_session($udom,$try_server,$remoterev,
1473: $remotesessions,
1474: $defdomdefaults{'hostedsessions'});
1475: }
1.1083 raeburn 1476: }
1477: return $canhost;
1478: }
1479:
1.1123 raeburn 1480: sub this_host_spares {
1481: my ($dom) = @_;
1.1126 raeburn 1482: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1483: my @hosts = ¤t_machine_ids();
1484: foreach my $lonhost (@hosts) {
1485: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1486: $dom_in_use = $dom;
1487: $lonhost_in_use = $lonhost;
1.1123 raeburn 1488: last;
1489: }
1490: }
1.1126 raeburn 1491: if ($dom_in_use ne '') {
1492: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1493: }
1494: if (ref($result) ne 'HASH') {
1495: $lonhost_in_use = $perlvar{'lonHostID'};
1496: $dom_in_use = &host_domain($lonhost_in_use);
1497: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1498: if (ref($result) ne 'HASH') {
1499: $result = \%spareid;
1500: }
1501: }
1502: return $result;
1503: }
1504:
1505: sub spares_for_offload {
1506: my ($dom_in_use,$lonhost_in_use) = @_;
1507: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1508: if (defined($cached)) {
1509: return $result;
1510: } else {
1.1126 raeburn 1511: my $cachetime = 60*60*24;
1512: my %domconfig =
1513: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1514: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1515: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1516: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1517: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1518: }
1519: }
1520: }
1521: }
1.1126 raeburn 1522: return;
1.1123 raeburn 1523: }
1524:
1.1129 raeburn 1525: sub get_lonbalancer_config {
1526: my ($servers) = @_;
1527: my ($currbalancer,$currtargets);
1528: if (ref($servers) eq 'HASH') {
1529: foreach my $server (keys(%{$servers})) {
1530: my %what = (
1531: spareid => 1,
1532: perlvar => 1,
1533: );
1534: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1535: if ($result eq 'ok') {
1536: if (ref($returnhash) eq 'HASH') {
1537: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1538: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1539: $currbalancer = $server;
1540: $currtargets = {};
1541: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1542: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1543: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1544: }
1545: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1546: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1547: }
1548: }
1549: last;
1550: }
1551: }
1552: }
1553: }
1554: }
1555: }
1556: return ($currbalancer,$currtargets);
1557: }
1558:
1559: sub check_loadbalancing {
1.1331 raeburn 1560: my ($uname,$udom,$caller) = @_;
1.1191 raeburn 1561: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391 raeburn 1562: $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129 raeburn 1563: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1564: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1565: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1566: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1567: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1568: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1569: my $domneedscache;
1.1129 raeburn 1570: my $cachetime = 60*60*24;
1571:
1572: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1573: $dom_in_use = $udom;
1574: $homeintdom = 1;
1575: } else {
1576: $dom_in_use = $serverhomedom;
1577: }
1578: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1579: unless (defined($cached)) {
1580: my %domconfig =
1581: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1582: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1583: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1584: } else {
1585: $domneedscache = $dom_in_use;
1.1129 raeburn 1586: }
1587: }
1588: if (ref($result) eq 'HASH') {
1.1391 raeburn 1589: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1590: &check_balancer_result($result,@hosts);
1.1129 raeburn 1591: if ($is_balancer) {
1592: if (ref($currrules) eq 'HASH') {
1593: if ($homeintdom) {
1594: if ($uname ne '') {
1595: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1596: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1597: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1598: $rule_in_effect = $currrules->{'_LC_author'};
1599: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1600: $rule_in_effect = $currrules->{'_LC_adv'}
1601: }
1602: }
1603: if ($rule_in_effect eq '') {
1604: my %userenv = &userenvironment($udom,$uname,'inststatus');
1605: if ($userenv{'inststatus'} ne '') {
1606: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1607: my ($othertitle,$usertypes,$types) =
1608: &Apache::loncommon::sorted_inst_types($udom);
1609: if (ref($types) eq 'ARRAY') {
1610: foreach my $type (@{$types}) {
1611: if (grep(/^\Q$type\E$/,@statuses)) {
1612: if (exists($currrules->{$type})) {
1613: $rule_in_effect = $currrules->{$type};
1614: }
1615: }
1616: }
1617: }
1618: } else {
1619: if (exists($currrules->{'default'})) {
1620: $rule_in_effect = $currrules->{'default'};
1621: }
1622: }
1623: }
1624: } else {
1625: if (exists($currrules->{'default'})) {
1626: $rule_in_effect = $currrules->{'default'};
1627: }
1628: }
1629: } else {
1630: if ($currrules->{'_LC_external'} ne '') {
1631: $rule_in_effect = $currrules->{'_LC_external'};
1632: }
1633: }
1634: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1635: $uname,$udom);
1636: }
1637: }
1638: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1639: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1640: unless (defined($cached)) {
1641: my %domconfig =
1642: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1643: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1644: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1645: } else {
1646: $domneedscache = $serverhomedom;
1.1129 raeburn 1647: }
1648: }
1649: if (ref($result) eq 'HASH') {
1.1391 raeburn 1650: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1651: &check_balancer_result($result,@hosts);
1652: if ($is_balancer) {
1.1129 raeburn 1653: if (ref($currrules) eq 'HASH') {
1654: if ($currrules->{'_LC_internetdom'} ne '') {
1655: $rule_in_effect = $currrules->{'_LC_internetdom'};
1656: }
1657: }
1658: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1659: $uname,$udom);
1660: }
1661: } else {
1662: if ($perlvar{'lonBalancer'} eq 'yes') {
1663: $is_balancer = 1;
1664: $offloadto = &this_host_spares($dom_in_use);
1665: }
1.1307 raeburn 1666: unless (defined($cached)) {
1667: $domneedscache = $serverhomedom;
1668: }
1.1129 raeburn 1669: }
1670: } else {
1671: if ($perlvar{'lonBalancer'} eq 'yes') {
1672: $is_balancer = 1;
1673: $offloadto = &this_host_spares($dom_in_use);
1674: }
1.1307 raeburn 1675: unless (defined($cached)) {
1676: $domneedscache = $serverhomedom;
1677: }
1678: }
1679: if ($domneedscache) {
1680: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1681: }
1.1430 raeburn 1682: if (($is_balancer) && ($caller ne 'switchserver')) {
1.1176 raeburn 1683: my $lowest_load = 30000;
1684: if (ref($offloadto) eq 'HASH') {
1685: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1686: foreach my $try_server (@{$offloadto->{'primary'}}) {
1687: ($otherserver,$lowest_load) =
1688: &compare_server_load($try_server,$otherserver,$lowest_load);
1689: }
1.1129 raeburn 1690: }
1.1176 raeburn 1691: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1692:
1.1176 raeburn 1693: if (!$found_server) {
1694: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1695: foreach my $try_server (@{$offloadto->{'default'}}) {
1696: ($otherserver,$lowest_load) =
1697: &compare_server_load($try_server,$otherserver,$lowest_load);
1698: }
1699: }
1700: }
1701: } elsif (ref($offloadto) eq 'ARRAY') {
1702: if (@{$offloadto} == 1) {
1703: $otherserver = $offloadto->[0];
1704: } elsif (@{$offloadto} > 1) {
1705: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1706: ($otherserver,$lowest_load) =
1707: &compare_server_load($try_server,$otherserver,$lowest_load);
1708: }
1709: }
1710: }
1.1331 raeburn 1711: unless ($caller eq 'login') {
1712: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1713: $is_balancer = 0;
1714: if ($uname ne '' && $udom ne '') {
1715: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389 raeburn 1716: &appenv({'user.loadbalexempt' => $lonhost,
1.1331 raeburn 1717: 'user.loadbalcheck.time' => time});
1718: }
1.1176 raeburn 1719: }
1.1129 raeburn 1720: }
1721: }
1.1430 raeburn 1722: }
1723: if (($is_balancer) && (!$homeintdom)) {
1724: undef($setcookie);
1.1129 raeburn 1725: }
1.1391 raeburn 1726: return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129 raeburn 1727: }
1728:
1.1191 raeburn 1729: sub check_balancer_result {
1730: my ($result,@hosts) = @_;
1.1391 raeburn 1731: my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1732: if (ref($result) eq 'HASH') {
1733: if ($result->{'lonhost'} ne '') {
1734: my $currbalancer = $result->{'lonhost'};
1735: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1736: $is_balancer = 1;
1737: $currtargets = $result->{'targets'};
1738: $currrules = $result->{'rules'};
1739: }
1.1391 raeburn 1740: $dom_balancers = $currbalancer;
1.1191 raeburn 1741: } else {
1.1391 raeburn 1742: if (keys(%{$result})) {
1743: foreach my $key (keys(%{$result})) {
1744: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1745: (ref($result->{$key}) eq 'HASH')) {
1746: $is_balancer = 1;
1747: $currrules = $result->{$key}{'rules'};
1748: $currtargets = $result->{$key}{'targets'};
1749: $setcookie = $result->{$key}{'cookie'};
1750: last;
1751: }
1.1191 raeburn 1752: }
1.1391 raeburn 1753: $dom_balancers = join(',',sort(keys(%{$result})));
1.1191 raeburn 1754: }
1755: }
1756: }
1.1391 raeburn 1757: return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1758: }
1759:
1.1129 raeburn 1760: sub get_loadbalancer_targets {
1761: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1762: my $offloadto;
1.1175 raeburn 1763: if ($rule_in_effect eq 'none') {
1764: return [$perlvar{'lonHostID'}];
1765: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1766: $offloadto = $currtargets;
1767: } else {
1768: if ($rule_in_effect eq 'homeserver') {
1769: my $homeserver = &homeserver($uname,$udom);
1770: if ($homeserver ne 'no_host') {
1771: $offloadto = [$homeserver];
1772: }
1773: } elsif ($rule_in_effect eq 'externalbalancer') {
1774: my %domconfig =
1775: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1776: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1777: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1778: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1779: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1780: }
1781: }
1782: } else {
1.1178 raeburn 1783: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1784: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1785: if (&hostname($remotebalancer) ne '') {
1786: $offloadto = [$remotebalancer];
1787: }
1788: }
1789: } elsif (&hostname($rule_in_effect) ne '') {
1790: $offloadto = [$rule_in_effect];
1791: }
1792: }
1793: return $offloadto;
1794: }
1795:
1.1127 raeburn 1796: sub internet_dom_servers {
1797: my ($dom) = @_;
1798: my (%uniqservers,%servers);
1799: my $primaryserver = &hostname(&domain($dom,'primary'));
1800: my @machinedoms = &machine_domains($primaryserver);
1801: foreach my $mdom (@machinedoms) {
1802: my %currservers = %servers;
1803: my %server = &get_servers($mdom);
1804: %servers = (%currservers,%server);
1805: }
1806: my %by_hostname;
1807: foreach my $id (keys(%servers)) {
1808: push(@{$by_hostname{$servers{$id}}},$id);
1809: }
1810: foreach my $hostname (sort(keys(%by_hostname))) {
1811: if (@{$by_hostname{$hostname}} > 1) {
1812: my $match = 0;
1813: foreach my $id (@{$by_hostname{$hostname}}) {
1814: if (&host_domain($id) eq $dom) {
1815: $uniqservers{$id} = $hostname;
1816: $match = 1;
1817: }
1818: }
1819: unless ($match) {
1820: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1821: }
1822: } else {
1823: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1824: }
1825: }
1826: return %uniqservers;
1827: }
1828:
1.1347 raeburn 1829: sub trusted_domains {
1830: my ($cmdtype,$calldom) = @_;
1.1349 raeburn 1831: my ($trusted,$untrusted);
1.1347 raeburn 1832: if (&domain($calldom) eq '') {
1.1349 raeburn 1833: return ($trusted,$untrusted);
1.1347 raeburn 1834: }
1.1395 raeburn 1835: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349 raeburn 1836: return ($trusted,$untrusted);
1.1347 raeburn 1837: }
1838: my $callprimary = &domain($calldom,'primary');
1839: my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
1840: if ($intcalldom eq '') {
1.1349 raeburn 1841: return ($trusted,$untrusted);
1.1347 raeburn 1842: }
1843:
1844: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
1845: unless (defined($cached)) {
1846: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
1847: &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1848: $trustconfig = $domconfig{'trust'};
1849: }
1850: if (ref($trustconfig)) {
1851: my (%possexc,%possinc,@allexc,@allinc);
1852: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1853: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1854: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1855: }
1856: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395 raeburn 1857: $possinc{$intcalldom} = 1;
1.1347 raeburn 1858: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1859: }
1860: }
1861: if (keys(%possexc)) {
1862: if (keys(%possinc)) {
1863: foreach my $key (sort(keys(%possexc))) {
1864: next if ($key eq $intcalldom);
1865: unless ($possinc{$key}) {
1866: push(@allexc,$key);
1867: }
1868: }
1869: } else {
1870: @allexc = sort(keys(%possexc));
1871: }
1872: }
1873: if (keys(%possinc)) {
1874: $possinc{$intcalldom} = 1;
1875: @allinc = sort(keys(%possinc));
1876: }
1877: if ((@allexc > 0) || (@allinc > 0)) {
1878: my %doms_by_intdom;
1879: my %allintdoms = &all_host_intdom();
1880: my %alldoms = &all_host_domain();
1881: foreach my $key (%allintdoms) {
1882: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1883: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1884: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1885: }
1886: } else {
1887: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1888: }
1889: }
1890: foreach my $exc (@allexc) {
1891: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395 raeburn 1892: push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347 raeburn 1893: }
1894: }
1895: foreach my $inc (@allinc) {
1896: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395 raeburn 1897: push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347 raeburn 1898: }
1899: }
1900: }
1901: }
1.1349 raeburn 1902: return ($trusted,$untrusted);
1.1347 raeburn 1903: }
1904:
1905: sub will_trust {
1906: my ($cmdtype,$domain,$possdom) = @_;
1907: return 1 if ($domain eq $possdom);
1908: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1909: my $willtrust;
1910: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1911: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1912: $willtrust = 1;
1913: }
1914: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1915: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1916: $willtrust = 1;
1917: }
1918: } else {
1919: $willtrust = 1;
1920: }
1921: return $willtrust;
1922: }
1923:
1.1 albertel 1924: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1925:
1.599 albertel 1926: my %homecache;
1.1 albertel 1927: sub homeserver {
1.230 stredwic 1928: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1929: my $index="$uname:$udom";
1.426 albertel 1930:
1.599 albertel 1931: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1932:
1933: my %servers = &get_servers($udom,'library');
1934: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1935: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1936: exists($badServerCache{$tryserver}));
1.841 albertel 1937:
1938: my $answer=reply("home:$udom:$uname",$tryserver);
1939: if ($answer eq 'found') {
1940: delete($badServerCache{$tryserver});
1941: return $homecache{$index}=$tryserver;
1942: } elsif ($answer eq 'no_host') {
1943: $badServerCache{$tryserver}=1;
1944: }
1.1 albertel 1945: }
1946: return 'no_host';
1.70 www 1947: }
1948:
1.1300 raeburn 1949: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1950:
1951: sub idget {
1.1300 raeburn 1952: my ($udom,$idsref,$namespace)=@_;
1.70 www 1953: my %returnhash=();
1.1300 raeburn 1954: my @ids=();
1955: if (ref($idsref) eq 'ARRAY') {
1956: @ids = @{$idsref};
1957: } else {
1958: return %returnhash;
1959: }
1960: if ($namespace eq '') {
1961: $namespace = 'ids';
1962: }
1.70 www 1963:
1.841 albertel 1964: my %servers = &get_servers($udom,'library');
1965: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1966: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1967: if ($namespace eq 'ids') {
1968: $idlist=~tr/A-Z/a-z/;
1969: }
1970: my $reply;
1971: if ($namespace eq 'ids') {
1972: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1973: } else {
1974: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1975: }
1.841 albertel 1976: my @answer=();
1977: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1978: @answer=split(/\&/,$reply);
1979: } ;
1980: my $i;
1981: for ($i=0;$i<=$#ids;$i++) {
1982: if ($answer[$i]) {
1.1299 raeburn 1983: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1984: }
1.841 albertel 1985: }
1.1300 raeburn 1986: }
1.70 www 1987: return %returnhash;
1988: }
1989:
1990: # ------------------------------------- Find the IDs behind a list of usernames
1991:
1992: sub idrget {
1993: my ($udom,@unames)=@_;
1994: my %returnhash=();
1.800 albertel 1995: foreach my $uname (@unames) {
1996: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1997: }
1.70 www 1998: return %returnhash;
1999: }
2000:
1.1300 raeburn 2001: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 2002:
2003: sub idput {
1.1300 raeburn 2004: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 2005: my %servers=();
1.1300 raeburn 2006: my %ids=();
2007: my %byid = ();
2008: if (ref($idsref) eq 'HASH') {
2009: %ids=%{$idsref};
2010: }
2011: if ($namespace eq '') {
2012: $namespace = 'ids';
2013: }
1.800 albertel 2014: foreach my $uname (keys(%ids)) {
2015: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 2016: if ($uhom eq '') {
2017: $uhom=&homeserver($uname,$udom);
2018: }
1.70 www 2019: if ($uhom ne 'no_host') {
1.800 albertel 2020: my $esc_unam=&escape($uname);
1.1300 raeburn 2021: if ($namespace eq 'ids') {
2022: my $id=&escape($ids{$uname});
2023: $id=~tr/A-Z/a-z/;
2024: my $esc_unam=&escape($uname);
2025: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 2026: } else {
1.1300 raeburn 2027: my @currids = split(/,/,$ids{$uname});
2028: foreach my $id (@currids) {
2029: $byid{$uhom}{$id} .= $uname.',';
2030: }
2031: }
2032: }
2033: }
2034: if ($namespace eq 'clickers') {
2035: foreach my $server (keys(%byid)) {
2036: if (ref($byid{$server}) eq 'HASH') {
2037: foreach my $id (keys(%{$byid{$server}})) {
2038: $byid{$server} =~ s/,$//;
2039: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
2040: }
1.70 www 2041: }
2042: }
1.191 harris41 2043: }
1.800 albertel 2044: foreach my $server (keys(%servers)) {
1.1300 raeburn 2045: $servers{$server} =~ s/\&$//;
2046: if ($namespace eq 'ids') {
2047: &critical('idput:'.$udom.':'.$servers{$server},$server);
2048: } else {
2049: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
2050: }
1.191 harris41 2051: }
1.344 www 2052: }
2053:
1.1300 raeburn 2054: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 2055:
2056: sub iddel {
1.1300 raeburn 2057: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 2058: my %result=();
1.1300 raeburn 2059: my %ids=();
2060: my %byid = ();
2061: if (ref($idshashref) eq 'HASH') {
2062: %ids=%{$idshashref};
2063: } else {
1.1231 raeburn 2064: return %result;
2065: }
1.1300 raeburn 2066: if ($namespace eq '') {
2067: $namespace = 'ids';
2068: }
1.1231 raeburn 2069: my %servers=();
1.1300 raeburn 2070: while (my ($id,$unamestr) = each(%ids)) {
2071: if ($namespace eq 'ids') {
2072: my $uhom = $uhome;
2073: if ($uhom eq '') {
2074: $uhom=&homeserver($unamestr,$udom);
2075: }
2076: if ($uhom ne 'no_host') {
2077: $servers{$uhom}.='&'.&escape($id);
2078: }
2079: } else {
2080: my @curritems = split(/,/,$ids{$id});
2081: foreach my $uname (@curritems) {
2082: my $uhom = $uhome;
2083: if ($uhom eq '') {
2084: $uhom=&homeserver($uname,$udom);
2085: }
2086: if ($uhom ne 'no_host') {
2087: $byid{$uhom}{$id} .= $uname.',';
2088: }
2089: }
1.1231 raeburn 2090: }
1.1300 raeburn 2091: }
2092: if ($namespace eq 'clickers') {
2093: foreach my $server (keys(%byid)) {
2094: if (ref($byid{$server}) eq 'HASH') {
2095: foreach my $id (keys(%{$byid{$server}})) {
2096: $byid{$server}{$id} =~ s/,$//;
2097: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
2098: }
1.1231 raeburn 2099: }
2100: }
2101: }
2102: foreach my $server (keys(%servers)) {
1.1300 raeburn 2103: $servers{$server} =~ s/\&$//;
2104: if ($namespace eq 'ids') {
2105: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
2106: } elsif ($namespace eq 'clickers') {
2107: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
2108: }
1.1231 raeburn 2109: }
2110: return %result;
2111: }
2112:
1.1300 raeburn 2113: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
2114:
2115: sub updateclickers {
2116: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
2117: my %clickers;
2118: if (ref($idshashref) eq 'HASH') {
2119: %clickers=%{$idshashref};
2120: } else {
2121: return;
2122: }
2123: my $items='';
2124: foreach my $item (keys(%clickers)) {
2125: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
2126: }
2127: $items=~s/\&$//;
2128: my $request = "updateclickers:$udom:$action:$items";
2129: if ($critical) {
2130: return &critical($request,$uhome);
2131: } else {
2132: return &reply($request,$uhome);
2133: }
2134: }
2135:
1.1023 raeburn 2136: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 2137: sub dump_dom {
1.1165 droeschl 2138: my ($namespace, $udom, $regexp) = @_;
2139:
2140: $udom ||= $env{'user.domain'};
2141:
2142: return () unless $udom;
2143:
2144: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 2145: }
2146:
1.1023 raeburn 2147: # ------------------------------------------ get items from domain db files
1.806 raeburn 2148:
2149: sub get_dom {
1.1462 raeburn 2150: my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1267 raeburn 2151: return if ($udom eq 'public');
1.806 raeburn 2152: my $items='';
2153: foreach my $item (@$storearr) {
2154: $items.=&escape($item).'&';
2155: }
2156: $items=~s/\&$//;
1.860 raeburn 2157: if (!$udom) {
2158: $udom=$env{'user.domain'};
1.1267 raeburn 2159: return if ($udom eq 'public');
1.860 raeburn 2160: if (defined(&domain($udom,'primary'))) {
2161: $uhome=&domain($udom,'primary');
2162: } else {
1.874 albertel 2163: undef($uhome);
1.860 raeburn 2164: }
2165: } else {
2166: if (!$uhome) {
2167: if (defined(&domain($udom,'primary'))) {
2168: $uhome=&domain($udom,'primary');
2169: }
2170: }
2171: }
2172: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344 raeburn 2173: my $rep;
1.1442 raeburn 2174: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
2175: # domain information is hosted on this machine
1.1462 raeburn 2176: $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1344 raeburn 2177: } else {
1.1462 raeburn 2178: if ($encrypt) {
1.1442 raeburn 2179: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
2180: } else {
2181: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
2182: }
1.1344 raeburn 2183: }
1.866 raeburn 2184: my %returnhash;
1.875 albertel 2185: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 2186: return %returnhash;
2187: }
1.806 raeburn 2188: my @pairs=split(/\&/,$rep);
2189: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2190: return @pairs;
2191: }
2192: my $i=0;
2193: foreach my $item (@$storearr) {
2194: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2195: $i++;
2196: }
2197: return %returnhash;
2198: } else {
1.880 banghart 2199: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 2200: }
2201: }
2202:
2203: # -------------------------------------------- put items in domain db files
2204:
2205: sub put_dom {
1.1462 raeburn 2206: my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860 raeburn 2207: if (!$udom) {
2208: $udom=$env{'user.domain'};
2209: if (defined(&domain($udom,'primary'))) {
2210: $uhome=&domain($udom,'primary');
2211: } else {
1.874 albertel 2212: undef($uhome);
1.860 raeburn 2213: }
2214: } else {
2215: if (!$uhome) {
2216: if (defined(&domain($udom,'primary'))) {
2217: $uhome=&domain($udom,'primary');
2218: }
2219: }
2220: }
2221: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 2222: my $items='';
2223: foreach my $item (keys(%$storehash)) {
2224: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2225: }
2226: $items=~s/\&$//;
1.1462 raeburn 2227: if ($encrypt) {
1.1344 raeburn 2228: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2229: } else {
2230: return &reply("putdom:$udom:$namespace:$items",$uhome);
2231: }
1.806 raeburn 2232: } else {
1.860 raeburn 2233: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 2234: }
2235: }
2236:
1.1023 raeburn 2237: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 2238: sub newput_dom {
1.1023 raeburn 2239: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 2240: my $result;
2241: if (!$udom) {
2242: $udom=$env{'user.domain'};
2243: }
1.1023 raeburn 2244: if ($udom) {
2245: my $uname = &get_domainconfiguser($udom);
2246: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 2247: }
2248: return $result;
2249: }
2250:
1.1023 raeburn 2251: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 2252: sub del_dom {
1.1023 raeburn 2253: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 2254: if (ref($storearr) eq 'ARRAY') {
2255: if (!$udom) {
2256: $udom=$env{'user.domain'};
2257: }
1.1023 raeburn 2258: if ($udom) {
2259: my $uname = &get_domainconfiguser($udom);
2260: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 2261: }
2262: }
2263: }
2264:
1.1481 raeburn 2265: sub store_dom {
1.1482 raeburn 2266: my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
1.1481 raeburn 2267: $$storehash{'ip'}=&get_requestor_ip();
2268: $$storehash{'host'}=$perlvar{'lonHostID'};
2269: my $namevalue='';
2270: foreach my $key (keys(%{$storehash})) {
2271: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2272: }
2273: $namevalue=~s/\&$//;
2274: if (grep { $_ eq $home } current_machine_ids()) {
2275: return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
2276: } else {
2277: if ($namespace eq 'private') {
2278: return 'refused';
1.1482 raeburn 2279: } elsif ($encrypt) {
2280: return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481 raeburn 2281: } else {
1.1482 raeburn 2282: return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481 raeburn 2283: }
2284: }
2285: }
2286:
1.1482 raeburn 2287: sub restore_dom {
2288: my ($id,$namespace,$dom,$home,$encrypt) = @_;
2289: my $answer;
2290: if (grep { $_ eq $home } current_machine_ids()) {
2291: $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
2292: } elsif ($namespace ne 'private') {
2293: if ($encrypt) {
2294: $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
2295: } else {
2296: $answer=&reply("restoredom:$dom:$namespace:$id",$home);
2297: }
2298: }
2299: my %returnhash=();
2300: unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') ||
2301: ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
2302: foreach my $line (split(/\&/,$answer)) {
2303: my ($name,$value)=split(/\=/,$line);
2304: $returnhash{&unescape($name)}=&thaw_unescape($value);
2305: }
2306: my $version;
2307: for ($version=1;$version<=$returnhash{'version'};$version++) {
2308: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2309: $returnhash{$item}=$returnhash{$version.':'.$item};
2310: }
2311: }
2312: }
2313: return %returnhash;
2314: }
2315:
1.1023 raeburn 2316: # ----------------------------------construct domainconfig user for a domain
2317: sub get_domainconfiguser {
2318: my ($udom) = @_;
2319: return $udom.'-domainconfig';
2320: }
2321:
1.837 raeburn 2322: sub retrieve_inst_usertypes {
2323: my ($udom) = @_;
2324: my (%returnhash,@order);
1.989 raeburn 2325: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2326: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2327: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 2328: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2329: } else {
2330: if (defined(&domain($udom,'primary'))) {
2331: my $uhome=&domain($udom,'primary');
2332: my $rep=&reply("inst_usertypes:$udom",$uhome);
2333: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 2334: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2335: return (\%returnhash,\@order);
2336: }
2337: my ($hashitems,$orderitems) = split(/:/,$rep);
2338: my @pairs=split(/\&/,$hashitems);
2339: foreach my $item (@pairs) {
2340: my ($key,$value)=split(/=/,$item,2);
2341: $key = &unescape($key);
2342: next if ($key =~ /^error: 2 /);
2343: $returnhash{$key}=&thaw_unescape($value);
2344: }
2345: my @esc_order = split(/\&/,$orderitems);
2346: foreach my $item (@esc_order) {
2347: push(@order,&unescape($item));
2348: }
2349: } else {
1.1256 raeburn 2350: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2351: }
1.1256 raeburn 2352: return (\%returnhash,\@order);
1.837 raeburn 2353: }
2354: }
2355:
1.868 raeburn 2356: sub is_domainimage {
2357: my ($url) = @_;
1.1468 raeburn 2358: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868 raeburn 2359: if (&domain($1) ne '') {
2360: return '1';
2361: }
2362: }
2363: return;
2364: }
2365:
1.899 raeburn 2366: sub inst_directory_query {
2367: my ($srch) = @_;
2368: my $udom = $srch->{'srchdomain'};
2369: my %results;
2370: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2371: my $outcome;
1.899 raeburn 2372: if ($homeserver ne '') {
1.1357 raeburn 2373: unless ($homeserver eq $perlvar{'lonHostID'}) {
2374: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2375: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357 raeburn 2376: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2377: if (($major eq '' && $minor eq '') || ($major < 2) ||
2378: (($major == 2) && ($minor < 12))) {
2379: return;
2380: }
2381: }
2382: }
1.904 albertel 2383: my $queryid=&reply("querysend:instdirsearch:".
2384: &escape($srch->{'srchby'}).':'.
2385: &escape($srch->{'srchterm'}).':'.
2386: &escape($srch->{'srchtype'}),$homeserver);
2387: my $host=&hostname($homeserver);
2388: if ($queryid !~/^\Q$host\E\_/) {
1.1343 raeburn 2389: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2390: return;
2391: }
2392: my $response = &get_query_reply($queryid);
2393: my $maxtries = 5;
2394: my $tries = 1;
2395: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2396: $response = &get_query_reply($queryid);
2397: $tries ++;
2398: }
2399:
2400: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2401: if ($response eq 'unavailable') {
2402: $outcome = $response;
2403: } else {
2404: $outcome = 'ok';
2405: my @matches = split(/\n/,$response);
2406: foreach my $match (@matches) {
2407: my ($key,$value) = split(/=/,$match);
2408: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2409: }
1.899 raeburn 2410: }
2411: }
2412: }
1.909 raeburn 2413: return ($outcome,%results);
1.899 raeburn 2414: }
2415:
2416: sub usersearch {
2417: my ($srch) = @_;
2418: my $dom = $srch->{'srchdomain'};
2419: my %results;
2420: my %libserv = &all_library();
2421: my $query = 'usersearch';
2422: foreach my $tryserver (keys(%libserv)) {
2423: if (&host_domain($tryserver) eq $dom) {
1.1357 raeburn 2424: unless ($tryserver eq $perlvar{'lonHostID'}) {
2425: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2426: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357 raeburn 2427: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2428: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2429: (($major == 2) && ($minor < 12)));
2430: }
2431: }
1.899 raeburn 2432: my $host=&hostname($tryserver);
2433: my $queryid=
1.911 raeburn 2434: &reply("querysend:".&escape($query).':'.
2435: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2436: &escape($srch->{'srchtype'}).':'.
2437: &escape($srch->{'srchterm'}),$tryserver);
2438: if ($queryid !~/^\Q$host\E\_/) {
2439: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2440: next;
1.899 raeburn 2441: }
2442: my $reply = &get_query_reply($queryid);
2443: my $maxtries = 1;
2444: my $tries = 1;
2445: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2446: $reply = &get_query_reply($queryid);
2447: $tries ++;
2448: }
2449: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2450: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2451: } else {
1.911 raeburn 2452: my @matches;
2453: if ($reply =~ /\n/) {
2454: @matches = split(/\n/,$reply);
2455: } else {
2456: @matches = split(/\&/,$reply);
2457: }
1.899 raeburn 2458: foreach my $match (@matches) {
2459: my ($uname,$udom,%userhash);
1.911 raeburn 2460: foreach my $entry (split(/:/,$match)) {
2461: my ($key,$value) =
2462: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2463: $userhash{$key} = $value;
2464: if ($key eq 'username') {
2465: $uname = $value;
2466: } elsif ($key eq 'domain') {
2467: $udom = $value;
1.911 raeburn 2468: }
1.899 raeburn 2469: }
2470: $results{$uname.':'.$udom} = \%userhash;
2471: }
2472: }
2473: }
2474: }
2475: return %results;
2476: }
2477:
1.912 raeburn 2478: sub get_instuser {
2479: my ($udom,$uname,$id) = @_;
2480: my $homeserver = &domain($udom,'primary');
2481: my ($outcome,%results);
2482: if ($homeserver ne '') {
2483: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2484: &escape($id).':'.&escape($udom),$homeserver);
2485: my $host=&hostname($homeserver);
2486: if ($queryid !~/^\Q$host\E\_/) {
2487: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2488: return;
2489: }
2490: my $response = &get_query_reply($queryid);
2491: my $maxtries = 5;
2492: my $tries = 1;
2493: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2494: $response = &get_query_reply($queryid);
2495: $tries ++;
2496: }
2497: if (!&error($response) && $response ne 'refused') {
2498: if ($response eq 'unavailable') {
2499: $outcome = $response;
2500: } else {
2501: $outcome = 'ok';
2502: my @matches = split(/\n/,$response);
2503: foreach my $match (@matches) {
2504: my ($key,$value) = split(/=/,$match);
2505: $results{&unescape($key)} = &thaw_unescape($value);
2506: }
2507: }
2508: }
2509: }
2510: my %userinfo;
2511: if (ref($results{$uname}) eq 'HASH') {
2512: %userinfo = %{$results{$uname}};
2513: }
2514: return ($outcome,%userinfo);
2515: }
2516:
1.1290 raeburn 2517: sub get_multiple_instusers {
2518: my ($udom,$users,$caller) = @_;
2519: my ($outcome,$results);
2520: if (ref($users) eq 'HASH') {
2521: my $count = keys(%{$users});
2522: my $requested = &freeze_escape($users);
2523: my $homeserver = &domain($udom,'primary');
2524: if ($homeserver ne '') {
2525: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2526: my $host=&hostname($homeserver);
2527: if ($queryid !~/^\Q$host\E\_/) {
2528: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2529: ' for host: '.$homeserver.'in domain '.$udom);
2530: return ($outcome,$results);
2531: }
2532: my $response = &get_query_reply($queryid);
2533: my $maxtries = 5;
2534: if ($count > 100) {
2535: $maxtries = 1+int($count/20);
2536: }
2537: my $tries = 1;
2538: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2539: $response = &get_query_reply($queryid);
2540: $tries ++;
2541: }
2542: if ($response eq '') {
2543: $results = {};
2544: foreach my $key (keys(%{$users})) {
2545: my ($uname,$id);
2546: if ($caller eq 'id') {
2547: $id = $key;
2548: } else {
2549: $uname = $key;
2550: }
2551: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2552: $outcome = $resp;
1.1290 raeburn 2553: if ($resp eq 'ok') {
2554: %{$results} = (%{$results}, %info);
2555: } else {
2556: last;
2557: }
2558: }
2559: } elsif(!&error($response) && ($response ne 'refused')) {
2560: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2561: $outcome = $response;
2562: } else {
1.1291 raeburn 2563: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2564: if ($outcome eq 'ok') {
2565: $results = &thaw_unescape($userdata);
2566: }
2567: }
2568: }
2569: }
2570: }
2571: return ($outcome,$results);
2572: }
2573:
1.912 raeburn 2574: sub inst_rulecheck {
1.923 raeburn 2575: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2576: my %returnhash;
2577: if ($udom ne '') {
2578: if (ref($rules) eq 'ARRAY') {
2579: @{$rules} = map {&escape($_);} (@{$rules});
2580: my $rulestr = join(':',@{$rules});
2581: my $homeserver=&domain($udom,'primary');
2582: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2583: my $response;
2584: if ($item eq 'username') {
2585: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2586: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2587: $homeserver));
1.923 raeburn 2588: } elsif ($item eq 'id') {
2589: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2590: ':'.&escape($id).':'.$rulestr,
2591: $homeserver));
1.945 raeburn 2592: } elsif ($item eq 'selfcreate') {
2593: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2594: &escape($udom).':'.&escape($uname).
2595: ':'.$rulestr,$homeserver));
1.923 raeburn 2596: }
1.912 raeburn 2597: if ($response ne 'refused') {
2598: my @pairs=split(/\&/,$response);
2599: foreach my $item (@pairs) {
2600: my ($key,$value)=split(/=/,$item,2);
2601: $key = &unescape($key);
2602: next if ($key =~ /^error: 2 /);
2603: $returnhash{$key}=&thaw_unescape($value);
2604: }
2605: }
2606: }
2607: }
2608: }
2609: return %returnhash;
2610: }
2611:
2612: sub inst_userrules {
1.923 raeburn 2613: my ($udom,$check) = @_;
1.912 raeburn 2614: my (%ruleshash,@ruleorder);
2615: if ($udom ne '') {
2616: my $homeserver=&domain($udom,'primary');
2617: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2618: my $response;
2619: if ($check eq 'id') {
2620: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2621: $homeserver);
1.943 raeburn 2622: } elsif ($check eq 'email') {
2623: $response=&reply('instemailrules:'.&escape($udom),
2624: $homeserver);
1.923 raeburn 2625: } else {
2626: $response=&reply('instuserrules:'.&escape($udom),
2627: $homeserver);
2628: }
1.912 raeburn 2629: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2630: ($response ne 'unknown_cmd') &&
1.912 raeburn 2631: ($response ne 'no_such_host')) {
2632: my ($hashitems,$orderitems) = split(/:/,$response);
2633: my @pairs=split(/\&/,$hashitems);
2634: foreach my $item (@pairs) {
2635: my ($key,$value)=split(/=/,$item,2);
2636: $key = &unescape($key);
2637: next if ($key =~ /^error: 2 /);
2638: $ruleshash{$key}=&thaw_unescape($value);
2639: }
2640: my @esc_order = split(/\&/,$orderitems);
2641: foreach my $item (@esc_order) {
2642: push(@ruleorder,&unescape($item));
2643: }
2644: }
2645: }
2646: }
2647: return (\%ruleshash,\@ruleorder);
2648: }
2649:
1.976 raeburn 2650: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2651:
2652: sub get_domain_defaults {
1.1240 raeburn 2653: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2654: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2655: my $cachetime = 60*60*24;
1.1240 raeburn 2656: unless ($ignore_cache) {
2657: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2658: if (defined($cached)) {
2659: if (ref($result) eq 'HASH') {
2660: return %{$result};
2661: }
1.943 raeburn 2662: }
2663: }
2664: my %domdefaults;
2665: my %domconfig =
1.989 raeburn 2666: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2667: 'requestcourses','inststatus',
1.1183 raeburn 2668: 'coursedefaults','usersessions',
1.1258 raeburn 2669: 'requestauthor','selfenrollment',
1.1320 raeburn 2670: 'coursecategories','ssl','autoenroll',
1.1482 raeburn 2671: 'trust','helpsettings','wafproxy','ltisec'],$domain);
1.1305 raeburn 2672: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2673: if (ref($domconfig{'defaults'}) eq 'HASH') {
2674: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2675: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2676: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2677: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2678: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2679: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340 raeburn 2680: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2681: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2682: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2683: } else {
2684: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2685: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2686: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2687: }
1.976 raeburn 2688: if (ref($domconfig{'quotas'}) eq 'HASH') {
2689: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2690: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2691: } else {
2692: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2693: }
1.1177 raeburn 2694: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2695: foreach my $item (@usertools) {
2696: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2697: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2698: }
2699: }
1.1229 raeburn 2700: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2701: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2702: }
1.976 raeburn 2703: }
1.985 raeburn 2704: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2705: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2706: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2707: }
2708: }
1.1183 raeburn 2709: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2710: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2711: }
1.989 raeburn 2712: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2713: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2714: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2715: }
2716: }
1.1047 raeburn 2717: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2718: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2719: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1476 raeburn 2720: $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1277 raeburn 2721: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2722: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2723: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2724: }
1.1254 raeburn 2725: foreach my $type (@coursetypes) {
2726: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2727: unless ($type eq 'community') {
2728: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2729: }
2730: }
2731: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2732: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2733: }
1.1277 raeburn 2734: if ($domdefaults{'postsubmit'} eq 'on') {
2735: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2736: $domdefaults{$type.'postsubtimeout'} =
2737: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2738: }
2739: }
1.1230 raeburn 2740: }
1.1286 raeburn 2741: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2742: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2743: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2744: if (@clonecodes) {
2745: $domdefaults{'canclone'} = join('+',@clonecodes);
2746: }
2747: }
2748: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2749: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2750: }
1.1356 raeburn 2751: if ($domconfig{'coursedefaults'}{'texengine'}) {
2752: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
1.1480 raeburn 2753: }
2754: if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
2755: $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
2756: }
1.1047 raeburn 2757: }
1.1073 raeburn 2758: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2759: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2760: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2761: }
2762: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2763: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2764: }
1.1279 raeburn 2765: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2766: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2767: }
1.1440 raeburn 2768: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439 raeburn 2769: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2770: }
1.1073 raeburn 2771: }
1.1254 raeburn 2772: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2773: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2774: my @settings = ('types','registered','enroll_dates','access_dates','section',
2775: 'approval','limit');
2776: foreach my $type (@coursetypes) {
2777: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2778: my @mgrdc = ();
2779: foreach my $item (@settings) {
2780: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2781: push(@mgrdc,$item);
2782: }
2783: }
2784: if (@mgrdc) {
2785: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2786: }
2787: }
2788: }
2789: }
2790: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2791: foreach my $type (@coursetypes) {
2792: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2793: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2794: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2795: }
2796: }
2797: }
2798: }
2799: }
1.1258 raeburn 2800: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2801: $domdefaults{'catauth'} = 'std';
2802: $domdefaults{'catunauth'} = 'std';
1.1413 raeburn 2803: if ($domconfig{'coursecategories'}{'auth'}) {
1.1258 raeburn 2804: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2805: }
2806: if ($domconfig{'coursecategories'}{'unauth'}) {
2807: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2808: }
2809: }
1.1315 raeburn 2810: if (ref($domconfig{'ssl'}) eq 'HASH') {
2811: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2812: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2813: }
1.1338 raeburn 2814: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2815: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2816: }
2817: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2818: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315 raeburn 2819: }
2820: }
1.1320 raeburn 2821: if (ref($domconfig{'trust'}) eq 'HASH') {
2822: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2823: foreach my $prefix (@prefixes) {
2824: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2825: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2826: }
2827: }
2828: }
1.1314 raeburn 2829: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2830: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1477 raeburn 2831: $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1314 raeburn 2832: }
1.1332 raeburn 2833: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2834: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2835: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2836: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2837: }
2838: }
1.1434 raeburn 2839: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1449 raeburn 2840: foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
1.1434 raeburn 2841: if ($domconfig{'wafproxy'}{$item}) {
2842: $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
2843: }
2844: }
1.1482 raeburn 2845: }
2846: if (ref($domconfig{'ltisec'}) eq 'HASH') {
2847: if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
2848: $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
2849: $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
2850: $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
2851: }
2852: if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
2853: if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
2854: $domdefaults{'privhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
2855: }
2856: }
2857: }
1.1219 raeburn 2858: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2859: return %domdefaults;
2860: }
2861:
1.1412 raeburn 2862: sub get_dom_cats {
2863: my ($dom) = @_;
2864: return unless (&domain($dom));
2865: my ($cats,$cached)=&is_cached_new('cats',$dom);
2866: unless (defined($cached)) {
2867: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2868: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2869: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2870: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2871: } else {
2872: $cats = {};
2873: }
2874: } else {
2875: $cats = {};
2876: }
2877: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2878: }
1.1413 raeburn 2879: return $cats;
2880: }
2881:
2882: sub get_dom_instcats {
2883: my ($dom) = @_;
2884: return unless (&domain($dom));
2885: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2886: unless (defined($cached)) {
2887: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2888: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2889: if ($totcodes > 0) {
2890: my $caller = 'global';
2891: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2892: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2893: $instcats = {
2894: codes => \%codes,
2895: codetitles => \@codetitles,
2896: cat_titles => \%cat_titles,
2897: cat_order => \%cat_order,
2898: };
2899: &do_cache_new('instcats',$dom,$instcats,3600);
2900: }
2901: }
2902: }
2903: return $instcats;
2904: }
2905:
2906: sub retrieve_instcodes {
2907: my ($coursecodes,$dom) = @_;
2908: my $totcodes;
2909: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2910: foreach my $course (keys(%courses)) {
2911: if (ref($courses{$course}) eq 'HASH') {
2912: if ($courses{$course}{'inst_code'} ne '') {
2913: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2914: $totcodes ++;
2915: }
2916: }
2917: }
2918: return $totcodes;
1.1412 raeburn 2919: }
2920:
1.1311 raeburn 2921: sub course_portal_url {
1.1451 raeburn 2922: my ($cnum,$cdom,$r) = @_;
1.1311 raeburn 2923: my $chome = &homeserver($cnum,$cdom);
2924: my $hostname = &hostname($chome);
2925: my $protocol = $protocol{$chome};
2926: $protocol = 'http' if ($protocol ne 'https');
2927: my %domdefaults = &get_domain_defaults($cdom);
2928: my $firsturl;
2929: if ($domdefaults{'portal_def'}) {
2930: $firsturl = $domdefaults{'portal_def'};
2931: } else {
1.1451 raeburn 2932: my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
2933: $hostname = $alias if ($alias ne '');
1.1311 raeburn 2934: $firsturl = $protocol.'://'.$hostname;
2935: }
2936: return $firsturl;
2937: }
2938:
1.1407 raeburn 2939: # --------------------------------------------- Get domain config for passwords
2940:
2941: sub get_passwdconf {
2942: my ($dom) = @_;
2943: my (%passwdconf,$gotconf,$lookup);
2944: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2945: if (defined($cached)) {
2946: if (ref($result) eq 'HASH') {
2947: %passwdconf = %{$result};
2948: $gotconf = 1;
2949: }
2950: }
2951: unless ($gotconf) {
2952: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2953: if (ref($domconfig{'passwords'}) eq 'HASH') {
2954: %passwdconf = %{$domconfig{'passwords'}};
2955: }
2956: my $cachetime = 24*60*60;
2957: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2958: }
2959: return %passwdconf;
2960: }
2961:
1.344 www 2962: # --------------------------------------------------- Assign a key to a student
2963:
2964: sub assign_access_key {
1.364 www 2965: #
2966: # a valid key looks like uname:udom#comments
2967: # comments are being appended
2968: #
1.498 www 2969: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2970: $kdom=
1.620 albertel 2971: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2972: $knum=
1.620 albertel 2973: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2974: $cdom=
1.620 albertel 2975: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2976: $cnum=
1.620 albertel 2977: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2978: $udom=$env{'user.name'} unless (defined($udom));
2979: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2980: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2981: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2982: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2983: # assigned to this person
2984: # - this should not happen,
1.345 www 2985: # unless something went wrong
2986: # the first time around
2987: # ready to assign
1.364 www 2988: $logentry=$1.'; '.$logentry;
1.496 www 2989: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2990: $kdom,$knum) eq 'ok') {
1.345 www 2991: # key now belongs to user
1.346 www 2992: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2993: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2994: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2995: return 'ok';
2996: } else {
2997: return
2998: 'error: Count not permanently assign key, will need to be re-entered later.';
2999: }
3000: } else {
3001: return 'error: Could not assign key, try again later.';
3002: }
1.364 www 3003: } elsif (!$existing{$ckey}) {
1.345 www 3004: # the key does not exist
3005: return 'error: The key does not exist';
3006: } else {
3007: # the key is somebody else's
3008: return 'error: The key is already in use';
3009: }
1.344 www 3010: }
3011:
1.364 www 3012: # ------------------------------------------ put an additional comment on a key
3013:
3014: sub comment_access_key {
3015: #
3016: # a valid key looks like uname:udom#comments
3017: # comments are being appended
3018: #
3019: my ($ckey,$cdom,$cnum,$logentry)=@_;
3020: $cdom=
1.620 albertel 3021: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 3022: $cnum=
1.620 albertel 3023: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 3024: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
3025: if ($existing{$ckey}) {
3026: $existing{$ckey}.='; '.$logentry;
3027: # ready to assign
1.367 www 3028: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 3029: $cdom,$cnum) eq 'ok') {
3030: return 'ok';
3031: } else {
3032: return 'error: Count not store comment.';
3033: }
3034: } else {
3035: # the key does not exist
3036: return 'error: The key does not exist';
3037: }
3038: }
3039:
1.344 www 3040: # ------------------------------------------------------ Generate a set of keys
3041:
3042: sub generate_access_keys {
1.364 www 3043: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 3044: $cdom=
1.620 albertel 3045: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3046: $cnum=
1.620 albertel 3047: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 3048: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 3049: unless (($cdom) && ($cnum)) { return 0; }
3050: if ($number>10000) { return 0; }
3051: sleep(2); # make sure don't get same seed twice
3052: srand(time()^($$+($$<<15))); # from "Programming Perl"
3053: my $total=0;
3054: for (my $i=1;$i<=$number;$i++) {
3055: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
3056: sprintf("%lx",int(100000*rand)).'-'.
3057: sprintf("%lx",int(100000*rand));
3058: $newkey=~s/1/g/g; # folks mix up 1 and l
3059: $newkey=~s/0/h/g; # and also 0 and O
3060: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
3061: if ($existing{$newkey}) {
3062: $i--;
3063: } else {
1.364 www 3064: if (&put('accesskeys',
3065: { $newkey => '# generated '.localtime().
1.620 albertel 3066: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 3067: '; '.$logentry },
3068: $cdom,$cnum) eq 'ok') {
1.344 www 3069: $total++;
3070: }
3071: }
3072: }
1.620 albertel 3073: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 3074: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
3075: return $total;
3076: }
3077:
3078: # ------------------------------------------------------- Validate an accesskey
3079:
3080: sub validate_access_key {
3081: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
3082: $cdom=
1.620 albertel 3083: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3084: $cnum=
1.620 albertel 3085: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3086: $udom=$env{'user.domain'} unless (defined($udom));
3087: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 3088: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 3089: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 3090: }
3091:
3092: # ------------------------------------- Find the section of student in a course
1.652 albertel 3093: sub devalidate_getsection_cache {
3094: my ($udom,$unam,$courseid)=@_;
3095: my $hashid="$udom:$unam:$courseid";
3096: &devalidate_cache_new('getsection',$hashid);
3097: }
1.298 matthew 3098:
1.815 albertel 3099: sub courseid_to_courseurl {
3100: my ($courseid) = @_;
3101: #already url style courseid
3102: return $courseid if ($courseid =~ m{^/});
3103:
3104: if (exists($env{'course.'.$courseid.'.num'})) {
3105: my $cnum = $env{'course.'.$courseid.'.num'};
3106: my $cdom = $env{'course.'.$courseid.'.domain'};
3107: return "/$cdom/$cnum";
3108: }
3109:
3110: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
3111: if (exists($courseinfo{'num'})) {
3112: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
3113: }
3114:
3115: return undef;
3116: }
3117:
1.298 matthew 3118: sub getsection {
3119: my ($udom,$unam,$courseid)=@_;
1.599 albertel 3120: my $cachetime=1800;
1.551 albertel 3121:
3122: my $hashid="$udom:$unam:$courseid";
1.599 albertel 3123: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 3124: if (defined($cached)) { return $result; }
3125:
1.298 matthew 3126: my %Pending;
3127: my %Expired;
3128: #
3129: # Each role can either have not started yet (pending), be active,
3130: # or have expired.
3131: #
3132: # If there is an active role, we are done.
3133: #
3134: # If there is more than one role which has not started yet,
3135: # choose the one which will start sooner
3136: # If there is one role which has not started yet, return it.
3137: #
3138: # If there is more than one expired role, choose the one which ended last.
3139: # If there is a role which has expired, return it.
3140: #
1.815 albertel 3141: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 3142: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 3143: foreach my $key (keys(%roleshash)) {
1.479 albertel 3144: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 3145: my $section=$1;
3146: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 3147: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 3148: my $now=time;
1.548 albertel 3149: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 3150: $Expired{$end}=$section;
3151: next;
3152: }
1.548 albertel 3153: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 3154: $Pending{$start}=$section;
3155: next;
3156: }
1.599 albertel 3157: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 3158: }
3159: #
3160: # Presumedly there will be few matching roles from the above
3161: # loop and the sorting time will be negligible.
3162: if (scalar(keys(%Pending))) {
3163: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 3164: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 3165: }
3166: if (scalar(keys(%Expired))) {
3167: my @sorted = sort {$a <=> $b} keys(%Expired);
3168: my $time = pop(@sorted);
1.599 albertel 3169: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 3170: }
1.599 albertel 3171: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 3172: }
1.70 www 3173:
1.599 albertel 3174: sub save_cache {
3175: &purge_remembered();
1.722 albertel 3176: #&Apache::loncommon::validate_page();
1.620 albertel 3177: undef(%env);
1.780 albertel 3178: undef($env_loaded);
1.599 albertel 3179: }
1.452 albertel 3180:
1.599 albertel 3181: my $to_remember=-1;
3182: my %remembered;
3183: my %accessed;
3184: my $kicks=0;
3185: my $hits=0;
1.849 albertel 3186: sub make_key {
3187: my ($name,$id) = @_;
1.872 albertel 3188: if (length($id) > 65
3189: && length(&escape($id)) > 200) {
3190: $id=length($id).':'.&Digest::MD5::md5_hex($id);
3191: }
1.849 albertel 3192: return &escape($name.':'.$id);
3193: }
3194:
1.599 albertel 3195: sub devalidate_cache_new {
3196: my ($name,$id,$debug) = @_;
3197: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 3198: my $remembered_id=$name.':'.$id;
1.849 albertel 3199: $id=&make_key($name,$id);
1.599 albertel 3200: $memcache->delete($id);
1.1319 damieng 3201: delete($remembered{$remembered_id});
3202: delete($accessed{$remembered_id});
1.599 albertel 3203: }
3204:
3205: sub is_cached_new {
3206: my ($name,$id,$debug) = @_;
1.1319 damieng 3207: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
3208: if (exists($remembered{$remembered_id})) {
3209: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
3210: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3211: $hits++;
1.1319 damieng 3212: return ($remembered{$remembered_id},1);
1.599 albertel 3213: }
1.1319 damieng 3214: $id=&make_key($name,$id);
1.599 albertel 3215: my $value = $memcache->get($id);
3216: if (!(defined($value))) {
3217: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 3218: return (undef,undef);
1.416 albertel 3219: }
1.599 albertel 3220: if ($value eq '__undef__') {
3221: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3222: $value=undef;
3223: }
1.1319 damieng 3224: &make_room($remembered_id,$value,$debug);
1.599 albertel 3225: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3226: return ($value,1);
3227: }
3228:
3229: sub do_cache_new {
3230: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 3231: my $remembered_id=$name.':'.$id;
1.849 albertel 3232: $id=&make_key($name,$id);
1.599 albertel 3233: my $setvalue=$value;
3234: if (!defined($setvalue)) {
3235: $setvalue='__undef__';
3236: }
1.623 albertel 3237: if (!defined($time) ) {
3238: $time=600;
3239: }
1.599 albertel 3240: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 3241: my $result = $memcache->set($id,$setvalue,$time);
3242: if (! $result) {
1.872 albertel 3243: &logthis("caching of id -> $id failed");
1.910 albertel 3244: $memcache->disconnect_all();
1.872 albertel 3245: }
1.600 albertel 3246: # need to make a copy of $value
1.1319 damieng 3247: &make_room($remembered_id,$value,$debug);
1.599 albertel 3248: return $value;
3249: }
3250:
3251: sub make_room {
1.1319 damieng 3252: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 3253:
1.1319 damieng 3254: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 3255: : $value;
1.599 albertel 3256: if ($to_remember<0) { return; }
1.1319 damieng 3257: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3258: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3259: my $to_kick;
3260: my $max_time=0;
3261: foreach my $other (keys(%accessed)) {
3262: if (&tv_interval($accessed{$other}) > $max_time) {
3263: $to_kick=$other;
3264: $max_time=&tv_interval($accessed{$other});
3265: }
3266: }
3267: delete($remembered{$to_kick});
3268: delete($accessed{$to_kick});
3269: $kicks++;
3270: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 3271: return;
3272: }
3273:
1.599 albertel 3274: sub purge_remembered {
1.604 albertel 3275: #&logthis("Tossing ".scalar(keys(%remembered)));
3276: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 3277: undef(%remembered);
3278: undef(%accessed);
1.428 albertel 3279: }
1.70 www 3280: # ------------------------------------- Read an entry from a user's environment
3281:
3282: sub userenvironment {
3283: my ($udom,$unam,@what)=@_;
1.976 raeburn 3284: my $items;
3285: foreach my $item (@what) {
3286: $items.=&escape($item).'&';
3287: }
3288: $items=~s/\&$//;
1.70 www 3289: my %returnhash=();
1.1009 raeburn 3290: my $uhome = &homeserver($unam,$udom);
3291: unless ($uhome eq 'no_host') {
3292: my @answer=split(/\&/,
3293: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 3294: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3295: return %returnhash;
3296: }
1.1009 raeburn 3297: my $i;
3298: for ($i=0;$i<=$#what;$i++) {
3299: $returnhash{$what[$i]}=&unescape($answer[$i]);
3300: }
1.70 www 3301: }
3302: return %returnhash;
1.1 albertel 3303: }
3304:
1.617 albertel 3305: # ---------------------------------------------------------- Get a studentphoto
3306: sub studentphoto {
3307: my ($udom,$unam,$ext) = @_;
3308: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 3309: if (defined($env{'request.course.id'})) {
1.708 raeburn 3310: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 3311: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3312: return(&retrievestudentphoto($udom,$unam,$ext));
3313: } else {
3314: my ($result,$perm_reqd)=
1.707 albertel 3315: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 3316: if ($result eq 'ok') {
3317: if (!($perm_reqd eq 'yes')) {
3318: return(&retrievestudentphoto($udom,$unam,$ext));
3319: }
3320: }
3321: }
3322: }
3323: } else {
3324: my ($result,$perm_reqd) =
1.707 albertel 3325: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 3326: if ($result eq 'ok') {
3327: if (!($perm_reqd eq 'yes')) {
3328: return(&retrievestudentphoto($udom,$unam,$ext));
3329: }
3330: }
3331: }
3332: return '/adm/lonKaputt/lonlogo_broken.gif';
3333: }
3334:
3335: sub retrievestudentphoto {
3336: my ($udom,$unam,$ext,$type) = @_;
3337: my $home=&Apache::lonnet::homeserver($unam,$udom);
3338: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
3339: if ($ret eq 'ok') {
3340: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3341: if ($type eq 'thumbnail') {
3342: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3343: }
3344: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
3345: return $tokenurl;
3346: } else {
3347: if ($type eq 'thumbnail') {
3348: return '/adm/lonKaputt/genericstudent_tn.gif';
3349: } else {
3350: return '/adm/lonKaputt/lonlogo_broken.gif';
3351: }
1.617 albertel 3352: }
3353: }
3354:
1.263 www 3355: # -------------------------------------------------------------------- New chat
3356:
3357: sub chatsend {
1.724 raeburn 3358: my ($newentry,$anon,$group)=@_;
1.620 albertel 3359: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3360: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3361: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 3362: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 3363: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 3364: &escape($newentry)).':'.$group,$chome);
1.292 www 3365: }
3366:
3367: # ------------------------------------------ Find current version of a resource
3368:
3369: sub getversion {
3370: my $fname=&clutter(shift);
1.1189 raeburn 3371: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3372: return ¤tversion(&filelocation('',$fname));
3373: }
3374:
3375: sub currentversion {
3376: my $fname=shift;
3377: my $author=$fname;
3378: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3379: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3380: my $home=&homeserver($uname,$udom);
1.292 www 3381: if ($home eq 'no_host') {
3382: return -1;
3383: }
1.1112 www 3384: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3385: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3386: return -1;
3387: }
1.1112 www 3388: return $answer;
1.263 www 3389: }
3390:
1.1111 www 3391: #
3392: # Return special version number of resource if set by override, empty otherwise
3393: #
3394: sub usedversion {
3395: my $fname=shift;
3396: unless ($fname) { $fname=$env{'request.uri'}; }
3397: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3398: if ($urlversion) { return $urlversion; }
3399: return '';
3400: }
3401:
1.1 albertel 3402: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3403:
1.1 albertel 3404: sub subscribe {
3405: my $fname=shift;
1.761 raeburn 3406: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3407: $fname=~s/[\n\r]//g;
1.1 albertel 3408: my $author=$fname;
3409: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3410: my ($udom,$uname)=split(/\//,$author);
3411: my $home=homeserver($uname,$udom);
1.335 albertel 3412: if ($home eq 'no_host') {
3413: return 'not_found';
1.1 albertel 3414: }
3415: my $answer=reply("sub:$fname",$home);
1.64 www 3416: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3417: $answer.=' by '.$home;
3418: }
1.1 albertel 3419: return $answer;
3420: }
3421:
1.8 www 3422: # -------------------------------------------------------------- Replicate file
3423:
3424: sub repcopy {
3425: my $filename=shift;
1.23 www 3426: $filename=~s/\/+/\//g;
1.1142 raeburn 3427: my $londocroot = $perlvar{'lonDocRoot'};
3428: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3429: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3430: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3431: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3432: return &repcopy_userfile($filename);
3433: }
1.532 albertel 3434: $filename=~s/[\n\r]//g;
1.8 www 3435: my $transname="$filename.in.transfer";
1.828 www 3436: # FIXME: this should flock
1.607 raeburn 3437: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3438: my $remoteurl=subscribe($filename);
1.64 www 3439: if ($remoteurl =~ /^con_lost by/) {
3440: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3441: return 'unavailable';
1.8 www 3442: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3443: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3444: return 'not_found';
1.64 www 3445: } elsif ($remoteurl =~ /^rejected by/) {
3446: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3447: return 'forbidden';
1.20 www 3448: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3449: return 'ok';
1.8 www 3450: } else {
1.290 www 3451: my $author=$filename;
3452: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3453: my ($udom,$uname)=split(/\//,$author);
3454: my $home=homeserver($uname,$udom);
3455: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3456: my @parts=split(/\//,$filename);
3457: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3458: if ($path ne "$londocroot/res") {
1.8 www 3459: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3460: return 'bad_request';
1.8 www 3461: }
3462: my $count;
3463: for ($count=5;$count<$#parts;$count++) {
3464: $path.="/$parts[$count]";
3465: if ((-e $path)!=1) {
3466: mkdir($path,0777);
3467: }
3468: }
3469: my $request=new HTTP::Request('GET',"$remoteurl");
1.1345 raeburn 3470: my $response;
3471: if ($remoteurl =~ m{/raw/}) {
3472: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3473: } else {
3474: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3475: }
1.8 www 3476: if ($response->is_error()) {
3477: unlink($transname);
3478: my $message=$response->status_line;
1.672 albertel 3479: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3480: ." LWP get: $message: $filename</font>");
1.607 raeburn 3481: return 'unavailable';
1.8 www 3482: } else {
1.16 www 3483: if ($remoteurl!~/\.meta$/) {
3484: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345 raeburn 3485: my $mresponse;
3486: if ($remoteurl =~ m{/raw/}) {
3487: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3488: } else {
3489: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3490: }
1.16 www 3491: if ($mresponse->is_error()) {
3492: unlink($filename.'.meta');
3493: &logthis(
1.672 albertel 3494: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3495: }
3496: }
1.8 www 3497: rename($transname,$filename);
1.607 raeburn 3498: return 'ok';
1.8 www 3499: }
1.290 www 3500: }
1.8 www 3501: }
1.330 www 3502: }
3503:
1.1422 raeburn 3504: # ------------------------------------------------- Unsubscribe from a resource
3505:
3506: sub unsubscribe {
3507: my ($fname) = @_;
3508: my $answer;
3509: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3510: $fname=~s/[\n\r]//g;
3511: my $author=$fname;
3512: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3513: my ($udom,$uname)=split(/\//,$author);
3514: my $home=homeserver($uname,$udom);
3515: if ($home eq 'no_host') {
3516: $answer = 'no_host';
3517: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3518: $answer = 'home';
3519: } else {
3520: my $defdom = $perlvar{'lonDefDomain'};
3521: if (&will_trust('content',$defdom,$udom)) {
3522: $answer = reply("unsub:$fname",$home);
3523: } else {
3524: $answer = 'untrusted';
3525: }
3526: }
3527: return $answer;
3528: }
3529:
1.330 www 3530: # ------------------------------------------------ Get server side include body
3531: sub ssi_body {
1.381 albertel 3532: my ($filelink,%form)=@_;
1.606 matthew 3533: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3534: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3535: }
1.953 www 3536: my $output='';
3537: my $response;
1.980 raeburn 3538: if ($filelink=~/^https?\:/) {
1.954 raeburn 3539: ($output,$response)=&externalssi($filelink);
1.953 www 3540: } else {
1.1004 droeschl 3541: $filelink .= $filelink=~/\?/ ? '&' : '?';
3542: $filelink .= 'inhibitmenu=yes';
1.953 www 3543: ($output,$response)=&ssi($filelink,%form);
3544: }
1.778 albertel 3545: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3546: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3547: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3548: if (wantarray) {
3549: return ($output, $response);
3550: } else {
3551: return $output;
3552: }
1.8 www 3553: }
3554:
1.15 www 3555: # --------------------------------------------------------- Server Side Include
3556:
1.782 albertel 3557: sub absolute_url {
1.1447 raeburn 3558: my ($host_name,$unalias,$keep_proto) = @_;
1.782 albertel 3559: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3560: if ($host_name eq '') {
3561: $host_name = $ENV{'SERVER_NAME'};
3562: }
1.1447 raeburn 3563: if ($unalias) {
3564: my $alias = &get_proxy_alias();
3565: if ($alias eq $host_name) {
3566: my $lonhost = $perlvar{'lonHostID'};
3567: my $hostname = &hostname($lonhost);
3568: my $lcproto;
3569: if (($keep_proto) || ($hostname eq '')) {
3570: $lcproto = $protocol;
3571: } else {
3572: $lcproto = $protocol{$lonhost};
3573: $lcproto = 'http' if ($lcproto ne 'https');
3574: $lcproto .= '://';
3575: }
3576: unless ($hostname eq '') {
3577: return $lcproto.$hostname;
3578: }
3579: }
3580: }
1.782 albertel 3581: return $protocol.$host_name;
3582: }
3583:
1.942 foxr 3584: #
3585: # Server side include.
3586: # Parameters:
3587: # fn Possibly encrypted resource name/id.
3588: # form Hash that describes how the rendering should be done
3589: # and other things.
1.944 foxr 3590: # Returns:
1.950 raeburn 3591: # Scalar context: The content of the response.
3592: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3593: #
1.15 www 3594: sub ssi {
3595:
1.944 foxr 3596: my ($fn,%form)=@_;
1.1447 raeburn 3597: my ($host,$request,$response);
3598: $host = &absolute_url('',1);
1.711 albertel 3599:
3600: $form{'no_update_last_known'}=1;
1.895 albertel 3601: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3602: if (%form) {
1.1447 raeburn 3603: $request=new HTTP::Request('POST',$host.$fn);
1.1272 droeschl 3604: $request->content(join('&',map {
3605: my $name = escape($_);
3606: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3607: ? join("&$name=", map {escape($_) } @{$form{$_}})
3608: : &escape($form{$_}) );
3609: } keys(%form)));
1.23 www 3610: } else {
1.1447 raeburn 3611: $request=new HTTP::Request('GET',$host.$fn);
1.23 www 3612: }
3613:
1.15 www 3614: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345 raeburn 3615: my $lonhost = $perlvar{'lonHostID'};
1.1385 raeburn 3616: my $islocal;
3617: if (($env{'request.course.id'}) &&
3618: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3619: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3620: ($form{'grade_symb'} ne '') &&
3621: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3622: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
3623: $islocal = 1;
3624: }
1.1447 raeburn 3625: $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
3626: '','','',$islocal);
1.1182 foxr 3627:
1.944 foxr 3628: if (wantarray) {
1.1345 raeburn 3629: return ($response->content, $response);
1.944 foxr 3630: } else {
1.1345 raeburn 3631: return $response->content;
1.942 foxr 3632: }
1.324 www 3633: }
3634:
3635: sub externalssi {
3636: my ($url)=@_;
3637: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 3638: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954 raeburn 3639: if (wantarray) {
3640: return ($response->content, $response);
3641: } else {
3642: return $response->content;
3643: }
1.15 www 3644: }
1.254 www 3645:
1.1354 raeburn 3646:
3647: # If the local copy of a replicated resource is outdated, trigger a
3648: # connection from the homeserver to flush the delayed queue. If no update
3649: # happens, remove local copies of outdated resource (and corresponding
3650: # metadata file).
3651:
1.1352 raeburn 3652: sub remove_stale_resfile {
3653: my ($url) = @_;
1.1354 raeburn 3654: my $removed;
1.1352 raeburn 3655: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3656: my $audom = $1;
3657: my $auname = $2;
1.1353 raeburn 3658: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352 raeburn 3659: my $homeserver = &homeserver($auname,$audom);
3660: unless (($homeserver eq 'no_host') ||
3661: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3662: my $fname = &filelocation('',$url);
3663: if (-e $fname) {
3664: my $hostname = &hostname($homeserver);
3665: if ($hostname) {
1.1397 raeburn 3666: my $protocol = $protocol{$homeserver};
3667: $protocol = 'http' if ($protocol ne 'https');
1.1352 raeburn 3668: my $uri = &declutter($url);
3669: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3670: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3671: if ($response->is_success()) {
3672: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3673: my $locmodtime = (stat($fname))[9];
3674: if ($locmodtime < $remmodtime) {
1.1354 raeburn 3675: my $stale;
3676: my $answer = &reply('pong',$homeserver);
3677: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3678: sleep(0.2);
3679: $locmodtime = (stat($fname))[9];
3680: if ($locmodtime < $remmodtime) {
3681: my $posstransfer = $fname.'.in.transfer';
3682: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3683: $removed = 1;
3684: } else {
3685: $stale = 1;
3686: }
3687: } else {
3688: $removed = 1;
3689: }
3690: } else {
3691: $stale = 1;
3692: }
3693: if ($stale) {
1.1421 raeburn 3694: if (unlink($fname)) {
3695: if ($uri!~/\.meta$/) {
3696: if (-e $fname.'.meta') {
3697: unlink($fname.'.meta');
3698: }
3699: }
1.1422 raeburn 3700: my $unsubresult = &unsubscribe($fname);
3701: unless ($unsubresult eq 'ok') {
3702: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3703: }
1.1421 raeburn 3704: $removed = 1;
1.1354 raeburn 3705: }
1.1352 raeburn 3706: }
3707: }
3708: }
3709: }
3710: }
3711: }
3712: }
3713: }
1.1354 raeburn 3714: return $removed;
1.1352 raeburn 3715: }
3716:
1.492 albertel 3717: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3718:
3719: sub allowuploaded {
3720: my ($srcurl,$url)=@_;
3721: $url=&clutter(&declutter($url));
3722: my $dir=$url;
3723: $dir=~s/\/[^\/]+$//;
3724: my %httpref=();
3725: my $httpurl=&hreflocation('',$url);
3726: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3727: &Apache::lonnet::appenv(\%httpref);
1.254 www 3728: }
1.477 raeburn 3729:
1.1193 raeburn 3730: #
3731: # Determine if the current user should be able to edit a particular resource,
3732: # when viewing in course context.
3733: # (a) When viewing resource used to determine if "Edit" item is included in
3734: # Functions.
3735: # (b) When displaying folder contents in course editor, used to determine if
3736: # "Edit" link will be displayed alongside resource.
3737: #
1.1196 raeburn 3738: # input: six args -- filename (decluttered), course number, course domain,
3739: # url, symb (if registered) and group (if this is a group
3740: # item -- e.g., bulletin board, group page etc.).
3741: # output: array of five scalars --
1.1193 raeburn 3742: # $cfile -- url for file editing if editable on current server
3743: # $home -- homeserver of resource (i.e., for author if published,
3744: # or course if uploaded.).
3745: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3746: # $forceedit -- 1 if icon/link should be to go to edit mode
3747: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3748: #
3749:
3750: sub can_edit_resource {
1.1194 raeburn 3751: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3752: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3753: #
3754: # For aboutme pages user can only edit his/her own.
3755: #
1.1199 raeburn 3756: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3757: my ($sdom,$sname) = ($1,$2);
3758: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3759: $home = $env{'user.home'};
3760: $cfile = $resurl;
3761: if ($env{'form.forceedit'}) {
3762: $forceview = 1;
3763: } else {
3764: $forceedit = 1;
3765: }
3766: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3767: } else {
3768: return;
3769: }
3770: }
3771:
3772: if ($env{'request.course.id'}) {
3773: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3774: if ($group ne '') {
3775: # if this is a group homepage or group bulletin board, check group privs
3776: my $allowed = 0;
1.1197 raeburn 3777: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3778: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3779: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3780: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3781: $allowed = 1;
3782: }
1.1197 raeburn 3783: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3784: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3785: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3786: $allowed = 1;
3787: }
3788: }
3789: if ($allowed) {
3790: $home=&homeserver($cnum,$cdom);
3791: if ($env{'form.forceedit'}) {
3792: $forceview = 1;
3793: } else {
3794: $forceedit = 1;
3795: }
3796: $cfile = $resurl;
3797: } else {
3798: return;
3799: }
3800: } else {
1.1208 raeburn 3801: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3802: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3803: return;
3804: }
3805: } elsif (!$crsedit) {
1.1194 raeburn 3806: #
3807: # No edit allowed where CC has switched to student role.
3808: #
3809: return;
3810: }
3811: }
3812: }
3813:
1.1193 raeburn 3814: if ($file ne '') {
3815: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3816: if (&is_course_upload($file,$cnum,$cdom)) {
3817: $uploaded = 1;
3818: $incourse = 1;
1.1193 raeburn 3819: if ($file =~/\.(htm|html|css|js|txt)$/) {
3820: $cfile = &hreflocation('',$file);
1.1201 raeburn 3821: if ($env{'form.forceedit'}) {
3822: $forceview = 1;
3823: } else {
3824: $forceedit = 1;
3825: }
1.1194 raeburn 3826: }
3827: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3828: $incourse = 1;
3829: if ($env{'form.forceedit'}) {
3830: $forceview = 1;
3831: } else {
3832: $forceedit = 1;
3833: }
3834: $cfile = $resurl;
3835: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3836: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3837: $incourse = 1;
3838: if ($env{'form.forceedit'}) {
3839: $forceview = 1;
3840: } else {
3841: $forceedit = 1;
3842: }
3843: $cfile = $resurl;
1.1199 raeburn 3844: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3845: $incourse = 1;
3846: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3847: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3848: $incourse = 1;
1.1199 raeburn 3849: if ($env{'form.forceedit'}) {
3850: $forceview = 1;
3851: } else {
3852: $forceedit = 1;
3853: }
3854: $cfile = $resurl;
1.1419 raeburn 3855: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3856: my ($map,$id,$res) = &decode_symb($symb);
3857: if ($map =~ /\.page$/) {
3858: $incourse = 1;
3859: if ($env{'form.forceedit'}) {
3860: $forceview = 1;
3861: $cfile = $map;
3862: } else {
3863: $forceedit = 1;
3864: $cfile = '/adm/wrapper'.$resurl;
3865: }
3866: }
1.1343 raeburn 3867: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3868: $incourse = 1;
3869: if ($env{'form.forceedit'}) {
3870: $forceview = 1;
3871: } else {
3872: $forceedit = 1;
3873: }
3874: $cfile = $resurl;
1.1208 raeburn 3875: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3876: $incourse = 1;
3877: if ($env{'form.forceedit'}) {
3878: $forceview = 1;
3879: } else {
3880: $forceedit = 1;
3881: }
3882: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3883: }
3884: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3885: my $template = '/res/lib/templates/simpleproblem.problem';
3886: if (&is_on_map($template)) {
3887: $incourse = 1;
3888: $forceview = 1;
3889: $cfile = $template;
1.1193 raeburn 3890: }
1.1199 raeburn 3891: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418 raeburn 3892: $incourse = 1;
3893: if ($env{'form.forceedit'}) {
3894: $forceview = 1;
3895: } else {
3896: $forceedit = 1;
3897: }
3898: $cfile = $resurl;
1.1343 raeburn 3899: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298 raeburn 3900: $incourse = 1;
3901: if ($env{'form.forceedit'}) {
3902: $forceview = 1;
3903: } else {
3904: $forceedit = 1;
3905: }
3906: $cfile = $resurl;
1.1199 raeburn 3907: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3908: $incourse = 1;
3909: $forceview = 1;
3910: if ($symb) {
3911: my ($map,$id,$res)=&decode_symb($symb);
3912: $env{'request.symb'} = $symb;
3913: $cfile = &clutter($res);
3914: } else {
3915: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3916: my $escfile = &unescape($cfile);
1.1343 raeburn 3917: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3918: $cfile = '/adm/wrapper'.$escfile;
3919: } else {
3920: $escfile =~ s{^http://}{};
3921: $cfile = &escape("/adm/wrapper/ext/$escfile");
3922: }
1.1199 raeburn 3923: }
1.1234 raeburn 3924: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3925: if ($env{'form.forceedit'}) {
3926: $forceview = 1;
3927: } else {
3928: $forceedit = 1;
3929: }
3930: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3931: }
3932: }
1.1194 raeburn 3933: if ($uploaded || $incourse) {
3934: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3935: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3936: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3937: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3938: # Check that the user has permission to edit this resource
3939: my $setpriv = 1;
3940: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3941: if (defined($cfudom)) {
3942: $home=&homeserver($cfuname,$cfudom);
3943: $cfile=$file;
3944: }
3945: }
1.1194 raeburn 3946: if (($cfile ne '') && (!$incourse || $uploaded) &&
3947: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3948: my @ids=¤t_machine_ids();
3949: unless (grep(/^\Q$home\E$/,@ids)) {
3950: $switchserver=1;
3951: }
3952: }
3953: }
1.1194 raeburn 3954: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3955: }
3956:
3957: sub is_course_upload {
3958: my ($file,$cnum,$cdom) = @_;
3959: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3960: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3961: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3962: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3963: return 1;
3964: }
3965: return;
3966: }
3967:
1.1194 raeburn 3968: sub in_course {
1.1195 raeburn 3969: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3970: if ($hideprivileged) {
3971: my $skipuser;
1.1219 raeburn 3972: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3973: my @possdoms = ($cdom);
3974: if ($coursehash{'checkforpriv'}) {
3975: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3976: }
3977: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3978: $skipuser = 1;
3979: if ($coursehash{'nothideprivileged'}) {
3980: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3981: my $user;
3982: if ($item =~ /:/) {
3983: $user = $item;
3984: } else {
3985: $user = join(':',split(/[\@]/,$item));
3986: }
3987: if ($user eq $uname.':'.$udom) {
3988: undef($skipuser);
3989: last;
3990: }
3991: }
3992: }
3993: if ($skipuser) {
3994: return 0;
3995: }
3996: }
3997: }
1.1194 raeburn 3998: $type ||= 'any';
3999: if (!defined($cdom) || !defined($cnum)) {
4000: my $cid = $env{'request.course.id'};
4001: $cdom = $env{'course.'.$cid.'.domain'};
4002: $cnum = $env{'course.'.$cid.'.num'};
4003: }
4004: my $typesref;
1.1195 raeburn 4005: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 4006: $typesref = ['active','previous','future'];
4007: } elsif ($type eq 'previous' || $type eq 'future') {
4008: $typesref = [$type];
4009: }
4010: my %roles = &get_my_roles($uname,$udom,'userroles',
4011: $typesref,undef,[$cdom]);
4012: my ($tmp) = keys(%roles);
4013: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
4014: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
4015: if (@course_roles > 0) {
4016: return 1;
4017: }
4018: return 0;
4019: }
4020:
1.478 albertel 4021: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 4022: # input: action, courseID, current domain, intended
1.637 raeburn 4023: # path to file, source of file, instruction to parse file for objects,
4024: # ref to hash for embedded objects,
4025: # ref to hash for codebase of java objects.
1.1095 raeburn 4026: # reference to scalar to accommodate mime type determined
4027: # from File::MMagic if $parser = parse.
1.637 raeburn 4028: #
1.485 raeburn 4029: # output: url to file (if action was uploaddoc),
4030: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 4031: #
1.478 albertel 4032: # Allows directory structure to be used within lonUsers/../userfiles/ for a
4033: # course.
1.477 raeburn 4034: #
1.478 albertel 4035: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4036: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
4037: # course's home server.
1.477 raeburn 4038: #
1.478 albertel 4039: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
4040: # be copied from $source (current location) to
4041: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4042: # and will then be copied to
4043: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
4044: # course's home server.
1.485 raeburn 4045: #
1.481 raeburn 4046: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 4047: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 4048: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4049: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
4050: # in course's home server.
1.637 raeburn 4051: #
1.477 raeburn 4052:
4053: sub process_coursefile {
1.1095 raeburn 4054: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
4055: $mimetype)=@_;
1.477 raeburn 4056: my $fetchresult;
1.638 albertel 4057: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 4058: if ($action eq 'propagate') {
1.638 albertel 4059: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4060: $home);
1.481 raeburn 4061: } else {
1.477 raeburn 4062: my $fpath = '';
4063: my $fname = $file;
1.478 albertel 4064: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 4065: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 4066: my $filepath = &build_filepath($fpath);
1.481 raeburn 4067: if ($action eq 'copy') {
4068: if ($source eq '') {
4069: $fetchresult = 'no source file';
4070: return $fetchresult;
4071: } else {
4072: my $destination = $filepath.'/'.$fname;
4073: rename($source,$destination);
4074: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4075: $home);
1.481 raeburn 4076: }
4077: } elsif ($action eq 'uploaddoc') {
1.1359 raeburn 4078: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 4079: print $fh $env{'form.'.$source};
1.481 raeburn 4080: close($fh);
1.637 raeburn 4081: if ($parser eq 'parse') {
1.1024 raeburn 4082: my $mm = new File::MMagic;
1.1095 raeburn 4083: my $type = $mm->checktype_filename($filepath.'/'.$fname);
4084: if ($type eq 'text/html') {
1.1024 raeburn 4085: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
4086: unless ($parse_result eq 'ok') {
4087: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
4088: }
1.637 raeburn 4089: }
1.1095 raeburn 4090: if (ref($mimetype)) {
4091: $$mimetype = $type;
4092: }
1.637 raeburn 4093: }
1.477 raeburn 4094: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4095: $home);
1.481 raeburn 4096: if ($fetchresult eq 'ok') {
4097: return '/uploaded/'.$fpath.'/'.$fname;
4098: } else {
4099: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4100: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 4101: return '/adm/notfound.html';
4102: }
1.477 raeburn 4103: }
4104: }
1.485 raeburn 4105: unless ( $fetchresult eq 'ok') {
1.477 raeburn 4106: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4107: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 4108: }
4109: return $fetchresult;
4110: }
4111:
1.637 raeburn 4112: sub build_filepath {
4113: my ($fpath) = @_;
4114: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
4115: unless ($fpath eq '') {
4116: my @parts=split('/',$fpath);
4117: foreach my $part (@parts) {
4118: $filepath.= '/'.$part;
4119: if ((-e $filepath)!=1) {
4120: mkdir($filepath,0777);
4121: }
4122: }
4123: }
4124: return $filepath;
4125: }
4126:
4127: sub store_edited_file {
1.638 albertel 4128: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 4129: my $file = $primary_url;
4130: $file =~ s#^/uploaded/$docudom/$docuname/##;
4131: my $fpath = '';
4132: my $fname = $file;
4133: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
4134: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
4135: my $filepath = &build_filepath($fpath);
1.1359 raeburn 4136: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 4137: print $fh $content;
4138: close($fh);
1.638 albertel 4139: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 4140: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4141: $home);
1.637 raeburn 4142: if ($$fetchresult eq 'ok') {
4143: return '/uploaded/'.$fpath.'/'.$fname;
4144: } else {
1.638 albertel 4145: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4146: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 4147: return '/adm/notfound.html';
4148: }
4149: }
4150:
1.531 albertel 4151: sub clean_filename {
1.831 albertel 4152: my ($fname,$args)=@_;
1.315 www 4153: # Replace Windows backslashes by forward slashes
1.257 www 4154: $fname=~s/\\/\//g;
1.831 albertel 4155: if (!$args->{'keep_path'}) {
4156: # Get rid of everything but the actual filename
4157: $fname=~s/^.*\/([^\/]+)$/$1/;
4158: }
1.315 www 4159: # Replace spaces by underscores
4160: $fname=~s/\s+/\_/g;
1.1406 raeburn 4161: # Transliterate non-ascii text to ascii
4162: my $lang = &Apache::lonlocal::current_language();
4163: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 4164: # Replace all other weird characters by nothing
1.831 albertel 4165: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 4166: # Replace all .\d. sequences with _\d. so they no longer look like version
4167: # numbers
4168: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443 raeburn 4169: # Replace three or more adjacent underscores with one for consistency
4170: # with loncfile::filename_check() so complete url can be extracted by
4171: # lonnet::decode_symb()
4172: $fname=~s/_{3,}/_/g;
1.531 albertel 4173: return $fname;
4174: }
1.1406 raeburn 4175:
1.1051 raeburn 4176: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4177: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4178: # image with the same aspect ratio as the original, but with dimensions which do
4179: # not exceed $resizewidth and $resizeheight.
4180:
1.984 neumanie 4181: sub resizeImage {
1.1051 raeburn 4182: my ($img_path,$resizewidth,$resizeheight) = @_;
4183: my $ima = Image::Magick->new;
4184: my $resized;
4185: if (-e $img_path) {
4186: $ima->Read($img_path);
4187: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4188: my $width = $ima->Get('width');
4189: my $height = $ima->Get('height');
4190: if ($width > $resizewidth) {
4191: my $factor = $width/$resizewidth;
4192: my $newheight = $height/$factor;
4193: $ima->Scale(width=>$resizewidth,height=>$newheight);
4194: $resized = 1;
4195: }
4196: }
4197: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4198: my $width = $ima->Get('width');
4199: my $height = $ima->Get('height');
4200: if ($height > $resizeheight) {
4201: my $factor = $height/$resizeheight;
4202: my $newwidth = $width/$factor;
4203: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4204: $resized = 1;
4205: }
4206: }
4207: if ($resized) {
4208: $ima->Write($img_path);
4209: }
4210: }
4211: return;
1.977 amueller 4212: }
4213:
1.608 albertel 4214: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 4215: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 4216: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 4217: # $context - possible values: coursedoc, existingfile, overwrite,
1.1401 raeburn 4218: # canceloverwrite, scantron or ''.
1.1090 raeburn 4219: # if 'coursedoc': upload to the current course
4220: # if 'existingfile': write file to tmp/overwrites directory
4221: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4222: # $context is passed as argument to &finishuserfileupload
1.686 albertel 4223: # $subdir - directory in userfile to store the file into
1.1401 raeburn 4224: # $parser - instruction to parse file for objects ($parser = parse) or
4225: # if context is 'scantron', $parser is hashref of csv column mapping
4226: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4227: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 4228: # $allfiles - reference to hash for embedded objects
4229: # $codebase - reference to hash for codebase of java objects
4230: # $desuname - username for permanent storage of uploaded file
4231: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 4232: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4233: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 4234: # $resizewidth - width (pixels) to which to resize uploaded image
4235: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 4236: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 4237: # from File::MMagic.
1.858 raeburn 4238: #
1.686 albertel 4239: # output: url of file in userspace, or error: <message>
4240: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 4241:
1.531 albertel 4242: sub userfileupload {
1.1090 raeburn 4243: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 4244: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 4245: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 4246: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 4247: $fname=&clean_filename($fname);
1.1090 raeburn 4248: # See if there is anything left
1.257 www 4249: unless ($fname) { return 'error: no uploaded file'; }
1.1406 raeburn 4250: # If filename now begins with a . prepend unix timestamp _ milliseconds
4251: if ($fname =~ /^\./) {
4252: my ($s,$usec) = &gettimeofday();
4253: while (length($usec) < 6) {
4254: $usec = '0'.$usec;
4255: }
4256: $fname = $s.'_'.substr($usec,0,3).$fname;
4257: }
1.1090 raeburn 4258: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4259: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4260: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4261: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 4262: my $now = time;
1.1090 raeburn 4263: my $filepath;
1.1095 raeburn 4264: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 4265: $filepath = 'tmp/helprequests/'.$now;
4266: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4267: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4268: '_'.$env{'user.domain'}.'/pending';
4269: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4270: my ($docuname,$docudom);
1.1350 raeburn 4271: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 4272: $docudom = $destudom;
4273: } else {
4274: $docudom = $env{'user.domain'};
4275: }
1.1350 raeburn 4276: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 4277: $docuname = $destuname;
4278: } else {
4279: $docuname = $env{'user.name'};
4280: }
4281: if (exists($env{'form.group'})) {
4282: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4283: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4284: }
4285: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4286: if ($context eq 'canceloverwrite') {
4287: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4288: if (-e $tempfile) {
4289: my @info = stat($tempfile);
4290: if ($info[9] eq $env{'form.timestamp'}) {
4291: unlink($tempfile);
4292: }
4293: }
4294: return;
1.523 raeburn 4295: }
4296: }
1.1090 raeburn 4297: # Create the directory if not present
1.741 raeburn 4298: my @parts=split(/\//,$filepath);
4299: my $fullpath = $perlvar{'lonDaemons'};
4300: for (my $i=0;$i<@parts;$i++) {
4301: $fullpath .= '/'.$parts[$i];
4302: if ((-e $fullpath)!=1) {
4303: mkdir($fullpath,0777);
4304: }
4305: }
1.1359 raeburn 4306: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 4307: print $fh $env{'form.'.$formname};
4308: close($fh);
1.1090 raeburn 4309: if ($context eq 'existingfile') {
4310: my @info = stat($fullpath.'/'.$fname);
4311: return ($fullpath.'/'.$fname,$info[9]);
4312: } else {
4313: return $fullpath.'/'.$fname;
4314: }
1.523 raeburn 4315: }
1.995 raeburn 4316: if ($subdir eq 'scantron') {
4317: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 4318: } else {
1.995 raeburn 4319: $fname="$subdir/$fname";
4320: }
1.1090 raeburn 4321: if ($context eq 'coursedoc') {
1.638 albertel 4322: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4323: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 4324: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 4325: return &finishuserfileupload($docuname,$docudom,
4326: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 4327: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 4328: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 4329: } else {
1.1218 raeburn 4330: if ($env{'form.folder'}) {
4331: $fname=$env{'form.folder'}.'/'.$fname;
4332: }
1.638 albertel 4333: return &process_coursefile('uploaddoc',$docuname,$docudom,
4334: $fname,$formname,$parser,
1.1095 raeburn 4335: $allfiles,$codebase,$mimetype);
1.481 raeburn 4336: }
1.719 banghart 4337: } elsif (defined($destuname)) {
4338: my $docuname=$destuname;
4339: my $docudom=$destudom;
1.860 raeburn 4340: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4341: $parser,$allfiles,$codebase,
1.1051 raeburn 4342: $thumbwidth,$thumbheight,
1.1095 raeburn 4343: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4344: } else {
1.638 albertel 4345: my $docuname=$env{'user.name'};
4346: my $docudom=$env{'user.domain'};
1.1220 raeburn 4347: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 4348: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4349: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4350: }
1.860 raeburn 4351: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4352: $parser,$allfiles,$codebase,
1.1051 raeburn 4353: $thumbwidth,$thumbheight,
1.1095 raeburn 4354: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4355: }
1.271 www 4356: }
4357:
4358: sub finishuserfileupload {
1.860 raeburn 4359: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4360: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4361: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4362: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4363:
1.860 raeburn 4364: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4365: $file=$fname;
4366: if ($fname=~m|/|) {
4367: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4368: $path.=$fnamepath.'/';
4369: }
1.259 www 4370: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4371: my $count;
4372: for ($count=4;$count<=$#parts;$count++) {
4373: $filepath.="/$parts[$count]";
4374: if ((-e $filepath)!=1) {
4375: mkdir($filepath,0777);
4376: }
4377: }
1.984 neumanie 4378:
1.258 www 4379: # Save the file
4380: {
1.1359 raeburn 4381: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4382: &logthis('Failed to create '.$filepath.'/'.$file);
4383: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4384: return '/adm/notfound.html';
4385: }
1.1090 raeburn 4386: if ($context eq 'overwrite') {
1.1117 foxr 4387: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4388: my $target = $filepath.'/'.$file;
4389: if (-e $source) {
4390: my @info = stat($source);
4391: if ($info[9] eq $env{'form.timestamp'}) {
4392: unless (&File::Copy::move($source,$target)) {
4393: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4394: return "Moving from $source failed";
4395: }
4396: } else {
4397: return "Temporary file: $source had unexpected date/time for last modification";
4398: }
4399: } else {
4400: return "Temporary file: $source missing";
4401: }
4402: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4403: &logthis('Failed to write to '.$filepath.'/'.$file);
4404: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4405: return '/adm/notfound.html';
4406: }
1.570 albertel 4407: close(FH);
1.1051 raeburn 4408: if ($resizewidth && $resizeheight) {
4409: my $mm = new File::MMagic;
4410: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4411: if ($mime_type =~ m{^image/}) {
4412: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4413: }
1.977 amueller 4414: }
1.258 www 4415: }
1.1152 raeburn 4416: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4417: if (ref($mimetype)) {
4418: if ($$mimetype eq '') {
4419: my $mm = new File::MMagic;
4420: my $type = $mm->checktype_filename($filepath.'/'.$file);
4421: $$mimetype = $type;
4422: }
4423: }
4424: }
1.1401 raeburn 4425: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4426: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4427: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4428: $allfiles,$codebase);
4429: unless ($parse_result eq 'ok') {
4430: &logthis('Failed to parse '.$filepath.$file.
4431: ' for embedded media: '.$parse_result);
4432: }
1.637 raeburn 4433: }
1.1401 raeburn 4434: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4435: my $format = $env{'form.scantron_format'};
4436: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4437: }
1.860 raeburn 4438: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4439: my $input = $filepath.'/'.$file;
4440: my $output = $filepath.'/'.'tn-'.$file;
4441: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359 raeburn 4442: my @args = ('convert','-sample',$thumbsize,$input,$output);
4443: system({$args[0]} @args);
1.860 raeburn 4444: if (-e $filepath.'/'.'tn-'.$file) {
4445: $fetchthumb = 1;
4446: }
4447: }
1.858 raeburn 4448:
1.259 www 4449: # Notify homeserver to grep it
4450: #
1.984 neumanie 4451: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4452: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4453: if ($fetchresult eq 'ok') {
1.860 raeburn 4454: if ($fetchthumb) {
4455: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4456: if ($thumbresult ne 'ok') {
4457: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4458: $docuhome.': '.$thumbresult);
4459: }
4460: }
1.259 www 4461: #
1.258 www 4462: # Return the URL to it
1.494 albertel 4463: return '/uploaded/'.$path.$file;
1.263 www 4464: } else {
1.494 albertel 4465: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4466: ': '.$fetchresult);
1.263 www 4467: return '/adm/notfound.html';
1.858 raeburn 4468: }
1.493 albertel 4469: }
4470:
1.637 raeburn 4471: sub extract_embedded_items {
1.961 raeburn 4472: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4473: my @state = ();
1.1164 raeburn 4474: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4475: my %javafiles = (
4476: codebase => '',
4477: code => '',
4478: archive => ''
4479: );
4480: my %mediafiles = (
4481: src => '',
4482: movie => '',
4483: );
1.648 raeburn 4484: my $p;
4485: if ($content) {
4486: $p = HTML::LCParser->new($content);
4487: } else {
1.961 raeburn 4488: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4489: }
1.641 albertel 4490: while (my $t=$p->get_token()) {
1.640 albertel 4491: if ($t->[0] eq 'S') {
4492: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4493: push(@state, $tagname);
1.648 raeburn 4494: if (lc($tagname) eq 'allow') {
4495: &add_filetype($allfiles,$attr->{'src'},'src');
4496: }
1.640 albertel 4497: if (lc($tagname) eq 'img') {
4498: &add_filetype($allfiles,$attr->{'src'},'src');
4499: }
1.886 albertel 4500: if (lc($tagname) eq 'a') {
1.1222 raeburn 4501: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 4502: &add_filetype($allfiles,$attr->{'href'},'href');
4503: }
1.886 albertel 4504: }
1.645 raeburn 4505: if (lc($tagname) eq 'script') {
1.1164 raeburn 4506: my $src;
1.645 raeburn 4507: if ($attr->{'archive'} =~ /\.jar$/i) {
4508: &add_filetype($allfiles,$attr->{'archive'},'archive');
4509: } else {
1.1164 raeburn 4510: if ($attr->{'src'} ne '') {
4511: $src = $attr->{'src'};
4512: &add_filetype($allfiles,$src,'src');
4513: }
4514: }
4515: my $text = $p->get_trimmed_text();
4516: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4517: my @swfargs = split(/,/,$1);
4518: foreach my $item (@swfargs) {
4519: $item =~ s/["']//g;
4520: $item =~ s/^\s+//;
4521: $item =~ s/\s+$//;
4522: }
4523: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4524: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4525: push(@{$related{$swfargs[0]}},$swfargs[2]);
4526: } else {
4527: $related{$swfargs[0]} = [$swfargs[2]];
4528: }
4529: }
1.645 raeburn 4530: }
4531: }
4532: if (lc($tagname) eq 'link') {
4533: if (lc($attr->{'rel'}) eq 'stylesheet') {
4534: &add_filetype($allfiles,$attr->{'href'},'href');
4535: }
4536: }
1.640 albertel 4537: if (lc($tagname) eq 'object' ||
4538: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4539: foreach my $item (keys(%javafiles)) {
4540: $javafiles{$item} = '';
4541: }
1.1164 raeburn 4542: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4543: $lastids{lc($tagname)} = $attr->{'id'};
4544: }
1.640 albertel 4545: }
4546: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4547: my $name = lc($attr->{'name'});
4548: foreach my $item (keys(%javafiles)) {
4549: if ($name eq $item) {
4550: $javafiles{$item} = $attr->{'value'};
4551: last;
4552: }
4553: }
1.1164 raeburn 4554: my $pathfrom;
1.640 albertel 4555: foreach my $item (keys(%mediafiles)) {
4556: if ($name eq $item) {
1.1164 raeburn 4557: $pathfrom = $attr->{'value'};
4558: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4559: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4560: last;
4561: }
4562: }
1.1164 raeburn 4563: if ($name eq 'flashvars') {
4564: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4565: }
4566: if ($pathfrom ne '') {
4567: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4568: $pathfrom);
4569: }
1.640 albertel 4570: }
4571: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4572: foreach my $item (keys(%javafiles)) {
4573: if ($attr->{$item}) {
4574: $javafiles{$item} = $attr->{$item};
4575: last;
4576: }
4577: }
4578: foreach my $item (keys(%mediafiles)) {
4579: if ($attr->{$item}) {
4580: &add_filetype($allfiles,$attr->{$item},$item);
4581: last;
4582: }
4583: }
1.1164 raeburn 4584: if (lc($tagname) eq 'embed') {
4585: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4586: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4587: $attr->{'src'});
4588: }
4589: }
1.640 albertel 4590: }
1.1243 raeburn 4591: if (lc($tagname) eq 'iframe') {
4592: my $src = $attr->{'src'} ;
4593: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4594: &add_filetype($allfiles,$src,'src');
4595: } elsif ($src =~ m{^/}) {
4596: if ($env{'request.course.id'}) {
4597: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4598: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4599: my $url = &hreflocation('',$fullpath);
4600: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4601: my $relpath = $1;
4602: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4603: &add_filetype($allfiles,$1,'src');
4604: }
4605: }
4606: }
4607: }
4608: }
1.1164 raeburn 4609: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 4610: pop(@state);
1.1164 raeburn 4611: }
1.640 albertel 4612: } elsif ($t->[0] eq 'E') {
4613: my ($tagname) = ($t->[1]);
4614: if ($javafiles{'codebase'} ne '') {
4615: $javafiles{'codebase'} .= '/';
4616: }
4617: if (lc($tagname) eq 'applet' ||
4618: lc($tagname) eq 'object' ||
4619: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4620: ) {
4621: foreach my $item (keys(%javafiles)) {
4622: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4623: my $file=$javafiles{'codebase'}.$javafiles{$item};
4624: &add_filetype($allfiles,$file,$item);
4625: }
4626: }
4627: }
4628: pop @state;
4629: }
4630: }
1.1164 raeburn 4631: foreach my $id (sort(keys(%flashvars))) {
4632: if ($shockwave{$id} ne '') {
4633: my @pairs = split(/\&/,$flashvars{$id});
4634: foreach my $pair (@pairs) {
4635: my ($key,$value) = split(/\=/,$pair);
4636: if ($key eq 'thumb') {
4637: &add_filetype($allfiles,$value,$key);
4638: } elsif ($key eq 'content') {
4639: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4640: my ($ext) = ($value =~ /\.([^.]+)$/);
4641: if ($ext ne '') {
4642: &add_filetype($allfiles,$path.$value,$ext);
4643: }
4644: }
4645: }
4646: }
4647: }
1.637 raeburn 4648: return 'ok';
4649: }
4650:
1.639 albertel 4651: sub add_filetype {
4652: my ($allfiles,$file,$type)=@_;
4653: if (exists($allfiles->{$file})) {
4654: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4655: push(@{$allfiles->{$file}}, &escape($type));
4656: }
4657: } else {
4658: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4659: }
4660: }
4661:
1.1164 raeburn 4662: sub embedded_dependency {
4663: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4664: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4665: if (($identifier ne '') &&
4666: (ref($related->{$identifier}) eq 'ARRAY') &&
4667: ($pathfrom ne '')) {
4668: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4669: foreach my $dep (@{$related->{$identifier}}) {
4670: &add_filetype($allfiles,$path.$dep,'object');
4671: }
4672: }
4673: }
4674: return;
4675: }
4676:
1.1401 raeburn 4677: sub bubblesheet_converter {
4678: my ($cdom,$fullpath,$config,$format) = @_;
4679: if ((&domain($cdom) ne '') &&
1.1403 raeburn 4680: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401 raeburn 4681: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404 raeburn 4682: my (%csvcols,%csvoptions);
4683: if (ref($config->{'fields'}) eq 'HASH') {
4684: %csvcols = %{$config->{'fields'}};
4685: }
4686: if (ref($config->{'options'}) eq 'HASH') {
4687: %csvoptions = %{$config->{'options'}};
4688: }
1.1401 raeburn 4689: my %csvbynum = reverse(%csvcols);
4690: my %scantronconf = &get_scantron_config($format,$cdom);
4691: if (keys(%scantronconf)) {
4692: my %bynum = (
4693: $scantronconf{CODEstart} => 'CODEstart',
4694: $scantronconf{IDstart} => 'IDstart',
4695: $scantronconf{PaperID} => 'PaperID',
4696: $scantronconf{FirstName} => 'FirstName',
4697: $scantronconf{LastName} => 'LastName',
4698: $scantronconf{Qstart} => 'Qstart',
4699: );
4700: my @ordered;
4701: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403 raeburn 4702: push(@ordered,$bynum{$item});
1.1401 raeburn 4703: }
4704: my %mapstart = (
4705: CODEstart => 'CODE',
4706: IDstart => 'ID',
4707: PaperID => 'PaperID',
4708: FirstName => 'FirstName',
4709: LastName => 'LastName',
4710: Qstart => 'FirstQuestion',
4711: );
4712: my %maplength = (
4713: CODEstart => 'CODElength',
4714: IDstart => 'IDlength',
4715: PaperID => 'PaperIDlength',
4716: FirstName => 'FirstNamelength',
4717: LastName => 'LastNamelength',
4718: );
4719: if (open(my $fh,'<',$fullpath)) {
4720: my $output;
1.1403 raeburn 4721: my %lettdig = &letter_to_digits();
4722: my %diglett = reverse(%lettdig);
4723: my $numletts = scalar(keys(%lettdig));
1.1404 raeburn 4724: my $num = 0;
1.1401 raeburn 4725: while (my $line=<$fh>) {
1.1404 raeburn 4726: $num ++;
4727: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401 raeburn 4728: $line =~ s{[\r\n]+$}{};
4729: my %found;
1.1475 raeburn 4730: my @values = split(/,/,$line,-1);
1.1401 raeburn 4731: my ($qstart,$record);
4732: for (my $i=0; $i<@values; $i++) {
1.1403 raeburn 4733: if ((($qstart ne '') && ($i > $qstart)) ||
4734: ($csvbynum{$i} eq 'FirstQuestion')) {
4735: if ($values[$i] eq '') {
4736: $values[$i] = $scantronconf{'Qoff'};
4737: } elsif ($scantronconf{'Qon'} eq 'number') {
4738: if ($values[$i] =~ /^[A-Ja-j]$/) {
4739: $values[$i] = $lettdig{uc($values[$i])};
4740: }
4741: } elsif ($scantronconf{'Qon'} eq 'letter') {
4742: if ($values[$i] =~ /^[0-9]$/) {
4743: $values[$i] = $diglett{$values[$i]};
4744: }
4745: } else {
4746: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4747: my $digit;
4748: if ($values[$i] =~ /^[A-Ja-j]$/) {
4749: $digit = $lettdig{uc($values[$i])}-1;
4750: if ($values[$i] eq 'J') {
4751: $digit += $numletts;
4752: }
4753: } elsif ($values[$i] =~ /^[0-9]$/) {
4754: $digit = $values[$i]-1;
4755: if ($values[$i] eq '0') {
4756: $digit += $numletts;
4757: }
4758: }
4759: my $qval='';
4760: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4761: if ($j == $digit) {
4762: $qval .= $scantronconf{'Qon'};
4763: } else {
4764: $qval .= $scantronconf{'Qoff'};
4765: }
4766: }
4767: $values[$i] = $qval;
4768: }
4769: }
4770: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4771: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4772: }
4773: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4774: if ($numblank > 0) {
4775: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4776: }
1.1401 raeburn 4777: if ($csvbynum{$i} eq 'FirstQuestion') {
4778: $qstart = $i;
1.1403 raeburn 4779: $found{$csvbynum{$i}} = $values[$i];
1.1401 raeburn 4780: } else {
1.1403 raeburn 4781: $found{'FirstQuestion'} .= $values[$i];
4782: }
4783: } elsif (exists($csvbynum{$i})) {
1.1404 raeburn 4784: if ($csvoptions{'rem'}) {
4785: $values[$i] =~ s/^\s+//;
4786: }
4787: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403 raeburn 4788: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4789: $values[$i] = '0'.$values[$i];
1.1401 raeburn 4790: }
4791: }
4792: $found{$csvbynum{$i}} = $values[$i];
4793: }
4794: }
4795: foreach my $item (@ordered) {
4796: my $currlength = 1+length($record);
4797: my $numspaces = $scantronconf{$item} - $currlength;
4798: if ($numspaces > 0) {
4799: $record .= (' ' x $numspaces);
4800: }
4801: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4802: unless ($item eq 'Qstart') {
4803: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4804: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4805: }
4806: }
4807: $record .= $found{$mapstart{$item}};
4808: }
4809: }
4810: $output .= "$record\n";
4811: }
4812: close($fh);
4813: if ($output) {
4814: if (open(my $fh,'>',$fullpath)) {
4815: print $fh $output;
4816: close($fh);
4817: }
4818: }
4819: }
4820: }
4821: return;
4822: }
4823: }
4824:
1.1403 raeburn 4825: sub letter_to_digits {
4826: my %lettdig = (
4827: A => 1,
4828: B => 2,
4829: C => 3,
4830: D => 4,
4831: E => 5,
4832: F => 6,
4833: G => 7,
4834: H => 8,
4835: I => 9,
4836: J => 0,
4837: );
4838: return %lettdig;
4839: }
4840:
1.1401 raeburn 4841: sub get_scantron_config {
4842: my ($which,$cdom) = @_;
4843: my @lines = &get_scantronformat_file($cdom);
4844: my %config;
4845: #FIXME probably should move to XML it has already gotten a bit much now
4846: foreach my $line (@lines) {
4847: my ($name,$descrip)=split(/:/,$line);
4848: if ($name ne $which ) { next; }
4849: chomp($line);
4850: my @config=split(/:/,$line);
4851: $config{'name'}=$config[0];
4852: $config{'description'}=$config[1];
4853: $config{'CODElocation'}=$config[2];
4854: $config{'CODEstart'}=$config[3];
4855: $config{'CODElength'}=$config[4];
4856: $config{'IDstart'}=$config[5];
4857: $config{'IDlength'}=$config[6];
4858: $config{'Qstart'}=$config[7];
4859: $config{'Qlength'}=$config[8];
4860: $config{'Qoff'}=$config[9];
4861: $config{'Qon'}=$config[10];
4862: $config{'PaperID'}=$config[11];
4863: $config{'PaperIDlength'}=$config[12];
4864: $config{'FirstName'}=$config[13];
4865: $config{'FirstNamelength'}=$config[14];
4866: $config{'LastName'}=$config[15];
4867: $config{'LastNamelength'}=$config[16];
4868: $config{'BubblesPerRow'}=$config[17];
4869: last;
4870: }
4871: return %config;
4872: }
4873:
4874: sub get_scantronformat_file {
4875: my ($cdom) = @_;
4876: if ($cdom eq '') {
4877: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4878: }
4879: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4880: my $gottab = 0;
4881: my @lines;
4882: if (ref($domconfig{'scantron'}) eq 'HASH') {
4883: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4884: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4885: if ($formatfile ne '-1') {
4886: @lines = split("\n",$formatfile,-1);
4887: $gottab = 1;
4888: }
4889: }
4890: }
4891: if (!$gottab) {
4892: my $confname = $cdom.'-domainconfig';
4893: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4894: my $formatfile = &getfile($default);
4895: if ($formatfile ne '-1') {
4896: @lines = split("\n",$formatfile,-1);
4897: $gottab = 1;
4898: }
4899: }
4900: if (!$gottab) {
4901: my @domains = ¤t_machine_domains();
4902: if (grep(/^\Q$cdom\E$/,@domains)) {
4903: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4904: @lines = <$fh>;
4905: close($fh);
1.1403 raeburn 4906: }
1.1401 raeburn 4907: } else {
4908: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4909: @lines = <$fh>;
4910: close($fh);
4911: }
4912: }
4913: }
4914: return @lines;
4915: }
4916:
1.493 albertel 4917: sub removeuploadedurl {
1.984 neumanie 4918: my ($url)=@_;
4919: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4920: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4921: }
4922:
4923: sub removeuserfile {
4924: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4925: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4926: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4927: if ($result eq 'ok') {
1.798 raeburn 4928: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4929: my $metafile = $fname.'.meta';
4930: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4931: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4932: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4933: my $sqlresult =
1.823 albertel 4934: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4935: 'portfolio_metadata',$group,
4936: 'delete');
1.798 raeburn 4937: }
4938: }
4939: return $result;
1.257 www 4940: }
1.15 www 4941:
1.530 albertel 4942: sub mkdiruserfile {
4943: my ($docuname,$docudom,$dir)=@_;
4944: my $home=&homeserver($docuname,$docudom);
4945: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4946: }
4947:
1.531 albertel 4948: sub renameuserfile {
4949: my ($docuname,$docudom,$old,$new)=@_;
4950: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4951: my $result = &reply("renameuserfile:$docudom:$docuname:".
4952: &escape("$old").':'.&escape("$new"),$home);
4953: if ($result eq 'ok') {
4954: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4955: my $oldmeta = $old.'.meta';
4956: my $newmeta = $new.'.meta';
4957: my $metaresult =
4958: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4959: my $url = "/uploaded/$docudom/$docuname/$old";
4960: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4961: my $sqlresult =
1.823 albertel 4962: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4963: 'portfolio_metadata',$group,
4964: 'delete');
1.798 raeburn 4965: }
4966: }
4967: return $result;
1.531 albertel 4968: }
4969:
1.14 www 4970: # ------------------------------------------------------------------------- Log
4971:
4972: sub log {
4973: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4974: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4975: }
4976:
4977: # ------------------------------------------------------------------ Course Log
1.352 www 4978: #
4979: # This routine flushes several buffers of non-mission-critical nature
4980: #
1.157 www 4981:
4982: sub flushcourselogs {
1.352 www 4983: &logthis('Flushing log buffers');
4984: #
4985: # course logs
4986: # This is a log of all transactions in a course, which can be used
4987: # for data mining purposes
4988: #
4989: # It also collects the courseid database, which lists last transaction
4990: # times and course titles for all courseids
4991: #
4992: my %courseidbuffer=();
1.921 raeburn 4993: foreach my $crsid (keys(%courselogs)) {
1.352 www 4994: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4995: &escape($courselogs{$crsid}),
4996: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4997: delete $courselogs{$crsid};
4998: } else {
4999: &logthis('Failed to flush log buffer for '.$crsid);
5000: if (length($courselogs{$crsid})>40000) {
1.672 albertel 5001: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 5002: " exceeded maximum size, deleting.</font>");
5003: delete $courselogs{$crsid};
5004: }
1.352 www 5005: }
1.920 raeburn 5006: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 5007: 'description' => $coursedescrbuf{$crsid},
5008: 'inst_code' => $courseinstcodebuf{$crsid},
5009: 'type' => $coursetypebuf{$crsid},
5010: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 5011: };
1.191 harris41 5012: }
1.352 www 5013: #
5014: # Write course id database (reverse lookup) to homeserver of courses
5015: # Is used in pickcourse
5016: #
1.840 albertel 5017: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 5018: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 5019: $courseidbuffer{$crs_home},
5020: $crs_home,'timeonly');
1.352 www 5021: }
5022: #
5023: # File accesses
5024: # Writes to the dynamic metadata of resources to get hit counts, etc.
5025: #
1.449 matthew 5026: foreach my $entry (keys(%accesshash)) {
1.458 matthew 5027: if ($entry =~ /___count$/) {
5028: my ($dom,$name);
1.807 albertel 5029: ($dom,$name,undef)=
1.811 albertel 5030: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 5031: if (! defined($dom) || $dom eq '' ||
5032: ! defined($name) || $name eq '') {
1.620 albertel 5033: my $cid = $env{'request.course.id'};
1.1472 raeburn 5034: #
5035: # FIXME 11/29/2021
5036: # Typo in rev. 1.458 (2003/12/09)??
5037: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
5038: #
5039: # While these ramain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
5040: # $dom and $name will always be null, so the &inc() call will default to storing this data
5041: # in a nohist_accesscount.db file for the user rather than the course.
5042: #
5043: # That said there is a lot of noise in the data being stored.
5044: # So counts for prtspool/ and adm/ etc. are recorded.
5045: #
5046: # A review of which items ending '___count' are written to %accesshash should likely be
5047: # made before deciding whether to set these to 'course.' instead of 'request.'
5048: #
5049: # Under the current scheme each user receives a nohist_accesscount.db file listing
5050: # accesses for things which are not published resources, regardless of course, and
5051: # there is not a nohist_accesscount.db file in a course, which might log accesses from
5052: # anyone in the course for things which are not published resources.
5053: #
5054: # For an author, nohist_accesscount.db ends up having records for other items
5055: # mixed up with the legitimate access counts for the author's published resources.
5056: #
1.620 albertel 5057: $dom = $env{'request.'.$cid.'.domain'};
5058: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 5059: }
1.450 matthew 5060: my $value = $accesshash{$entry};
5061: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
5062: my %temphash=($url => $value);
1.449 matthew 5063: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
5064: if ($result eq 'ok') {
5065: delete $accesshash{$entry};
5066: }
5067: } else {
1.811 albertel 5068: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 5069: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 5070: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 5071: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
5072: delete $accesshash{$entry};
5073: }
1.185 www 5074: }
1.191 harris41 5075: }
1.352 www 5076: #
5077: # Roles
5078: # Reverse lookup of user roles for course faculty/staff and co-authorship
5079: #
1.800 albertel 5080: foreach my $entry (keys(%userrolehash)) {
1.351 www 5081: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 5082: split(/\:/,$entry);
5083: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 5084: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 5085: $rudom,$runame) eq 'ok') {
5086: delete $userrolehash{$entry};
5087: }
5088: }
1.662 raeburn 5089: #
1.1334 raeburn 5090: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 5091: #
5092: my %domrolebuffer = ();
1.1000 raeburn 5093: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 5094: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 5095: if ($domrolebuffer{$rudom}) {
5096: $domrolebuffer{$rudom}.='&'.&escape($entry).
5097: '='.&escape($domainrolehash{$entry});
5098: } else {
5099: $domrolebuffer{$rudom}.=&escape($entry).
5100: '='.&escape($domainrolehash{$entry});
5101: }
5102: delete $domainrolehash{$entry};
5103: }
5104: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 5105: my %servers;
5106: if (defined(&domain($dom,'primary'))) {
5107: my $primary=&domain($dom,'primary');
5108: my $hostname=&hostname($primary);
5109: $servers{$primary} = $hostname;
5110: } else {
5111: %servers = &get_servers($dom,'library');
5112: }
1.841 albertel 5113: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 5114: if (&reply('domroleput:'.$dom.':'.
5115: $domrolebuffer{$dom},$tryserver) eq 'ok') {
5116: last;
5117: } else {
1.841 albertel 5118: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
5119: }
1.662 raeburn 5120: }
5121: }
1.186 www 5122: $dumpcount++;
1.157 www 5123: }
5124:
5125: sub courselog {
5126: my $what=shift;
1.158 www 5127: $what=time.':'.$what;
1.620 albertel 5128: unless ($env{'request.course.id'}) { return ''; }
5129: $coursedombuf{$env{'request.course.id'}}=
5130: $env{'course.'.$env{'request.course.id'}.'.domain'};
5131: $coursenumbuf{$env{'request.course.id'}}=
5132: $env{'course.'.$env{'request.course.id'}.'.num'};
5133: $coursehombuf{$env{'request.course.id'}}=
5134: $env{'course.'.$env{'request.course.id'}.'.home'};
5135: $coursedescrbuf{$env{'request.course.id'}}=
5136: $env{'course.'.$env{'request.course.id'}.'.description'};
5137: $courseinstcodebuf{$env{'request.course.id'}}=
5138: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
5139: $courseownerbuf{$env{'request.course.id'}}=
5140: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 5141: $coursetypebuf{$env{'request.course.id'}}=
5142: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 5143: if (defined $courselogs{$env{'request.course.id'}}) {
5144: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 5145: } else {
1.620 albertel 5146: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 5147: }
1.620 albertel 5148: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 5149: &flushcourselogs();
5150: }
1.158 www 5151: }
5152:
5153: sub courseacclog {
5154: my $fnsymb=shift;
1.620 albertel 5155: unless ($env{'request.course.id'}) { return ''; }
5156: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 5157: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 5158: $what.=':POST';
1.583 matthew 5159: # FIXME: Probably ought to escape things....
1.800 albertel 5160: foreach my $key (keys(%env)) {
5161: if ($key=~/^form\.(.*)/) {
1.975 raeburn 5162: my $formitem = $1;
5163: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
5164: $what.=':'.$formitem.'='.$env{$key};
5165: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432 raeburn 5166: if ($formitem eq 'proctorpassword') {
1.1433 raeburn 5167: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432 raeburn 5168: } else {
5169: $what.=':'.$formitem.'='.$env{$key};
5170: }
1.975 raeburn 5171: }
1.158 www 5172: }
1.191 harris41 5173: }
1.583 matthew 5174: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
5175: # FIXME: We should not be depending on a form parameter that someone
5176: # editing lonsearchcat.pm might change in the future.
1.620 albertel 5177: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 5178: $what.= ':POST';
5179: # FIXME: Probably ought to escape things....
5180: foreach my $element ('courseexp','crsfulltext','crsrelated',
5181: 'crsdiscuss') {
1.620 albertel 5182: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 5183: }
5184: }
1.158 www 5185: }
5186: &courselog($what);
1.149 www 5187: }
5188:
1.185 www 5189: sub countacc {
5190: my $url=&declutter(shift);
1.458 matthew 5191: return if (! defined($url) || $url eq '');
1.620 albertel 5192: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 5193: #
5194: # Mark that this url was used in this course
5195: #
1.620 albertel 5196: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 5197: #
5198: # Increase the access count for this resource in this child process
5199: #
1.281 www 5200: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 5201: $accesshash{$key}++;
1.185 www 5202: }
1.349 www 5203:
1.361 www 5204: sub linklog {
5205: my ($from,$to)=@_;
5206: $from=&declutter($from);
5207: $to=&declutter($to);
5208: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5209: $accesshash{$to.'___'.$from.'___goto'}=1;
5210: }
1.1160 www 5211:
5212: sub statslog {
5213: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5214: if ($users<2) { return; }
5215: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5216: 'course' => $env{'request.course.id'},
5217: 'sections' => '"all"',
5218: 'num_students' => $users,
5219: 'part' => $part,
5220: 'symb' => $symb,
5221: 'mean_tries' => $av_attempts,
5222: 'deg_of_diff' => $degdiff});
5223: foreach my $key (keys(%dynstore)) {
5224: $accesshash{$key}=$dynstore{$key};
5225: }
5226: }
1.361 www 5227:
1.349 www 5228: sub userrolelog {
5229: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 5230: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 5231: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5232: $userrolehash
5233: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 5234: =$tend.':'.$tstart;
1.662 raeburn 5235: }
1.1169 droeschl 5236: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 5237: $userrolehash
5238: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5239: =$tend.':'.$tstart;
5240: }
1.1334 raeburn 5241: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 5242: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5243: $domainrolehash
5244: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5245: = $tend.':'.$tstart;
5246: }
1.351 www 5247: }
5248:
1.957 raeburn 5249: sub courserolelog {
5250: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 5251: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5252: my $cdom = $1;
5253: my $cnum = $2;
5254: my $sec = $3;
5255: my $namespace = 'rolelog';
5256: my %storehash = (
5257: role => $trole,
5258: start => $tstart,
5259: end => $tend,
5260: selfenroll => $selfenroll,
5261: context => $context,
5262: );
5263: if ($trole eq 'gr') {
5264: $namespace = 'groupslog';
5265: $storehash{'group'} = $sec;
5266: } else {
5267: $storehash{'section'} = $sec;
5268: }
1.1188 raeburn 5269: &write_log('course',$namespace,\%storehash,$delflag,$username,
5270: $domain,$cnum,$cdom);
1.1184 raeburn 5271: if (($trole ne 'st') || ($sec ne '')) {
5272: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 5273: }
5274: }
5275: return;
5276: }
5277:
1.1184 raeburn 5278: sub domainrolelog {
5279: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5280: if ($area =~ m{^/($match_domain)/$}) {
5281: my $cdom = $1;
5282: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
5283: my $namespace = 'rolelog';
5284: my %storehash = (
5285: role => $trole,
5286: start => $tstart,
5287: end => $tend,
5288: context => $context,
5289: );
1.1188 raeburn 5290: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5291: $domain,$domconfiguser,$cdom);
1.1184 raeburn 5292: }
5293: return;
5294:
5295: }
5296:
5297: sub coauthorrolelog {
5298: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5299: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5300: my $audom = $1;
5301: my $auname = $2;
5302: my $namespace = 'rolelog';
5303: my %storehash = (
5304: role => $trole,
5305: start => $tstart,
5306: end => $tend,
5307: context => $context,
5308: );
1.1188 raeburn 5309: &write_log('author',$namespace,\%storehash,$delflag,$username,
5310: $domain,$auname,$audom);
1.1184 raeburn 5311: }
5312: return;
5313: }
5314:
1.351 www 5315: sub get_course_adv_roles {
1.948 raeburn 5316: my ($cid,$codes) = @_;
1.620 albertel 5317: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 5318: my %coursehash=&coursedescription($cid);
1.988 raeburn 5319: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 5320: my %nothide=();
1.800 albertel 5321: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 5322: if ($user !~ /:/) {
5323: $nothide{join(':',split(/[\@]/,$user))}=1;
5324: } else {
5325: $nothide{$user}=1;
5326: }
1.470 www 5327: }
1.1219 raeburn 5328: my @possdoms = ($coursehash{'domain'});
5329: if ($coursehash{'checkforpriv'}) {
5330: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5331: }
1.351 www 5332: my %returnhash=();
5333: my %dumphash=
5334: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5335: my $now=time;
1.997 raeburn 5336: my %privileged;
1.1000 raeburn 5337: foreach my $entry (keys(%dumphash)) {
1.800 albertel 5338: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 5339: if (($tstart) && ($tstart<0)) { next; }
5340: if (($tend) && ($tend<$now)) { next; }
5341: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 5342: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 5343: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 5344: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 5345: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 5346: if ($role eq 'cr') { next; }
1.948 raeburn 5347: if ($codes) {
5348: if ($section) { $role .= ':'.$section; }
5349: if ($returnhash{$role}) {
5350: $returnhash{$role}.=','.$username.':'.$domain;
5351: } else {
5352: $returnhash{$role}=$username.':'.$domain;
5353: }
1.351 www 5354: } else {
1.988 raeburn 5355: my $key=&plaintext($role,$crstype);
1.973 bisitz 5356: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 5357: if ($returnhash{$key}) {
5358: $returnhash{$key}.=','.$username.':'.$domain;
5359: } else {
5360: $returnhash{$key}=$username.':'.$domain;
5361: }
1.351 www 5362: }
1.948 raeburn 5363: }
1.400 www 5364: return %returnhash;
5365: }
5366:
5367: sub get_my_roles {
1.937 raeburn 5368: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5369: unless (defined($uname)) { $uname=$env{'user.name'}; }
5370: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5371: my (%dumphash,%nothide);
1.1086 raeburn 5372: if ($context eq 'userroles') {
1.1166 raeburn 5373: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5374: } else {
1.1219 raeburn 5375: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5376: if ($hidepriv) {
5377: my %coursehash=&coursedescription($udom.'_'.$uname);
5378: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5379: if ($user !~ /:/) {
5380: $nothide{join(':',split(/[\@]/,$user))} = 1;
5381: } else {
5382: $nothide{$user} = 1;
5383: }
5384: }
5385: }
1.858 raeburn 5386: }
1.400 www 5387: my %returnhash=();
5388: my $now=time;
1.999 raeburn 5389: my %privileged;
1.800 albertel 5390: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5391: my ($role,$tend,$tstart);
5392: if ($context eq 'userroles') {
1.1149 raeburn 5393: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5394: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5395: } else {
5396: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5397: }
1.400 www 5398: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5399: my $status = 'active';
1.939 raeburn 5400: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5401: $status = 'previous';
5402: }
5403: if (($tstart) && ($now<$tstart)) {
5404: $status = 'future';
5405: }
5406: if (ref($types) eq 'ARRAY') {
5407: if (!grep(/^\Q$status\E$/,@{$types})) {
5408: next;
5409: }
5410: } else {
5411: if ($status ne 'active') {
5412: next;
5413: }
5414: }
1.867 raeburn 5415: my ($rolecode,$username,$domain,$section,$area);
5416: if ($context eq 'userroles') {
1.1186 raeburn 5417: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5418: (undef,$domain,$username,$section) = split(/\//,$area);
5419: } else {
5420: ($role,$username,$domain,$section) = split(/\:/,$entry);
5421: }
1.832 raeburn 5422: if (ref($roledoms) eq 'ARRAY') {
5423: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5424: next;
5425: }
5426: }
5427: if (ref($roles) eq 'ARRAY') {
5428: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5429: if ($role =~ /^cr\//) {
5430: if (!grep(/^cr$/,@{$roles})) {
5431: next;
5432: }
1.1104 raeburn 5433: } elsif ($role =~ /^gr\//) {
5434: if (!grep(/^gr$/,@{$roles})) {
5435: next;
5436: }
1.922 raeburn 5437: } else {
5438: next;
5439: }
1.832 raeburn 5440: }
1.867 raeburn 5441: }
1.937 raeburn 5442: if ($hidepriv) {
1.1219 raeburn 5443: my @privroles = ('dc','su');
1.999 raeburn 5444: if ($context eq 'userroles') {
1.1219 raeburn 5445: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5446: } else {
1.1219 raeburn 5447: my $possdoms = [$domain];
5448: if (ref($roledoms) eq 'ARRAY') {
5449: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5450: }
1.1219 raeburn 5451: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5452: if (!$nothide{$username.':'.$domain}) {
5453: next;
5454: }
5455: }
1.937 raeburn 5456: }
5457: }
1.933 raeburn 5458: if ($withsec) {
5459: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5460: $tstart.':'.$tend;
5461: } else {
5462: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5463: }
1.832 raeburn 5464: }
1.373 www 5465: return %returnhash;
1.399 www 5466: }
5467:
1.1333 raeburn 5468: sub get_all_adhocroles {
5469: my ($dom) = @_;
5470: my @roles_by_num = ();
5471: my %domdefaults = &get_domain_defaults($dom);
5472: my (%description,%access_in_dom,%access_info);
5473: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5474: my $count = 0;
5475: my %domcurrent = %{$domdefaults{'adhocroles'}};
5476: my %ordered;
5477: foreach my $role (sort(keys(%domcurrent))) {
5478: my ($order,$desc,$access_in_dom);
5479: if (ref($domcurrent{$role}) eq 'HASH') {
5480: $order = $domcurrent{$role}{'order'};
5481: $desc = $domcurrent{$role}{'desc'};
5482: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5483: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5484: }
5485: if ($order eq '') {
5486: $order = $count;
5487: }
5488: $ordered{$order} = $role;
5489: if ($desc ne '') {
5490: $description{$role} = $desc;
5491: } else {
5492: $description{$role}= $role;
5493: }
5494: $count++;
5495: }
5496: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5497: push(@roles_by_num,$ordered{$item});
5498: }
5499: }
5500: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5501: }
5502:
1.1332 raeburn 5503: sub get_my_adhocroles {
1.1333 raeburn 5504: my ($cid,$checkreg) = @_;
5505: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5506: if ($env{'request.course.id'} eq $cid) {
5507: $cdom = $env{'course.'.$cid.'.domain'};
5508: $cnum = $env{'course.'.$cid.'.num'};
5509: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5510: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5511: $cdom = $1;
5512: $cnum = $2;
5513: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5514: $cdom,$cnum);
5515: }
5516: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5517: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5518: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5519: if ($rosterhash{$user} ne '') {
5520: my $type = (split(/:/,$rosterhash{$user}))[5];
5521: return ([],{}) if ($type eq 'auto');
5522: }
5523: }
5524: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 5525: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 5526: my $then=$env{'user.login.time'};
5527: my $update=$env{'user.update.time'};
1.1335 raeburn 5528: if (!$update) {
5529: $update = $then;
5530: }
5531: my @liveroles;
1.1334 raeburn 5532: foreach my $role ('dh','da') {
5533: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 5534: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 5535: my $limit = $update;
5536: if ($env{'request.role'} eq "$role./$cdom/") {
5537: $limit = $then;
5538: }
1.1335 raeburn 5539: my $activerole = 1;
5540: if ($tstart && $tstart>$limit) { $activerole = 0; }
5541: if ($tend && $tend <$limit) { $activerole = 0; }
5542: if ($activerole) {
5543: push(@liveroles,$role);
5544: }
1.1334 raeburn 5545: }
1.1332 raeburn 5546: }
1.1335 raeburn 5547: if (@liveroles) {
1.1332 raeburn 5548: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 5549: my ($accessref,$accessinfo,%access_in_dom);
5550: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5551: if (ref($roles_by_num) eq 'ARRAY') {
5552: if (@{$roles_by_num}) {
1.1332 raeburn 5553: my %settings;
5554: if ($env{'request.course.id'} eq $cid) {
5555: foreach my $envkey (keys(%env)) {
5556: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5557: $settings{$1} = $env{$envkey};
5558: }
5559: }
5560: } else {
5561: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5562: }
5563: my %setincrs;
5564: if ($settings{'internal.adhocaccess'}) {
5565: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5566: }
5567: my @statuses;
5568: if ($env{'environment.inststatus'}) {
5569: @statuses = split(/,/,$env{'environment.inststatus'});
5570: }
5571: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 5572: if (ref($accessref) eq 'HASH') {
5573: %access_in_dom = %{$accessref};
5574: }
5575: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 5576: my ($curraccess,@okstatus,@personnel);
5577: if ($setincrs{$role}) {
5578: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5579: if ($curraccess eq 'status') {
5580: @okstatus = split(/\&/,$rest);
5581: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5582: @personnel = split(/\&/,$rest);
5583: }
5584: } else {
5585: $curraccess = $access_in_dom{$role};
1.1333 raeburn 5586: if (ref($accessinfo) eq 'HASH') {
5587: if ($curraccess eq 'status') {
5588: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5589: @okstatus = @{$accessinfo->{$role}};
5590: }
5591: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5592: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5593: @personnel = @{$accessinfo->{$role}};
5594: }
1.1332 raeburn 5595: }
5596: }
5597: }
5598: if ($curraccess eq 'none') {
5599: next;
5600: } elsif ($curraccess eq 'all') {
5601: push(@possroles,$role);
1.1336 raeburn 5602: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 5603: if (grep(/^dh$/,@liveroles)) {
5604: push(@possroles,$role);
5605: } else {
5606: next;
5607: }
1.1336 raeburn 5608: } elsif ($curraccess eq 'da') {
1.1335 raeburn 5609: if (grep(/^da$/,@liveroles)) {
5610: push(@possroles,$role);
5611: } else {
5612: next;
5613: }
1.1332 raeburn 5614: } elsif ($curraccess eq 'status') {
5615: if (@okstatus) {
5616: if (!@statuses) {
5617: if (grep(/^default$/,@okstatus)) {
5618: push(@possroles,$role);
5619: }
5620: } else {
5621: foreach my $status (@okstatus) {
5622: if (grep(/^\Q$status\E$/,@statuses)) {
5623: push(@possroles,$role);
5624: last;
5625: }
5626: }
5627: }
5628: }
5629: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5630: if (grep(/^\Q$user\E$/,@personnel)) {
5631: if ($curraccess eq 'exc') {
5632: push(@possroles,$role);
5633: }
5634: } elsif ($curraccess eq 'inc') {
5635: push(@possroles,$role);
5636: }
5637: }
5638: }
5639: }
5640: }
5641: }
5642: }
5643: }
5644: }
1.1333 raeburn 5645: unless (ref($description) eq 'HASH') {
5646: if (ref($roles_by_num) eq 'ARRAY') {
5647: my %desc;
5648: map { $desc{$_} = $_; } (@{$roles_by_num});
5649: $description = \%desc;
5650: } else {
5651: $description = {};
5652: }
5653: }
5654: return (\@possroles,$description);
1.1332 raeburn 5655: }
5656:
1.399 www 5657: # ----------------------------------------------------- Frontpage Announcements
5658: #
5659: #
5660:
5661: sub postannounce {
5662: my ($server,$text)=@_;
1.844 albertel 5663: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5664: unless ($text=~/\w/) { $text=''; }
5665: return &reply('setannounce:'.&escape($text),$server);
5666: }
5667:
5668: sub getannounce {
1.448 albertel 5669:
1.1359 raeburn 5670: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5671: my $announcement='';
1.800 albertel 5672: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5673: close($fh);
1.399 www 5674: if ($announcement=~/\w/) {
5675: return
5676: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5677: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5678: } else {
5679: return '';
5680: }
5681: } else {
5682: return '';
5683: }
1.351 www 5684: }
1.353 www 5685:
5686: # ---------------------------------------------------------- Course ID routines
5687: # Deal with domain's nohist_courseid.db files
5688: #
5689:
5690: sub courseidput {
1.921 raeburn 5691: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5692: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5693: my $outcome;
5694: if ($caller eq 'timeonly') {
5695: my $cids = '';
5696: foreach my $item (keys(%$storehash)) {
5697: $cids.=&escape($item).'&';
5698: }
5699: $cids=~s/\&$//;
5700: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5701: $coursehome);
5702: } else {
5703: my $items = '';
5704: foreach my $item (keys(%$storehash)) {
5705: $items.= &escape($item).'='.
5706: &freeze_escape($$storehash{$item}).'&';
5707: }
5708: $items=~s/\&$//;
5709: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5710: $coursehome);
1.918 raeburn 5711: }
5712: if ($outcome eq 'unknown_cmd') {
5713: my $what;
5714: foreach my $cid (keys(%$storehash)) {
5715: $what .= &escape($cid).'=';
1.921 raeburn 5716: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5717: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5718: }
5719: $what =~ s/\:$/&/;
5720: }
5721: $what =~ s/\&$//;
5722: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5723: } else {
5724: return $outcome;
5725: }
1.353 www 5726: }
5727:
5728: sub courseiddump {
1.921 raeburn 5729: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5730: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5731: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 5732: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 5733: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5734: my $as_hash = 1;
5735: my %returnhash;
5736: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5737: my %libserv = &all_library();
5738: foreach my $tryserver (keys(%libserv)) {
5739: if ( ( $hostidflag == 1
5740: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5741: || (!defined($hostidflag)) ) {
5742:
1.918 raeburn 5743: if (($domfilter eq '') ||
5744: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 5745: my $rep;
5746: if (grep { $_ eq $tryserver } current_machine_ids()) {
5747: $rep = LONCAPA::Lond::dump_course_id_handler(
5748: join(":", (&host_domain($tryserver), $sincefilter,
5749: &escape($descfilter), &escape($instcodefilter),
5750: &escape($ownerfilter), &escape($coursefilter),
5751: &escape($typefilter), &escape($regexp_ok),
5752: $as_hash, &escape($selfenrollonly),
5753: &escape($catfilter), $showhidden, $caller,
5754: &escape($cloner), &escape($cc_clone), $cloneonly,
5755: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 5756: &escape($creationcontext),$domcloner,$hasuniquecode,
5757: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 5758: } else {
5759: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5760: $sincefilter.':'.&escape($descfilter).':'.
5761: &escape($instcodefilter).':'.&escape($ownerfilter).
5762: ':'.&escape($coursefilter).':'.&escape($typefilter).
5763: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5764: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5765: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5766: &escape($cc_clone).':'.$cloneonly.':'.
5767: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 5768: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5769: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 5770: }
5771:
1.918 raeburn 5772: my @pairs=split(/\&/,$rep);
5773: foreach my $item (@pairs) {
5774: my ($key,$value)=split(/\=/,$item,2);
5775: $key = &unescape($key);
5776: next if ($key =~ /^error: 2 /);
5777: my $result = &thaw_unescape($value);
5778: if (ref($result) eq 'HASH') {
5779: $returnhash{$key}=$result;
5780: } else {
1.921 raeburn 5781: my @responses = split(/:/,$value);
5782: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5783: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5784: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5785: }
1.1008 raeburn 5786: }
1.353 www 5787: }
5788: }
5789: }
5790: }
5791: return %returnhash;
5792: }
5793:
1.1055 raeburn 5794: sub courselastaccess {
5795: my ($cdom,$cnum,$hostidref) = @_;
5796: my %returnhash;
5797: if ($cdom && $cnum) {
5798: my $chome = &homeserver($cnum,$cdom);
5799: if ($chome ne 'no_host') {
5800: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5801: &extract_lastaccess(\%returnhash,$rep);
5802: }
5803: } else {
5804: if (!$cdom) { $cdom=''; }
5805: my %libserv = &all_library();
5806: foreach my $tryserver (keys(%libserv)) {
5807: if (ref($hostidref) eq 'ARRAY') {
5808: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5809: }
5810: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5811: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5812: &extract_lastaccess(\%returnhash,$rep);
5813: }
5814: }
5815: }
5816: return %returnhash;
5817: }
5818:
5819: sub extract_lastaccess {
5820: my ($returnhash,$rep) = @_;
5821: if (ref($returnhash) eq 'HASH') {
5822: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5823: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5824: $rep eq '') {
5825: my @pairs=split(/\&/,$rep);
5826: foreach my $item (@pairs) {
5827: my ($key,$value)=split(/\=/,$item,2);
5828: $key = &unescape($key);
5829: next if ($key =~ /^error: 2 /);
5830: $returnhash->{$key} = &thaw_unescape($value);
5831: }
5832: }
5833: }
5834: return;
5835: }
5836:
1.658 raeburn 5837: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5838:
5839: sub dcmailput {
1.685 raeburn 5840: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5841: my $status = &Apache::lonnet::critical(
1.740 www 5842: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5843: &escape($message),$server);
1.662 raeburn 5844: return $status;
5845: }
5846:
1.658 raeburn 5847: sub dcmaildump {
5848: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5849: my %returnhash=();
1.846 albertel 5850:
5851: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5852: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5853: &escape($enddate).':';
5854: my @esc_senders=map { &escape($_)} @$senders;
5855: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5856: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5857: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5858: if (($key) && ($value)) {
5859: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5860: }
5861: }
5862: }
5863: return %returnhash;
5864: }
1.662 raeburn 5865: # ---------------------------------------------------------- Domain roles
5866:
5867: sub get_domain_roles {
5868: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5869: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5870: $startdate = '.';
5871: }
1.1018 raeburn 5872: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5873: $enddate = '.';
5874: }
1.922 raeburn 5875: my $rolelist;
5876: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 5877: $rolelist = join('&',@{$roles});
1.922 raeburn 5878: }
1.662 raeburn 5879: my %personnel = ();
1.841 albertel 5880:
5881: my %servers = &get_servers($dom,'library');
5882: foreach my $tryserver (keys(%servers)) {
5883: %{$personnel{$tryserver}}=();
5884: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5885: &escape($startdate).':'.
5886: &escape($enddate).':'.
5887: &escape($rolelist), $tryserver))) {
5888: my ($key,$value) = split(/\=/,$line,2);
5889: if (($key) && ($value)) {
5890: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5891: }
5892: }
1.662 raeburn 5893: }
5894: return %personnel;
5895: }
1.658 raeburn 5896:
1.1332 raeburn 5897: sub get_active_domroles {
5898: my ($dom,$roles) = @_;
5899: return () unless (ref($roles) eq 'ARRAY');
5900: my $now = time;
5901: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5902: my %domroles;
5903: foreach my $server (keys(%dompersonnel)) {
5904: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5905: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5906: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5907: }
5908: }
5909: return %domroles;
5910: }
5911:
1.1057 www 5912: # ----------------------------------------------------------- Interval timing
1.149 www 5913:
1.1153 www 5914: {
5915: # Caches needed for speedup of navmaps
5916: # We don't want to cache this for very long at all (5 seconds at most)
5917: #
5918: # The user for whom we cache
5919: my $cachedkey='';
5920: # The cached times for this user
5921: my %cachedtimes=();
5922: # When this was last done
1.1282 raeburn 5923: my $cachedtime='';
1.1153 www 5924:
5925: sub load_all_first_access {
1.1308 raeburn 5926: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5927: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 5928: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5929: (!$ignorecache)) {
1.1154 raeburn 5930: return;
5931: }
5932: $cachedtime=time;
5933: $cachedkey=$uname.':'.$udom;
5934: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5935: }
5936:
1.504 albertel 5937: sub get_first_access {
1.1308 raeburn 5938: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5939: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5940: if ($argsymb) { $symb=$argsymb; }
5941: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5942: if ($argmap) { $map = $argmap; }
1.926 albertel 5943: if ($type eq 'course') {
5944: $res='course';
5945: } elsif ($type eq 'map') {
1.588 albertel 5946: $res=&symbread($map);
5947: } else {
5948: $res=$symb;
5949: }
1.1308 raeburn 5950: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 5951: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5952: }
5953:
5954: sub set_first_access {
1.1162 raeburn 5955: my ($type,$interval)=@_;
1.790 albertel 5956: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5957: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5958: if ($type eq 'course') {
5959: $res='course';
5960: } elsif ($type eq 'map') {
1.588 albertel 5961: $res=&symbread($map);
5962: } else {
5963: $res=$symb;
5964: }
1.1153 www 5965: $cachedkey='';
1.1162 raeburn 5966: my $firstaccess=&get_first_access($type,$symb,$map);
1.1386 raeburn 5967: if ($firstaccess) {
5968: &logthis("First access time already set ($firstaccess) when attempting ".
1.1393 raeburn 5969: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5970: "in $courseid");
1.1386 raeburn 5971: return 'already_set';
5972: } else {
1.1162 raeburn 5973: my $start = time;
5974: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5975: $udom,$uname);
5976: if ($putres eq 'ok') {
5977: &put('timerinterval',{"$courseid\0$res"=>$interval},
5978: $udom,$uname);
5979: &appenv(
5980: {
5981: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5982: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5983: }
5984: );
1.1365 raeburn 5985: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5986: $cachedtimes{"$courseid\0$res"} = $start;
5987: }
1.1386 raeburn 5988: } elsif ($putres ne 'refused') {
5989: &logthis("Result: $putres when attempting to set first access time ".
5990: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5991: }
5992: return $putres;
1.505 albertel 5993: }
5994: return 'already_set';
1.504 albertel 5995: }
1.1153 www 5996: }
1.1282 raeburn 5997:
1.110 www 5998: # --------------------------------------------- Set Expire Date for Spreadsheet
5999:
6000: sub expirespread {
6001: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 6002: my $cid=$env{'request.course.id'};
1.110 www 6003: if ($cid) {
6004: my $now=time;
6005: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 6006: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
6007: $env{'course.'.$cid.'.num'}.
1.110 www 6008: ':nohist_expirationdates:'.
6009: &escape($key).'='.$now,
1.620 albertel 6010: $env{'course.'.$cid.'.home'})
1.110 www 6011: }
6012: return 'ok';
1.14 www 6013: }
6014:
1.109 www 6015: # ----------------------------------------------------- Devalidate Spreadsheets
6016:
6017: sub devalidate {
1.325 www 6018: my ($symb,$uname,$udom)=@_;
1.620 albertel 6019: my $cid=$env{'request.course.id'};
1.109 www 6020: if ($cid) {
1.391 matthew 6021: # delete the stored spreadsheets for
6022: # - the student level sheet of this user in course's homespace
6023: # - the assessment level sheet for this resource
6024: # for this user in user's homespace
1.553 albertel 6025: # - current conditional state info
1.325 www 6026: my $key=$uname.':'.$udom.':';
1.109 www 6027: my $status=
1.299 matthew 6028: &del('nohist_calculatedsheets',
1.391 matthew 6029: [$key.'studentcalc:'],
1.620 albertel 6030: $env{'course.'.$cid.'.domain'},
6031: $env{'course.'.$cid.'.num'})
1.133 albertel 6032: .' '.
6033: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 6034: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 6035: unless ($status eq 'ok ok') {
6036: &logthis('Could not devalidate spreadsheet '.
1.325 www 6037: $uname.' at '.$udom.' for '.
1.109 www 6038: $symb.': '.$status);
1.133 albertel 6039: }
1.553 albertel 6040: &delenv('user.state.'.$cid);
1.109 www 6041: }
6042: }
6043:
1.265 albertel 6044: sub get_scalar {
6045: my ($string,$end) = @_;
6046: my $value;
6047: if ($$string =~ s/^([^&]*?)($end)/$2/) {
6048: $value = $1;
6049: } elsif ($$string =~ s/^([^&]*?)&//) {
6050: $value = $1;
6051: }
6052: return &unescape($value);
6053: }
6054:
6055: sub array2str {
6056: my (@array) = @_;
6057: my $result=&arrayref2str(\@array);
6058: $result=~s/^__ARRAY_REF__//;
6059: $result=~s/__END_ARRAY_REF__$//;
6060: return $result;
6061: }
6062:
1.204 albertel 6063: sub arrayref2str {
6064: my ($arrayref) = @_;
1.265 albertel 6065: my $result='__ARRAY_REF__';
1.204 albertel 6066: foreach my $elem (@$arrayref) {
1.265 albertel 6067: if(ref($elem) eq 'ARRAY') {
6068: $result.=&arrayref2str($elem).'&';
6069: } elsif(ref($elem) eq 'HASH') {
6070: $result.=&hashref2str($elem).'&';
6071: } elsif(ref($elem)) {
6072: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 6073: } else {
6074: $result.=&escape($elem).'&';
6075: }
6076: }
6077: $result=~s/\&$//;
1.265 albertel 6078: $result .= '__END_ARRAY_REF__';
1.204 albertel 6079: return $result;
6080: }
6081:
1.168 albertel 6082: sub hash2str {
1.204 albertel 6083: my (%hash) = @_;
6084: my $result=&hashref2str(\%hash);
1.265 albertel 6085: $result=~s/^__HASH_REF__//;
6086: $result=~s/__END_HASH_REF__$//;
1.204 albertel 6087: return $result;
6088: }
6089:
6090: sub hashref2str {
6091: my ($hashref)=@_;
1.265 albertel 6092: my $result='__HASH_REF__';
1.800 albertel 6093: foreach my $key (sort(keys(%$hashref))) {
6094: if (ref($key) eq 'ARRAY') {
6095: $result.=&arrayref2str($key).'=';
6096: } elsif (ref($key) eq 'HASH') {
6097: $result.=&hashref2str($key).'=';
6098: } elsif (ref($key)) {
1.265 albertel 6099: $result.='=';
1.800 albertel 6100: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 6101: } else {
1.1132 raeburn 6102: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 6103: }
6104:
1.800 albertel 6105: if(ref($hashref->{$key}) eq 'ARRAY') {
6106: $result.=&arrayref2str($hashref->{$key}).'&';
6107: } elsif(ref($hashref->{$key}) eq 'HASH') {
6108: $result.=&hashref2str($hashref->{$key}).'&';
6109: } elsif(ref($hashref->{$key})) {
1.265 albertel 6110: $result.='&';
1.800 albertel 6111: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 6112: } else {
1.800 albertel 6113: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 6114: }
6115: }
1.168 albertel 6116: $result=~s/\&$//;
1.265 albertel 6117: $result .= '__END_HASH_REF__';
1.168 albertel 6118: return $result;
6119: }
6120:
6121: sub str2hash {
1.265 albertel 6122: my ($string)=@_;
6123: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
6124: return %$hash;
6125: }
6126:
6127: sub str2hashref {
1.168 albertel 6128: my ($string) = @_;
1.265 albertel 6129:
6130: my %hash;
6131:
6132: if($string !~ /^__HASH_REF__/) {
6133: if (! ($string eq '' || !defined($string))) {
6134: $hash{'error'}='Not hash reference';
6135: }
6136: return (\%hash, $string);
6137: }
6138:
6139: $string =~ s/^__HASH_REF__//;
6140:
6141: while($string !~ /^__END_HASH_REF__/) {
6142: #key
6143: my $key='';
6144: if($string =~ /^__HASH_REF__/) {
6145: ($key, $string)=&str2hashref($string);
6146: if(defined($key->{'error'})) {
6147: $hash{'error'}='Bad data';
6148: return (\%hash, $string);
6149: }
6150: } elsif($string =~ /^__ARRAY_REF__/) {
6151: ($key, $string)=&str2arrayref($string);
6152: if($key->[0] eq 'Array reference error') {
6153: $hash{'error'}='Bad data';
6154: return (\%hash, $string);
6155: }
6156: } else {
6157: $string =~ s/^(.*?)=//;
1.267 albertel 6158: $key=&unescape($1);
1.265 albertel 6159: }
6160: $string =~ s/^=//;
6161:
6162: #value
6163: my $value='';
6164: if($string =~ /^__HASH_REF__/) {
6165: ($value, $string)=&str2hashref($string);
6166: if(defined($value->{'error'})) {
6167: $hash{'error'}='Bad data';
6168: return (\%hash, $string);
6169: }
6170: } elsif($string =~ /^__ARRAY_REF__/) {
6171: ($value, $string)=&str2arrayref($string);
6172: if($value->[0] eq 'Array reference error') {
6173: $hash{'error'}='Bad data';
6174: return (\%hash, $string);
6175: }
6176: } else {
6177: $value=&get_scalar(\$string,'__END_HASH_REF__');
6178: }
6179: $string =~ s/^&//;
6180:
6181: $hash{$key}=$value;
1.204 albertel 6182: }
1.265 albertel 6183:
6184: $string =~ s/^__END_HASH_REF__//;
6185:
6186: return (\%hash, $string);
1.204 albertel 6187: }
6188:
6189: sub str2array {
1.265 albertel 6190: my ($string)=@_;
6191: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
6192: return @$array;
6193: }
6194:
6195: sub str2arrayref {
1.204 albertel 6196: my ($string) = @_;
1.265 albertel 6197: my @array;
6198:
6199: if($string !~ /^__ARRAY_REF__/) {
6200: if (! ($string eq '' || !defined($string))) {
6201: $array[0]='Array reference error';
6202: }
6203: return (\@array, $string);
6204: }
6205:
6206: $string =~ s/^__ARRAY_REF__//;
6207:
6208: while($string !~ /^__END_ARRAY_REF__/) {
6209: my $value='';
6210: if($string =~ /^__HASH_REF__/) {
6211: ($value, $string)=&str2hashref($string);
6212: if(defined($value->{'error'})) {
6213: $array[0] ='Array reference error';
6214: return (\@array, $string);
6215: }
6216: } elsif($string =~ /^__ARRAY_REF__/) {
6217: ($value, $string)=&str2arrayref($string);
6218: if($value->[0] eq 'Array reference error') {
6219: $array[0] ='Array reference error';
6220: return (\@array, $string);
6221: }
6222: } else {
6223: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6224: }
6225: $string =~ s/^&//;
6226:
6227: push(@array, $value);
1.191 harris41 6228: }
1.265 albertel 6229:
6230: $string =~ s/^__END_ARRAY_REF__//;
6231:
6232: return (\@array, $string);
1.168 albertel 6233: }
6234:
1.167 albertel 6235: # -------------------------------------------------------------------Temp Store
6236:
1.168 albertel 6237: sub tmpreset {
6238: my ($symb,$namespace,$domain,$stuname) = @_;
6239: if (!$symb) {
6240: $symb=&symbread();
1.620 albertel 6241: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6242: }
6243: $symb=escape($symb);
6244:
1.620 albertel 6245: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 6246: $namespace=~s/\//\_/g;
6247: $namespace=~s/\W//g;
6248:
1.620 albertel 6249: if (!$domain) { $domain=$env{'user.domain'}; }
6250: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6251: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6252: $stuname=&get_requestor_ip();
1.591 albertel 6253: }
1.1117 foxr 6254: my $path=LONCAPA::tempdir();
1.168 albertel 6255: my %hash;
6256: if (tie(%hash,'GDBM_File',
6257: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6258: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 6259: foreach my $key (keys(%hash)) {
1.180 albertel 6260: if ($key=~ /:$symb/) {
1.168 albertel 6261: delete($hash{$key});
6262: }
6263: }
6264: }
6265: }
6266:
1.167 albertel 6267: sub tmpstore {
1.168 albertel 6268: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6269:
6270: if (!$symb) {
6271: $symb=&symbread();
1.620 albertel 6272: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6273: }
6274: $symb=escape($symb);
6275:
6276: if (!$namespace) {
6277: # I don't think we would ever want to store this for a course.
6278: # it seems this will only be used if we don't have a course.
1.620 albertel 6279: #$namespace=$env{'request.course.id'};
1.168 albertel 6280: #if (!$namespace) {
1.620 albertel 6281: $namespace=$env{'request.state'};
1.168 albertel 6282: #}
6283: }
6284: $namespace=~s/\//\_/g;
6285: $namespace=~s/\W//g;
1.620 albertel 6286: if (!$domain) { $domain=$env{'user.domain'}; }
6287: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6288: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6289: $stuname=&get_requestor_ip();
1.591 albertel 6290: }
1.168 albertel 6291: my $now=time;
6292: my %hash;
1.1117 foxr 6293: my $path=LONCAPA::tempdir();
1.168 albertel 6294: if (tie(%hash,'GDBM_File',
6295: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6296: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6297: $hash{"version:$symb"}++;
6298: my $version=$hash{"version:$symb"};
6299: my $allkeys='';
6300: foreach my $key (keys(%$storehash)) {
6301: $allkeys.=$key.':';
1.591 albertel 6302: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6303: }
6304: $hash{"$version:$symb:timestamp"}=$now;
6305: $allkeys.='timestamp';
6306: $hash{"$version:keys:$symb"}=$allkeys;
6307: if (untie(%hash)) {
6308: return 'ok';
6309: } else {
6310: return "error:$!";
6311: }
6312: } else {
6313: return "error:$!";
6314: }
6315: }
1.167 albertel 6316:
1.168 albertel 6317: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6318:
1.168 albertel 6319: sub tmprestore {
6320: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6321:
1.168 albertel 6322: if (!$symb) {
6323: $symb=&symbread();
1.620 albertel 6324: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6325: }
6326: $symb=escape($symb);
6327:
1.620 albertel 6328: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6329:
1.620 albertel 6330: if (!$domain) { $domain=$env{'user.domain'}; }
6331: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6332: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6333: $stuname=&get_requestor_ip();
1.591 albertel 6334: }
1.168 albertel 6335: my %returnhash;
6336: $namespace=~s/\//\_/g;
6337: $namespace=~s/\W//g;
6338: my %hash;
1.1117 foxr 6339: my $path=LONCAPA::tempdir();
1.168 albertel 6340: if (tie(%hash,'GDBM_File',
6341: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6342: &GDBM_READER(),0640)) {
1.168 albertel 6343: my $version=$hash{"version:$symb"};
6344: $returnhash{'version'}=$version;
6345: my $scope;
6346: for ($scope=1;$scope<=$version;$scope++) {
6347: my $vkeys=$hash{"$scope:keys:$symb"};
6348: my @keys=split(/:/,$vkeys);
6349: my $key;
6350: $returnhash{"$scope:keys"}=$vkeys;
6351: foreach $key (@keys) {
1.591 albertel 6352: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6353: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6354: }
6355: }
1.168 albertel 6356: if (!(untie(%hash))) {
6357: return "error:$!";
6358: }
6359: } else {
6360: return "error:$!";
6361: }
6362: return %returnhash;
1.167 albertel 6363: }
6364:
1.9 www 6365: # ----------------------------------------------------------------------- Store
6366:
6367: sub store {
1.1269 raeburn 6368: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6369: my $home='';
6370:
1.168 albertel 6371: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6372:
1.213 www 6373: $symb=&symbclean($symb);
1.122 albertel 6374: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6375:
1.620 albertel 6376: if (!$domain) { $domain=$env{'user.domain'}; }
6377: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6378:
6379: &devalidate($symb,$stuname,$domain);
1.109 www 6380:
6381: $symb=escape($symb);
1.187 www 6382: if (!$namespace) {
1.620 albertel 6383: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6384: return '';
6385: }
6386: }
1.620 albertel 6387: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6388:
1.1434 raeburn 6389: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6390: $$storehash{'host'}=$perlvar{'lonHostID'};
6391:
1.12 www 6392: my $namevalue='';
1.800 albertel 6393: foreach my $key (keys(%$storehash)) {
6394: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6395: }
1.12 www 6396: $namevalue=~s/\&$//;
1.187 www 6397: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 6398: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6399: }
6400:
1.47 www 6401: # -------------------------------------------------------------- Critical Store
6402:
6403: sub cstore {
1.1269 raeburn 6404: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6405: my $home='';
6406:
1.168 albertel 6407: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6408:
1.213 www 6409: $symb=&symbclean($symb);
1.122 albertel 6410: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6411:
1.620 albertel 6412: if (!$domain) { $domain=$env{'user.domain'}; }
6413: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6414:
6415: &devalidate($symb,$stuname,$domain);
1.109 www 6416:
6417: $symb=escape($symb);
1.187 www 6418: if (!$namespace) {
1.620 albertel 6419: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6420: return '';
6421: }
6422: }
1.620 albertel 6423: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6424:
1.1434 raeburn 6425: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6426: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6427:
1.47 www 6428: my $namevalue='';
1.800 albertel 6429: foreach my $key (keys(%$storehash)) {
6430: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6431: }
1.47 www 6432: $namevalue=~s/\&$//;
1.187 www 6433: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6434: return critical
1.1269 raeburn 6435: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6436: }
6437:
1.9 www 6438: # --------------------------------------------------------------------- Restore
6439:
6440: sub restore {
1.124 www 6441: my ($symb,$namespace,$domain,$stuname) = @_;
6442: my $home='';
6443:
1.168 albertel 6444: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6445:
1.122 albertel 6446: if (!$symb) {
1.1224 raeburn 6447: return if ($namespace eq 'courserequests');
6448: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6449: } else {
1.1224 raeburn 6450: unless ($namespace eq 'courserequests') {
6451: $symb=&escape(&symbclean($symb));
6452: }
1.122 albertel 6453: }
1.188 www 6454: if (!$namespace) {
1.620 albertel 6455: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6456: return '';
6457: }
6458: }
1.620 albertel 6459: if (!$domain) { $domain=$env{'user.domain'}; }
6460: if (!$stuname) { $stuname=$env{'user.name'}; }
6461: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6462: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6463:
1.12 www 6464: my %returnhash=();
1.800 albertel 6465: foreach my $line (split(/\&/,$answer)) {
6466: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6467: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6468: }
1.75 www 6469: my $version;
6470: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6471: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6472: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6473: }
1.75 www 6474: }
1.13 www 6475: return %returnhash;
1.34 www 6476: }
6477:
6478: # ---------------------------------------------------------- Course Description
1.1118 foxr 6479: #
6480: #
1.34 www 6481:
6482: sub coursedescription {
1.731 albertel 6483: my ($courseid,$args)=@_;
1.34 www 6484: $courseid=~s/^\///;
1.49 www 6485: $courseid=~s/\_/\//g;
1.34 www 6486: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6487: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6488: my $normalid=$cdomain.'_'.$cnum;
6489: # need to always cache even if we get errors otherwise we keep
6490: # trying and trying and trying to get the course description.
6491: my %envhash=();
6492: my %returnhash=();
1.731 albertel 6493:
6494: my $expiretime=600;
6495: if ($env{'request.course.id'} eq $normalid) {
6496: $expiretime=120;
6497: }
6498:
6499: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6500: if (!$args->{'freshen_cache'}
6501: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6502: foreach my $key (keys(%env)) {
6503: next if ($key !~ /^\Q$prefix\E(.*)/);
6504: my ($setting) = $1;
6505: $returnhash{$setting} = $env{$key};
6506: }
6507: return %returnhash;
6508: }
6509:
1.1118 foxr 6510: # get the data again
6511:
1.731 albertel 6512: if (!$args->{'one_time'}) {
6513: $envhash{'course.'.$normalid.'.last_cache'}=time;
6514: }
1.811 albertel 6515:
1.34 www 6516: if ($chome ne 'no_host') {
1.302 albertel 6517: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6518: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6519: my $username = $env{'user.name'}; # Defult username
6520: if(defined $args->{'user'}) {
6521: $username = $args->{'user'};
6522: }
1.129 albertel 6523: $returnhash{'home'}= $chome;
6524: $returnhash{'domain'} = $cdomain;
6525: $returnhash{'num'} = $cnum;
1.741 raeburn 6526: if (!defined($returnhash{'type'})) {
6527: $returnhash{'type'} = 'Course';
6528: }
1.130 albertel 6529: while (my ($name,$value) = each %returnhash) {
1.53 www 6530: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6531: }
1.270 www 6532: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6533: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6534: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6535: $envhash{'course.'.$normalid.'.home'}=$chome;
6536: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6537: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6538: }
6539: }
1.731 albertel 6540: if (!$args->{'one_time'}) {
1.949 raeburn 6541: &appenv(\%envhash);
1.731 albertel 6542: }
1.302 albertel 6543: return %returnhash;
1.461 www 6544: }
6545:
1.1080 raeburn 6546: sub update_released_required {
6547: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6548: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6549: $cid = $env{'request.course.id'};
6550: $cdom = $env{'course.'.$cid.'.domain'};
6551: $cnum = $env{'course.'.$cid.'.num'};
6552: $chome = $env{'course.'.$cid.'.home'};
6553: }
6554: if ($needsrelease) {
6555: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6556: my $needsupdate;
6557: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6558: $needsupdate = 1;
6559: } else {
6560: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6561: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6562: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6563: $needsupdate = 1;
6564: }
6565: }
6566: if ($needsupdate) {
6567: my %needshash = (
6568: 'internal.releaserequired' => $needsrelease,
6569: );
6570: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6571: if ($putresult eq 'ok') {
6572: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6573: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6574: if (ref($crsinfo{$cid}) eq 'HASH') {
6575: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6576: &courseidput($cdom,\%crsinfo,$chome,'notime');
6577: }
6578: }
6579: }
6580: }
6581: return;
6582: }
6583:
1.461 www 6584: # -------------------------------------------------See if a user is privileged
6585:
6586: sub privileged {
1.1219 raeburn 6587: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6588: my $now = time;
1.1219 raeburn 6589: my $roles;
6590: if (ref($possroles) eq 'ARRAY') {
6591: $roles = $possroles;
6592: } else {
6593: $roles = ['dc','su'];
6594: }
6595: if (ref($possdomains) eq 'ARRAY') {
6596: my %privileged = &privileged_by_domain($possdomains,$roles);
6597: foreach my $dom (@{$possdomains}) {
6598: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6599: (ref($privileged{$dom}) eq 'HASH')) {
6600: foreach my $role (@{$roles}) {
6601: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6602: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6603: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6604: return 1 unless (($end && $end < $now) ||
6605: ($start && $start > $now));
6606: }
6607: }
6608: }
6609: }
6610: }
6611: } else {
6612: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6613: my $now = time;
1.1170 droeschl 6614:
1.1275 musolffc 6615: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6616: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 6617: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 6618: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 6619: or ($tstart && $tstart > $now);
1.1170 droeschl 6620: }
1.1219 raeburn 6621: }
6622: }
6623: return 0;
6624: }
1.1170 droeschl 6625:
1.1219 raeburn 6626: sub privileged_by_domain {
6627: my ($domains,$roles) = @_;
6628: my %privileged = ();
6629: my $cachetime = 60*60*24;
6630: my $now = time;
6631: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6632: return %privileged;
6633: }
6634: foreach my $dom (@{$domains}) {
6635: next if (ref($privileged{$dom}) eq 'HASH');
6636: my $needroles;
6637: foreach my $role (@{$roles}) {
6638: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6639: if (defined($cached)) {
6640: if (ref($result) eq 'HASH') {
6641: $privileged{$dom}{$role} = $result;
6642: }
6643: } else {
6644: $needroles = 1;
6645: }
6646: }
6647: if ($needroles) {
6648: my %dompersonnel = &get_domain_roles($dom,$roles);
6649: $privileged{$dom} = {};
6650: foreach my $server (keys(%dompersonnel)) {
6651: if (ref($dompersonnel{$server}) eq 'HASH') {
6652: foreach my $item (keys(%{$dompersonnel{$server}})) {
6653: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6654: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6655: next if ($end && $end < $now);
6656: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6657: $dompersonnel{$server}{$item};
6658: }
6659: }
6660: }
6661: if (ref($privileged{$dom}) eq 'HASH') {
6662: foreach my $role (@{$roles}) {
6663: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6664: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6665: } else {
6666: my %hash = ();
6667: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6668: }
6669: }
6670: }
6671: }
6672: }
6673: return %privileged;
1.9 www 6674: }
1.1 albertel 6675:
1.103 harris41 6676: # -------------------------------------------------------- Get user privileges
1.11 www 6677:
6678: sub rolesinit {
1.1169 droeschl 6679: my ($domain, $username) = @_;
6680: my %userroles = ('user.login.time' => time);
6681: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6682:
6683: # firstaccess and timerinterval are related to timed maps/resources.
6684: # also, blocking can be triggered by an activating timer
6685: # it's saved in the user's %env.
6686: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6687: my %timerinterval = &dump('timerinterval', $domain, $username);
6688: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6689: %timerintchk, %timerintenv);
6690:
1.1162 raeburn 6691: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6692: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6693: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6694: }
1.1169 droeschl 6695:
1.1162 raeburn 6696: foreach my $key (keys(%timerinterval)) {
6697: my ($cid,$rest) = split(/\0/,$key);
6698: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6699: }
1.1169 droeschl 6700:
1.11 www 6701: my %allroles=();
1.1162 raeburn 6702: my %allgroups=();
1.11 www 6703:
1.1274 raeburn 6704: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6705: my $role = $rolesdump{$area};
6706: $area =~ s/\_\w\w$//;
6707:
6708: my ($trole, $tend, $tstart, $group_privs);
6709:
6710: if ($role =~ /^cr/) {
6711: # Custom role, defined by a user
6712: # e.g., user.role.cr/msu/smith/mynewrole
6713: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6714: $trole = $1;
6715: ($tend, $tstart) = split('_', $2);
6716: } else {
6717: $trole = $role;
6718: }
6719: } elsif ($role =~ m|^gr/|) {
6720: # Role of member in a group, defined within a course/community
6721: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6722: ($trole, $tend, $tstart) = split(/_/, $role);
6723: next if $tstart eq '-1';
6724: ($trole, $group_privs) = split(/\//, $trole);
6725: $group_privs = &unescape($group_privs);
6726: } else {
6727: # Just a normal role, defined in roles.tab
6728: ($trole, $tend, $tstart) = split(/_/,$role);
6729: }
6730:
6731: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6732: $username);
6733: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6734:
6735: # role expired or not available yet?
6736: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6737: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6738:
6739: next if $area eq '' or $trole eq '';
6740:
6741: my $spec = "$trole.$area";
6742: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6743:
6744: if ($trole =~ /^cr\//) {
6745: # Custom role, defined by a user
6746: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6747: } elsif ($trole eq 'gr') {
6748: # Role of a member in a group, defined within a course/community
6749: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6750: next;
6751: } else {
6752: # Normal role, defined in roles.tab
6753: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6754: }
6755:
6756: my $cid = $tdomain.'_'.$trest;
6757: unless ($firstaccchk{$cid}) {
6758: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6759: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6760: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6761: $coursetimerstarts{$cid}{$item};
6762: }
6763: }
6764: $firstaccchk{$cid} = 1;
6765: }
6766: unless ($timerintchk{$cid}) {
6767: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6768: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6769: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6770: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6771: }
1.12 www 6772: }
1.1169 droeschl 6773: $timerintchk{$cid} = 1;
1.191 harris41 6774: }
1.11 www 6775: }
1.1169 droeschl 6776:
1.1341 raeburn 6777: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6778: \%allroles, \%allgroups);
1.1169 droeschl 6779: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 6780: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6781:
1.1162 raeburn 6782: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6783: }
6784:
1.567 raeburn 6785: sub set_arearole {
1.1215 raeburn 6786: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6787: unless ($nolog) {
1.567 raeburn 6788: # log the associated role with the area
1.1215 raeburn 6789: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6790: }
1.743 albertel 6791: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6792: }
6793:
6794: sub custom_roleprivs {
6795: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6796: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 6797: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6798: if (&hostname($homsvr) ne '') {
1.567 raeburn 6799: my ($rdummy,$roledef)=
6800: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6801: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6802: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6803: if (defined($syspriv)) {
1.1043 raeburn 6804: if ($trest =~ /^$match_community$/) {
6805: $syspriv =~ s/bre\&S//;
6806: }
1.567 raeburn 6807: $$allroles{'cm./'}.=':'.$syspriv;
6808: $$allroles{$spec.'./'}.=':'.$syspriv;
6809: }
6810: if ($tdomain ne '') {
6811: if (defined($dompriv)) {
6812: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6813: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6814: }
6815: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 6816: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6817: my $rolename = $1;
6818: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6819: }
1.567 raeburn 6820: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6821: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6822: }
6823: }
6824: }
6825: }
6826: }
6827:
1.1332 raeburn 6828: sub course_adhocrole_privs {
6829: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6830: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6831: if ($overrides{"internal.adhocpriv.$rolename"}) {
6832: my (%currprivs,%storeprivs);
6833: foreach my $item (split(/:/,$coursepriv)) {
6834: my ($priv,$restrict) = split(/\&/,$item);
6835: $currprivs{$priv} = $restrict;
6836: }
6837: my (%possadd,%possremove,%full);
6838: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6839: my ($priv,$restrict)=split(/\&/,$item);
6840: $full{$priv} = $restrict;
6841: }
6842: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6843: next if ($item eq '');
6844: my ($rule,$rest) = split(/=/,$item);
6845: next unless (($rule eq 'off') || ($rule eq 'on'));
6846: foreach my $priv (split(/:/,$rest)) {
6847: if ($priv ne '') {
6848: if ($rule eq 'off') {
6849: $possremove{$priv} = 1;
6850: } else {
6851: $possadd{$priv} = 1;
6852: }
6853: }
6854: }
6855: }
6856: foreach my $priv (sort(keys(%full))) {
6857: if (exists($currprivs{$priv})) {
6858: unless (exists($possremove{$priv})) {
6859: $storeprivs{$priv} = $currprivs{$priv};
6860: }
6861: } elsif (exists($possadd{$priv})) {
6862: $storeprivs{$priv} = $full{$priv};
6863: }
6864: }
6865: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6866: }
6867: return $coursepriv;
6868: }
6869:
1.678 raeburn 6870: sub group_roleprivs {
6871: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6872: my $access = 1;
6873: my $now = time;
6874: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6875: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6876: if ($access) {
1.811 albertel 6877: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6878: $$allgroups{$course}{$group} .=':'.$group_privs;
6879: }
6880: }
1.567 raeburn 6881:
6882: sub standard_roleprivs {
6883: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6884: if (defined($pr{$trole.':s'})) {
6885: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6886: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6887: }
6888: if ($tdomain ne '') {
6889: if (defined($pr{$trole.':d'})) {
6890: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6891: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6892: }
6893: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6894: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6895: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6896: }
6897: }
6898: }
6899:
6900: sub set_userprivs {
1.1064 raeburn 6901: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6902: my $author=0;
6903: my $adv=0;
1.1341 raeburn 6904: my $rar=0;
1.678 raeburn 6905: my %grouproles = ();
6906: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6907: my @groupkeys;
1.1000 raeburn 6908: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6909: push(@groupkeys,$role);
6910: }
6911: if (ref($groups_roles) eq 'HASH') {
6912: foreach my $key (keys(%{$groups_roles})) {
6913: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6914: push(@groupkeys,$key);
6915: }
6916: }
6917: }
6918: if (@groupkeys > 0) {
6919: foreach my $role (@groupkeys) {
6920: my ($trole,$area,$sec,$extendedarea);
6921: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6922: $trole = $1;
6923: $area = $2;
6924: $sec = $3;
6925: $extendedarea = $area.$sec;
6926: if (exists($$allgroups{$area})) {
6927: foreach my $group (keys(%{$$allgroups{$area}})) {
6928: my $spec = $trole.'.'.$extendedarea;
6929: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6930: $$allgroups{$area}{$group};
1.1064 raeburn 6931: }
1.678 raeburn 6932: }
6933: }
6934: }
6935: }
6936: }
1.800 albertel 6937: foreach my $group (keys(%grouproles)) {
6938: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6939: }
1.800 albertel 6940: foreach my $role (keys(%{$allroles})) {
6941: my %thesepriv;
1.941 raeburn 6942: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6943: foreach my $item (split(/:/,$$allroles{$role})) {
6944: if ($item ne '') {
6945: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6946: if ($restrictions eq '') {
6947: $thesepriv{$privilege}='F';
6948: } elsif ($thesepriv{$privilege} ne 'F') {
6949: $thesepriv{$privilege}.=$restrictions;
6950: }
6951: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 6952: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6953: }
6954: }
6955: my $thesestr='';
1.1104 raeburn 6956: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6957: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6958: }
6959: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6960: }
1.1341 raeburn 6961: return ($author,$adv,$rar);
1.567 raeburn 6962: }
6963:
1.994 raeburn 6964: sub role_status {
1.1104 raeburn 6965: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6966: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 6967: my ($one,$two) = split(m{\./},$rolekey,2);
6968: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6969: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 6970: $$where = '/'.$two;
1.994 raeburn 6971: $$trolecode=$$role.'.'.$$where;
6972: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6973: $$tstatus='is';
1.1104 raeburn 6974: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6975: $$tstatus='future';
1.1034 raeburn 6976: if ($$tstart<$now) {
6977: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6978: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6979: my (%allroles,%allgroups,$group_privs,
6980: %groups_roles,@rolecodes);
1.1002 raeburn 6981: my %userroles = (
6982: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6983: );
1.1064 raeburn 6984: @rolecodes = ('cm');
1.1002 raeburn 6985: my $spec=$$role.'.'.$$where;
6986: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6987: if ($$role =~ /^cr\//) {
6988: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6989: push(@rolecodes,'cr');
1.1002 raeburn 6990: } elsif ($$role eq 'gr') {
1.1064 raeburn 6991: push(@rolecodes,$$role);
1.1002 raeburn 6992: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6993: $env{'user.name'});
1.1064 raeburn 6994: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6995: (undef,my $group_privs) = split(/\//,$trole);
6996: $group_privs = &unescape($group_privs);
6997: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6998: 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 6999: &get_groups_roles($tdomain,$trest,
7000: \%course_roles,\@rolecodes,
7001: \%groups_roles);
1.1002 raeburn 7002: } else {
1.1064 raeburn 7003: push(@rolecodes,$$role);
1.1002 raeburn 7004: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
7005: }
1.1341 raeburn 7006: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
7007: \%groups_roles);
1.1064 raeburn 7008: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 7009: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 7010: }
7011: }
1.1034 raeburn 7012: $$tstatus = 'is';
1.1002 raeburn 7013: }
1.994 raeburn 7014: }
7015: if ($$tend) {
1.1104 raeburn 7016: if ($$tend<$update) {
1.994 raeburn 7017: $$tstatus='expired';
7018: } elsif ($$tend<$now) {
7019: $$tstatus='will_not';
7020: }
7021: }
7022: }
7023: }
7024: }
7025:
1.1104 raeburn 7026: sub get_groups_roles {
7027: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
7028: return unless((ref($cdom_courseroles) eq 'HASH') &&
7029: (ref($rolecodes) eq 'ARRAY') &&
7030: (ref($groups_roles) eq 'HASH'));
7031: if (keys(%{$cdom_courseroles}) > 0) {
7032: my ($cnum) = ($rest =~ /^($match_courseid)/);
7033: if ($cdom ne '' && $cnum ne '') {
7034: foreach my $key (keys(%{$cdom_courseroles})) {
7035: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
7036: my $crsrole = $1;
7037: my $crssec = $2;
7038: if ($crsrole =~ /^cr/) {
7039: unless (grep(/^cr$/,@{$rolecodes})) {
7040: push(@{$rolecodes},'cr');
7041: }
7042: } else {
7043: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
7044: push(@{$rolecodes},$crsrole);
7045: }
7046: }
7047: my $rolekey = "$crsrole./$cdom/$cnum";
7048: if ($crssec ne '') {
7049: $rolekey .= "/$crssec";
7050: }
7051: $rolekey .= './';
7052: $groups_roles->{$rolekey} = $rolecodes;
7053: }
7054: }
7055: }
7056: }
7057: return;
7058: }
7059:
7060: sub delete_env_groupprivs {
7061: my ($where,$courseroles,$possroles) = @_;
7062: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
7063: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
7064: unless (ref($courseroles->{$udom}) eq 'HASH') {
7065: %{$courseroles->{$udom}} =
7066: &get_my_roles('','','userroles',['active'],
7067: $possroles,[$udom],1);
7068: }
7069: if (ref($courseroles->{$udom}) eq 'HASH') {
7070: foreach my $item (keys(%{$courseroles->{$udom}})) {
7071: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
7072: my $area = '/'.$cdom.'/'.$cnum;
7073: my $privkey = "user.priv.$crsrole.$area";
7074: if ($crssec ne '') {
7075: $privkey .= '/'.$crssec;
7076: }
7077: $privkey .= ".$area/$group";
7078: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
7079: }
7080: }
7081: return;
7082: }
7083:
1.994 raeburn 7084: sub check_adhoc_privs {
1.1329 raeburn 7085: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 7086: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 7087: if ($sec) {
7088: $cckey .= '/'.$sec;
7089: }
1.1185 raeburn 7090: my $setprivs;
1.994 raeburn 7091: if ($env{$cckey}) {
7092: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 7093: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 7094: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 7095: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7096: $setprivs = 1;
1.994 raeburn 7097: }
7098: } else {
1.1330 raeburn 7099: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7100: $setprivs = 1;
1.994 raeburn 7101: }
1.1185 raeburn 7102: return $setprivs;
1.994 raeburn 7103: }
7104:
7105: sub set_adhoc_privileges {
1.1326 raeburn 7106: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 7107: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 7108: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 7109: if ($sec ne '') {
7110: $area .= '/'.$sec;
7111: }
1.994 raeburn 7112: my $spec = $role.'.'.$area;
7113: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 7114: $env{'user.name'},1);
1.1326 raeburn 7115: my %rolehash = ();
1.1332 raeburn 7116: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
7117: my $rolename = $1;
1.1326 raeburn 7118: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 7119: my %domdef = &get_domain_defaults($dcdom);
7120: if (ref($domdef{'adhocroles'}) eq 'HASH') {
7121: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
7122: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
7123: }
7124: }
1.1326 raeburn 7125: } else {
7126: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
7127: }
1.1341 raeburn 7128: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 7129: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 7130: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402 raeburn 7131: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
7132: ($caller eq 'tiny')) {
1.1088 raeburn 7133: &appenv( {'request.role' => $spec,
7134: 'request.role.domain' => $dcdom,
1.1332 raeburn 7135: 'request.course.sec' => $sec,
1.1088 raeburn 7136: }
7137: );
7138: my $tadv=0;
7139: if (&allowed('adv') eq 'F') { $tadv=1; }
7140: &appenv({'request.role.adv' => $tadv});
7141: }
1.994 raeburn 7142: }
7143:
1.12 www 7144: # --------------------------------------------------------------- get interface
7145:
7146: sub get {
1.131 albertel 7147: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7148: my $items='';
1.800 albertel 7149: foreach my $item (@$storearr) {
7150: $items.=&escape($item).'&';
1.191 harris41 7151: }
1.12 www 7152: $items=~s/\&$//;
1.620 albertel 7153: if (!$udomain) { $udomain=$env{'user.domain'}; }
7154: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 7155: my $uhome=&homeserver($uname,$udomain);
7156:
1.133 albertel 7157: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7158: my @pairs=split(/\&/,$rep);
1.273 albertel 7159: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
7160: return @pairs;
7161: }
1.15 www 7162: my %returnhash=();
1.42 www 7163: my $i=0;
1.800 albertel 7164: foreach my $item (@$storearr) {
7165: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7166: $i++;
1.191 harris41 7167: }
1.15 www 7168: return %returnhash;
1.27 www 7169: }
7170:
7171: # --------------------------------------------------------------- del interface
7172:
7173: sub del {
1.133 albertel 7174: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 7175: my $items='';
1.800 albertel 7176: foreach my $item (@$storearr) {
7177: $items.=&escape($item).'&';
1.191 harris41 7178: }
1.984 neumanie 7179:
1.27 www 7180: $items=~s/\&$//;
1.620 albertel 7181: if (!$udomain) { $udomain=$env{'user.domain'}; }
7182: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7183: my $uhome=&homeserver($uname,$udomain);
7184: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7185: }
7186:
7187: # -------------------------------------------------------------- dump interface
7188:
1.1180 droeschl 7189: sub unserialize {
7190: my ($rep, $escapedkeys) = @_;
7191:
7192: return {} if $rep =~ /^error/;
7193:
7194: my %returnhash=();
1.1252 raeburn 7195: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 7196: my ($key, $value) = split(/=/, $item, 2);
7197: $key = unescape($key) unless $escapedkeys;
7198: next if $key =~ /^error: 2 /;
1.1252 raeburn 7199: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 7200: }
7201: #return %returnhash;
7202: return \%returnhash;
7203: }
7204:
7205: # see Lond::dump_with_regexp
7206: # if $escapedkeys hash keys won't get unescaped.
1.15 www 7207: sub dump {
1.1462 raeburn 7208: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755 albertel 7209: if (!$udomain) { $udomain=$env{'user.domain'}; }
7210: if (!$uname) { $uname=$env{'user.name'}; }
7211: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 7212:
1.1266 raeburn 7213: if ($regexp) {
7214: $regexp=&escape($regexp);
7215: } else {
7216: $regexp='.';
7217: }
1.1180 droeschl 7218: if (grep { $_ eq $uhome } current_machine_ids()) {
7219: # user is hosted on this machine
1.1266 raeburn 7220: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 7221: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 7222: return %{unserialize($reply, $escapedkeys)};
7223: }
1.1462 raeburn 7224: my $rep;
7225: if ($encrypt) {
7226: $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.1463 raeburn 7227: } else {
1.1462 raeburn 7228: $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7229: }
1.755 albertel 7230: my @pairs=split(/\&/,$rep);
7231: my %returnhash=();
1.1098 foxr 7232: if (!($rep =~ /^error/ )) {
7233: foreach my $item (@pairs) {
7234: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 7235: $key = unescape($key) unless $escapedkeys;
7236: #$key = &unescape($key);
1.1098 foxr 7237: next if ($key =~ /^error: 2 /);
7238: $returnhash{$key}=&thaw_unescape($value);
7239: }
1.755 albertel 7240: }
7241: return %returnhash;
1.407 www 7242: }
7243:
1.1098 foxr 7244:
1.717 albertel 7245: # --------------------------------------------------------- dumpstore interface
7246:
7247: sub dumpstore {
7248: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 7249: # same as dump but keys must be escaped. They may contain colon separated
7250: # lists of values that may themself contain colons (e.g. symbs).
7251: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 7252: }
7253:
1.407 www 7254: # -------------------------------------------------------------- keys interface
7255:
7256: sub getkeys {
7257: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 7258: if (!$udomain) { $udomain=$env{'user.domain'}; }
7259: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 7260: my $uhome=&homeserver($uname,$udomain);
7261: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7262: my @keyarray=();
1.800 albertel 7263: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 7264: next if ($key =~ /^error: 2 /);
1.800 albertel 7265: push(@keyarray,&unescape($key));
1.407 www 7266: }
7267: return @keyarray;
1.318 matthew 7268: }
7269:
1.319 matthew 7270: # --------------------------------------------------------------- currentdump
7271: sub currentdump {
1.328 matthew 7272: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 7273: $courseid = $env{'request.course.id'} if (! defined($courseid));
7274: $sdom = $env{'user.domain'} if (! defined($sdom));
7275: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 7276: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 7277: my $rep;
7278:
7279: if (grep { $_ eq $uhome } current_machine_ids()) {
7280: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7281: $courseid)));
7282: } else {
7283: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7284: }
7285:
1.318 matthew 7286: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7287: #
1.318 matthew 7288: my %returnhash=();
1.319 matthew 7289: #
1.1343 raeburn 7290: if ($rep eq 'unknown_cmd') {
1.319 matthew 7291: # an old lond will not know currentdump
7292: # Do a dump and make it look like a currentdump
1.822 albertel 7293: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7294: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7295: my %hash = @tmp;
7296: @tmp=();
1.424 matthew 7297: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7298: } else {
7299: my @pairs=split(/\&/,$rep);
1.800 albertel 7300: foreach my $pair (@pairs) {
7301: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7302: my ($symb,$param) = split(/:/,$key);
7303: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7304: &thaw_unescape($value);
1.319 matthew 7305: }
1.191 harris41 7306: }
1.12 www 7307: return %returnhash;
1.424 matthew 7308: }
7309:
7310: sub convert_dump_to_currentdump{
7311: my %hash = %{shift()};
7312: my %returnhash;
7313: # Code ripped from lond, essentially. The only difference
7314: # here is the unescaping done by lonnet::dump(). Conceivably
7315: # we might run in to problems with parameter names =~ /^v\./
7316: while (my ($key,$value) = each(%hash)) {
7317: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7318: $symb = &unescape($symb);
7319: $param = &unescape($param);
1.424 matthew 7320: next if ($v eq 'version' || $symb eq 'keys');
7321: next if (exists($returnhash{$symb}) &&
7322: exists($returnhash{$symb}->{$param}) &&
7323: $returnhash{$symb}->{'v.'.$param} > $v);
7324: $returnhash{$symb}->{$param}=$value;
7325: $returnhash{$symb}->{'v.'.$param}=$v;
7326: }
7327: #
7328: # Remove all of the keys in the hashes which keep track of
7329: # the version of the parameter.
7330: while (my ($symb,$param_hash) = each(%returnhash)) {
7331: # use a foreach because we are going to delete from the hash.
7332: foreach my $key (keys(%$param_hash)) {
7333: delete($param_hash->{$key}) if ($key =~ /^v\./);
7334: }
7335: }
7336: return \%returnhash;
1.12 www 7337: }
7338:
1.627 albertel 7339: # ------------------------------------------------------ critical inc interface
7340:
7341: sub cinc {
7342: return &inc(@_,'critical');
7343: }
7344:
1.449 matthew 7345: # --------------------------------------------------------------- inc interface
7346:
7347: sub inc {
1.627 albertel 7348: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7349: if (!$udomain) { $udomain=$env{'user.domain'}; }
7350: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7351: my $uhome=&homeserver($uname,$udomain);
7352: my $items='';
7353: if (! ref($store)) {
7354: # got a single value, so use that instead
7355: $items = &escape($store).'=&';
7356: } elsif (ref($store) eq 'SCALAR') {
7357: $items = &escape($$store).'=&';
7358: } elsif (ref($store) eq 'ARRAY') {
7359: $items = join('=&',map {&escape($_);} @{$store});
7360: } elsif (ref($store) eq 'HASH') {
7361: while (my($key,$value) = each(%{$store})) {
7362: $items.= &escape($key).'='.&escape($value).'&';
7363: }
7364: }
7365: $items=~s/\&$//;
1.627 albertel 7366: if ($critical) {
7367: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7368: } else {
7369: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7370: }
1.449 matthew 7371: }
7372:
1.12 www 7373: # --------------------------------------------------------------- put interface
7374:
7375: sub put {
1.1462 raeburn 7376: my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620 albertel 7377: if (!$udomain) { $udomain=$env{'user.domain'}; }
7378: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7379: my $uhome=&homeserver($uname,$udomain);
1.12 www 7380: my $items='';
1.800 albertel 7381: foreach my $item (keys(%$storehash)) {
7382: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7383: }
1.12 www 7384: $items=~s/\&$//;
1.1462 raeburn 7385: if ($encrypt) {
7386: return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
7387: } else {
7388: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7389: }
1.47 www 7390: }
7391:
1.631 albertel 7392: # ------------------------------------------------------------ newput interface
7393:
7394: sub newput {
7395: my ($namespace,$storehash,$udomain,$uname)=@_;
7396: if (!$udomain) { $udomain=$env{'user.domain'}; }
7397: if (!$uname) { $uname=$env{'user.name'}; }
7398: my $uhome=&homeserver($uname,$udomain);
7399: my $items='';
7400: foreach my $key (keys(%$storehash)) {
7401: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7402: }
7403: $items=~s/\&$//;
7404: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7405: }
7406:
7407: # --------------------------------------------------------- putstore interface
7408:
1.524 raeburn 7409: sub putstore {
1.1269 raeburn 7410: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7411: if (!$udomain) { $udomain=$env{'user.domain'}; }
7412: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7413: my $uhome=&homeserver($uname,$udomain);
7414: my $items='';
1.715 albertel 7415: foreach my $key (keys(%$storehash)) {
7416: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7417: }
1.715 albertel 7418: $items=~s/\&$//;
1.716 albertel 7419: my $esc_symb=&escape($symb);
7420: my $esc_v=&escape($version);
1.715 albertel 7421: my $reply =
1.716 albertel 7422: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7423: $uhome);
1.1269 raeburn 7424: if (($tolog) && ($reply eq 'ok')) {
7425: my $namevalue='';
7426: foreach my $key (keys(%{$storehash})) {
7427: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7428: }
1.1434 raeburn 7429: my $ip = &get_requestor_ip();
7430: $namevalue .= 'ip='.&escape($ip).
1.1269 raeburn 7431: '&host='.&escape($perlvar{'lonHostID'}).
7432: '&version='.$esc_v.
7433: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7434: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7435: }
1.715 albertel 7436: if ($reply eq 'unknown_cmd') {
1.716 albertel 7437: # gfall back to way things use to be done
1.715 albertel 7438: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7439: $uname);
1.524 raeburn 7440: }
1.715 albertel 7441: return $reply;
7442: }
7443:
7444: sub old_putstore {
1.716 albertel 7445: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7446: if (!$udomain) { $udomain=$env{'user.domain'}; }
7447: if (!$uname) { $uname=$env{'user.name'}; }
7448: my $uhome=&homeserver($uname,$udomain);
7449: my %newstorehash;
1.800 albertel 7450: foreach my $item (keys(%$storehash)) {
7451: my $key = $version.':'.&escape($symb).':'.$item;
7452: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7453: }
7454: my $items='';
7455: my %allitems = ();
1.800 albertel 7456: foreach my $item (keys(%newstorehash)) {
7457: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7458: my $key = $1.':keys:'.$2;
7459: $allitems{$key} .= $3.':';
7460: }
1.800 albertel 7461: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7462: }
1.800 albertel 7463: foreach my $item (keys(%allitems)) {
7464: $allitems{$item} =~ s/\:$//;
7465: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7466: }
7467: $items=~s/\&$//;
7468: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7469: }
7470:
1.47 www 7471: # ------------------------------------------------------ critical put interface
7472:
7473: sub cput {
1.134 albertel 7474: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7475: if (!$udomain) { $udomain=$env{'user.domain'}; }
7476: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7477: my $uhome=&homeserver($uname,$udomain);
1.47 www 7478: my $items='';
1.800 albertel 7479: foreach my $item (keys(%$storehash)) {
7480: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7481: }
1.47 www 7482: $items=~s/\&$//;
1.134 albertel 7483: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7484: }
7485:
7486: # -------------------------------------------------------------- eget interface
7487:
7488: sub eget {
1.133 albertel 7489: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7490: my $items='';
1.800 albertel 7491: foreach my $item (@$storearr) {
7492: $items.=&escape($item).'&';
1.191 harris41 7493: }
1.12 www 7494: $items=~s/\&$//;
1.620 albertel 7495: if (!$udomain) { $udomain=$env{'user.domain'}; }
7496: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7497: my $uhome=&homeserver($uname,$udomain);
7498: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7499: my @pairs=split(/\&/,$rep);
7500: my %returnhash=();
1.42 www 7501: my $i=0;
1.800 albertel 7502: foreach my $item (@$storearr) {
7503: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7504: $i++;
1.191 harris41 7505: }
1.12 www 7506: return %returnhash;
7507: }
7508:
1.667 albertel 7509: # ------------------------------------------------------------ tmpput interface
7510: sub tmpput {
1.802 raeburn 7511: my ($storehash,$server,$context)=@_;
1.667 albertel 7512: my $items='';
1.800 albertel 7513: foreach my $item (keys(%$storehash)) {
7514: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7515: }
7516: $items=~s/\&$//;
1.802 raeburn 7517: if (defined($context)) {
7518: $items .= ':'.&escape($context);
7519: }
1.667 albertel 7520: return &reply("tmpput:$items",$server);
7521: }
7522:
7523: # ------------------------------------------------------------ tmpget interface
7524: sub tmpget {
1.688 albertel 7525: my ($token,$server)=@_;
7526: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7527: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7528: my %returnhash;
1.1328 raeburn 7529: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7530: return %returnhash;
7531: }
1.667 albertel 7532: foreach my $item (split(/\&/,$rep)) {
7533: my ($key,$value)=split(/=/,$item);
7534: $returnhash{&unescape($key)}=&thaw_unescape($value);
7535: }
7536: return %returnhash;
7537: }
7538:
1.1113 raeburn 7539: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7540: sub tmpdel {
7541: my ($token,$server)=@_;
7542: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7543: return &reply("tmpdel:$token",$server);
7544: }
7545:
1.1198 raeburn 7546: # ------------------------------------------------------------ get_timebased_id
7547:
7548: sub get_timebased_id {
7549: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7550: $maxtries) = @_;
7551: my ($newid,$error,$dellock);
7552: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7553: return ('','ok','invalid call to get suffix');
7554: }
7555:
7556: # set defaults for any optional args for which values were not supplied
7557: if ($who eq '') {
7558: $who = $env{'user.name'}.':'.$env{'user.domain'};
7559: }
7560: if (!$locktries) {
7561: $locktries = 3;
7562: }
7563: if (!$maxtries) {
7564: $maxtries = 10;
7565: }
7566:
7567: if (($cdom eq '') || ($cnum eq '')) {
7568: if ($env{'request.course.id'}) {
7569: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7570: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7571: }
7572: if (($cdom eq '') || ($cnum eq '')) {
7573: return ('','ok','call to get suffix not in course context');
7574: }
7575: }
7576:
7577: # construct locking item
7578: my $lockhash = {
7579: $prefix."\0".'locked_'.$keyid => $who,
7580: };
7581: my $tries = 0;
7582:
7583: # attempt to get lock on nohist_$namespace file
7584: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7585: while (($gotlock ne 'ok') && $tries <$locktries) {
7586: $tries ++;
7587: sleep 1;
7588: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7589: }
7590:
7591: # attempt to get unique identifier, based on current timestamp
7592: if ($gotlock eq 'ok') {
7593: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7594: my $id = time;
7595: $newid = $id;
1.1268 raeburn 7596: if ($idtype eq 'addcode') {
7597: $newid .= &sixnum_code();
7598: }
1.1198 raeburn 7599: my $idtries = 0;
7600: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7601: if ($idtype eq 'concat') {
7602: $newid = $id.$idtries;
1.1268 raeburn 7603: } elsif ($idtype eq 'addcode') {
7604: $newid = $newid.&sixnum_code();
1.1198 raeburn 7605: } else {
7606: $newid ++;
7607: }
7608: $idtries ++;
7609: }
7610: if (!exists($inuse{$prefix."\0".$newid})) {
7611: my %new_item = (
7612: $prefix."\0".$newid => $who,
7613: );
7614: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7615: $cdom,$cnum);
7616: if ($putresult ne 'ok') {
7617: undef($newid);
7618: $error = 'error saving new item: '.$putresult;
7619: }
7620: } else {
1.1268 raeburn 7621: undef($newid);
1.1198 raeburn 7622: $error = ('error: no unique suffix available for the new item ');
7623: }
7624: # remove lock
7625: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7626: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7627: } else {
7628: $error = "error: could not obtain lockfile\n";
7629: $dellock = 'ok';
1.1276 raeburn 7630: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7631: $dellock = 'nolock';
7632: }
1.1198 raeburn 7633: }
7634: return ($newid,$dellock,$error);
7635: }
7636:
1.1268 raeburn 7637: sub sixnum_code {
7638: my $code;
7639: for (0..6) {
7640: $code .= int( rand(9) );
7641: }
7642: return $code;
7643: }
7644:
1.765 albertel 7645: # -------------------------------------------------- portfolio access checking
7646:
7647: sub portfolio_access {
1.1270 raeburn 7648: my ($requrl,$clientip) = @_;
1.765 albertel 7649: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 7650: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7651: if ($result) {
7652: my %setters;
7653: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1473 raeburn 7654: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7655: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
7656: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7657: return 'B';
7658: }
7659: } else {
1.1473 raeburn 7660: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7661: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7662: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7663: return 'B';
7664: }
7665: }
7666: }
1.765 albertel 7667: if ($result eq 'ok') {
1.766 albertel 7668: return 'F';
1.765 albertel 7669: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7670: return 'A';
1.765 albertel 7671: }
1.766 albertel 7672: return '';
1.765 albertel 7673: }
7674:
7675: sub get_portfolio_access {
1.1270 raeburn 7676: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7677:
7678: if (!ref($access_hash)) {
7679: my $current_perms = &get_portfile_permissions($udom,$unum);
7680: my %access_controls = &get_access_controls($current_perms,$group,
7681: $file_name);
7682: $access_hash = $access_controls{$file_name};
7683: }
7684:
1.1270 raeburn 7685: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7686: my $now = time;
7687: if (ref($access_hash) eq 'HASH') {
7688: foreach my $key (keys(%{$access_hash})) {
7689: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7690: if ($start > $now) {
7691: next;
7692: }
7693: if ($end && $end<$now) {
7694: next;
7695: }
7696: if ($scope eq 'public') {
7697: $public = $key;
7698: last;
7699: } elsif ($scope eq 'guest') {
7700: $guest = $key;
7701: } elsif ($scope eq 'domains') {
7702: push(@domains,$key);
7703: } elsif ($scope eq 'users') {
7704: push(@users,$key);
7705: } elsif ($scope eq 'course') {
7706: push(@courses,$key);
7707: } elsif ($scope eq 'group') {
7708: push(@groups,$key);
1.1270 raeburn 7709: } elsif ($scope eq 'ip') {
7710: push(@ips,$key);
1.765 albertel 7711: }
7712: }
7713: if ($public) {
7714: return 'ok';
1.1270 raeburn 7715: } elsif (@ips > 0) {
7716: my $allowed;
7717: foreach my $ipkey (@ips) {
7718: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7719: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7720: $allowed = 1;
7721: last;
7722: }
7723: }
7724: }
7725: if ($allowed) {
7726: return 'ok';
7727: }
1.765 albertel 7728: }
7729: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7730: if ($guest) {
7731: return $guest;
7732: }
7733: } else {
7734: if (@domains > 0) {
7735: foreach my $domkey (@domains) {
7736: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7737: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7738: return 'ok';
7739: }
7740: }
7741: }
7742: }
7743: if (@users > 0) {
7744: foreach my $userkey (@users) {
1.865 raeburn 7745: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7746: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7747: if (ref($item) eq 'HASH') {
7748: if (($item->{'uname'} eq $env{'user.name'}) &&
7749: ($item->{'udom'} eq $env{'user.domain'})) {
7750: return 'ok';
7751: }
7752: }
7753: }
7754: }
1.765 albertel 7755: }
7756: }
7757: my %roleshash;
7758: my @courses_and_groups = @courses;
7759: push(@courses_and_groups,@groups);
7760: if (@courses_and_groups > 0) {
7761: my (%allgroups,%allroles);
7762: my ($start,$end,$role,$sec,$group);
7763: foreach my $envkey (%env) {
1.1060 raeburn 7764: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7765: my $cid = $2.'_'.$3;
7766: if ($1 eq 'gr') {
7767: $group = $4;
7768: $allgroups{$cid}{$group} = $env{$envkey};
7769: } else {
7770: if ($4 eq '') {
7771: $sec = 'none';
7772: } else {
7773: $sec = $4;
7774: }
7775: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7776: }
1.811 albertel 7777: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7778: my $cid = $2.'_'.$3;
7779: if ($4 eq '') {
7780: $sec = 'none';
7781: } else {
7782: $sec = $4;
7783: }
7784: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7785: }
7786: }
7787: if (keys(%allroles) == 0) {
7788: return;
7789: }
7790: foreach my $key (@courses_and_groups) {
7791: my %content = %{$$access_hash{$key}};
7792: my $cnum = $content{'number'};
7793: my $cdom = $content{'domain'};
7794: my $cid = $cdom.'_'.$cnum;
7795: if (!exists($allroles{$cid})) {
7796: next;
7797: }
7798: foreach my $role_id (keys(%{$content{'roles'}})) {
7799: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7800: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7801: my @status = @{$content{'roles'}{$role_id}{'access'}};
7802: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7803: foreach my $role (keys(%{$allroles{$cid}})) {
7804: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7805: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7806: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7807: if (grep/^all$/,@sections) {
7808: return 'ok';
7809: } else {
7810: if (grep/^$sec$/,@sections) {
7811: return 'ok';
7812: }
7813: }
7814: }
7815: }
7816: if (keys(%{$allgroups{$cid}}) == 0) {
7817: if (grep/^none$/,@groups) {
7818: return 'ok';
7819: }
7820: } else {
7821: if (grep/^all$/,@groups) {
7822: return 'ok';
7823: }
7824: foreach my $group (keys(%{$allgroups{$cid}})) {
7825: if (grep/^$group$/,@groups) {
7826: return 'ok';
7827: }
7828: }
7829: }
7830: }
7831: }
7832: }
7833: }
7834: }
7835: if ($guest) {
7836: return $guest;
7837: }
7838: }
7839: }
7840: return;
7841: }
7842:
7843: sub course_group_datechecker {
7844: my ($dates,$now,$status) = @_;
7845: my ($start,$end) = split(/\./,$dates);
7846: if (!$start && !$end) {
7847: return 'ok';
7848: }
7849: if (grep/^active$/,@{$status}) {
7850: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7851: return 'ok';
7852: }
7853: }
7854: if (grep/^previous$/,@{$status}) {
7855: if ($end > $now ) {
7856: return 'ok';
7857: }
7858: }
7859: if (grep/^future$/,@{$status}) {
7860: if ($start > $now) {
7861: return 'ok';
7862: }
7863: }
7864: return;
7865: }
7866:
7867: sub parse_portfolio_url {
7868: my ($url) = @_;
7869:
7870: my ($type,$udom,$unum,$group,$file_name);
7871:
1.823 albertel 7872: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7873: $type = 1;
7874: $udom = $1;
7875: $unum = $2;
7876: $file_name = $3;
1.823 albertel 7877: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7878: $type = 2;
7879: $udom = $1;
7880: $unum = $2;
7881: $group = $3;
7882: $file_name = $3.'/'.$4;
7883: }
7884: if (wantarray) {
7885: return ($type,$udom,$unum,$file_name,$group);
7886: }
7887: return $type;
7888: }
7889:
7890: sub is_portfolio_url {
7891: my ($url) = @_;
7892: return scalar(&parse_portfolio_url($url));
7893: }
7894:
1.798 raeburn 7895: sub is_portfolio_file {
7896: my ($file) = @_;
1.820 raeburn 7897: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7898: return 1;
7899: }
7900: return;
7901: }
7902:
1.976 raeburn 7903: sub usertools_access {
1.1084 raeburn 7904: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7905: my ($access,%tools);
7906: if ($context eq '') {
7907: $context = 'tools';
7908: }
7909: if ($context eq 'requestcourses') {
7910: %tools = (
7911: official => 1,
7912: unofficial => 1,
1.1006 raeburn 7913: community => 1,
1.1246 raeburn 7914: textbook => 1,
1.1305 raeburn 7915: placement => 1,
1.1368 raeburn 7916: lti => 1,
1.985 raeburn 7917: );
1.1183 raeburn 7918: } elsif ($context eq 'requestauthor') {
7919: %tools = (
7920: requestauthor => 1,
7921: );
1.985 raeburn 7922: } else {
7923: %tools = (
7924: aboutme => 1,
7925: blog => 1,
1.1177 raeburn 7926: webdav => 1,
1.985 raeburn 7927: portfolio => 1,
7928: );
7929: }
1.976 raeburn 7930: return if (!defined($tools{$tool}));
7931:
1.1242 raeburn 7932: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7933: $udom = $env{'user.domain'};
7934: $uname = $env{'user.name'};
7935: }
7936:
1.978 raeburn 7937: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7938: if ($action ne 'reload') {
1.985 raeburn 7939: if ($context eq 'requestcourses') {
7940: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 7941: } elsif ($context eq 'requestauthor') {
7942: return $env{'environment.canrequest.author'};
1.985 raeburn 7943: } else {
7944: return $env{'environment.availabletools.'.$tool};
7945: }
7946: }
1.976 raeburn 7947: }
7948:
1.1183 raeburn 7949: my ($toolstatus,$inststatus,$envkey);
7950: if ($context eq 'requestauthor') {
7951: $envkey = $context;
7952: } else {
7953: $envkey = $context.'.'.$tool;
7954: }
1.976 raeburn 7955:
1.985 raeburn 7956: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7957: ($action ne 'reload')) {
1.1183 raeburn 7958: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7959: $inststatus = $env{'environment.inststatus'};
7960: } else {
1.1084 raeburn 7961: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 7962: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7963: $inststatus = $userenvref->{'inststatus'};
7964: } else {
1.1183 raeburn 7965: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7966: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7967: $inststatus = $userenv{'inststatus'};
7968: }
1.976 raeburn 7969: }
7970:
7971: if ($toolstatus ne '') {
7972: if ($toolstatus) {
7973: $access = 1;
7974: } else {
7975: $access = 0;
7976: }
7977: return $access;
7978: }
7979:
1.1084 raeburn 7980: my ($is_adv,%domdef);
7981: if (ref($is_advref) eq 'HASH') {
7982: $is_adv = $is_advref->{'is_adv'};
7983: } else {
7984: $is_adv = &is_advanced_user($udom,$uname);
7985: }
7986: if (ref($domdefref) eq 'HASH') {
7987: %domdef = %{$domdefref};
7988: } else {
7989: %domdef = &get_domain_defaults($udom);
7990: }
1.976 raeburn 7991: if (ref($domdef{$tool}) eq 'HASH') {
7992: if ($is_adv) {
7993: if ($domdef{$tool}{'_LC_adv'} ne '') {
7994: if ($domdef{$tool}{'_LC_adv'}) {
7995: $access = 1;
7996: } else {
7997: $access = 0;
7998: }
7999: return $access;
8000: }
8001: }
8002: if ($inststatus ne '') {
8003: my ($hasaccess,$hasnoaccess);
8004: foreach my $affiliation (split(/:/,$inststatus)) {
8005: if ($domdef{$tool}{$affiliation} ne '') {
8006: if ($domdef{$tool}{$affiliation}) {
8007: $hasaccess = 1;
8008: } else {
8009: $hasnoaccess = 1;
8010: }
8011: }
8012: }
8013: if ($hasaccess || $hasnoaccess) {
8014: if ($hasaccess) {
8015: $access = 1;
8016: } elsif ($hasnoaccess) {
8017: $access = 0;
8018: }
8019: return $access;
8020: }
8021: } else {
8022: if ($domdef{$tool}{'default'} ne '') {
8023: if ($domdef{$tool}{'default'}) {
8024: $access = 1;
8025: } elsif ($domdef{$tool}{'default'} == 0) {
8026: $access = 0;
8027: }
8028: return $access;
8029: }
8030: }
8031: } else {
1.1177 raeburn 8032: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 8033: $access = 1;
8034: } else {
8035: $access = 0;
8036: }
1.976 raeburn 8037: return $access;
8038: }
8039: }
8040:
1.1050 raeburn 8041: sub is_course_owner {
8042: my ($cdom,$cnum,$udom,$uname) = @_;
8043: if (($udom eq '') || ($uname eq '')) {
8044: $udom = $env{'user.domain'};
8045: $uname = $env{'user.name'};
8046: }
8047: unless (($udom eq '') || ($uname eq '')) {
8048: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
8049: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
8050: return 1;
8051: } else {
8052: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
8053: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
8054: return 1;
8055: }
8056: }
8057: }
8058: }
8059: return;
8060: }
8061:
1.976 raeburn 8062: sub is_advanced_user {
8063: my ($udom,$uname) = @_;
1.1085 raeburn 8064: if ($udom ne '' && $uname ne '') {
8065: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 8066: if (wantarray) {
8067: return ($env{'user.adv'},$env{'user.author'});
8068: } else {
8069: return $env{'user.adv'};
8070: }
1.1085 raeburn 8071: }
8072: }
1.976 raeburn 8073: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
8074: my %allroles;
1.1128 raeburn 8075: my ($is_adv,$is_author);
1.976 raeburn 8076: foreach my $role (keys(%roleshash)) {
8077: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
8078: my $area = '/'.$tdomain.'/'.$trest;
8079: if ($sec ne '') {
8080: $area .= '/'.$sec;
8081: }
8082: if (($area ne '') && ($trole ne '')) {
8083: my $spec=$trole.'.'.$area;
8084: if ($trole =~ /^cr\//) {
8085: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
8086: } elsif ($trole ne 'gr') {
8087: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
8088: }
1.1128 raeburn 8089: if ($trole eq 'au') {
8090: $is_author = 1;
8091: }
1.976 raeburn 8092: }
8093: }
8094: foreach my $role (keys(%allroles)) {
8095: last if ($is_adv);
8096: foreach my $item (split(/:/,$allroles{$role})) {
8097: if ($item ne '') {
8098: my ($privilege,$restrictions)=split(/&/,$item);
8099: if ($privilege eq 'adv') {
8100: $is_adv = 1;
8101: last;
8102: }
8103: }
8104: }
8105: }
1.1128 raeburn 8106: if (wantarray) {
8107: return ($is_adv,$is_author);
8108: }
1.976 raeburn 8109: return $is_adv;
8110: }
1.798 raeburn 8111:
1.1035 raeburn 8112: sub check_can_request {
1.1368 raeburn 8113: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035 raeburn 8114: my $canreq = 0;
1.1368 raeburn 8115: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8116: $uname = $env{'user.name'};
8117: $udom = $env{'user.domain'};
8118: }
1.1035 raeburn 8119: my ($types,$typename) = &Apache::loncommon::course_types();
8120: my @options = ('approval','validate','autolimit');
8121: my $optregex = join('|',@options);
8122: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
8123: foreach my $type (@{$types}) {
1.1368 raeburn 8124: if (&usertools_access($uname,$udom,$type,undef,
8125: 'requestcourses')) {
1.1035 raeburn 8126: $canreq ++;
1.1036 raeburn 8127: if (ref($request_domains) eq 'HASH') {
1.1368 raeburn 8128: push(@{$request_domains->{$type}},$udom);
1.1036 raeburn 8129: }
1.1368 raeburn 8130: if ($dom eq $udom) {
1.1035 raeburn 8131: $can_request->{$type} = 1;
8132: }
8133: }
1.1368 raeburn 8134: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
8135: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035 raeburn 8136: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
8137: if (@curr > 0) {
1.1036 raeburn 8138: foreach my $item (@curr) {
8139: if (ref($request_domains) eq 'HASH') {
8140: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
8141: if ($otherdom ne '') {
8142: if (ref($request_domains->{$type}) eq 'ARRAY') {
8143: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
8144: push(@{$request_domains->{$type}},$otherdom);
8145: }
8146: } else {
8147: push(@{$request_domains->{$type}},$otherdom);
8148: }
8149: }
8150: }
8151: }
1.1368 raeburn 8152: unless ($dom eq $env{'user.domain'}) {
1.1036 raeburn 8153: $canreq ++;
1.1035 raeburn 8154: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
8155: $can_request->{$type} = 1;
8156: }
8157: }
8158: }
8159: }
8160: }
8161: }
8162: return $canreq;
8163: }
8164:
1.341 www 8165: # ---------------------------------------------- Custom access rule evaluation
8166:
8167: sub customaccess {
8168: my ($priv,$uri)=@_;
1.807 albertel 8169: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 8170: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 8171: $udom = &LONCAPA::clean_domain($udom);
8172: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 8173: my $access=0;
1.800 albertel 8174: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 8175: my ($effect,$realm,$role,$type)=split(/\:/,$right);
8176: if ($type eq 'user') {
8177: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 8178: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 8179: if ($tdom) {
8180: if ($tdom ne $env{'user.domain'}) { next; }
8181: }
1.896 albertel 8182: if ($tuname) {
8183: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 8184: }
8185: $access=($effect eq 'allow');
8186: last;
8187: }
8188: } else {
8189: if ($role) {
8190: if ($role ne $urole) { next; }
8191: }
8192: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8193: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8194: if ($tdom) {
8195: if ($tdom ne $udom) { next; }
8196: }
8197: if ($tcrs) {
8198: if ($tcrs ne $ucrs) { next; }
8199: }
8200: if ($tsec) {
8201: if ($tsec ne $usec) { next; }
8202: }
8203: $access=($effect eq 'allow');
8204: last;
8205: }
8206: if ($realm eq '' && $role eq '') {
8207: $access=($effect eq 'allow');
8208: }
1.402 bowersj2 8209: }
1.341 www 8210: }
8211: return $access;
8212: }
8213:
1.103 harris41 8214: # ------------------------------------------------- Check for a user privilege
1.12 www 8215:
8216: sub allowed {
1.1461 raeburn 8217: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705 albertel 8218: my $ver_orguri=$uri;
1.439 www 8219: $uri=&deversion($uri);
1.152 www 8220: my $orguri=$uri;
1.52 www 8221: $uri=&declutter($uri);
1.809 raeburn 8222:
1.810 raeburn 8223: if ($priv eq 'evb') {
1.1478 raeburn 8224: # Evade communication block restrictions for specified role in a course or domain
1.810 raeburn 8225: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8226: return $1;
8227: } else {
8228: return;
8229: }
8230: }
8231:
1.620 albertel 8232: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 8233: # Free bre access to adm and meta resources
1.1436 raeburn 8234: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$}))
1.769 albertel 8235: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8236: && ($priv eq 'bre')) {
1.14 www 8237: return 'F';
1.159 www 8238: }
8239:
1.545 banghart 8240: # Free bre access to user's own portfolio contents
1.714 raeburn 8241: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 8242: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 8243: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 8244: my %setters;
1.1473 raeburn 8245: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
8246: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
8247: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 8248: return 'B';
8249: } else {
8250: return 'F';
8251: }
1.545 banghart 8252: }
8253:
1.762 raeburn 8254: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 8255: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8256: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8257: if (exists($env{'request.course.id'})) {
8258: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8259: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8260: if (($domain eq $cdom) && ($name eq $cnum)) {
8261: my $courseprivid=$env{'request.course.id'};
8262: $courseprivid=~s/\_/\//;
8263: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8264: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8265: return $1;
1.762 raeburn 8266: } else {
8267: if ($env{'request.course.sec'}) {
8268: $courseprivid.='/'.$env{'request.course.sec'};
8269: }
8270: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8271: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8272: return $2;
8273: }
1.714 raeburn 8274: }
8275: }
8276: }
8277: }
8278:
1.159 www 8279: # Free bre to public access
8280:
8281: if ($priv eq 'bre') {
1.1362 raeburn 8282: my $copyright;
8283: unless ($uri =~ /ext\.tool/) {
8284: $copyright=&metadata($uri,'copyright');
8285: }
1.620 albertel 8286: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 8287: return 'F';
8288: }
1.238 www 8289: if ($copyright eq 'priv') {
8290: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8291: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 8292: return '';
8293: }
8294: }
8295: if ($copyright eq 'domain') {
8296: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8297: unless (($env{'user.domain'} eq $1) ||
8298: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8299: return '';
8300: }
1.262 matthew 8301: }
1.620 albertel 8302: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8303: # Library role, so allow browsing of resources in this domain.
8304: return 'F';
1.238 www 8305: }
1.341 www 8306: if ($copyright eq 'custom') {
8307: unless (&customaccess($priv,$uri)) { return ''; }
8308: }
1.14 www 8309: }
1.264 matthew 8310: # Domain coordinator is trying to create a course
1.620 albertel 8311: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8312: # uri is the requested domain in this case.
8313: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8314: # a role of dc for the domain in question.
1.620 albertel 8315: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8316: }
1.29 www 8317:
1.52 www 8318: my $thisallowed='';
8319: my $statecond=0;
8320: my $courseprivid='';
8321:
1.1039 raeburn 8322: my $ownaccess;
1.1043 raeburn 8323: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8324: if (($priv eq 'bro') && ($env{'user.author'})) {
8325: if ($uri eq '') {
8326: $ownaccess = 1;
8327: } else {
8328: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8329: my $udom = $env{'user.domain'};
8330: my $uname = $env{'user.name'};
8331: if ($uri =~ m{^\Q$udom\E/?$}) {
8332: $ownaccess = 1;
1.1040 raeburn 8333: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8334: unless ($uri =~ m{\.\./}) {
8335: $ownaccess = 1;
8336: }
8337: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8338: my $now = time;
8339: if ($uri =~ m{^([^/]+)/?$}) {
8340: my $adom = $1;
8341: foreach my $key (keys(%env)) {
1.1042 raeburn 8342: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452 raeburn 8343: my ($start,$end) = split(/\./,$env{$key});
8344: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8345: $ownaccess = 1;
8346: last;
8347: }
8348: }
8349: }
8350: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8351: my $adom = $1;
8352: my $aname = $2;
1.1042 raeburn 8353: foreach my $role ('ca','aa') {
8354: if ($env{"user.role.$role./$adom/$aname"}) {
8355: my ($start,$end) =
1.1452 raeburn 8356: split(/\./,$env{"user.role.$role./$adom/$aname"});
8357: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8358: $ownaccess = 1;
8359: last;
8360: }
1.1039 raeburn 8361: }
8362: }
8363: }
8364: }
8365: }
8366: }
8367: }
8368:
1.52 www 8369: # Course
8370:
1.620 albertel 8371: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8372: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8373: $thisallowed.=$1;
8374: }
1.52 www 8375: }
1.29 www 8376:
1.52 www 8377: # Domain
8378:
1.620 albertel 8379: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8380: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8381: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8382: $thisallowed.=$1;
8383: }
1.12 www 8384: }
1.52 www 8385:
1.1141 raeburn 8386: # User who is not author or co-author might still be able to edit
8387: # resource of an author in the domain (e.g., if Domain Coordinator).
8388: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8389: (&allowed('mdc',$env{'request.course.id'}))) {
8390: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8391: $thisallowed.=$1;
8392: }
8393: }
8394:
1.52 www 8395: # Course: uri itself is a course
1.66 www 8396: my $courseuri=$uri;
8397: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8398: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8399:
1.620 albertel 8400: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8401: =~/\Q$priv\E\&([^\:]*)/) {
1.1409 raeburn 8402: if ($priv eq 'mip') {
8403: my $rem = $1;
8404: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8405: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8406: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8407: if ($cdom ne '') {
1.1410 raeburn 8408: my %passwdconf = &get_passwdconf($cdom);
8409: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8410: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8411: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8412: my @inststatuses = split(':',$env{'environment.inststatus'});
8413: unless (@inststatuses) {
8414: @inststatuses = ('default');
8415: }
8416: foreach my $status (@inststatuses) {
8417: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8418: $thisallowed.=$rem;
8419: }
8420: }
8421: }
8422: }
1.1409 raeburn 8423: }
8424: }
8425: }
8426: } else {
8427: unless (($priv eq 'bro') && (!$ownaccess)) {
8428: $thisallowed.=$1;
8429: }
1.1039 raeburn 8430: }
1.12 www 8431: }
1.29 www 8432:
1.665 albertel 8433: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8434: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8435: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8436: $thisallowed='';
1.671 raeburn 8437: my ($match)=&is_on_map($uri);
8438: if ($match) {
8439: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8440: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 8441: my $value = $1;
1.1461 raeburn 8442: my $deeplinkblock;
8443: unless ($nodeeplinkcheck) {
8444: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8445: }
1.1402 raeburn 8446: if ($deeplinkblock) {
8447: $thisallowed='D';
8448: } elsif ($noblockcheck) {
1.1281 raeburn 8449: $thisallowed.=$value;
1.1162 raeburn 8450: } else {
1.1424 raeburn 8451: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8452: if (@blockers > 0) {
8453: $thisallowed = 'B';
8454: } else {
8455: $thisallowed.=$value;
8456: }
1.1162 raeburn 8457: }
1.671 raeburn 8458: }
8459: } else {
1.705 albertel 8460: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8461: if ($refuri) {
8462: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8463: $thisallowed='F';
1.671 raeburn 8464: } else {
8465: $refuri=&declutter($refuri);
8466: my ($match) = &is_on_map($refuri);
8467: if ($match) {
1.1461 raeburn 8468: my $deeplinkblock;
8469: unless ($nodeeplinkcheck) {
8470: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8471: }
1.1402 raeburn 8472: if ($deeplinkblock) {
8473: $thisallowed='D';
8474: } elsif ($noblockcheck) {
1.1281 raeburn 8475: $thisallowed='F';
1.1162 raeburn 8476: } else {
1.1426 raeburn 8477: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8478: if (@blockers > 0) {
8479: $thisallowed = 'B';
8480: } else {
8481: $thisallowed='F';
8482: }
1.1162 raeburn 8483: }
1.671 raeburn 8484: }
1.669 raeburn 8485: }
1.671 raeburn 8486: }
8487: }
1.314 www 8488: }
1.492 albertel 8489:
1.766 albertel 8490: if ($priv eq 'bre'
8491: && $thisallowed ne 'F'
8492: && $thisallowed ne '2'
8493: && &is_portfolio_url($uri)) {
1.1270 raeburn 8494: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8495: }
1.1250 raeburn 8496:
1.52 www 8497: # Full access at system, domain or course-wide level? Exit.
1.29 www 8498: if ($thisallowed=~/F/) {
8499: return 'F';
8500: }
8501:
1.52 www 8502: # If this is generating or modifying users, exit with special codes
1.29 www 8503:
1.643 www 8504: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8505: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8506: my ($audom,$auname)=split('/',$uri);
1.643 www 8507: # no author name given, so this just checks on the general right to make a co-author in this domain
8508: unless ($auname) { return $thisallowed; }
8509: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8510: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8511: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8512: ($audom ne $env{'request.role.domain'}))) { return ''; }
8513: }
1.52 www 8514: return $thisallowed;
8515: }
8516: #
1.103 harris41 8517: # Gathered so far: system, domain and course wide privileges
1.52 www 8518: #
8519: # Course: See if uri or referer is an individual resource that is part of
8520: # the course
8521:
1.620 albertel 8522: if ($env{'request.course.id'}) {
1.232 www 8523:
1.1409 raeburn 8524: # If this is modifying password (internal auth) domains must match for user and user's role.
8525:
8526: if ($priv eq 'mip') {
8527: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8528: return $thisallowed;
8529: } else {
8530: return '';
8531: }
8532: }
8533:
1.620 albertel 8534: $courseprivid=$env{'request.course.id'};
8535: if ($env{'request.course.sec'}) {
8536: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8537: }
8538: $courseprivid=~s/\_/\//;
8539: my $checkreferer=1;
1.232 www 8540: my ($match,$cond)=&is_on_map($uri);
8541: if ($match) {
8542: $statecond=$cond;
1.620 albertel 8543: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8544: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8545: my $value = $1;
8546: if ($priv eq 'bre') {
1.1461 raeburn 8547: my $deeplinkblock;
8548: unless ($nodeeplinkcheck) {
8549: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8550: }
1.1458 raeburn 8551: if ($deeplinkblock) {
8552: $thisallowed = 'D';
8553: } elsif ($noblockcheck) {
1.1281 raeburn 8554: $thisallowed.=$value;
1.1162 raeburn 8555: } else {
1.1424 raeburn 8556: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8557: if (@blockers > 0) {
8558: $thisallowed = 'B';
8559: } else {
8560: $thisallowed.=$value;
8561: }
1.1162 raeburn 8562: }
8563: } else {
8564: $thisallowed.=$value;
8565: }
1.52 www 8566: $checkreferer=0;
8567: }
1.29 www 8568: }
1.1424 raeburn 8569:
1.148 www 8570: if ($checkreferer) {
1.620 albertel 8571: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8572: unless ($refuri) {
1.800 albertel 8573: foreach my $key (keys(%env)) {
8574: if ($key=~/^httpref\..*\*/) {
8575: my $pattern=$key;
1.156 www 8576: $pattern=~s/^httpref\.\/res\///;
1.148 www 8577: $pattern=~s/\*/\[\^\/\]\+/g;
8578: $pattern=~s/\//\\\//g;
1.152 www 8579: if ($orguri=~/$pattern/) {
1.800 albertel 8580: $refuri=$env{$key};
1.148 www 8581: }
8582: }
1.191 harris41 8583: }
1.148 www 8584: }
1.232 www 8585:
1.148 www 8586: if ($refuri) {
1.152 www 8587: $refuri=&declutter($refuri);
1.232 www 8588: my ($match,$cond)=&is_on_map($refuri);
8589: if ($match) {
8590: my $refstatecond=$cond;
1.620 albertel 8591: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8592: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8593: my $value = $1;
8594: if ($priv eq 'bre') {
1.1461 raeburn 8595: my $deeplinkblock;
8596: unless ($nodeeplinkcheck) {
8597: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8598: }
1.1402 raeburn 8599: if ($deeplinkblock) {
8600: $thisallowed = 'D';
8601: } elsif ($noblockcheck) {
1.1281 raeburn 8602: $thisallowed.=$value;
1.1162 raeburn 8603: } else {
1.1426 raeburn 8604: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8605: if (@blockers > 0) {
8606: $thisallowed = 'B';
8607: } else {
8608: $thisallowed.=$value;
8609: }
1.1162 raeburn 8610: }
8611: } else {
8612: $thisallowed.=$value;
8613: }
1.53 www 8614: $uri=$refuri;
8615: $statecond=$refstatecond;
1.52 www 8616: }
8617: }
1.148 www 8618: }
1.29 www 8619: }
1.52 www 8620: }
1.29 www 8621:
1.52 www 8622: #
1.103 harris41 8623: # Gathered now: all privileges that could apply, and condition number
1.52 www 8624: #
8625: #
8626: # Full or no access?
8627: #
1.29 www 8628:
1.52 www 8629: if ($thisallowed=~/F/) {
8630: return 'F';
8631: }
1.29 www 8632:
1.52 www 8633: unless ($thisallowed) {
8634: return '';
8635: }
1.29 www 8636:
1.52 www 8637: # Restrictions exist, deal with them
8638: #
8639: # C:according to course preferences
8640: # R:according to resource settings
8641: # L:unless locked
8642: # X:according to user session state
8643: #
8644:
8645: # Possibly locked functionality, check all courses
1.1454 raeburn 8646: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 8647: # Locks might take effect only after 10 minutes cache expiration for other
1.1454 raeburn 8648: # courses, and 2 minutes for current course, in which user has st or ta role
8649: # which is neither expired nor a future role (unless current course).
1.52 www 8650:
1.1454 raeburn 8651: my ($needlockcheck,$now,$crsonly);
1.52 www 8652: if ($thisallowed=~/L/) {
1.1454 raeburn 8653: $now = time;
8654: if ($priv eq 'bre') {
8655: if ($uri ne '') {
8656: if ($orguri =~ m{^/+res/}) {
8657: if ($uri =~ m{^lib/templates/}) {
8658: if ($env{'request.course.id'}) {
8659: $crsonly = 1;
8660: $needlockcheck = 1;
8661: }
8662: } else {
8663: $needlockcheck = 1;
8664: }
8665: } elsif ($env{'request.course.id'}) {
8666: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8667: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8668: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8669: $crsonly = 1;
8670: }
8671: $needlockcheck = 1;
8672: }
8673: }
8674: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8675: $needlockcheck = 1;
8676: }
8677: }
8678: if ($needlockcheck) {
1.1453 raeburn 8679: foreach my $envkey (keys(%env)) {
1.54 www 8680: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8681: my $courseid=$2;
8682: my $roleid=$1.'.'.$2;
1.92 www 8683: $courseid=~s/^\///;
1.1453 raeburn 8684: unless ($env{'request.role'} eq $roleid) {
8685: my ($start,$end) = split(/\./,$env{$envkey});
8686: next unless (($now >= $start) && (!$end || $end > $now));
8687: }
1.54 www 8688: my $expiretime=600;
1.620 albertel 8689: if ($env{'request.role'} eq $roleid) {
1.54 www 8690: $expiretime=120;
8691: }
8692: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8693: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8694: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8695: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8696: }
1.620 albertel 8697: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8698: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8699: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8700: &log($env{'user.domain'},$env{'user.name'},
8701: $env{'user.home'},
1.57 www 8702: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8703: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8704: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8705: return '';
8706: }
8707: }
1.620 albertel 8708: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8709: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455 raeburn 8710: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 8711: &log($env{'user.domain'},$env{'user.name'},
8712: $env{'user.home'},
1.57 www 8713: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8714: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8715: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8716: return '';
8717: }
8718: }
8719: }
1.29 www 8720: }
1.52 www 8721: }
1.1424 raeburn 8722:
1.52 www 8723: #
8724: # Rest of the restrictions depend on selected course
8725: #
8726:
1.620 albertel 8727: unless ($env{'request.course.id'}) {
1.766 albertel 8728: if ($thisallowed eq 'A') {
8729: return 'A';
1.814 raeburn 8730: } elsif ($thisallowed eq 'B') {
8731: return 'B';
1.766 albertel 8732: } else {
8733: return '1';
8734: }
1.52 www 8735: }
1.29 www 8736:
1.52 www 8737: #
8738: # Now user is definitely in a course
8739: #
1.53 www 8740:
8741:
8742: # Course preferences
8743:
8744: if ($thisallowed=~/C/) {
1.620 albertel 8745: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8746: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8747: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8748: =~/\Q$rolecode\E/) {
1.1304 raeburn 8749: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8750: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8751: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8752: $env{'request.course.id'});
8753: }
1.237 www 8754: return '';
8755: }
8756:
1.620 albertel 8757: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8758: =~/\Q$unamedom\E/) {
1.1304 raeburn 8759: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8760: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8761: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8762: $env{'request.course.id'});
8763: }
1.54 www 8764: return '';
8765: }
1.53 www 8766: }
8767:
8768: # Resource preferences
8769:
8770: if ($thisallowed=~/R/) {
1.620 albertel 8771: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8772: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8773: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8774: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8775: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8776: }
8777: return '';
1.54 www 8778: }
1.53 www 8779: }
1.30 www 8780:
1.1461 raeburn 8781: # Restricted for deeplinked session?
8782:
8783: if ($env{'request.deeplink.login'}) {
8784: if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
8785: if (!$symb) { $symb=&symbread($uri,1); }
8786: if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
8787: return '';
8788: }
8789: }
8790: }
8791:
1.246 www 8792: # Restricted by state or randomout?
1.30 www 8793:
1.52 www 8794: if ($thisallowed=~/X/) {
1.620 albertel 8795: if ($env{'acc.randomout'}) {
1.579 albertel 8796: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8797: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8798: return '';
8799: }
1.247 www 8800: }
8801: if (&condval($statecond)) {
1.52 www 8802: return '2';
8803: } else {
8804: return '';
8805: }
8806: }
1.30 www 8807:
1.766 albertel 8808: if ($thisallowed eq 'A') {
8809: return 'A';
1.814 raeburn 8810: } elsif ($thisallowed eq 'B') {
8811: return 'B';
1.1402 raeburn 8812: } elsif ($thisallowed eq 'D') {
8813: return 'D';
1.766 albertel 8814: }
1.52 www 8815: return 'F';
1.232 www 8816: }
1.1162 raeburn 8817:
1.1192 raeburn 8818: # ------------------------------------------- Check construction space access
8819:
8820: sub constructaccess {
8821: my ($url,$setpriv)=@_;
8822:
8823: # We do not allow editing of previous versions of files
8824: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8825:
8826: # Get username and domain from URL
8827: my ($ownername,$ownerdomain,$ownerhome);
8828:
8829: ($ownerdomain,$ownername) =
1.1325 raeburn 8830: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 8831:
8832: # The URL does not really point to any authorspace, forget it
8833: unless (($ownername) && ($ownerdomain)) { return ''; }
8834:
8835: # Now we need to see if the user has access to the authorspace of
8836: # $ownername at $ownerdomain
8837:
8838: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8839: # Real author for this?
8840: $ownerhome = $env{'user.home'};
8841: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8842: return ($ownername,$ownerdomain,$ownerhome);
8843: }
8844: } else {
8845: # Co-author for this?
8846: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8847: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8848: $ownerhome = &homeserver($ownername,$ownerdomain);
8849: return ($ownername,$ownerdomain,$ownerhome);
8850: }
1.1312 raeburn 8851: if ($env{'request.course.id'}) {
8852: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
8853: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
8854: if (&allowed('mdc',$env{'request.course.id'})) {
8855: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
8856: return ($ownername,$ownerdomain,$ownerhome);
8857: }
8858: }
8859: }
1.1192 raeburn 8860: }
8861:
8862: # We don't have any access right now. If we are not possibly going to do anything about this,
8863: # we might as well leave
8864: unless ($setpriv) { return ''; }
8865:
8866: # Backdoor access?
8867: my $allowed=&allowed('eco',$ownerdomain);
8868: # Nope
8869: unless ($allowed) { return ''; }
8870: # Looks like we may have access, but could be locked by the owner of the construction space
8871: if ($allowed eq 'U') {
8872: my %blocked=&get('environment',['domcoord.author'],
8873: $ownerdomain,$ownername);
8874: # Is blocked by owner
8875: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8876: }
8877: if (($allowed eq 'F') || ($allowed eq 'U')) {
8878: # Grant temporary access
8879: my $then=$env{'user.login.time'};
1.1209 raeburn 8880: my $update=$env{'user.update.time'};
1.1192 raeburn 8881: if (!$update) { $update = $then; }
8882: my $refresh=$env{'user.refresh.time'};
8883: if (!$refresh) { $refresh = $update; }
8884: my $now = time;
8885: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8886: $now,'ca','constructaccess');
8887: $ownerhome = &homeserver($ownername,$ownerdomain);
8888: return($ownername,$ownerdomain,$ownerhome);
8889: }
8890: # No business here
8891: return '';
8892: }
8893:
1.1282 raeburn 8894: # ----------------------------------------------------------- Content Blocking
8895:
8896: {
8897: # Caches for faster Course Contents display where content blocking
8898: # is in operation (i.e., interval param set) for timed quiz.
8899: #
8900: # User for whom data are being temporarily cached.
8901: my $cacheduser='';
1.1424 raeburn 8902: # Course for which data are being temporarily cached.
8903: my $cachedcid='';
1.1282 raeburn 8904: # Cached blockers for this user (a hash of blocking items).
8905: my %cachedblockers=();
8906: # When the data were last cached.
8907: my $cachedlast='';
8908:
8909: sub load_all_blockers {
1.1427 raeburn 8910: my ($uname,$udom)=@_;
1.1282 raeburn 8911: if (($uname ne '') && ($udom ne '')) {
8912: if (($cacheduser eq $uname.':'.$udom) &&
1.1424 raeburn 8913: ($cachedcid eq $env{'request.course.id'}) &&
1.1427 raeburn 8914: (abs($cachedlast-time)<5)) {
1.1282 raeburn 8915: return;
8916: }
8917: }
8918: $cachedlast=time;
8919: $cacheduser=$uname.':'.$udom;
1.1424 raeburn 8920: $cachedcid=$env{'request.course.id'};
1.1427 raeburn 8921: %cachedblockers = &get_commblock_resources();
1.1424 raeburn 8922: return;
1.1282 raeburn 8923: }
8924:
1.1162 raeburn 8925: sub get_comm_blocks {
8926: my ($cdom,$cnum) = @_;
8927: if ($cdom eq '' || $cnum eq '') {
8928: return unless ($env{'request.course.id'});
8929: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8930: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8931: }
8932: my %commblocks;
8933: my $hashid=$cdom.'_'.$cnum;
8934: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8935: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8936: %commblocks = %{$blocksref};
8937: } else {
8938: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8939: my $cachetime = 600;
8940: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8941: }
8942: return %commblocks;
8943: }
8944:
1.1282 raeburn 8945: sub get_commblock_resources {
8946: my ($blocks) = @_;
8947: my %blockers = ();
8948: return %blockers unless ($env{'request.course.id'});
1.1470 raeburn 8949: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8950: if ($env{'request.course.sec'}) {
8951: $courseurl .= '/'.$env{'request.course.sec'};
8952: }
8953: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162 raeburn 8954: my %commblocks;
8955: if (ref($blocks) eq 'HASH') {
8956: %commblocks = %{$blocks};
8957: } else {
8958: %commblocks = &get_comm_blocks();
8959: }
1.1282 raeburn 8960: return %blockers unless (keys(%commblocks) > 0);
8961: my $navmap = Apache::lonnavmaps::navmap->new();
8962: return %blockers unless (ref($navmap));
1.1162 raeburn 8963: my $now = time;
8964: foreach my $block (keys(%commblocks)) {
8965: if ($block =~ /^(\d+)____(\d+)$/) {
8966: my ($start,$end) = ($1,$2);
8967: if ($start <= $now && $end >= $now) {
8968: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8969: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8970: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 8971: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8972: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8973: }
8974: }
8975: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 8976: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8977: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8978: }
8979: }
8980: }
8981: }
8982: }
8983: } elsif ($block =~ /^firstaccess____(.+)$/) {
8984: my $item = $1;
8985: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8986: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1471 raeburn 8987: my (@interval,$mapname);
1.1282 raeburn 8988: my $type = 'map';
8989: if ($item eq 'course') {
8990: $type = 'course';
8991: @interval=&EXT("resource.0.interval");
8992: } else {
8993: if ($item =~ /___\d+___/) {
8994: $type = 'resource';
8995: @interval=&EXT("resource.0.interval",$item);
1.1162 raeburn 8996: } else {
1.1471 raeburn 8997: $mapname = &deversion($item);
8998: if (ref($navmap)) {
8999: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
9000: @interval = ($timelimit,'map');
1.1162 raeburn 9001: }
9002: }
1.1282 raeburn 9003: }
1.1310 raeburn 9004: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 9005: my $timelimit = $1;
1.1282 raeburn 9006: my $first_access;
9007: if ($type eq 'resource') {
9008: $first_access=&get_first_access($interval[1],$item);
9009: } elsif ($type eq 'map') {
9010: $first_access=&get_first_access($interval[1],undef,$item);
9011: } else {
9012: $first_access=&get_first_access($interval[1]);
9013: }
9014: if ($first_access) {
1.1292 raeburn 9015: my $timesup = $first_access+$timelimit;
1.1282 raeburn 9016: if ($timesup > $now) {
9017: my $activeblock;
1.1471 raeburn 9018: if ($type eq 'resource') {
9019: if (ref($navmap)) {
9020: my $res = $navmap->getBySymb($item);
9021: if ($res->answerable()) {
9022: $activeblock = 1;
9023: }
9024: }
9025: } elsif ($type eq 'map') {
9026: my $mapsymb = &symbread($mapname,1);
9027: if (($mapsymb) && (ref($navmap))) {
9028: my $mapres = $navmap->getBySymb($mapsymb);
9029: if (ref($mapres)) {
9030: my $first = $mapres->map_start();
9031: my $finish = $mapres->map_finish();
9032: my $it = $navmap->getIterator($first,$finish,undef,0,0);
9033: if (ref($it)) {
9034: my $res;
9035: while ($res = $it->next(undef,1)) {
9036: next unless (ref($res));
9037: my $symb = $res->symb();
9038: next if (($symb eq $mapsymb) || ($symb eq ''));
9039: @interval=&EXT("resource.0.interval",$symb);
9040: if ($interval[1] eq 'map') {
9041: if ($res->answerable()) {
9042: $activeblock = 1;
9043: last;
9044: }
9045: }
9046: }
9047: }
9048: }
1.1282 raeburn 9049: }
9050: }
9051: if ($activeblock) {
9052: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
9053: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9054: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
9055: }
9056: }
9057: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
9058: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9059: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 9060: }
1.1162 raeburn 9061: }
9062: }
9063: }
9064: }
9065: }
9066: }
9067: }
9068: }
9069: }
1.1282 raeburn 9070: return %blockers;
1.1162 raeburn 9071: }
9072:
1.1282 raeburn 9073: sub has_comm_blocking {
1.1427 raeburn 9074: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282 raeburn 9075: my @blockers;
9076: return unless ($env{'request.course.id'});
9077: return unless ($priv eq 'bre');
9078: return if ($env{'request.state'} eq 'construct');
1.1470 raeburn 9079: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9080: if ($env{'request.course.sec'}) {
9081: $courseurl .= '/'.$env{'request.course.sec'};
9082: }
9083: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1427 raeburn 9084: my %blockinfo;
9085: if (ref($blocks) eq 'HASH') {
9086: %blockinfo = &get_commblock_resources($blocks);
9087: } else {
9088: &load_all_blockers($env{'user.name'},$env{'user.domain'});
9089: %blockinfo = %cachedblockers;
9090: }
9091: return unless (keys(%blockinfo) > 0);
1.1282 raeburn 9092: my (%possibles,@symbs);
9093: if (!$symb) {
1.1427 raeburn 9094: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 9095: }
1.1282 raeburn 9096: if ($symb) {
9097: @symbs = ($symb);
9098: } elsif (keys(%possibles)) {
9099: @symbs = keys(%possibles);
9100: }
9101: my $noblock;
9102: foreach my $symb (@symbs) {
9103: last if ($noblock);
9104: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427 raeburn 9105: foreach my $block (keys(%blockinfo)) {
1.1282 raeburn 9106: if ($block =~ /^firstaccess____(.+)$/) {
9107: my $item = $1;
1.1424 raeburn 9108: unless ($blocked) {
9109: if (($item eq $map) || ($item eq $symb)) {
9110: $noblock = 1;
9111: last;
9112: }
1.1282 raeburn 9113: }
9114: }
1.1427 raeburn 9115: if (ref($blockinfo{$block}) eq 'HASH') {
9116: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
9117: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282 raeburn 9118: unless (grep(/^\Q$block\E$/,@blockers)) {
9119: push(@blockers,$block);
9120: }
9121: }
9122: }
1.1427 raeburn 9123: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
9124: if ($blockinfo{$block}{'maps'}{$map}) {
1.1424 raeburn 9125: unless (grep(/^\Q$block\E$/,@blockers)) {
9126: push(@blockers,$block);
9127: }
1.1282 raeburn 9128: }
9129: }
1.1162 raeburn 9130: }
9131: }
9132: }
1.1424 raeburn 9133: unless ($noblock) {
9134: return @blockers;
9135: }
9136: return;
1.1282 raeburn 9137: }
1.1162 raeburn 9138: }
9139:
1.1402 raeburn 9140: sub deeplink_check {
9141: my ($priv,$symb,$uri) = @_;
9142: return unless ($env{'request.course.id'});
9143: return unless ($priv eq 'bre');
9144: return if ($env{'request.state'} eq 'construct');
9145: return if ($env{'request.role.adv'});
9146: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9147: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9148: my (%possibles,@symbs);
9149: if (!$symb) {
9150: $symb = &symbread($uri,1,1,1,\%possibles);
9151: }
9152: if ($symb) {
9153: @symbs = ($symb);
9154: } elsif (keys(%possibles)) {
9155: @symbs = keys(%possibles);
9156: }
9157:
1.1461 raeburn 9158: my ($deeplink_symb,$allow);
9159: if ($env{'request.deeplink.login'}) {
9160: $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1.1402 raeburn 9161: }
9162: foreach my $symb (@symbs) {
9163: last if ($allow);
9164: my $deeplink = &EXT("resource.0.deeplink",$symb);
9165: if ($deeplink eq '') {
9166: $allow = 1;
9167: } else {
1.1463 raeburn 9168: my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
9169: if ($state ne 'only') {
1.1402 raeburn 9170: $allow = 1;
1.1463 raeburn 9171: } else {
9172: my $check_deeplink_entry;
9173: if ($protect ne 'none') {
9174: my ($acctype,$item) = split(/:/,$protect);
9175: if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
9176: if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
9177: $check_deeplink_entry = 1
9178: }
9179: } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
9180: if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
9181: $check_deeplink_entry = 1;
9182: }
9183: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
9184: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
9185: $check_deeplink_entry = 1;
9186: }
9187: }
9188: }
9189: if (($protect eq 'none') || ($check_deeplink_entry)) {
1.1402 raeburn 9190: if ($scope eq 'res') {
1.1461 raeburn 9191: if ($symb eq $deeplink_symb) {
1.1402 raeburn 9192: $allow = 1;
9193: }
1.1459 raeburn 9194: } elsif (($scope eq 'map') || ($scope eq 'rec')) {
1.1463 raeburn 9195: my ($map_from_symb,$map_from_login);
1.1461 raeburn 9196: $map_from_symb = &deversion((&decode_symb($symb))[0]);
9197: if ($deeplink_symb =~ /\.(page|sequence)$/) {
9198: $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
9199: } else {
9200: $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
9201: }
1.1459 raeburn 9202: if (($map_from_symb) && ($map_from_login)) {
9203: if ($map_from_symb eq $map_from_login) {
9204: $allow = 1;
9205: } elsif ($scope eq 'rec') {
9206: my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
9207: if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
9208: $allow = 1;
9209: }
9210: }
9211: }
1.1402 raeburn 9212: }
9213: }
9214: }
9215: }
9216: }
9217: return if ($allow);
9218: return 1;
9219: }
9220:
1.1282 raeburn 9221: # -------------------------------- Deversion and split uri into path an filename
9222:
1.1133 foxr 9223: #
1.1282 raeburn 9224: # Removes the version from a URI and
1.1133 foxr 9225: # splits it in to its filename and path to the filename.
9226: # Seems like File::Basename could have done this more clearly.
9227: # Parameters:
9228: # $uri - input URI
9229: # Returns:
9230: # Two element list consisting of
9231: # $pathname - the URI up to and excluding the trailing /
9232: # $filename - The part of the URI following the last /
9233: # NOTE:
9234: # Another realization of this is simply:
9235: # use File::Basename;
9236: # ...
9237: # $uri = shift;
9238: # $filename = basename($uri);
9239: # $path = dirname($uri);
9240: # return ($filename, $path);
9241: #
9242: # The implementation below is probably faster however.
9243: #
1.710 albertel 9244: sub split_uri_for_cond {
9245: my $uri=&deversion(&declutter(shift));
9246: my @uriparts=split(/\//,$uri);
9247: my $filename=pop(@uriparts);
9248: my $pathname=join('/',@uriparts);
9249: return ($pathname,$filename);
9250: }
1.232 www 9251: # --------------------------------------------------- Is a resource on the map?
9252:
9253: sub is_on_map {
1.710 albertel 9254: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 9255: #Trying to find the conditional for the file
1.620 albertel 9256: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 9257: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 9258: if ($match) {
1.289 bowersj2 9259: return (1,$1);
9260: } else {
1.434 www 9261: return (0,0);
1.289 bowersj2 9262: }
1.12 www 9263: }
9264:
1.427 www 9265: # --------------------------------------------------------- Get symb from alias
9266:
9267: sub get_symb_from_alias {
9268: my $symb=shift;
9269: my ($map,$resid,$url)=&decode_symb($symb);
9270: # Already is a symb
9271: if ($url) { return $symb; }
9272: # Must be an alias
9273: my $aliassymb='';
9274: my %bighash;
1.620 albertel 9275: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 9276: &GDBM_READER(),0640)) {
9277: my $rid=$bighash{'mapalias_'.$symb};
9278: if ($rid) {
9279: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 9280: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9281: $resid,$bighash{'src_'.$rid});
1.427 www 9282: }
9283: untie %bighash;
9284: }
9285: return $aliassymb;
9286: }
9287:
1.12 www 9288: # ----------------------------------------------------------------- Define Role
9289:
9290: sub definerole {
9291: if (allowed('mcr','/')) {
1.1326 raeburn 9292: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 9293: foreach my $role (split(':',$sysrole)) {
9294: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9295: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9296: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9297: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9298: return "refused:s:$crole&$cqual";
9299: }
9300: }
1.191 harris41 9301: }
1.800 albertel 9302: foreach my $role (split(':',$domrole)) {
9303: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9304: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9305: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9306: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 9307: return "refused:d:$crole&$cqual";
9308: }
9309: }
1.191 harris41 9310: }
1.800 albertel 9311: foreach my $role (split(':',$courole)) {
9312: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9313: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9314: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9315: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9316: return "refused:c:$crole&$cqual";
9317: }
9318: }
1.191 harris41 9319: }
1.1326 raeburn 9320: my $uhome;
9321: if (($uname ne '') && ($udom ne '')) {
9322: $uhome = &homeserver($uname,$udom);
9323: return $uhome if ($uhome eq 'no_host');
9324: } else {
9325: $uname = $env{'user.name'};
9326: $udom = $env{'user.domain'};
9327: $uhome = $env{'user.home'};
9328: }
1.620 albertel 9329: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 9330: "$udom:$uname:rolesdef_$rolename=".
1.21 www 9331: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 9332: return reply($command,$uhome);
1.12 www 9333: } else {
9334: return 'refused';
9335: }
1.105 harris41 9336: }
9337:
9338: # ---------------- Make a metadata query against the network of library servers
9339:
9340: sub metadata_query {
1.1237 raeburn 9341: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 9342: my %rhash;
1.845 albertel 9343: my %libserv = &all_library();
1.244 matthew 9344: my @server_list = (defined($server_array) ? @$server_array
9345: : keys(%libserv) );
9346: for my $server (@server_list) {
1.1237 raeburn 9347: my $domains = '';
9348: if (ref($domains_hash) eq 'HASH') {
9349: $domains = $domains_hash->{$server};
9350: }
1.118 harris41 9351: unless ($custom or $customshow) {
1.1237 raeburn 9352: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 9353: $rhash{$server}=$reply;
9354: }
9355: else {
9356: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 9357: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 9358: $server);
9359: $rhash{$server}=$reply;
9360: }
1.112 harris41 9361: }
1.118 harris41 9362: return \%rhash;
1.240 www 9363: }
9364:
9365: # ----------------------------------------- Send log queries and wait for reply
9366:
9367: sub log_query {
9368: my ($uname,$udom,$query,%filters)=@_;
9369: my $uhome=&homeserver($uname,$udom);
9370: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 9371: my $uhost=&hostname($uhome);
1.800 albertel 9372: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 9373: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9374: $uhome);
1.479 albertel 9375: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 9376: return get_query_reply($queryid);
9377: }
9378:
1.818 raeburn 9379: # -------------------------- Update MySQL table for portfolio file
9380:
9381: sub update_portfolio_table {
1.821 raeburn 9382: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 9383: if ($group ne '') {
9384: $file_name =~s /^\Q$group\E//;
9385: }
1.818 raeburn 9386: my $homeserver = &homeserver($uname,$udom);
9387: my $queryid=
1.821 raeburn 9388: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9389: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 9390: my $reply = &get_query_reply($queryid);
9391: return $reply;
9392: }
9393:
1.899 raeburn 9394: # -------------------------- Update MySQL allusers table
9395:
9396: sub update_allusers_table {
9397: my ($uname,$udom,$names) = @_;
9398: my $homeserver = &homeserver($uname,$udom);
9399: my $queryid=
9400: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9401: 'lastname='.&escape($names->{'lastname'}).'%%'.
9402: 'firstname='.&escape($names->{'firstname'}).'%%'.
9403: 'middlename='.&escape($names->{'middlename'}).'%%'.
9404: 'generation='.&escape($names->{'generation'}).'%%'.
9405: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9406: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 9407: return;
1.899 raeburn 9408: }
9409:
1.508 raeburn 9410: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 9411:
9412: sub fetch_enrollment_query {
1.511 raeburn 9413: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 9414: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 9415: my $maxtries = 1;
1.508 raeburn 9416: if ($context eq 'automated') {
9417: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 9418: $sleep = 2;
9419: $loopmax = 100;
1.547 raeburn 9420: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 9421: } else {
9422: $homeserver = &homeserver($cnum,$dom);
9423: }
1.838 albertel 9424: my $host=&hostname($homeserver);
1.506 raeburn 9425: my $cmd = '';
1.1000 raeburn 9426: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9427: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9428: }
9429: $cmd =~ s/%%$//;
9430: $cmd = &escape($cmd);
9431: my $query = 'fetchenrollment';
1.620 albertel 9432: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9433: unless ($queryid=~/^\Q$host\E\_/) {
9434: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9435: return 'error: '.$queryid;
9436: }
1.1317 raeburn 9437: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9438: my $tries = 1;
9439: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 9440: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9441: $tries ++;
9442: }
1.526 raeburn 9443: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9444: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9445: } else {
1.901 albertel 9446: my @responses = split(/:/,$reply);
1.1322 raeburn 9447: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9448: foreach my $line (@responses) {
9449: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9450: $$replyref{$key} = $value;
9451: }
9452: } else {
1.1117 foxr 9453: my $pathname = LONCAPA::tempdir();
1.800 albertel 9454: foreach my $line (@responses) {
9455: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9456: $$replyref{$key} = $value;
9457: if ($value > 0) {
1.800 albertel 9458: foreach my $item (@{$$affiliatesref{$key}}) {
9459: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9460: my $destname = $pathname.'/'.$filename;
9461: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9462: if ($xml_classlist =~ /^error/) {
9463: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9464: } else {
1.1359 raeburn 9465: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9466: print FILE &unescape($xml_classlist);
9467: close(FILE);
1.526 raeburn 9468: } else {
9469: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9470: }
9471: }
9472: }
9473: }
9474: }
9475: }
9476: return 'ok';
9477: }
9478: return 'error';
9479: }
9480:
1.242 www 9481: sub get_query_reply {
1.1471 raeburn 9482: my ($queryid,$sleep,$loopmax) = @_;
1.1317 raeburn 9483: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9484: $sleep = 0.2;
9485: }
9486: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9487: $loopmax = 100;
9488: }
1.1117 foxr 9489: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9490: my $reply='';
1.1317 raeburn 9491: for (1..$loopmax) {
9492: sleep($sleep);
1.240 www 9493: if (-e $replyfile.'.end') {
1.1359 raeburn 9494: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9495: $reply = join('',<$fh>);
9496: close($fh);
1.240 www 9497: } else { return 'error: reply_file_error'; }
1.242 www 9498: return &unescape($reply);
9499: }
1.240 www 9500: }
1.242 www 9501: return 'timeout:'.$queryid;
1.240 www 9502: }
9503:
9504: sub courselog_query {
1.241 www 9505: #
9506: # possible filters:
9507: # url: url or symb
9508: # username
9509: # domain
9510: # action: view, submit, grade
9511: # start: timestamp
9512: # end: timestamp
9513: #
1.240 www 9514: my (%filters)=@_;
1.620 albertel 9515: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9516: if ($filters{'url'}) {
9517: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9518: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9519: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9520: }
1.620 albertel 9521: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9522: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9523: return &log_query($cname,$cdom,'courselog',%filters);
9524: }
9525:
9526: sub userlog_query {
1.858 raeburn 9527: #
9528: # possible filters:
9529: # action: log check role
9530: # start: timestamp
9531: # end: timestamp
9532: #
1.240 www 9533: my ($uname,$udom,%filters)=@_;
9534: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9535: }
9536:
1.506 raeburn 9537: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9538:
9539: sub auto_run {
1.508 raeburn 9540: my ($cnum,$cdom) = @_;
1.876 raeburn 9541: my $response = 0;
9542: my $settings;
9543: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9544: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9545: $settings = $domconfig{'autoenroll'};
9546: if ($settings->{'run'} eq '1') {
9547: $response = 1;
9548: }
9549: } else {
1.934 raeburn 9550: my $homeserver;
9551: if (&is_course($cdom,$cnum)) {
9552: $homeserver = &homeserver($cnum,$cdom);
9553: } else {
9554: $homeserver = &domain($cdom,'primary');
9555: }
9556: if ($homeserver ne 'no_host') {
9557: $response = &reply('autorun:'.$cdom,$homeserver);
9558: }
1.876 raeburn 9559: }
1.506 raeburn 9560: return $response;
9561: }
1.776 albertel 9562:
1.506 raeburn 9563: sub auto_get_sections {
1.508 raeburn 9564: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9565: my $homeserver;
9566: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9567: $homeserver = &homeserver($cnum,$cdom);
9568: }
9569: if (!defined($homeserver)) {
9570: if ($cdom =~ /^$match_domain$/) {
9571: $homeserver = &domain($cdom,'primary');
9572: }
9573: }
9574: my @secs;
9575: if (defined($homeserver)) {
9576: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9577: unless ($response eq 'refused') {
9578: @secs = split(/:/,$response);
9579: }
1.506 raeburn 9580: }
9581: return @secs;
9582: }
1.776 albertel 9583:
1.506 raeburn 9584: sub auto_new_course {
1.1099 raeburn 9585: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9586: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9587: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9588: return $response;
9589: }
1.776 albertel 9590:
1.506 raeburn 9591: sub auto_validate_courseID {
1.508 raeburn 9592: my ($cnum,$cdom,$inst_course_id) = @_;
9593: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9594: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9595: return $response;
9596: }
1.776 albertel 9597:
1.1007 raeburn 9598: sub auto_validate_instcode {
1.1020 raeburn 9599: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9600: my ($homeserver,$response);
9601: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9602: $homeserver = &homeserver($cnum,$cdom);
9603: }
9604: if (!defined($homeserver)) {
9605: if ($cdom =~ /^$match_domain$/) {
9606: $homeserver = &domain($cdom,'primary');
9607: }
9608: }
1.1065 raeburn 9609: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9610: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 9611: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9612: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9613: }
9614:
1.1444 raeburn 9615: sub auto_validate_inst_crosslist {
9616: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9617: my ($homeserver,$response);
9618: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9619: $homeserver = &homeserver($cnum,$cdom);
9620: }
9621: if (!defined($homeserver)) {
9622: if ($cdom =~ /^$match_domain$/) {
9623: $homeserver = &domain($cdom,'primary');
9624: }
9625: }
9626: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9627: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9628: &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445 raeburn 9629: &escape($coowner),$homeserver);
1.1444 raeburn 9630: }
9631: return $response;
9632: }
9633:
1.506 raeburn 9634: sub auto_create_password {
1.873 raeburn 9635: my ($cnum,$cdom,$authparam,$udom) = @_;
9636: my ($homeserver,$response);
1.506 raeburn 9637: my $create_passwd = 0;
9638: my $authchk = '';
1.873 raeburn 9639: if ($udom =~ /^$match_domain$/) {
9640: $homeserver = &domain($udom,'primary');
9641: }
9642: if ($homeserver eq '') {
9643: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9644: $homeserver = &homeserver($cnum,$cdom);
9645: }
9646: }
9647: if ($homeserver eq '') {
9648: $authchk = 'nodomain';
1.506 raeburn 9649: } else {
1.873 raeburn 9650: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9651: if ($response eq 'refused') {
9652: $authchk = 'refused';
9653: } else {
1.901 albertel 9654: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9655: }
1.506 raeburn 9656: }
9657: return ($authparam,$create_passwd,$authchk);
9658: }
9659:
1.706 raeburn 9660: sub auto_photo_permission {
9661: my ($cnum,$cdom,$students) = @_;
9662: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9663: my ($outcome,$perm_reqd,$conditions) =
9664: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9665: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9666: return (undef,undef);
9667: }
1.706 raeburn 9668: return ($outcome,$perm_reqd,$conditions);
9669: }
9670:
9671: sub auto_checkphotos {
9672: my ($uname,$udom,$pid) = @_;
9673: my $homeserver = &homeserver($uname,$udom);
9674: my ($result,$resulttype);
9675: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9676: &escape($uname).':'.&escape($pid),
9677: $homeserver));
1.709 albertel 9678: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9679: return (undef,undef);
9680: }
1.706 raeburn 9681: if ($outcome) {
9682: ($result,$resulttype) = split(/:/,$outcome);
9683: }
9684: return ($result,$resulttype);
9685: }
9686:
9687: sub auto_photochoice {
9688: my ($cnum,$cdom) = @_;
9689: my $homeserver = &homeserver($cnum,$cdom);
9690: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9691: &escape($cdom),
9692: $homeserver)));
1.709 albertel 9693: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9694: return (undef,undef);
9695: }
1.706 raeburn 9696: return ($update,$comment);
9697: }
9698:
9699: sub auto_photoupdate {
9700: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9701: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9702: my $host=&hostname($homeserver);
1.706 raeburn 9703: my $cmd = '';
9704: my $maxtries = 1;
1.800 albertel 9705: foreach my $affiliate (keys(%{$affiliatesref})) {
9706: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9707: }
9708: $cmd =~ s/%%$//;
9709: $cmd = &escape($cmd);
9710: my $query = 'institutionalphotos';
9711: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9712: unless ($queryid=~/^\Q$host\E\_/) {
9713: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9714: return 'error: '.$queryid;
9715: }
9716: my $reply = &get_query_reply($queryid);
9717: my $tries = 1;
9718: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9719: $reply = &get_query_reply($queryid);
9720: $tries ++;
9721: }
9722: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9723: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9724: } else {
9725: my @responses = split(/:/,$reply);
9726: my $outcome = shift(@responses);
9727: foreach my $item (@responses) {
9728: my ($key,$value) = split(/=/,$item);
9729: $$photo{$key} = $value;
9730: }
9731: return $outcome;
9732: }
9733: return 'error';
9734: }
9735:
1.521 raeburn 9736: sub auto_instcode_format {
1.793 albertel 9737: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9738: $cat_order) = @_;
1.521 raeburn 9739: my $courses = '';
1.772 raeburn 9740: my @homeservers;
1.521 raeburn 9741: if ($caller eq 'global') {
1.841 albertel 9742: my %servers = &get_servers($codedom,'library');
9743: foreach my $tryserver (keys(%servers)) {
9744: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9745: push(@homeservers,$tryserver);
9746: }
1.584 raeburn 9747: }
1.1022 raeburn 9748: } elsif ($caller eq 'requests') {
9749: if ($codedom =~ /^$match_domain$/) {
9750: my $chome = &domain($codedom,'primary');
9751: unless ($chome eq 'no_host') {
9752: push(@homeservers,$chome);
9753: }
9754: }
1.521 raeburn 9755: } else {
1.772 raeburn 9756: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9757: }
1.793 albertel 9758: foreach my $code (keys(%{$instcodes})) {
9759: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9760: }
9761: chop($courses);
1.772 raeburn 9762: my $ok_response = 0;
9763: my $response;
9764: while (@homeservers > 0 && $ok_response == 0) {
9765: my $server = shift(@homeservers);
9766: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9767: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9768: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9769: split(/:/,$response);
1.772 raeburn 9770: %{$codes} = (%{$codes},&str2hash($codes_str));
9771: push(@{$codetitles},&str2array($codetitles_str));
9772: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9773: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9774: $ok_response = 1;
9775: }
9776: }
9777: if ($ok_response) {
1.521 raeburn 9778: return 'ok';
1.772 raeburn 9779: } else {
9780: return $response;
1.521 raeburn 9781: }
9782: }
9783:
1.792 raeburn 9784: sub auto_instcode_defaults {
9785: my ($domain,$returnhash,$code_order) = @_;
9786: my @homeservers;
1.841 albertel 9787:
9788: my %servers = &get_servers($domain,'library');
9789: foreach my $tryserver (keys(%servers)) {
9790: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9791: push(@homeservers,$tryserver);
9792: }
1.792 raeburn 9793: }
1.841 albertel 9794:
1.792 raeburn 9795: my $response;
1.841 albertel 9796: foreach my $server (@homeservers) {
1.792 raeburn 9797: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9798: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9799:
9800: foreach my $pair (split(/\&/,$response)) {
9801: my ($name,$value)=split(/\=/,$pair);
9802: if ($name eq 'code_order') {
9803: @{$code_order} = split(/\&/,&unescape($value));
9804: } else {
9805: $returnhash->{&unescape($name)}=&unescape($value);
9806: }
9807: }
9808: return 'ok';
1.792 raeburn 9809: }
1.841 albertel 9810:
9811: return $response;
1.1003 raeburn 9812: }
9813:
9814: sub auto_possible_instcodes {
1.1007 raeburn 9815: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9816: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9817: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9818: return;
9819: }
1.1003 raeburn 9820: my (@homeservers,$uhome);
9821: if (defined(&domain($domain,'primary'))) {
9822: $uhome=&domain($domain,'primary');
9823: push(@homeservers,&domain($domain,'primary'));
9824: } else {
9825: my %servers = &get_servers($domain,'library');
9826: foreach my $tryserver (keys(%servers)) {
9827: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9828: push(@homeservers,$tryserver);
9829: }
9830: }
9831: }
9832: my $response;
9833: foreach my $server (@homeservers) {
9834: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9835: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9836: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9837: split(':',$response);
9838: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9839: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9840: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9841: my ($name,$value)=split('=',$item);
9842: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9843: }
9844: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9845: my ($name,$value)=split('=',$item);
9846: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9847: }
9848: return 'ok';
9849: }
9850: return $response;
9851: }
1.792 raeburn 9852:
1.1010 raeburn 9853: sub auto_courserequest_checks {
9854: my ($dom) = @_;
1.1020 raeburn 9855: my ($homeserver,%validations);
9856: if ($dom =~ /^$match_domain$/) {
9857: $homeserver = &domain($dom,'primary');
9858: }
9859: unless ($homeserver eq 'no_host') {
9860: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9861: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9862: my @items = split(/&/,$response);
9863: foreach my $item (@items) {
9864: my ($key,$value) = split('=',$item);
9865: $validations{&unescape($key)} = &thaw_unescape($value);
9866: }
9867: }
9868: }
1.1010 raeburn 9869: return %validations;
9870: }
9871:
1.1020 raeburn 9872: sub auto_courserequest_validation {
1.1255 raeburn 9873: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9874: my ($homeserver,$response);
9875: if ($dom =~ /^$match_domain$/) {
9876: $homeserver = &domain($dom,'primary');
9877: }
1.1255 raeburn 9878: unless ($homeserver eq 'no_host') {
9879: my $customdata;
9880: if (ref($custominfo) eq 'HASH') {
9881: $customdata = &freeze_escape($custominfo);
9882: }
1.1020 raeburn 9883: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9884: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 9885: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9886: $customdata,$homeserver));
1.1020 raeburn 9887: }
9888: return $response;
9889: }
9890:
1.777 albertel 9891: sub auto_validate_class_sec {
1.918 raeburn 9892: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9893: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9894: my $ownerlist;
9895: if (ref($owners) eq 'ARRAY') {
9896: $ownerlist = join(',',@{$owners});
9897: } else {
9898: $ownerlist = $owners;
9899: }
1.773 raeburn 9900: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9901: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9902: return $response;
9903: }
9904:
1.1460 raeburn 9905: sub auto_instsec_reformat {
9906: my ($cdom,$action,$instsecref) = @_;
9907: return unless(($action eq 'clutter') || ($action eq 'declutter'));
9908: my @homeservers;
9909: if (defined(&domain($cdom,'primary'))) {
9910: push(@homeservers,&domain($cdom,'primary'));
9911: } else {
9912: my %servers = &get_servers($cdom,'library');
9913: foreach my $tryserver (keys(%servers)) {
9914: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9915: push(@homeservers,$tryserver);
9916: }
9917: }
9918: }
9919: my $response;
9920: my %reformatted = %{$instsecref};
9921: foreach my $server (@homeservers) {
9922: if (ref($instsecref) eq 'HASH') {
9923: my $info = &freeze_escape($instsecref);
9924: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
9925: $action.':'.$info,$server);
9926: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
9927: my @items = split(/&/,$response);
9928: foreach my $item (@items) {
9929: my ($key,$value) = split(/=/,$item);
9930: $reformatted{&unescape($key)} = &thaw_unescape($value);
9931: }
9932: }
9933: }
9934: return %reformatted;
9935: }
9936:
1.1367 raeburn 9937: sub auto_validate_instclasses {
9938: my ($cdom,$cnum,$owners,$classesref) = @_;
9939: my ($homeserver,%validations);
9940: $homeserver = &homeserver($cnum,$cdom);
9941: unless ($homeserver eq 'no_host') {
9942: my $ownerlist;
9943: if (ref($owners) eq 'ARRAY') {
9944: $ownerlist = join(',',@{$owners});
9945: } else {
9946: $ownerlist = $owners;
9947: }
9948: if (ref($classesref) eq 'HASH') {
9949: my $classes = &freeze_escape($classesref);
9950: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9951: ':'.$cdom.':'.$classes,$homeserver);
9952: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9953: my @items = split(/&/,$response);
9954: foreach my $item (@items) {
9955: my ($key,$value) = split('=',$item);
9956: $validations{&unescape($key)} = &thaw_unescape($value);
9957: }
9958: }
9959: }
9960: }
9961: return %validations;
9962: }
9963:
1.1248 raeburn 9964: sub auto_crsreq_update {
9965: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 9966: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 9967: my ($homeserver,%crsreqresponse);
9968: if ($cdom =~ /^$match_domain$/) {
9969: $homeserver = &domain($cdom,'primary');
9970: }
9971: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9972: my $info;
9973: if (ref($inbound) eq 'HASH') {
9974: $info = &freeze_escape($inbound);
9975: }
9976: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9977: ':'.&escape($action).':'.&escape($ownername).':'.
9978: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 9979: &escape($title).':'.&escape($code).':'.
9980: &escape($accessstart).':'.&escape($accessend).':'.$info,
9981: $homeserver);
1.1248 raeburn 9982: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9983: my @items = split(/&/,$response);
9984: foreach my $item (@items) {
9985: my ($key,$value) = split('=',$item);
9986: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9987: }
9988: }
9989: }
9990: return \%crsreqresponse;
9991: }
9992:
1.1305 raeburn 9993: sub auto_export_grades {
1.1309 raeburn 9994: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9995: my ($homeserver,%exportresponse);
9996: if ($cdom =~ /^$match_domain$/) {
9997: $homeserver = &domain($cdom,'primary');
9998: }
9999: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10000: my $info;
10001: if (ref($inforef) eq 'HASH') {
10002: $info = &freeze_escape($inforef);
10003: }
10004: if (ref($gradesref) eq 'HASH') {
10005: my $grades = &freeze_escape($gradesref);
10006: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10007: $info.':'.$grades,$homeserver);
10008: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10009: my @items = split(/&/,$response);
10010: foreach my $item (@items) {
10011: my ($key,$value) = split('=',$item);
10012: $exportresponse{&unescape($key)} = &thaw_unescape($value);
10013: }
10014: }
10015: }
10016: }
10017: return \%exportresponse;
1.1305 raeburn 10018: }
10019:
1.1287 raeburn 10020: sub check_instcode_cloning {
10021: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10022: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10023: return;
10024: }
10025: my $canclone;
10026: if (@{$code_order} > 0) {
10027: my $instcoderegexp ='^';
10028: my @clonecodes = split(/\&/,$cloner);
10029: foreach my $item (@{$code_order}) {
10030: if (grep(/^\Q$item\E=/,@clonecodes)) {
10031: foreach my $pair (@clonecodes) {
10032: my ($key,$val) = split(/\=/,$pair,2);
10033: $val = &unescape($val);
10034: if ($key eq $item) {
10035: $instcoderegexp .= '('.$val.')';
10036: last;
10037: }
10038: }
10039: } else {
10040: $instcoderegexp .= $codedefaults->{$item};
10041: }
10042: }
10043: $instcoderegexp .= '$';
10044: my (@from,@to);
10045: eval {
10046: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10047: (@to) = ($clonetocode =~ /$instcoderegexp/);
10048: };
10049: if ((@from > 0) && (@to > 0)) {
10050: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10051: if (!@diffs) {
10052: $canclone = 1;
10053: }
10054: }
10055: }
10056: return $canclone;
10057: }
10058:
10059: sub default_instcode_cloning {
10060: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10061: my (%codedefaults,@code_order,$canclone);
10062: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10063: %codedefaults = %{$codedefaultsref};
10064: @code_order = @{$codeorderref};
10065: } elsif ($clonedom) {
10066: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10067: }
10068: if (($domdefclone) && (@code_order)) {
10069: my @clonecodes = split(/\+/,$domdefclone);
10070: my $instcoderegexp ='^';
10071: foreach my $item (@code_order) {
10072: if (grep(/^\Q$item\E$/,@clonecodes)) {
10073: $instcoderegexp .= '('.$codedefaults{$item}.')';
10074: } else {
10075: $instcoderegexp .= $codedefaults{$item};
10076: }
10077: }
10078: $instcoderegexp .= '$';
10079: my (@from,@to);
10080: eval {
10081: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10082: (@to) = ($clonetocode =~ /$instcoderegexp/);
10083: };
10084: if ((@from > 0) && (@to > 0)) {
10085: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10086: if (!@diffs) {
10087: $canclone = 1;
10088: }
10089: }
10090: }
10091: return $canclone;
10092: }
10093:
1.679 raeburn 10094: # ------------------------------------------------------- Course Group routines
10095:
10096: sub get_coursegroups {
1.809 raeburn 10097: my ($cdom,$cnum,$group,$namespace) = @_;
10098: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 10099: }
10100:
1.679 raeburn 10101: sub modify_coursegroup {
10102: my ($cdom,$cnum,$groupsettings) = @_;
10103: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10104: }
10105:
1.809 raeburn 10106: sub toggle_coursegroup_status {
10107: my ($cdom,$cnum,$group,$action) = @_;
10108: my ($from_namespace,$to_namespace);
10109: if ($action eq 'delete') {
10110: $from_namespace = 'coursegroups';
10111: $to_namespace = 'deleted_groups';
10112: } else {
10113: $from_namespace = 'deleted_groups';
10114: $to_namespace = 'coursegroups';
10115: }
10116: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 10117: if (my $tmp = &error(%curr_group)) {
10118: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10119: return ('read error',$tmp);
10120: } else {
10121: my %savedsettings = %curr_group;
1.809 raeburn 10122: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 10123: my $deloutcome;
10124: if ($result eq 'ok') {
1.809 raeburn 10125: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 10126: } else {
10127: return ('write error',$result);
10128: }
10129: if ($deloutcome eq 'ok') {
10130: return 'ok';
10131: } else {
10132: return ('delete error',$deloutcome);
10133: }
10134: }
10135: }
10136:
1.679 raeburn 10137: sub modify_group_roles {
1.957 raeburn 10138: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 10139: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10140: my $role = 'gr/'.&escape($userprivs);
10141: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 10142: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 10143: if ($result eq 'ok') {
10144: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10145: }
1.679 raeburn 10146: return $result;
10147: }
10148:
10149: sub modify_coursegroup_membership {
10150: my ($cdom,$cnum,$membership) = @_;
10151: my $result = &put('groupmembership',$membership,$cdom,$cnum);
10152: return $result;
10153: }
10154:
1.682 raeburn 10155: sub get_active_groups {
10156: my ($udom,$uname,$cdom,$cnum) = @_;
10157: my $now = time;
10158: my %groups = ();
10159: foreach my $key (keys(%env)) {
1.811 albertel 10160: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 10161: my ($start,$end) = split(/\./,$env{$key});
10162: if (($end!=0) && ($end<$now)) { next; }
10163: if (($start!=0) && ($start>$now)) { next; }
10164: if ($1 eq $cdom && $2 eq $cnum) {
10165: $groups{$3} = $env{$key} ;
10166: }
10167: }
10168: }
10169: return %groups;
10170: }
10171:
1.683 raeburn 10172: sub get_group_membership {
10173: my ($cdom,$cnum,$group) = @_;
10174: return(&dump('groupmembership',$cdom,$cnum,$group));
10175: }
10176:
10177: sub get_users_groups {
10178: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 10179: my @usersgroups;
1.683 raeburn 10180: my $cachetime=1800;
10181:
10182: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 10183: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10184: if (defined($cached)) {
1.734 albertel 10185: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 10186: } else {
10187: $grouplist = '';
1.816 raeburn 10188: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 10189: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 10190: my $access_end = $env{'course.'.$courseid.
10191: '.default_enrollment_end_date'};
10192: my $now = time;
10193: foreach my $key (keys(%roleshash)) {
10194: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10195: my $group = $1;
10196: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10197: my $start = $2;
10198: my $end = $1;
10199: if ($start == -1) { next; } # deleted from group
10200: if (($start!=0) && ($start>$now)) { next; }
10201: if (($end!=0) && ($end<$now)) {
10202: if ($access_end && $access_end < $now) {
10203: if ($access_end - $end < 86400) {
10204: push(@usersgroups,$group);
1.733 raeburn 10205: }
10206: }
1.817 raeburn 10207: next;
1.733 raeburn 10208: }
1.817 raeburn 10209: push(@usersgroups,$group);
1.683 raeburn 10210: }
10211: }
10212: }
1.817 raeburn 10213: @usersgroups = &sort_course_groups($courseid,@usersgroups);
10214: $grouplist = join(':',@usersgroups);
10215: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 10216: }
1.733 raeburn 10217: return @usersgroups;
1.683 raeburn 10218: }
10219:
10220: sub devalidate_getgroups_cache {
10221: my ($udom,$uname,$cdom,$cnum)=@_;
10222: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 10223:
1.683 raeburn 10224: my $hashid="$udom:$uname:$courseid";
10225: &devalidate_cache_new('getgroups',$hashid);
10226: }
10227:
1.12 www 10228: # ------------------------------------------------------------------ Plain Text
10229:
10230: sub plaintext {
1.988 raeburn 10231: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 10232: if ($short =~ m{^cr/}) {
1.758 albertel 10233: return (split('/',$short))[-1];
10234: }
1.742 raeburn 10235: if (!defined($cid)) {
10236: $cid = $env{'request.course.id'};
10237: }
10238: my %rolenames = (
1.1008 raeburn 10239: Course => 'std',
10240: Community => 'alt1',
1.1305 raeburn 10241: Placement => 'std',
1.742 raeburn 10242: );
1.1037 raeburn 10243: if ($cid ne '') {
10244: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10245: unless ($forcedefault) {
10246: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
10247: &Apache::lonlocal::mt_escape(\$roletext);
10248: return &Apache::lonlocal::mt($roletext);
10249: }
10250: }
10251: }
10252: if ((defined($type)) && (defined($rolenames{$type})) &&
10253: (defined($rolenames{$type})) &&
10254: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 10255: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 10256: } elsif ($cid ne '') {
10257: my $crstype = $env{'course.'.$cid.'.type'};
10258: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10259: (defined($prp{$short}{$rolenames{$crstype}}))) {
10260: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10261: }
1.742 raeburn 10262: }
1.1037 raeburn 10263: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 10264: }
10265:
10266: # ----------------------------------------------------------------- Assign Role
10267:
10268: sub assignrole {
1.957 raeburn 10269: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10270: $context)=@_;
1.21 www 10271: my $mrole;
10272: if ($role =~ /^cr\//) {
1.393 www 10273: my $cwosec=$url;
1.811 albertel 10274: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 10275: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 10276: my $refused = 1;
10277: if ($context eq 'requestcourses') {
10278: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10279: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10280: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10281: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10282: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10283: if ($crsenv{'internal.courseowner'} eq
10284: $env{'user.name'}.':'.$env{'user.domain'}) {
10285: $refused = '';
10286: }
10287: }
10288: }
10289: }
10290: }
10291: if ($refused) {
10292: &logthis('Refused custom assignrole: '.
10293: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10294: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10295: return 'refused';
10296: }
1.104 www 10297: }
1.21 www 10298: $mrole='cr';
1.678 raeburn 10299: } elsif ($role =~ /^gr\//) {
10300: my $cwogrp=$url;
1.811 albertel 10301: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 10302: unless (&allowed('mdg',$cwogrp)) {
10303: &logthis('Refused group assignrole: '.
10304: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10305: $env{'user.name'}.' at '.$env{'user.domain'});
10306: return 'refused';
10307: }
10308: $mrole='gr';
1.21 www 10309: } else {
1.82 www 10310: my $cwosec=$url;
1.811 albertel 10311: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 10312: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10313: my $refused;
10314: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10315: if (!(&allowed('c'.$role,$url))) {
10316: $refused = 1;
10317: }
10318: } else {
10319: $refused = 1;
10320: }
1.947 raeburn 10321: if ($refused) {
1.1045 raeburn 10322: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377 raeburn 10323: if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045 raeburn 10324: my %crsenv;
10325: if ($role eq 'cc' || $role eq 'co') {
10326: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10327: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10328: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10329: if ($crsenv{'internal.courseowner'} eq
10330: $env{'user.name'}.':'.$env{'user.domain'}) {
10331: $refused = '';
10332: }
10333: }
10334: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10335: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10336: if ($crsenv{'internal.courseowner'} eq
10337: $env{'user.name'}.':'.$env{'user.domain'}) {
10338: $refused = '';
10339: }
10340: }
10341: }
10342: }
1.1368 raeburn 10343: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10344: if ($role eq 'st') {
10345: $refused = '';
1.1377 raeburn 10346: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368 raeburn 10347: $refused = '';
10348: }
1.1017 raeburn 10349: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 10350: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 10351: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 10352: my $wrongcc;
10353: if ($cnum =~ /^$match_community$/) {
10354: $wrongcc = 1 if ($role eq 'cc');
10355: } else {
10356: $wrongcc = 1 if ($role eq 'co');
10357: }
10358: unless ($wrongcc) {
10359: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10360: if ($crsenv{'internal.courseowner'} eq
10361: $env{'user.name'}.':'.$env{'user.domain'}) {
10362: $refused = '';
10363: }
1.1017 raeburn 10364: }
10365: }
1.1183 raeburn 10366: } elsif ($context eq 'requestauthor') {
10367: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10368: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10369: if ($env{'environment.requestauthor'} eq 'automatic') {
10370: $refused = '';
10371: } else {
10372: my %domdefaults = &get_domain_defaults($udom);
10373: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10374: my $checkbystatus;
10375: if ($env{'user.adv'}) {
10376: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10377: if ($disposition eq 'automatic') {
10378: $refused = '';
10379: } elsif ($disposition eq '') {
10380: $checkbystatus = 1;
10381: }
10382: } else {
10383: $checkbystatus = 1;
10384: }
10385: if ($checkbystatus) {
10386: if ($env{'environment.inststatus'}) {
10387: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10388: foreach my $type (@inststatuses) {
10389: if (($type ne '') &&
10390: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10391: $refused = '';
10392: }
10393: }
10394: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10395: $refused = '';
10396: }
10397: }
10398: }
10399: }
10400: }
1.1017 raeburn 10401: }
10402: if ($refused) {
1.947 raeburn 10403: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10404: ' '.$role.' '.$end.' '.$start.' by '.
10405: $env{'user.name'}.' at '.$env{'user.domain'});
10406: return 'refused';
10407: }
1.932 raeburn 10408: }
1.1131 raeburn 10409: } elsif ($role eq 'au') {
10410: if ($url ne '/'.$udom.'/') {
10411: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10412: ' to assign author role for '.$uname.':'.$udom.
10413: ' in domain: '.$url.' refused (wrong domain).');
10414: return 'refused';
10415: }
1.104 www 10416: }
1.21 www 10417: $mrole=$role;
10418: }
1.620 albertel 10419: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 10420: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 10421: if ($end) { $command.='_'.$end; }
1.21 www 10422: if ($start) {
10423: if ($end) {
1.81 www 10424: $command.='_'.$start;
1.21 www 10425: } else {
1.81 www 10426: $command.='_0_'.$start;
1.21 www 10427: }
10428: }
1.739 raeburn 10429: my $origstart = $start;
10430: my $origend = $end;
1.957 raeburn 10431: my $delflag;
1.357 www 10432: # actually delete
10433: if ($deleteflag) {
1.373 www 10434: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 10435: # modify command to delete the role
1.620 albertel 10436: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 10437: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 10438: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 10439: # set start and finish to negative values for userrolelog
10440: $start=-1;
10441: $end=-1;
1.957 raeburn 10442: $delflag = 1;
1.357 www 10443: }
10444: }
10445: # send command
1.349 www 10446: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 10447: # log new user role if status is ok
1.349 www 10448: if ($answer eq 'ok') {
1.663 raeburn 10449: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 10450: if (($role eq 'cc') || ($role eq 'in') ||
10451: ($role eq 'ep') || ($role eq 'ad') ||
10452: ($role eq 'ta') || ($role eq 'st') ||
10453: ($role=~/^cr/) || ($role eq 'gr') ||
10454: ($role eq 'co')) {
1.1200 raeburn 10455: # for course roles, perform group memberships changes triggered by role change.
10456: unless ($role =~ /^gr/) {
10457: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10458: $origstart,$selfenroll,$context);
10459: }
1.1184 raeburn 10460: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10461: $selfenroll,$context);
10462: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 10463: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10464: ($role eq 'da')) {
1.1184 raeburn 10465: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10466: $context);
10467: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10468: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10469: $context);
10470: }
1.1053 raeburn 10471: if ($role eq 'cc') {
10472: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10473: }
1.349 www 10474: }
10475: return $answer;
1.169 harris41 10476: }
10477:
1.1053 raeburn 10478: sub autoupdate_coowners {
10479: my ($url,$end,$start,$uname,$udom) = @_;
10480: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10481: if (($cdom ne '') && ($cnum ne '')) {
10482: my $now = time;
10483: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10484: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10485: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10486: my $instcode = $coursehash{'internal.coursecode'};
1.1444 raeburn 10487: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 10488: if ($instcode ne '') {
1.1056 raeburn 10489: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10490: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10491: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10492: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444 raeburn 10493: unless ($result eq 'valid') {
10494: if ($xlists ne '') {
10495: foreach my $xlist (split(',',$xlists)) {
10496: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10497: $result =
1.1446 raeburn 10498: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10499: $inst_crosslist,$uname.':'.$udom);
10500: last if ($result eq 'valid');
1.1444 raeburn 10501: }
10502: }
10503: }
1.1056 raeburn 10504: if ($result eq 'valid') {
10505: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10506: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10507: push(@newcoowners,$coowner);
10508: }
10509: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10510: push(@newcoowners,$uname.':'.$udom);
10511: }
10512: @newcoowners = sort(@newcoowners);
10513: } else {
10514: push(@newcoowners,$uname.':'.$udom);
10515: }
1.1444 raeburn 10516: } elsif ($coursehash{'internal.co-owners'}) {
10517: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10518: unless ($coowner eq $uname.':'.$udom) {
10519: push(@newcoowners,$coowner);
1.1053 raeburn 10520: }
1.1444 raeburn 10521: }
10522: unless (@newcoowners > 0) {
10523: $delcoowners = 1;
10524: $coowners = '';
1.1053 raeburn 10525: }
10526: }
10527: if (@newcoowners || $delcoowners) {
10528: &store_coowners($cdom,$cnum,$coursehash{'home'},
10529: $delcoowners,@newcoowners);
10530: }
10531: }
10532: }
10533: }
10534: }
10535: }
10536: }
10537:
10538: sub store_coowners {
10539: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10540: my $cid = $cdom.'_'.$cnum;
10541: my ($coowners,$delresult,$putresult);
10542: if (@newcoowners) {
10543: $coowners = join(',',@newcoowners);
10544: my %coownershash = (
10545: 'internal.co-owners' => $coowners,
10546: );
10547: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10548: if ($putresult eq 'ok') {
10549: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10550: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10551: }
10552: }
10553: }
10554: if ($delcoowners) {
10555: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10556: if ($delresult eq 'ok') {
10557: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10558: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10559: }
10560: }
10561: }
10562: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10563: my %crsinfo =
10564: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10565: if (ref($crsinfo{$cid}) eq 'HASH') {
10566: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10567: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10568: }
10569: }
10570: }
10571:
1.169 harris41 10572: # -------------------------------------------------- Modify user authentication
1.197 www 10573: # Overrides without validation
10574:
1.169 harris41 10575: sub modifyuserauth {
10576: my ($udom,$uname,$umode,$upass)=@_;
10577: my $uhome=&homeserver($uname,$udom);
1.1409 raeburn 10578: my $allowed;
10579: if (&allowed('mau',$udom)) {
10580: $allowed = 1;
10581: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10582: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10583: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10584: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10585: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10586: if (($cdom ne '') && ($cnum ne '')) {
10587: my $is_owner = &is_course_owner($cdom,$cnum);
10588: if ($is_owner) {
10589: $allowed = 1;
10590: }
10591: }
10592: }
10593: unless ($allowed) { return 'refused'; }
1.197 www 10594: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10595: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10596: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10597: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10598: &escape($upass),$uhome);
1.1434 raeburn 10599: my $ip = &get_requestor_ip();
1.620 albertel 10600: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10601: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434 raeburn 10602: '(Remote '.$ip.'): '.$reply);
1.197 www 10603: &log($udom,,$uname,$uhome,
1.620 albertel 10604: 'Authentication changed by '.$env{'user.domain'}.', '.
10605: $env{'user.name'}.', '.$umode.
1.1435 raeburn 10606: '(Remote '.$ip.'): '.$reply);
1.169 harris41 10607: unless ($reply eq 'ok') {
1.197 www 10608: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10609: return 'error: '.$reply;
10610: }
1.170 harris41 10611: return 'ok';
1.80 www 10612: }
10613:
1.81 www 10614: # --------------------------------------------------------------- Modify a user
1.80 www 10615:
1.81 www 10616: sub modifyuser {
1.206 matthew 10617: my ($udom, $uname, $uid,
10618: $umode, $upass, $first,
10619: $middle, $last, $gene,
1.1058 raeburn 10620: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10621: $udom= &LONCAPA::clean_domain($udom);
10622: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10623: my $showcandelete = 'none';
10624: if (ref($candelete) eq 'ARRAY') {
10625: if (@{$candelete} > 0) {
10626: $showcandelete = join(', ',@{$candelete});
10627: }
10628: }
1.81 www 10629: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10630: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10631: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10632: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10633: ' desiredhome not specified').
1.620 albertel 10634: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10635: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10636: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10637: my $newuser;
10638: if ($uhome eq 'no_host') {
10639: $newuser = 1;
1.1368 raeburn 10640: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10641: ($umode eq 'lti')) {
10642: return 'error: more information needed to create new user';
10643: }
1.1075 raeburn 10644: }
1.80 www 10645: # ----------------------------------------------------------------- Create User
1.406 albertel 10646: if (($uhome eq 'no_host') &&
1.1368 raeburn 10647: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80 www 10648: my $unhome='';
1.844 albertel 10649: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10650: $unhome = $desiredhome;
1.620 albertel 10651: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10652: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10653: } else { # load balancing routine for determining $unhome
1.81 www 10654: my $loadm=10000000;
1.841 albertel 10655: my %servers = &get_servers($udom,'library');
10656: foreach my $tryserver (keys(%servers)) {
10657: my $answer=reply('load',$tryserver);
10658: if (($answer=~/\d+/) && ($answer<$loadm)) {
10659: $loadm=$answer;
10660: $unhome=$tryserver;
10661: }
1.80 www 10662: }
10663: }
10664: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10665: return 'error: unable to find a home server for '.$uname.
10666: ' in domain '.$udom;
1.80 www 10667: }
10668: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10669: &escape($upass),$unhome);
10670: unless ($reply eq 'ok') {
10671: return 'error: '.$reply;
10672: }
1.230 stredwic 10673: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10674: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10675: return 'error: unable verify users home machine.';
1.80 www 10676: }
1.209 matthew 10677: } # End of creation of new user
1.80 www 10678: # ---------------------------------------------------------------------- Add ID
10679: if ($uid) {
10680: $uid=~tr/A-Z/a-z/;
10681: my %uidhash=&idrget($udom,$uname);
1.196 www 10682: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10683: && (!$forceid)) {
1.80 www 10684: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10685: return 'error: user id "'.$uid.'" does not match '.
10686: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10687: }
10688: } else {
1.1300 raeburn 10689: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 10690: }
10691: }
10692: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10693: my @tmp=&get('environment',
1.899 raeburn 10694: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10695: 'permanentemail','inststatus'],
1.134 albertel 10696: $udom,$uname);
1.1075 raeburn 10697: my (%names,%oldnames);
1.313 matthew 10698: if ($tmp[0] =~ m/^error:.*/) {
10699: %names=();
10700: } else {
10701: %names = @tmp;
1.1075 raeburn 10702: %oldnames = %names;
1.313 matthew 10703: }
1.388 www 10704: #
1.1058 raeburn 10705: # If name, email and/or uid are blank (e.g., because an uploaded file
10706: # of users did not contain them), do not overwrite existing values
10707: # unless field is in $candelete array ref.
10708: #
10709:
10710: my @fields = ('firstname','middlename','lastname','generation',
10711: 'permanentemail','id');
10712: my %newvalues;
10713: if (ref($candelete) eq 'ARRAY') {
10714: foreach my $field (@fields) {
10715: if (grep(/^\Q$field\E$/,@{$candelete})) {
10716: if ($field eq 'firstname') {
10717: $names{$field} = $first;
10718: } elsif ($field eq 'middlename') {
10719: $names{$field} = $middle;
10720: } elsif ($field eq 'lastname') {
10721: $names{$field} = $last;
10722: } elsif ($field eq 'generation') {
10723: $names{$field} = $gene;
10724: } elsif ($field eq 'permanentemail') {
10725: $names{$field} = $email;
10726: } elsif ($field eq 'id') {
10727: $names{$field} = $uid;
10728: }
10729: }
10730: }
10731: }
1.388 www 10732: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10733: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10734: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10735: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10736: if ($email) {
10737: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10738: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10739: }
1.899 raeburn 10740: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10741: if (defined($inststatus)) {
10742: $names{'inststatus'} = '';
10743: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10744: if (ref($usertypes) eq 'HASH') {
10745: my @okstatuses;
10746: foreach my $item (split(/:/,$inststatus)) {
10747: if (defined($usertypes->{$item})) {
10748: push(@okstatuses,$item);
10749: }
10750: }
10751: if (@okstatuses) {
10752: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10753: }
10754: }
10755: }
1.1075 raeburn 10756: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10757: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10758: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10759: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10760: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10761: } else {
10762: $logmsg .= ' during self creation';
10763: }
1.1075 raeburn 10764: my $changed;
10765: if ($newuser) {
10766: $changed = 1;
10767: } else {
10768: foreach my $field (@fields) {
10769: if ($names{$field} ne $oldnames{$field}) {
10770: $changed = 1;
10771: last;
10772: }
10773: }
10774: }
10775: unless ($changed) {
10776: $logmsg = 'No changes in user information needed for: '.$logmsg;
10777: &logthis($logmsg);
10778: return 'ok';
10779: }
10780: my $reply = &put('environment', \%names, $udom,$uname);
10781: if ($reply ne 'ok') {
10782: return 'error: '.$reply;
10783: }
1.1087 raeburn 10784: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10785: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10786: }
1.1075 raeburn 10787: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10788: &devalidate_cache_new('namescache',$uname.':'.$udom);
10789: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10790: &logthis($logmsg);
1.134 albertel 10791: return 'ok';
1.80 www 10792: }
10793:
1.81 www 10794: # -------------------------------------------------------------- Modify student
1.80 www 10795:
1.81 www 10796: sub modifystudent {
10797: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10798: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 10799: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10800: if (!$cid) {
1.620 albertel 10801: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10802: return 'not_in_class';
10803: }
1.80 www 10804: }
10805: # --------------------------------------------------------------- Make the user
1.81 www 10806: my $reply=&modifyuser
1.209 matthew 10807: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10808: $desiredhome,$email,$inststatus);
1.80 www 10809: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10810: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 10811: # student's environment
1.297 matthew 10812: $uid = undef if (!$forceid);
1.455 albertel 10813: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 10814: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 10815: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10816: return $reply;
10817: }
10818:
10819: sub modify_student_enrollment {
1.1216 raeburn 10820: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 10821: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10822: my ($cdom,$cnum,$chome);
10823: if (!$cid) {
1.620 albertel 10824: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10825: return 'not_in_class';
10826: }
1.620 albertel 10827: $cdom=$env{'course.'.$cid.'.domain'};
10828: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10829: } else {
10830: ($cdom,$cnum)=split(/_/,$cid);
10831: }
1.620 albertel 10832: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10833: if (!$chome) {
1.457 raeburn 10834: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10835: }
1.455 albertel 10836: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10837: # Make sure the user exists
1.81 www 10838: my $uhome=&homeserver($uname,$udom);
10839: if (($uhome eq '') || ($uhome eq 'no_host')) {
10840: return 'error: no such user';
10841: }
1.297 matthew 10842: # Get student data if we were not given enough information
10843: if (!defined($first) || $first eq '' ||
10844: !defined($last) || $last eq '' ||
10845: !defined($uid) || $uid eq '' ||
10846: !defined($middle) || $middle eq '' ||
10847: !defined($gene) || $gene eq '') {
1.294 matthew 10848: # They did not supply us with enough data to enroll the student, so
10849: # we need to pick up more information.
1.297 matthew 10850: my %tmp = &get('environment',
1.294 matthew 10851: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10852: ,$udom,$uname);
10853:
1.800 albertel 10854: #foreach my $key (keys(%tmp)) {
10855: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10856: #}
1.294 matthew 10857: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10858: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10859: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10860: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10861: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10862: }
1.556 albertel 10863: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10864: my $user = "$uname:$udom";
10865: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10866: my $reply=cput('classlist',
1.1148 raeburn 10867: {$user =>
1.1314 raeburn 10868: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10869: $cdom,$cnum);
1.1148 raeburn 10870: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10871: &devalidate_getsection_cache($udom,$uname,$cid);
10872: } else {
1.81 www 10873: return 'error: '.$reply;
10874: }
1.297 matthew 10875: # Add student role to user
1.83 www 10876: my $uurl='/'.$cid;
1.81 www 10877: $uurl=~s/\_/\//g;
10878: if ($usec) {
10879: $uurl.='/'.$usec;
10880: }
1.1148 raeburn 10881: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10882: $selfenroll,$context);
10883: if ($result ne 'ok') {
10884: if ($old_entry{$user} ne '') {
10885: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10886: } else {
10887: $reply = &del('classlist',[$user],$cdom,$cnum);
10888: }
10889: }
10890: return $result;
1.21 www 10891: }
10892:
1.556 albertel 10893: sub format_name {
10894: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10895: my $name;
10896: if ($first ne 'lastname') {
10897: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10898: } else {
10899: if ($lastname=~/\S/) {
10900: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10901: $name=~s/\s+,/,/;
10902: } else {
10903: $name.= $firstname.' '.$middlename.' '.$generation;
10904: }
10905: }
10906: $name=~s/^\s+//;
10907: $name=~s/\s+$//;
10908: $name=~s/\s+/ /g;
10909: return $name;
10910: }
10911:
1.84 www 10912: # ------------------------------------------------- Write to course preferences
10913:
10914: sub writecoursepref {
10915: my ($courseid,%prefs)=@_;
10916: $courseid=~s/^\///;
10917: $courseid=~s/\_/\//g;
10918: my ($cdomain,$cnum)=split(/\//,$courseid);
10919: my $chome=homeserver($cnum,$cdomain);
10920: if (($chome eq '') || ($chome eq 'no_host')) {
10921: return 'error: no such course';
10922: }
10923: my $cstring='';
1.800 albertel 10924: foreach my $pref (keys(%prefs)) {
10925: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10926: }
1.84 www 10927: $cstring=~s/\&$//;
10928: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10929: }
10930:
10931: # ---------------------------------------------------------- Make/modify course
10932:
10933: sub createcourse {
1.741 raeburn 10934: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423 raeburn 10935: $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84 www 10936: $url=&declutter($url);
10937: my $cid='';
1.1028 raeburn 10938: if ($context eq 'requestcourses') {
10939: my $can_create = 0;
10940: my ($ownername,$ownerdom) = split(':',$course_owner);
10941: if ($udom eq $ownerdom) {
1.1423 raeburn 10942: my $reload;
10943: if (($callercontext eq 'auto') &&
10944: ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10945: $reload = 'reload';
10946: }
10947: if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028 raeburn 10948: $context)) {
10949: $can_create = 1;
10950: }
10951: } else {
10952: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10953: $category);
10954: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10955: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10956: if (@curr > 0) {
10957: my @options = qw(approval validate autolimit);
10958: my $optregex = join('|',@options);
10959: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10960: $can_create = 1;
10961: }
10962: }
10963: }
10964: }
10965: if ($can_create) {
10966: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10967: unless (&allowed('ccc',$udom)) {
10968: return 'refused';
10969: }
1.1017 raeburn 10970: }
10971: } else {
10972: return 'refused';
10973: }
1.1028 raeburn 10974: } elsif (!&allowed('ccc',$udom)) {
10975: return 'refused';
1.84 www 10976: }
1.1011 raeburn 10977: # --------------------------------------------------------------- Get Unique ID
10978: my $uname;
10979: if ($cnum =~ /^$match_courseid$/) {
10980: my $chome=&homeserver($cnum,$udom,'true');
10981: if (($chome eq '') || ($chome eq 'no_host')) {
10982: $uname = $cnum;
10983: } else {
1.1038 raeburn 10984: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10985: }
10986: } else {
1.1038 raeburn 10987: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10988: }
10989: return $uname if ($uname =~ /^error/);
10990: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10991: if (!defined($course_server)) {
10992: if (defined(&domain($udom,'primary'))) {
10993: $course_server = &domain($udom,'primary');
10994: } else {
10995: $course_server = $env{'user.home'};
10996: }
10997: }
10998: my %host_servers =
10999: &Apache::lonnet::get_servers($udom,'library');
11000: unless ($host_servers{$course_server}) {
11001: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 11002: }
1.84 www 11003: # ------------------------------------------------------------- Make the course
11004: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 11005: $course_server);
1.84 www 11006: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 11007: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 11008: if (($uhome eq '') || ($uhome eq 'no_host')) {
11009: return 'error: no such course';
11010: }
1.271 www 11011: # ----------------------------------------------------------------- Course made
1.516 raeburn 11012: # log existence
1.1029 raeburn 11013: my $now = time;
1.918 raeburn 11014: my $newcourse = {
11015: $udom.'_'.$uname => {
1.921 raeburn 11016: description => $description,
11017: inst_code => $inst_code,
11018: owner => $course_owner,
11019: type => $crstype,
1.1029 raeburn 11020: creator => $env{'user.name'}.':'.
11021: $env{'user.domain'},
11022: created => $now,
11023: context => $context,
1.918 raeburn 11024: },
11025: };
1.921 raeburn 11026: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 11027: # set toplevel url
1.271 www 11028: my $topurl=$url;
11029: unless ($nonstandard) {
11030: # ------------------------------------------ For standard courses, make top url
11031: my $mapurl=&clutter($url);
1.278 www 11032: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 11033: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 11034: <map>
11035: <resource id="1" type="start"></resource>
11036: <resource id="2" src="$mapurl"></resource>
11037: <resource id="3" type="finish"></resource>
11038: <link index="1" from="1" to="2"></link>
11039: <link index="2" from="2" to="3"></link>
11040: </map>
11041: ENDINITMAP
11042: $topurl=&declutter(
1.638 albertel 11043: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 11044: );
11045: }
11046: # ----------------------------------------------------------- Write preferences
1.84 www 11047: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 11048: ('description' => $description,
11049: 'url' => $topurl,
11050: 'internal.creator' => $env{'user.name'}.':'.
11051: $env{'user.domain'},
11052: 'internal.created' => $now,
11053: 'internal.creationcontext' => $context)
11054: );
1.84 www 11055: return '/'.$udom.'/'.$uname;
11056: }
11057:
1.1011 raeburn 11058: # ------------------------------------------------------------------- Create ID
11059: sub generate_coursenum {
1.1038 raeburn 11060: my ($udom,$crstype) = @_;
1.1011 raeburn 11061: my $domdesc = &domain($udom);
11062: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 11063: my $first;
11064: if ($crstype eq 'Community') {
11065: $first = '0';
11066: } else {
11067: $first = int(1+rand(9));
11068: }
11069: my $uname=$first.
1.1011 raeburn 11070: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11071: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11072: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11073: # ----------------------------------------------- Make sure that does not exist
11074: my $uhome=&homeserver($uname,$udom,'true');
11075: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 11076: if ($crstype eq 'Community') {
11077: $first = '0';
11078: } else {
11079: $first = int(1+rand(9));
11080: }
11081: $uname=$first.
1.1011 raeburn 11082: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11083: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11084: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11085: $uhome=&homeserver($uname,$udom,'true');
11086: unless (($uhome eq '') || ($uhome eq 'no_host')) {
11087: return 'error: unable to generate unique course-ID';
11088: }
11089: }
11090: return $uname;
11091: }
11092:
1.813 albertel 11093: sub is_course {
1.1167 droeschl 11094: my ($cdom, $cnum) = scalar(@_) == 1 ?
11095: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
11096:
1.1381 raeburn 11097: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11098: my $uhome=&homeserver($cnum,$cdom);
11099: my $iscourse;
11100: if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382 raeburn 11101: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381 raeburn 11102: } else {
11103: my $hashid = $cdom.':'.$cnum;
11104: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11105: unless (defined($cached)) {
11106: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11107: $cnum,undef,undef,'.');
11108: $iscourse = 0;
11109: if (exists($courses{$cdom.'_'.$cnum})) {
11110: $iscourse = 1;
11111: }
11112: &do_cache_new('iscourse',$hashid,$iscourse,3600);
11113: }
11114: }
11115: return unless ($iscourse);
1.1167 droeschl 11116: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 11117: }
11118:
1.1015 raeburn 11119: sub store_userdata {
11120: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 11121: my $result;
1.1016 raeburn 11122: if ($datakey ne '') {
1.1013 raeburn 11123: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 11124: if ($udom eq '' || $uname eq '') {
11125: $udom = $env{'user.domain'};
11126: $uname = $env{'user.name'};
11127: }
11128: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 11129: if (($uhome eq '') || ($uhome eq 'no_host')) {
11130: $result = 'error: no_host';
11131: } else {
1.1434 raeburn 11132: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 11133: $storehash->{'host'} = $perlvar{'lonHostID'};
11134:
11135: my $namevalue='';
11136: foreach my $key (keys(%{$storehash})) {
11137: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11138: }
11139: $namevalue=~s/\&$//;
1.1224 raeburn 11140: unless ($namespace eq 'courserequests') {
11141: $datakey = &escape($datakey);
11142: }
1.1105 raeburn 11143: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
11144: $namevalue,$uhome);
1.1013 raeburn 11145: }
11146: } else {
11147: $result = 'error: data to store was not a hash reference';
11148: }
11149: } else {
11150: $result= 'error: invalid requestkey';
11151: }
11152: return $result;
11153: }
11154:
1.21 www 11155: # ---------------------------------------------------------- Assign Custom Role
11156:
11157: sub assigncustomrole {
1.957 raeburn 11158: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11159: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 11160: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 11161: }
11162:
11163: # ----------------------------------------------------------------- Revoke Role
11164:
11165: sub revokerole {
1.957 raeburn 11166: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11167: my $now=time;
1.965 raeburn 11168: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 11169: }
11170:
11171: # ---------------------------------------------------------- Revoke Custom Role
11172:
11173: sub revokecustomrole {
1.957 raeburn 11174: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11175: my $now=time;
1.357 www 11176: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 11177: $deleteflag,$selfenroll,$context);
1.17 www 11178: }
11179:
1.533 banghart 11180: # ------------------------------------------------------------ Disk usage
1.535 albertel 11181: sub diskusage {
1.955 raeburn 11182: my ($udom,$uname,$directorypath,$getpropath)=@_;
11183: $directorypath =~ s/\/$//;
11184: my $listing=&reply('du2:'.&escape($directorypath).':'
11185: .&escape($getpropath).':'.&escape($uname).':'
11186: .&escape($udom),homeserver($uname,$udom));
11187: if ($listing eq 'unknown_cmd') {
11188: if ($getpropath) {
11189: $directorypath = &propath($udom,$uname).'/'.$directorypath;
11190: }
11191: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11192: }
1.514 albertel 11193: return $listing;
1.512 banghart 11194: }
11195:
1.566 banghart 11196: sub is_locked {
1.1096 raeburn 11197: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 11198: my @check;
11199: my $is_locked;
1.1093 raeburn 11200: push (@check,$file_name);
1.613 albertel 11201: my %locked = &get('file_permissions',\@check,
1.620 albertel 11202: $env{'user.domain'},$env{'user.name'});
1.615 albertel 11203: my ($tmp)=keys(%locked);
11204: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 11205:
1.566 banghart 11206: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 11207: $is_locked = 'false';
11208: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 11209: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 11210: $is_locked = 'true';
1.1096 raeburn 11211: if (ref($which) eq 'ARRAY') {
11212: push(@{$which},$entry);
11213: } else {
11214: last;
11215: }
1.745 raeburn 11216: }
11217: }
1.566 banghart 11218: } else {
11219: $is_locked = 'false';
11220: }
1.1093 raeburn 11221: return $is_locked;
1.566 banghart 11222: }
11223:
1.759 albertel 11224: sub declutter_portfile {
11225: my ($file) = @_;
1.833 albertel 11226: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 11227: return $file;
11228: }
11229:
1.559 banghart 11230: # ------------------------------------------------------------- Mark as Read Only
11231:
11232: sub mark_as_readonly {
11233: my ($domain,$user,$files,$what) = @_;
1.613 albertel 11234: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11235: my ($tmp)=keys(%current_permissions);
11236: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 11237: foreach my $file (@{$files}) {
1.759 albertel 11238: $file = &declutter_portfile($file);
1.561 banghart 11239: push(@{$current_permissions{$file}},$what);
1.559 banghart 11240: }
1.613 albertel 11241: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11242: return;
11243: }
11244:
1.572 banghart 11245: # ------------------------------------------------------------Save Selected Files
11246:
11247: sub save_selected_files {
11248: my ($user, $path, @files) = @_;
11249: my $filename = $user."savedfiles";
1.573 banghart 11250: my @other_files = &files_not_in_path($user, $path);
1.1359 raeburn 11251: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 11252: foreach my $file (@files) {
1.620 albertel 11253: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 11254: }
11255: foreach my $file (@other_files) {
1.574 banghart 11256: print (OUT $file."\n");
1.572 banghart 11257: }
1.574 banghart 11258: close (OUT);
1.572 banghart 11259: return 'ok';
11260: }
11261:
1.574 banghart 11262: sub clear_selected_files {
11263: my ($user) = @_;
11264: my $filename = $user."savedfiles";
1.1359 raeburn 11265: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 11266: print (OUT undef);
11267: close (OUT);
11268: return ("ok");
11269: }
11270:
1.572 banghart 11271: sub files_in_path {
11272: my ($user, $path) = @_;
11273: my $filename = $user."savedfiles";
11274: my %return_files;
1.1359 raeburn 11275: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 11276: while (my $line_in = <IN>) {
1.574 banghart 11277: chomp ($line_in);
11278: my @paths_and_file = split (m!/!, $line_in);
11279: my $file_part = pop (@paths_and_file);
11280: my $path_part = join ('/', @paths_and_file);
1.573 banghart 11281: $path_part.='/';
11282: my $path_and_file = $path_part.$file_part;
11283: if ($path_part eq $path) {
11284: $return_files{$file_part}= 'selected';
11285: }
11286: }
1.574 banghart 11287: close (IN);
11288: return (\%return_files);
1.572 banghart 11289: }
11290:
11291: # called in portfolio select mode, to show files selected NOT in current directory
11292: sub files_not_in_path {
11293: my ($user, $path) = @_;
11294: my $filename = $user."savedfiles";
11295: my @return_files;
11296: my $path_part;
1.1359 raeburn 11297: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 11298: while (my $line = <IN>) {
1.572 banghart 11299: #ok, I know it's clunky, but I want it to work
1.800 albertel 11300: my @paths_and_file = split(m|/|, $line);
11301: my $file_part = pop(@paths_and_file);
11302: chomp($file_part);
11303: my $path_part = join('/', @paths_and_file);
1.572 banghart 11304: $path_part .= '/';
11305: my $path_and_file = $path_part.$file_part;
11306: if ($path_part ne $path) {
1.800 albertel 11307: push(@return_files, ($path_and_file));
1.572 banghart 11308: }
11309: }
1.800 albertel 11310: close(OUT);
1.574 banghart 11311: return (@return_files);
1.572 banghart 11312: }
11313:
1.1273 raeburn 11314: #------------------------------Submitted/Handedback Portfolio Files Versioning
11315:
11316: sub portfiles_versioning {
11317: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11318: my $portfolio_root = '/userfiles/portfolio';
11319: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11320: foreach my $file (@{$portfiles}) {
11321: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11322: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11323: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11324: my $getpropath = 1;
11325: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11326: $stu_name,$getpropath);
11327: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11328: my $new_answer =
11329: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11330: if ($new_answer ne 'problem getting file') {
11331: push(@{$versioned_portfiles}, $directory.$new_answer);
11332: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11333: [$symb,$env{'request.course.id'},'graded']);
11334: }
11335: }
11336: }
11337:
11338: sub get_next_version {
11339: my ($answer_name, $answer_ext, $dir_list) = @_;
11340: my $version;
11341: if (ref($dir_list) eq 'ARRAY') {
11342: foreach my $row (@{$dir_list}) {
11343: my ($file) = split(/\&/,$row,2);
11344: my ($file_name,$file_version,$file_ext) =
11345: &file_name_version_ext($file);
11346: if (($file_name eq $answer_name) &&
11347: ($file_ext eq $answer_ext)) {
11348: # gets here if filename and extension match,
11349: # regardless of version
11350: if ($file_version ne '') {
11351: # a versioned file is found so save it for later
11352: if ($file_version > $version) {
11353: $version = $file_version;
11354: }
11355: }
11356: }
11357: }
11358: }
11359: $version ++;
11360: return($version);
11361: }
11362:
11363: sub version_selected_portfile {
11364: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11365: my ($answer_name,$answer_ver,$answer_ext) =
11366: &file_name_version_ext($file_name);
11367: my $new_answer;
11368: $env{'form.copy'} =
11369: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11370: if($env{'form.copy'} eq '-1') {
11371: $new_answer = 'problem getting file';
11372: } else {
11373: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11374: my $copy_result =
11375: &finishuserfileupload($stu_name,$domain,'copy',
11376: '/portfolio'.$directory.$new_answer);
11377: }
11378: undef($env{'form.copy'});
11379: return ($new_answer);
11380: }
11381:
11382: sub file_name_version_ext {
11383: my ($file)=@_;
11384: my @file_parts = split(/\./, $file);
11385: my ($name,$version,$ext);
11386: if (@file_parts > 1) {
11387: $ext=pop(@file_parts);
11388: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11389: $version=pop(@file_parts);
11390: }
11391: $name=join('.',@file_parts);
11392: } else {
11393: $name=join('.',@file_parts);
11394: }
11395: return($name,$version,$ext);
11396: }
11397:
1.745 raeburn 11398: #----------------------------------------------Get portfolio file permissions
1.629 banghart 11399:
1.745 raeburn 11400: sub get_portfile_permissions {
11401: my ($domain,$user) = @_;
1.613 albertel 11402: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11403: my ($tmp)=keys(%current_permissions);
11404: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11405: return \%current_permissions;
11406: }
11407:
11408: #---------------------------------------------Get portfolio file access controls
11409:
1.749 raeburn 11410: sub get_access_controls {
1.745 raeburn 11411: my ($current_permissions,$group,$file) = @_;
1.769 albertel 11412: my %access;
11413: my $real_file = $file;
11414: $file =~ s/\.meta$//;
1.745 raeburn 11415: if (defined($file)) {
1.749 raeburn 11416: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11417: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 11418: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 11419: }
11420: }
1.745 raeburn 11421: } else {
1.749 raeburn 11422: foreach my $key (keys(%{$current_permissions})) {
11423: if ($key =~ /\0accesscontrol$/) {
11424: if (defined($group)) {
11425: if ($key !~ m-^\Q$group\E/-) {
11426: next;
11427: }
11428: }
11429: my ($fullpath) = split(/\0/,$key);
11430: if (ref($$current_permissions{$key}) eq 'HASH') {
11431: foreach my $control (keys(%{$$current_permissions{$key}})) {
11432: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11433: }
11434: }
11435: }
11436: }
11437: }
11438: return %access;
11439: }
11440:
11441: sub modify_access_controls {
11442: my ($file_name,$changes,$domain,$user)=@_;
11443: my ($outcome,$deloutcome);
11444: my %store_permissions;
11445: my %new_values;
11446: my %new_control;
11447: my %translation;
11448: my @deletions = ();
11449: my $now = time;
11450: if (exists($$changes{'activate'})) {
11451: if (ref($$changes{'activate'}) eq 'HASH') {
11452: my @newitems = sort(keys(%{$$changes{'activate'}}));
11453: my $numnew = scalar(@newitems);
11454: for (my $i=0; $i<$numnew; $i++) {
11455: my $newkey = $newitems[$i];
11456: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 11457: if ($newkey =~ /^\d+:/) {
11458: $newkey =~ s/^(\d+)/$newid/;
11459: $translation{$1} = $newid;
11460: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11461: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11462: $translation{$1} = $newid;
11463: }
1.749 raeburn 11464: $new_values{$file_name."\0".$newkey} =
11465: $$changes{'activate'}{$newitems[$i]};
11466: $new_control{$newkey} = $now;
11467: }
11468: }
11469: }
11470: my %todelete;
11471: my %changed_items;
11472: foreach my $action ('delete','update') {
11473: if (exists($$changes{$action})) {
11474: if (ref($$changes{$action}) eq 'HASH') {
11475: foreach my $key (keys(%{$$changes{$action}})) {
11476: my ($itemnum) = ($key =~ /^([^:]+):/);
11477: if ($action eq 'delete') {
11478: $todelete{$itemnum} = 1;
11479: } else {
11480: $changed_items{$itemnum} = $key;
11481: }
11482: }
1.745 raeburn 11483: }
11484: }
1.749 raeburn 11485: }
11486: # get lock on access controls for file.
11487: my $lockhash = {
11488: $file_name."\0".'locked_access_records' => $env{'user.name'}.
11489: ':'.$env{'user.domain'},
11490: };
11491: my $tries = 0;
11492: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11493:
1.1288 damieng 11494: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 11495: $tries ++;
1.1289 damieng 11496: sleep(0.1);
1.749 raeburn 11497: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11498: }
11499: if ($gotlock eq 'ok') {
11500: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11501: my ($tmp)=keys(%curr_permissions);
11502: if ($tmp=~/^error:/) { undef(%curr_permissions); }
11503: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11504: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11505: if (ref($curr_controls) eq 'HASH') {
11506: foreach my $control_item (keys(%{$curr_controls})) {
11507: my ($itemnum) = ($control_item =~ /^([^:]+):/);
11508: if (defined($todelete{$itemnum})) {
11509: push(@deletions,$file_name."\0".$control_item);
11510: } else {
11511: if (defined($changed_items{$itemnum})) {
11512: $new_control{$changed_items{$itemnum}} = $now;
11513: push(@deletions,$file_name."\0".$control_item);
11514: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11515: } else {
11516: $new_control{$control_item} = $$curr_controls{$control_item};
11517: }
11518: }
1.745 raeburn 11519: }
11520: }
11521: }
1.970 raeburn 11522: my ($group);
11523: if (&is_course($domain,$user)) {
11524: ($group,my $file) = split(/\//,$file_name,2);
11525: }
1.749 raeburn 11526: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11527: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11528: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11529: # remove lock
11530: my @del_lock = ($file_name."\0".'locked_access_records');
11531: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11532: my $sqlresult =
1.970 raeburn 11533: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11534: $group);
1.749 raeburn 11535: } else {
11536: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11537: }
1.749 raeburn 11538: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11539: }
11540:
1.827 raeburn 11541: sub make_public_indefinitely {
1.1271 raeburn 11542: my (@requrl) = @_;
11543: return &automated_portfile_access('public',\@requrl);
11544: }
11545:
11546: sub automated_portfile_access {
11547: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 11548: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11549: return 'invalid';
11550: }
1.1271 raeburn 11551: my %urls;
11552: if (ref($addsref) eq 'ARRAY') {
11553: foreach my $requrl (@{$addsref}) {
11554: if (&is_portfolio_url($requrl)) {
11555: unless (exists($urls{$requrl})) {
11556: $urls{$requrl} = 'add';
11557: }
11558: }
11559: }
11560: }
11561: if (ref($delsref) eq 'ARRAY') {
11562: foreach my $requrl (@{$delsref}) {
11563: if (&is_portfolio_url($requrl)) {
11564: unless (exists($urls{$requrl})) {
11565: $urls{$requrl} = 'delete';
11566: }
11567: }
11568: }
11569: }
11570: unless (keys(%urls)) {
11571: return 'invalid';
11572: }
11573: my $ip;
11574: if ($accesstype eq 'ip') {
11575: if (ref($info) eq 'HASH') {
11576: if ($info->{'ip'} ne '') {
11577: $ip = $info->{'ip'};
11578: }
11579: }
11580: if ($ip eq '') {
11581: return 'invalid';
11582: }
11583: }
11584: my $errors;
1.827 raeburn 11585: my $now = time;
1.1271 raeburn 11586: my %current_perms;
11587: foreach my $requrl (sort(keys(%urls))) {
11588: my $action;
11589: if ($urls{$requrl} eq 'add') {
11590: $action = 'activate';
11591: } else {
11592: $action = 'none';
11593: }
11594: my $aclnum = 0;
1.827 raeburn 11595: my (undef,$udom,$unum,$file_name,$group) =
11596: &parse_portfolio_url($requrl);
1.1271 raeburn 11597: unless (exists($current_perms{$unum.':'.$udom})) {
11598: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11599: }
11600: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 11601: $group,$file_name);
11602: foreach my $key (keys(%{$access_controls{$file_name}})) {
11603: my ($num,$scope,$end,$start) =
11604: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 11605: if ($scope eq $accesstype) {
11606: if (($start <= $now) && ($end == 0)) {
11607: if ($accesstype eq 'ip') {
11608: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11609: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11610: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11611: if ($urls{$requrl} eq 'add') {
11612: $action = 'none';
11613: last;
11614: } else {
11615: $action = 'delete';
11616: $aclnum = $num;
11617: last;
11618: }
11619: }
11620: }
11621: }
11622: } elsif ($accesstype eq 'public') {
11623: if ($urls{$requrl} eq 'add') {
11624: $action = 'none';
11625: last;
11626: } else {
11627: $action = 'delete';
11628: $aclnum = $num;
11629: last;
11630: }
11631: }
11632: } elsif ($accesstype eq 'public') {
1.827 raeburn 11633: $action = 'update';
11634: $aclnum = $num;
1.1271 raeburn 11635: last;
1.827 raeburn 11636: }
11637: }
11638: }
11639: if ($action eq 'none') {
1.1271 raeburn 11640: next;
1.827 raeburn 11641: } else {
11642: my %changes;
11643: my $newend = 0;
11644: my $newstart = $now;
1.1271 raeburn 11645: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 11646: $changes{$action}{$newkey} = {
1.1271 raeburn 11647: type => $accesstype,
1.827 raeburn 11648: time => {
11649: start => $newstart,
11650: end => $newend,
11651: },
11652: };
1.1271 raeburn 11653: if ($accesstype eq 'ip') {
11654: $changes{$action}{$newkey}{'ip'} = [$ip];
11655: }
1.827 raeburn 11656: my ($outcome,$deloutcome,$new_values,$translation) =
11657: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 11658: unless ($outcome eq 'ok') {
11659: $errors .= $outcome.' ';
11660: }
1.827 raeburn 11661: }
1.1271 raeburn 11662: }
11663: if ($errors) {
11664: $errors =~ s/\s$//;
11665: return $errors;
1.827 raeburn 11666: } else {
1.1271 raeburn 11667: return 'ok';
1.827 raeburn 11668: }
11669: }
11670:
1.745 raeburn 11671: #------------------------------------------------------Get Marked as Read Only
11672:
11673: sub get_marked_as_readonly {
11674: my ($domain,$user,$what,$group) = @_;
11675: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11676: my @readonly_files;
1.629 banghart 11677: my $cmp1=$what;
11678: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11679: while (my ($file_name,$value) = each(%{$current_permissions})) {
11680: if (defined($group)) {
11681: if ($file_name !~ m-^\Q$group\E/-) {
11682: next;
11683: }
11684: }
1.561 banghart 11685: if (ref($value) eq "ARRAY"){
11686: foreach my $stored_what (@{$value}) {
1.629 banghart 11687: my $cmp2=$stored_what;
1.759 albertel 11688: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11689: $cmp2=join('',@{$stored_what});
1.745 raeburn 11690: }
1.629 banghart 11691: if ($cmp1 eq $cmp2) {
1.561 banghart 11692: push(@readonly_files, $file_name);
1.745 raeburn 11693: last;
1.563 banghart 11694: } elsif (!defined($what)) {
11695: push(@readonly_files, $file_name);
1.745 raeburn 11696: last;
1.561 banghart 11697: }
11698: }
1.745 raeburn 11699: }
1.561 banghart 11700: }
11701: return @readonly_files;
11702: }
1.577 banghart 11703: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11704:
1.577 banghart 11705: sub get_marked_as_readonly_hash {
1.745 raeburn 11706: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11707: my %readonly_files;
1.745 raeburn 11708: while (my ($file_name,$value) = each(%{$current_permissions})) {
11709: if (defined($group)) {
11710: if ($file_name !~ m-^\Q$group\E/-) {
11711: next;
11712: }
11713: }
1.577 banghart 11714: if (ref($value) eq "ARRAY"){
11715: foreach my $stored_what (@{$value}) {
1.745 raeburn 11716: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11717: foreach my $lock_descriptor(@{$stored_what}) {
11718: if ($lock_descriptor eq 'graded') {
11719: $readonly_files{$file_name} = 'graded';
11720: } elsif ($lock_descriptor eq 'handback') {
11721: $readonly_files{$file_name} = 'handback';
11722: } else {
11723: if (!exists($readonly_files{$file_name})) {
11724: $readonly_files{$file_name} = 'locked';
11725: }
11726: }
1.745 raeburn 11727: }
1.750 banghart 11728: }
1.577 banghart 11729: }
11730: }
11731: }
11732: return %readonly_files;
11733: }
1.559 banghart 11734: # ------------------------------------------------------------ Unmark as Read Only
11735:
11736: sub unmark_as_readonly {
1.629 banghart 11737: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11738: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11739: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11740: $file_name = &declutter_portfile($file_name);
1.634 albertel 11741: my $symb_crs = $what;
11742: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11743: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11744: my ($tmp)=keys(%current_permissions);
11745: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11746: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11747: foreach my $file (@readonly_files) {
1.759 albertel 11748: my $clean_file = &declutter_portfile($file);
11749: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11750: my $current_locks = $current_permissions{$file};
1.563 banghart 11751: my @new_locks;
11752: my @del_keys;
11753: if (ref($current_locks) eq "ARRAY"){
11754: foreach my $locker (@{$current_locks}) {
1.632 albertel 11755: my $compare=$locker;
1.749 raeburn 11756: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11757: $compare=join('',@{$locker});
1.746 raeburn 11758: if ($compare ne $symb_crs) {
11759: push(@new_locks, $locker);
11760: }
1.563 banghart 11761: }
11762: }
1.650 albertel 11763: if (scalar(@new_locks) > 0) {
1.563 banghart 11764: $current_permissions{$file} = \@new_locks;
11765: } else {
11766: push(@del_keys, $file);
1.613 albertel 11767: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11768: delete($current_permissions{$file});
1.563 banghart 11769: }
11770: }
1.561 banghart 11771: }
1.613 albertel 11772: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11773: return;
11774: }
1.512 banghart 11775:
1.17 www 11776: # ------------------------------------------------------------ Directory lister
11777:
11778: sub dirlist {
1.955 raeburn 11779: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11780: $uri=~s/^\///;
11781: $uri=~s/\/$//;
1.253 stredwic 11782: my ($udom, $uname);
1.955 raeburn 11783: if ($getuserdir) {
1.253 stredwic 11784: $udom = $userdomain;
11785: $uname = $username;
1.955 raeburn 11786: } else {
11787: (undef,$udom,$uname)=split(/\//,$uri);
11788: if(defined($userdomain)) {
11789: $udom = $userdomain;
11790: }
11791: if(defined($username)) {
11792: $uname = $username;
11793: }
1.253 stredwic 11794: }
1.955 raeburn 11795: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11796:
1.955 raeburn 11797: $dirRoot = $perlvar{'lonDocRoot'};
11798: if (defined($getpropath)) {
11799: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11800: $dirRoot =~ s/\/$//;
1.955 raeburn 11801: } elsif (defined($getuserdir)) {
11802: my $subdir=$uname.'__';
11803: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11804: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11805: ."/$udom/$subdir/$uname";
11806: } elsif (defined($alternateRoot)) {
11807: $dirRoot = $alternateRoot;
1.751 banghart 11808: }
1.253 stredwic 11809:
11810: if($udom) {
11811: if($uname) {
1.1135 raeburn 11812: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11813: if ($uhome eq 'no_host') {
11814: return ([],'no_host');
11815: }
1.955 raeburn 11816: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11817: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11818: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11819: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11820: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11821: } else {
11822: @listing_results = map { &unescape($_); } split(/:/,$listing);
11823: }
1.605 matthew 11824: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11825: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11826: @listing_results = split(/:/,$listing);
11827: } else {
11828: @listing_results = map { &unescape($_); } split(/:/,$listing);
11829: }
1.1135 raeburn 11830: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11831: ($listing eq 'rejected') || ($listing eq 'refused') ||
11832: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11833: return ([],$listing);
11834: } else {
11835: return (\@listing_results);
1.1135 raeburn 11836: }
1.955 raeburn 11837: } elsif(!$alternateRoot) {
1.1136 raeburn 11838: my (%allusers,%listerror);
1.841 albertel 11839: my %servers = &get_servers($udom,'library');
1.955 raeburn 11840: foreach my $tryserver (keys(%servers)) {
11841: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11842: &escape($udom),$tryserver);
11843: if ($listing eq 'unknown_cmd') {
11844: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11845: $udom, $tryserver);
11846: } else {
11847: @listing_results = map { &unescape($_); } split(/:/,$listing);
11848: }
1.841 albertel 11849: if ($listing eq 'unknown_cmd') {
11850: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11851: $udom, $tryserver);
11852: @listing_results = split(/:/,$listing);
11853: } else {
11854: @listing_results =
11855: map { &unescape($_); } split(/:/,$listing);
11856: }
1.1136 raeburn 11857: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11858: ($listing eq 'rejected') || ($listing eq 'refused') ||
11859: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11860: $listerror{$tryserver} = $listing;
11861: } else {
1.841 albertel 11862: foreach my $line (@listing_results) {
11863: my ($entry) = split(/&/,$line,2);
11864: $allusers{$entry} = 1;
11865: }
11866: }
1.253 stredwic 11867: }
1.1136 raeburn 11868: my @alluserslist=();
1.800 albertel 11869: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11870: push(@alluserslist,$user.'&user');
1.253 stredwic 11871: }
1.1318 droeschl 11872:
11873: if (!%listerror) {
11874: # no errors
11875: return (\@alluserslist);
11876: } elsif (scalar(keys(%servers)) == 1) {
11877: # one library server, one error
11878: my ($key) = keys(%listerror);
11879: return (\@alluserslist, $listerror{$key});
11880: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11881: # con_lost indicates that we might miss data from at least one
11882: # library server
11883: return (\@alluserslist, 'con_lost');
11884: } else {
11885: # multiple library servers and no con_lost -> data should be
11886: # complete.
11887: return (\@alluserslist);
11888: }
11889:
1.253 stredwic 11890: } else {
1.1136 raeburn 11891: return ([],'missing username');
1.253 stredwic 11892: }
1.955 raeburn 11893: } elsif(!defined($getpropath)) {
1.1136 raeburn 11894: my $path = $perlvar{'lonDocRoot'}.'/res/';
11895: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11896: return (\@all_domains);
1.955 raeburn 11897: } else {
1.1136 raeburn 11898: return ([],'missing domain');
1.275 stredwic 11899: }
11900: }
11901:
11902: # --------------------------------------------- GetFileTimestamp
11903: # This function utilizes dirlist and returns the date stamp for
11904: # when it was last modified. It will also return an error of -1
11905: # if an error occurs
11906:
11907: sub GetFileTimestamp {
1.955 raeburn 11908: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11909: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11910: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11911: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11912: undef,$getuserdir);
11913: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11914: return -1;
11915: }
11916: if (ref($fileref) eq 'ARRAY') {
11917: my @stats = split('&',$fileref->[0]);
1.375 matthew 11918: # @stats contains first the filename, then the stat output
11919: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11920: } else {
11921: return -1;
1.253 stredwic 11922: }
1.26 www 11923: }
11924:
1.712 albertel 11925: sub stat_file {
11926: my ($uri) = @_;
1.787 albertel 11927: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11928:
1.955 raeburn 11929: my ($udom,$uname,$file);
1.712 albertel 11930: if ($uri =~ m-^/(uploaded|editupload)/-) {
11931: ($udom,$uname,$file) =
1.811 albertel 11932: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11933: $file = 'userfiles/'.$file;
11934: }
11935: if ($uri =~ m-^/res/-) {
11936: ($udom,$uname) =
1.807 albertel 11937: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11938: $file = $uri;
11939: }
11940:
11941: if (!$udom || !$uname || !$file) {
11942: # unable to handle the uri
11943: return ();
11944: }
1.956 raeburn 11945: my $getpropath;
11946: if ($file =~ /^userfiles\//) {
11947: $getpropath = 1;
11948: }
1.1136 raeburn 11949: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11950: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11951: return ();
11952: } else {
11953: if (ref($listref) eq 'ARRAY') {
11954: my @stats = split('&',$listref->[0]);
11955: shift(@stats); #filename is first
11956: return @stats;
11957: }
1.712 albertel 11958: }
11959: return ();
11960: }
11961:
1.1313 raeburn 11962: # --------------------------------------------------------- recursedirs
11963: # Recursive function to traverse either a specific user's Authoring Space
11964: # or corresponding Published Resource Space, and populate the hash ref:
11965: # $dirhashref with URLs of all directories, and if $filehashref hash
11966: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11967: # or .rights files in resource space, and .meta, .save, .log, and .bak
11968: # files in Authoring Space.
11969: #
11970: # Inputs:
11971: #
11972: # $is_home - true if current server is home server for user's space
11973: # $context - either: priv, or res respectively for Authoring or Resource Space.
11974: # $docroot - Document root (i.e., /home/httpd/html
11975: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11976: # $relpath - Current path (relative to top level).
11977: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11978: # $filehashref - reference to hash to populate with URLs of files (Optional)
11979: #
11980: # Returns: nothing
11981: #
11982: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11983: #
11984: # Currently used by interface/londocs.pm to create linked select boxes for
11985: # directory and filename to import a Course "Author" resource into a course, and
11986: # also to create linked select boxes for Authoring Space and Directory to choose
11987: # save location for creation of a new "standard" problem from the Course Editor.
11988: #
11989:
11990: sub recursedirs {
11991: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11992: return unless (ref($dirhashref) eq 'HASH');
11993: my $currpath = $docroot.$toppath;
11994: if ($relpath) {
11995: $currpath .= "/$relpath";
11996: }
11997: my $savefile;
11998: if (ref($filehashref)) {
11999: $savefile = 1;
12000: }
12001: if ($is_home) {
12002: if (opendir(my $dirh,$currpath)) {
12003: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12004: next if ($item eq '');
12005: if (-d "$currpath/$item") {
12006: my $newpath;
12007: if ($relpath) {
12008: $newpath = "$relpath/$item";
12009: } else {
12010: $newpath = $item;
12011: }
12012: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12013: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
12014: } elsif ($savefile) {
12015: if ($context eq 'priv') {
12016: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
12017: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12018: }
12019: } else {
12020: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
12021: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12022: }
12023: }
12024: }
12025: }
12026: closedir($dirh);
12027: }
12028: } else {
12029: my ($dirlistref,$listerror) =
12030: &dirlist($toppath.$relpath);
12031: my @dir_lines;
12032: my $dirptr=16384;
12033: if (ref($dirlistref) eq 'ARRAY') {
12034: foreach my $dir_line (sort
12035: {
12036: my ($afile)=split('&',$a,2);
12037: my ($bfile)=split('&',$b,2);
12038: return (lc($afile) cmp lc($bfile));
12039: } (@{$dirlistref})) {
12040: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12041: split(/\&/,$dir_line,16);
12042: $item =~ s/\s+$//;
12043: next if (($item =~ /^\.\.?$/) || ($obs));
12044: if ($dirptr&$testdir) {
12045: my $newpath;
12046: if ($relpath) {
12047: $newpath = "$relpath/$item";
12048: } else {
12049: $relpath = '/';
12050: $newpath = $item;
12051: }
12052: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12053: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
12054: } elsif ($savefile) {
12055: if ($context eq 'priv') {
12056: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
12057: $filehashref->{$relpath}{$item} = 1;
12058: }
12059: } else {
12060: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
12061: $filehashref->{$relpath}{$item} = 1;
12062: }
12063: }
12064: }
12065: }
12066: }
12067: }
12068: return;
12069: }
12070:
1.26 www 12071: # -------------------------------------------------------- Value of a Condition
12072:
1.713 albertel 12073: # gets the value of a specific preevaluated condition
12074: # stored in the string $env{user.state.<cid>}
12075: # or looks up a condition reference in the bighash and if if hasn't
12076: # already been evaluated recurses into docondval to get the value of
12077: # the condition, then memoizing it to
12078: # $env{user.state.<cid>.<condition>}
1.40 www 12079: sub directcondval {
12080: my $number=shift;
1.620 albertel 12081: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 12082: &Apache::lonuserstate::evalstate();
12083: }
1.713 albertel 12084: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12085: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12086: } elsif ($number =~ /^_/) {
12087: my $sub_condition;
12088: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12089: &GDBM_READER(),0640)) {
12090: $sub_condition=$bighash{'conditions'.$number};
12091: untie(%bighash);
12092: }
12093: my $value = &docondval($sub_condition);
1.949 raeburn 12094: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 12095: return $value;
12096: }
1.620 albertel 12097: if ($env{'user.state.'.$env{'request.course.id'}}) {
12098: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 12099: } else {
12100: return 2;
12101: }
12102: }
12103:
1.713 albertel 12104: # get the collection of conditions for this resource
1.26 www 12105: sub condval {
12106: my $condidx=shift;
1.54 www 12107: my $allpathcond='';
1.713 albertel 12108: foreach my $cond (split(/\|/,$condidx)) {
12109: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12110: $allpathcond.=
12111: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12112: }
1.191 harris41 12113: }
1.54 www 12114: $allpathcond=~s/\|$//;
1.713 albertel 12115: return &docondval($allpathcond);
12116: }
12117:
12118: #evaluates an expression of conditions
12119: sub docondval {
12120: my ($allpathcond) = @_;
12121: my $result=0;
12122: if ($env{'request.course.id'}
12123: && defined($allpathcond)) {
12124: my $operand='|';
12125: my @stack;
12126: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12127: if ($chunk eq '(') {
12128: push @stack,($operand,$result);
12129: } elsif ($chunk eq ')') {
12130: my $before=pop @stack;
12131: if (pop @stack eq '&') {
12132: $result=$result>$before?$before:$result;
12133: } else {
12134: $result=$result>$before?$result:$before;
12135: }
12136: } elsif (($chunk eq '&') || ($chunk eq '|')) {
12137: $operand=$chunk;
12138: } else {
12139: my $new=directcondval($chunk);
12140: if ($operand eq '&') {
12141: $result=$result>$new?$new:$result;
12142: } else {
12143: $result=$result>$new?$result:$new;
12144: }
12145: }
12146: }
1.26 www 12147: }
12148: return $result;
1.421 albertel 12149: }
12150:
12151: # ---------------------------------------------------- Devalidate courseresdata
12152:
12153: sub devalidatecourseresdata {
12154: my ($coursenum,$coursedomain)=@_;
12155: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12156: &devalidate_cache_new('courseres',$hashid);
1.28 www 12157: }
12158:
1.763 www 12159:
1.200 www 12160: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 12161: #
12162: # Parameters:
12163: # $coursenum - Number of the course.
12164: # $coursedomain - Domain at which the course was created.
12165: # Returns:
12166: # A hash of the course parameters along (I think) with timestamps
12167: # and version info.
1.877 foxr 12168:
1.624 albertel 12169: sub get_courseresdata {
12170: my ($coursenum,$coursedomain)=@_;
1.200 www 12171: my $coursehom=&homeserver($coursenum,$coursedomain);
12172: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12173: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 12174: my %dumpreply;
1.417 albertel 12175: unless (defined($cached)) {
1.624 albertel 12176: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 12177: $result=\%dumpreply;
1.251 albertel 12178: my ($tmp) = keys(%dumpreply);
12179: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 12180: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 12181: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12182: return $tmp;
1.416 albertel 12183: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 12184: $result=undef;
1.599 albertel 12185: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 12186: }
12187: }
1.624 albertel 12188: return $result;
12189: }
12190:
1.633 albertel 12191: sub devalidateuserresdata {
12192: my ($uname,$udom)=@_;
12193: my $hashid="$udom:$uname";
12194: &devalidate_cache_new('userres',$hashid);
12195: }
12196:
1.624 albertel 12197: sub get_userresdata {
12198: my ($uname,$udom)=@_;
12199: #most student don\'t have any data set, check if there is some data
12200: if (&EXT_cache_status($udom,$uname)) { return undef; }
12201:
12202: my $hashid="$udom:$uname";
12203: my ($result,$cached)=&is_cached_new('userres',$hashid);
12204: if (!defined($cached)) {
12205: my %resourcedata=&dump('resourcedata',$udom,$uname);
12206: $result=\%resourcedata;
12207: &do_cache_new('userres',$hashid,$result,600);
12208: }
12209: my ($tmp)=keys(%$result);
12210: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12211: return $result;
12212: }
12213: #error 2 occurs when the .db doesn't exist
12214: if ($tmp!~/error: 2 /) {
1.1294 raeburn 12215: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12216: &logthis("<font color=\"blue\">WARNING:".
12217: " Trying to get resource data for ".
12218: $uname." at ".$udom.": ".
12219: $tmp."</font>");
12220: }
1.624 albertel 12221: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 12222: #&EXT_cache_set($udom,$uname);
12223: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 12224: undef($tmp); # not really an error so don't send it back
1.624 albertel 12225: }
12226: return $tmp;
12227: }
1.879 foxr 12228: #----------------------------------------------- resdata - return resource data
12229: # Purpose:
12230: # Return resource data for either users or for a course.
12231: # Parameters:
12232: # $name - Course/user name.
12233: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 12234: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 12235: # $mapp - decluttered URL of enclosing map
12236: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
12237: # $recurseup - Ref to array of map URLs, starting with map containing
12238: # $mapp up through hierarchy of nested maps to top level map.
12239: # $courseid - CourseID (first part of param identifier).
12240: # $modifier - Middle part of param identifier.
12241: # $what - Last part of param identifier.
1.879 foxr 12242: # @which - Array of names of resources desired.
12243: # Returns:
12244: # The value of the first reasource in @which that is found in the
12245: # resource hash.
12246: # Exceptional Conditions:
12247: # If the $type passed in is not valid (not the string 'course' or
12248: # 'user', an undefined reference is returned.
12249: # If none of the resources are found, an undef is returned
1.624 albertel 12250: sub resdata {
1.1301 raeburn 12251: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12252: $modifier,$what,@which)=@_;
1.624 albertel 12253: my $result;
12254: if ($type eq 'course') {
12255: $result=&get_courseresdata($name,$domain);
12256: } elsif ($type eq 'user') {
12257: $result=&get_userresdata($name,$domain);
12258: }
12259: if (!ref($result)) { return $result; }
1.251 albertel 12260: foreach my $item (@which) {
1.1301 raeburn 12261: if ($item->[1] eq 'course') {
12262: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12263: unless ($$recursed) {
1.1302 raeburn 12264: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 12265: $$recursed = 1;
12266: }
12267: foreach my $item (@${recurseup}) {
12268: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12269: last if (defined($result->{$norecursechk}));
12270: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12271: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12272: }
12273: }
12274: }
12275: if (defined($result->{$item->[0]})) {
1.927 albertel 12276: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 12277: }
1.250 albertel 12278: }
1.291 albertel 12279: return undef;
1.200 www 12280: }
12281:
1.1360 raeburn 12282: sub get_domain_lti {
12283: my ($cdom,$context) = @_;
1.1483 ! raeburn 12284: my ($name,$cachename,%lti);
1.1360 raeburn 12285: if ($context eq 'consumer') {
12286: $name = 'ltitools';
12287: } elsif ($context eq 'provider') {
12288: $name = 'lti';
1.1483 ! raeburn 12289: } elsif ($context eq 'linkprot') {
! 12290: $name = 'ltisec';
1.1360 raeburn 12291: } else {
12292: return %lti;
12293: }
1.1483 ! raeburn 12294:
! 12295: if ($context eq 'linkprot') {
! 12296: $cachename = $context;
! 12297: } else {
! 12298: $cachename = $name;
! 12299: }
! 12300:
! 12301: my ($result,$cached)=&is_cached_new($cachename,$cdom);
1.1298 raeburn 12302: if (defined($cached)) {
12303: if (ref($result) eq 'HASH') {
1.1360 raeburn 12304: %lti = %{$result};
1.1298 raeburn 12305: }
12306: } else {
1.1360 raeburn 12307: my %domconfig = &get_dom('configuration',[$name],$cdom);
12308: if (ref($domconfig{$name}) eq 'HASH') {
1.1483 ! raeburn 12309: if ($context eq 'linkprot') {
! 12310: if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
! 12311: %lti = %{$domconfig{$name}{'linkprot'}};
! 12312: }
! 12313: } else {
! 12314: %lti = %{$domconfig{$name}};
! 12315: }
! 12316: if (($context eq 'consumer') && (keys(%lti))) {
! 12317: my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
! 12318: if (ref($encdomconfig{$name}) eq 'HASH') {
! 12319: foreach my $id (keys(%lti)) {
! 12320: if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
! 12321: foreach my $item ('key','secret') {
! 12322: $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
! 12323: }
1.1344 raeburn 12324: }
12325: }
12326: }
12327: }
1.1298 raeburn 12328: }
12329: my $cachetime = 24*60*60;
1.1483 ! raeburn 12330: &do_cache_new($cachename,$cdom,\%lti,$cachetime);
1.1298 raeburn 12331: }
1.1360 raeburn 12332: return %lti;
1.1298 raeburn 12333: }
12334:
1.1463 raeburn 12335: sub get_course_lti {
12336: my ($cnum,$cdom) = @_;
12337: my $hashid=$cdom.'_'.$cnum;
12338: my %courselti;
12339: my ($result,$cached)=&is_cached_new('courselti',$hashid);
12340: if (defined($cached)) {
12341: if (ref($result) eq 'HASH') {
12342: %courselti = %{$result};
12343: }
12344: } else {
12345: %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
12346: my $cachetime = 24*60*60;
12347: &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
12348: }
12349: return %courselti;
12350: }
12351:
1.1479 raeburn 12352: sub courselti_itemid {
12353: my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12354: my ($chome,$itemid);
12355: $chome = &homeserver($cnum,$cdom);
12356: return if ($chome eq 'no_host');
12357: if (ref($params) eq 'HASH') {
12358: my $items = &freeze_escape($params);
12359: my $rep;
12360: if (grep { $_ eq $chome } current_machine_ids()) {
12361: $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12362: } else {
12363: my $escurl = &escape($url);
12364: my $escmethod = &escape($method);
12365: my $items = &freeze_escape($params);
12366: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12367: }
12368: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12369: ($rep eq 'unknown_cmd')) {
12370: $itemid = $rep;
12371: }
12372: }
12373: return $itemid;
12374: }
12375:
12376: sub domainlti_itemid {
12377: my ($cdom,$url,$method,$params,$context) = @_;
12378: my ($primary_id,$itemid);
12379: $primary_id = &domain($cdom,'primary');
12380: return if ($primary_id eq '');
12381: if (ref($params) eq 'HASH') {
12382: my $items = &freeze_escape($params);
12383: my $rep;
12384: if (grep { $_ eq $primary_id } current_machine_ids()) {
12385: $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12386: } else {
12387: my $cnum = '';
12388: my $escurl = &escape($url);
12389: my $escmethod = &escape($method);
12390: my $items = &freeze_escape($params);
12391: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12392: }
12393: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12394: ($rep eq 'unknown_cmd')) {
12395: $itemid = $rep;
12396: }
12397: }
12398: return $itemid;
12399: }
12400:
1.1236 raeburn 12401: sub get_numsuppfiles {
12402: my ($cnum,$cdom,$ignorecache)=@_;
12403: my $hashid=$cnum.':'.$cdom;
12404: my ($suppcount,$cached);
12405: unless ($ignorecache) {
12406: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12407: }
12408: unless (defined($cached)) {
12409: my $chome=&homeserver($cnum,$cdom);
12410: unless ($chome eq 'no_host') {
1.1366 raeburn 12411: ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236 raeburn 12412: my $suppmap = 'supplemental.sequence';
1.1366 raeburn 12413: ($suppcount,$supptools,$errors) =
12414: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12415: $supptools,$errors);
1.1236 raeburn 12416: }
12417: &do_cache_new('suppcount',$hashid,$suppcount,600);
12418: }
12419: return $suppcount;
12420: }
12421:
1.379 matthew 12422: #
12423: # EXT resource caching routines
12424: #
12425:
1.1302 raeburn 12426: {
12427: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12428: #
12429: # The course for which we cache
12430: my $cachedmapkey='';
12431: # The cached recursive maps for this course
12432: my %cachedmaps=();
12433: # When this was last done
12434: my $cachedmaptime='';
12435:
1.379 matthew 12436: sub clear_EXT_cache_status {
1.383 albertel 12437: &delenv('cache.EXT.');
1.379 matthew 12438: }
12439:
12440: sub EXT_cache_status {
12441: my ($target_domain,$target_user) = @_;
1.383 albertel 12442: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 12443: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 12444: # We know already the user has no data
12445: return 1;
12446: } else {
12447: return 0;
12448: }
12449: }
12450:
12451: sub EXT_cache_set {
12452: my ($target_domain,$target_user) = @_;
1.383 albertel 12453: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 12454: #&appenv({$cachename => time});
1.379 matthew 12455: }
12456:
1.28 www 12457: # --------------------------------------------------------- Value of a Variable
1.58 www 12458: sub EXT {
1.715 albertel 12459:
1.1461 raeburn 12460: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
1.68 www 12461: unless ($varname) { return ''; }
1.218 albertel 12462: #get real user name/domain, courseid and symb
12463: my $courseid;
1.359 albertel 12464: my $publicuser;
1.427 www 12465: if ($symbparm) {
12466: $symbparm=&get_symb_from_alias($symbparm);
12467: }
1.218 albertel 12468: if (!($uname && $udom)) {
1.790 albertel 12469: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 12470: if (!$symbparm) { $symbparm=$cursymb; }
12471: } else {
1.620 albertel 12472: $courseid=$env{'request.course.id'};
1.218 albertel 12473: }
1.48 www 12474: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12475: my $rest;
1.320 albertel 12476: if (defined($therest[0])) {
1.48 www 12477: $rest=join('.',@therest);
12478: } else {
12479: $rest='';
12480: }
1.320 albertel 12481:
1.57 www 12482: my $qualifierrest=$qualifier;
12483: if ($rest) { $qualifierrest.='.'.$rest; }
12484: my $spacequalifierrest=$space;
12485: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 12486: if ($realm eq 'user') {
1.48 www 12487: # --------------------------------------------------------------- user.resource
12488: if ($space eq 'resource') {
1.651 albertel 12489: if ( (defined($Apache::lonhomework::parsing_a_problem)
12490: || defined($Apache::lonhomework::parsing_a_task))
12491: &&
1.1469 raeburn 12492: ($symbparm eq &symbread()) ) {
1.744 albertel 12493: # if we are in the middle of processing the resource the
12494: # get the value we are planning on committing
12495: if (defined($Apache::lonhomework::results{$qualifierrest})) {
12496: return $Apache::lonhomework::results{$qualifierrest};
12497: } else {
12498: return $Apache::lonhomework::history{$qualifierrest};
12499: }
1.335 albertel 12500: } else {
1.359 albertel 12501: my %restored;
1.620 albertel 12502: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 12503: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12504: } else {
12505: %restored=&restore($symbparm,$courseid,$udom,$uname);
12506: }
1.335 albertel 12507: return $restored{$qualifierrest};
12508: }
1.48 www 12509: # ----------------------------------------------------------------- user.access
12510: } elsif ($space eq 'access') {
1.218 albertel 12511: # FIXME - not supporting calls for a specific user
1.48 www 12512: return &allowed($qualifier,$rest);
12513: # ------------------------------------------ user.preferences, user.environment
12514: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 12515: if (($uname eq $env{'user.name'}) &&
12516: ($udom eq $env{'user.domain'})) {
12517: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 12518: } else {
1.359 albertel 12519: my %returnhash;
12520: if (!$publicuser) {
12521: %returnhash=&userenvironment($udom,$uname,
12522: $qualifierrest);
12523: }
1.218 albertel 12524: return $returnhash{$qualifierrest};
12525: }
1.48 www 12526: # ----------------------------------------------------------------- user.course
12527: } elsif ($space eq 'course') {
1.218 albertel 12528: # FIXME - not supporting calls for a specific user
1.620 albertel 12529: return $env{join('.',('request.course',$qualifier))};
1.48 www 12530: # ------------------------------------------------------------------- user.role
12531: } elsif ($space eq 'role') {
1.218 albertel 12532: # FIXME - not supporting calls for a specific user
1.620 albertel 12533: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 12534: if ($qualifier eq 'value') {
12535: return $role;
12536: } elsif ($qualifier eq 'extent') {
12537: return $where;
12538: }
12539: # ----------------------------------------------------------------- user.domain
12540: } elsif ($space eq 'domain') {
1.218 albertel 12541: return $udom;
1.48 www 12542: # ------------------------------------------------------------------- user.name
12543: } elsif ($space eq 'name') {
1.218 albertel 12544: return $uname;
1.48 www 12545: # ---------------------------------------------------- Any other user namespace
1.29 www 12546: } else {
1.359 albertel 12547: my %reply;
12548: if (!$publicuser) {
12549: %reply=&get($space,[$qualifierrest],$udom,$uname);
12550: }
12551: return $reply{$qualifierrest};
1.48 www 12552: }
1.236 www 12553: } elsif ($realm eq 'query') {
12554: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 12555: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12556: [$spacequalifierrest]);
1.620 albertel 12557: return $env{'form.'.$spacequalifierrest};
1.236 www 12558: } elsif ($realm eq 'request') {
1.48 www 12559: # ------------------------------------------------------------- request.browser
12560: if ($space eq 'browser') {
1.1145 bisitz 12561: return $env{'browser.'.$qualifier};
1.57 www 12562: # ------------------------------------------------------------ request.filename
12563: } else {
1.620 albertel 12564: return $env{'request.'.$spacequalifierrest};
1.29 www 12565: }
1.28 www 12566: } elsif ($realm eq 'course') {
1.48 www 12567: # ---------------------------------------------------------- course.description
1.620 albertel 12568: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 12569: } elsif ($realm eq 'resource') {
1.165 www 12570:
1.620 albertel 12571: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 12572: if (!$symbparm) { $symbparm=&symbread(); }
12573: }
1.693 albertel 12574:
1.1232 raeburn 12575: if ($qualifier eq '') {
12576: if ($space eq 'title') {
12577: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12578: return &gettitle($symbparm);
12579: }
1.693 albertel 12580:
1.1232 raeburn 12581: if ($space eq 'map') {
12582: my ($map) = &decode_symb($symbparm);
12583: return &symbread($map);
12584: }
12585: if ($space eq 'maptitle') {
12586: my ($map) = &decode_symb($symbparm);
12587: return &gettitle($map);
12588: }
12589: if ($space eq 'filename') {
12590: if ($symbparm) {
12591: return &clutter((&decode_symb($symbparm))[2]);
12592: }
12593: return &hreflocation('',$env{'request.filename'});
1.905 albertel 12594: }
1.1232 raeburn 12595:
1.1233 raeburn 12596: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12597: if ($space eq 'visibleparts') {
12598: my $navmap = Apache::lonnavmaps::navmap->new();
12599: my $item;
12600: if (ref($navmap)) {
12601: my $res = $navmap->getBySymb($symbparm);
12602: my $parts = $res->parts();
12603: if (ref($parts) eq 'ARRAY') {
12604: $item = join(',',@{$parts});
12605: }
12606: undef($navmap);
1.1232 raeburn 12607: }
1.1233 raeburn 12608: return $item;
1.1232 raeburn 12609: }
12610: }
12611: }
1.693 albertel 12612:
1.1301 raeburn 12613: my ($section, $group, @groups, @recurseup, $recursed);
1.1461 raeburn 12614: if (ref($recurseupref) eq 'ARRAY') {
12615: @recurseup = @{$recurseupref};
12616: $recursed = 1;
12617: }
1.1301 raeburn 12618: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 12619: if (($courseid eq '') && ($cid)) {
12620: $courseid = $cid;
12621: }
12622: if (($symbparm && $courseid) &&
12623: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 12624:
1.218 albertel 12625: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 12626:
1.60 www 12627: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 12628: my $symbp=$symbparm;
1.1301 raeburn 12629: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 12630: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 12631: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 12632: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 12633: if (($env{'user.name'} eq $uname) &&
12634: ($env{'user.domain'} eq $udom)) {
12635: $section=$env{'request.course.sec'};
1.733 raeburn 12636: @groups = split(/:/,$env{'request.course.groups'});
12637: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 12638: } else {
1.539 albertel 12639: if (! defined($usection)) {
1.551 albertel 12640: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 12641: } else {
12642: $section = $usection;
12643: }
1.733 raeburn 12644: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 12645: }
12646:
12647: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12648: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 12649: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 12650: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12651:
1.593 albertel 12652: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 12653: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 12654: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 12655: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 12656:
1.60 www 12657: # ----------------------------------------------------------- first, check user
1.624 albertel 12658:
1.1301 raeburn 12659: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12660: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 12661: ([$courselevelr,'resource'],
12662: [$courselevelm,'map' ],
1.1301 raeburn 12663: [$courseleveli,'map' ],
1.927 albertel 12664: [$courselevel, 'course' ]));
1.931 albertel 12665: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 12666:
1.594 albertel 12667: # ------------------------------------------------ second, check some of course
1.684 raeburn 12668: my $coursereply;
1.691 raeburn 12669: if (@groups > 0) {
12670: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 12671: $recurseparm,$mapparm,$spacequalifierrest,
12672: $mapp,\$recursed,\@recurseup);
12673: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 12674: }
1.96 www 12675:
1.684 raeburn 12676: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 12677: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12678: 'course',$mapp,\$recursed,\@recurseup,
12679: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 12680: ([$seclevelr, 'resource'],
12681: [$seclevelm, 'map' ],
1.1301 raeburn 12682: [$secleveli, 'map' ],
1.927 albertel 12683: [$seclevel, 'course' ],
12684: [$courselevelr,'resource']));
12685: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 12686:
1.60 www 12687: # ------------------------------------------------------ third, check map parms
1.218 albertel 12688: my %parmhash=();
12689: my $thisparm='';
12690: if (tie(%parmhash,'GDBM_File',
1.620 albertel 12691: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 12692: &GDBM_READER(),0640)) {
1.218 albertel 12693: $thisparm=$parmhash{$symbparm};
12694: untie(%parmhash);
12695: }
1.927 albertel 12696: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 12697: }
1.594 albertel 12698: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 12699:
12700: my $what = $spacequalifierrest;
12701: $what=~s/\./\_/;
1.282 albertel 12702: my $filename;
12703: if (!$symbparm) { $symbparm=&symbread(); }
12704: if ($symbparm) {
1.409 www 12705: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 12706: } else {
1.620 albertel 12707: $filename=$env{'request.filename'};
1.282 albertel 12708: }
1.1362 raeburn 12709: my $toolsymb;
12710: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12711: $toolsymb = $symbparm;
12712: }
12713: my $metadata=&metadata($filename,$what,$toolsymb);
1.927 albertel 12714: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362 raeburn 12715: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927 albertel 12716: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 12717:
1.1301 raeburn 12718: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 12719: if ($symbparm && defined($courseid) &&
1.620 albertel 12720: $courseid eq $env{'request.course.id'}) {
1.624 albertel 12721: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12722: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12723: 'course',$mapp,\$recursed,\@recurseup,
12724: $courseid,'.',$spacequalifierrest,
1.927 albertel 12725: ([$courselevelm,'map' ],
1.1301 raeburn 12726: [$courseleveli,'map' ],
1.927 albertel 12727: [$courselevel, 'course']));
12728: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 12729: }
1.145 www 12730: # ------------------------------------------------------------------ Cascade up
1.218 albertel 12731: unless ($space eq '0') {
1.336 albertel 12732: my @parts=split(/_/,$space);
12733: my $id=pop(@parts);
12734: my $part=join('_',@parts);
12735: if ($part eq '') { $part='0'; }
1.927 albertel 12736: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 12737: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 12738: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 12739: }
1.395 albertel 12740: if ($recurse) { return undef; }
1.1362 raeburn 12741: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927 albertel 12742: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 12743: # ---------------------------------------------------- Any other user namespace
12744: } elsif ($realm eq 'environment') {
12745: # ----------------------------------------------------------------- environment
1.620 albertel 12746: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12747: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 12748: } else {
1.770 albertel 12749: if ($uname eq 'anonymous' && $udom eq '') {
12750: return '';
12751: }
1.219 albertel 12752: my %returnhash=&userenvironment($udom,$uname,
12753: $spacequalifierrest);
12754: return $returnhash{$spacequalifierrest};
12755: }
1.28 www 12756: } elsif ($realm eq 'system') {
1.48 www 12757: # ----------------------------------------------------------------- system.time
12758: if ($space eq 'time') {
12759: return time;
12760: }
1.696 albertel 12761: } elsif ($realm eq 'server') {
12762: # ----------------------------------------------------------------- system.time
12763: if ($space eq 'name') {
12764: return $ENV{'SERVER_NAME'};
12765: }
1.1415 raeburn 12766: } elsif ($realm eq 'client') {
12767: if ($space eq 'remote_addr') {
1.1441 raeburn 12768: return &get_requestor_ip();
1.1415 raeburn 12769: }
1.28 www 12770: }
1.48 www 12771: return '';
1.61 www 12772: }
12773:
1.927 albertel 12774: sub get_reply {
12775: my ($reply_value) = @_;
1.940 raeburn 12776: if (ref($reply_value) eq 'ARRAY') {
12777: if (wantarray) {
12778: return @$reply_value;
12779: }
12780: return $reply_value->[0];
12781: } else {
12782: return $reply_value;
1.927 albertel 12783: }
12784: }
12785:
1.691 raeburn 12786: sub check_group_parms {
1.1301 raeburn 12787: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12788: $recursed,$recurseupref) = @_;
12789: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12790: [$what,'course']);
12791: my $coursereply;
1.691 raeburn 12792: foreach my $group (@{$groups}) {
1.1301 raeburn 12793: my @groupitems = ();
1.691 raeburn 12794: foreach my $level (@levels) {
1.927 albertel 12795: my $item = $courseid.'.['.$group.'].'.$level->[0];
12796: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 12797: }
1.1301 raeburn 12798: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12799: $env{'course.'.$courseid.'.domain'},
12800: 'course',$mapp,$recursed,$recurseupref,
12801: $courseid,'.['.$group.'].',$what,
12802: @groupitems);
12803: last if (defined($coursereply));
1.691 raeburn 12804: }
12805: return $coursereply;
12806: }
12807:
1.1301 raeburn 12808: sub get_map_hierarchy {
1.1302 raeburn 12809: my ($mapname,$courseid) = @_;
12810: my @recurseup = ();
1.1301 raeburn 12811: if ($mapname) {
1.1302 raeburn 12812: if (($cachedmapkey eq $courseid) &&
12813: (abs($cachedmaptime-time)<5)) {
12814: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12815: return @{$cachedmaps{$mapname}};
12816: }
12817: }
1.1301 raeburn 12818: my $navmap = Apache::lonnavmaps::navmap->new();
12819: if (ref($navmap)) {
12820: @recurseup = $navmap->recurseup_maps($mapname);
12821: undef($navmap);
1.1302 raeburn 12822: $cachedmaps{$mapname} = \@recurseup;
12823: $cachedmaptime=time;
12824: $cachedmapkey=$courseid;
1.1301 raeburn 12825: }
12826: }
12827: return @recurseup;
12828: }
12829:
1.1302 raeburn 12830: }
12831:
1.691 raeburn 12832: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 12833: my ($courseid,@groups) = @_;
12834: @groups = sort(@groups);
1.691 raeburn 12835: return @groups;
12836: }
12837:
1.395 albertel 12838: sub packages_tab_default {
1.1362 raeburn 12839: my ($uri,$varname,$toolsymb)=@_;
1.395 albertel 12840: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 12841:
12842: my (@extension,@specifics,$do_default);
1.1362 raeburn 12843: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395 albertel 12844: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 12845: if ($pack_type eq 'default') {
12846: $do_default=1;
12847: } elsif ($pack_type eq 'extension') {
12848: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 12849: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 12850: # only look at packages defaults for packages that this id is
1.738 albertel 12851: push(@specifics,[$package,$pack_type,$pack_part]);
12852: }
12853: }
12854: # first look for a package that matches the requested part id
12855: foreach my $package (@specifics) {
12856: my (undef,$pack_type,$pack_part)=@{$package};
12857: next if ($pack_part ne $part);
12858: if (defined($packagetab{"$pack_type&$name&default"})) {
12859: return $packagetab{"$pack_type&$name&default"};
12860: }
12861: }
12862: # look for any possible matching non extension_ package
12863: foreach my $package (@specifics) {
12864: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 12865: if (defined($packagetab{"$pack_type&$name&default"})) {
12866: return $packagetab{"$pack_type&$name&default"};
12867: }
1.585 albertel 12868: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 12869: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12870: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 12871: }
12872: }
1.738 albertel 12873: # look for any posible extension_ match
12874: foreach my $package (@extension) {
12875: my ($package,$pack_type)=@{$package};
12876: if (defined($packagetab{"$pack_type&$name&default"})) {
12877: return $packagetab{"$pack_type&$name&default"};
12878: }
12879: if (defined($packagetab{$package."&$name&default"})) {
12880: return $packagetab{$package."&$name&default"};
12881: }
12882: }
12883: # look for a global default setting
12884: if ($do_default && defined($packagetab{"default&$name&default"})) {
12885: return $packagetab{"default&$name&default"};
12886: }
1.395 albertel 12887: return undef;
12888: }
12889:
1.334 albertel 12890: sub add_prefix_and_part {
12891: my ($prefix,$part)=@_;
12892: my $keyroot;
12893: if (defined($prefix) && $prefix !~ /^__/) {
12894: # prefix that has a part already
12895: $keyroot=$prefix;
12896: } elsif (defined($prefix)) {
12897: # prefix that is missing a part
12898: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12899: } else {
12900: # no prefix at all
12901: if (defined($part)) { $keyroot='_'.$part; }
12902: }
12903: return $keyroot;
12904: }
12905:
1.71 www 12906: # ---------------------------------------------------------------- Get metadata
12907:
1.599 albertel 12908: my %metaentry;
1.1070 www 12909: my %importedpartids;
1.1369 raeburn 12910: my %importedrespids;
1.71 www 12911: sub metadata {
1.1362 raeburn 12912: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71 www 12913: $uri=&declutter($uri);
1.288 albertel 12914: # if it is a non metadata possible uri return quickly
1.529 albertel 12915: if (($uri eq '') ||
12916: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 12917: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 12918: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 12919: return undef;
12920: }
1.1261 raeburn 12921: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 12922: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 12923: return undef;
1.288 albertel 12924: }
1.73 www 12925: my $filename=$uri;
12926: $uri=~s/\.meta$//;
1.172 www 12927: #
12928: # Is the metadata already cached?
1.177 www 12929: # Look at timestamp of caching
1.172 www 12930: # Everything is cached by the main uri, libraries are never directly cached
12931: #
1.428 albertel 12932: if (!defined($liburi)) {
1.599 albertel 12933: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 12934: if (defined($cached)) { return $result->{':'.$what}; }
12935: }
1.1362 raeburn 12936:
12937: #
12938: # If the uri is for an external tool the file from
12939: # which metadata should be retrieved depends on whether
12940: # the tool had been configured to be gradable (set in the Course
12941: # Editor or Resource Editor).
12942: #
12943: # If a valid symb has been included as the third arg in the call
12944: # to &metadata() that can be used to retrieve the value of
12945: # parameter_0_gradable set for the resource, and included in the
12946: # uploaded map containing the tool. The value is retrieved via
12947: # &EXT(), if a valid symb is available. Otherwise the value of
12948: # gradable in the exttool_$marker.db file for the tool instance
1.1364 raeburn 12949: # is retrieved via &get().
12950: #
12951: # When lonuserstate::traceroute() calls lonnet::EXT() for
12952: # hiddenresource and encrypturl (during course initialization)
12953: # the map-level parameter for resource.0.gradable included in the
12954: # uploaded map containing the tool will not yet have been stored
12955: # in the user_course_parms.db file for the user's session, so in
12956: # this case fall back to retrieving gradable status from the
12957: # exttool_$marker.db file.
1.1362 raeburn 12958: #
12959: # In order to avoid an infinite loop, &metadata() will return
12960: # before a call to &EXT(), if the uri is for an external tool
12961: # and the $what for which metadata is being requested is
12962: # parameter_0_gradable or 0_gradable.
12963: #
12964:
12965: if ($uri =~ /ext\.tool$/) {
12966: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12967: return;
12968: } else {
12969: my ($checked,$use_passback);
12970: if ($toolsymb ne '') {
12971: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364 raeburn 12972: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362 raeburn 12973: $checked = 1;
12974: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12975: $use_passback = 1;
12976: }
12977: }
12978: }
12979: unless ($checked) {
12980: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12981: $marker=~s/\D//g;
1.1363 raeburn 12982: if ($marker) {
1.1362 raeburn 12983: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12984: $use_passback = $toolsettings{'gradable'};
12985: }
12986: }
12987: if ($use_passback) {
12988: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12989: } else {
12990: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12991: }
12992: }
12993: }
12994:
1.428 albertel 12995: {
1.1069 www 12996: # Imported parts would go here
1.1369 raeburn 12997: my @origfiletagids=();
1.1069 www 12998: my $importedparts=0;
1.1369 raeburn 12999:
13000: # Imported responseids would go here
13001: my $importedresponses=0;
1.172 www 13002: #
13003: # Is this a recursive call for a library?
13004: #
1.599 albertel 13005: # if (! exists($metacache{$uri})) {
13006: # $metacache{$uri}={};
13007: # }
1.924 albertel 13008: my $cachetime = 60*60;
1.171 www 13009: if ($liburi) {
13010: $liburi=&declutter($liburi);
13011: $filename=$liburi;
1.401 bowersj2 13012: } else {
1.599 albertel 13013: &devalidate_cache_new('meta',$uri);
13014: undef(%metaentry);
1.401 bowersj2 13015: }
1.140 www 13016: my %metathesekeys=();
1.73 www 13017: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 13018: my $metastring;
1.1140 www 13019: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 13020: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 13021: $metastring =
1.929 albertel 13022: &Apache::lonnet::ssi_body($which,
1.924 albertel 13023: ('grade_target' => 'meta'));
13024: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 13025: } elsif (($uri !~ m -^(editupload)/-) &&
13026: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 13027: my $file=&filelocation('',&clutter($filename));
1.599 albertel 13028: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 13029: $metastring=&getfile($file);
1.489 albertel 13030: }
1.208 albertel 13031: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 13032: my $token;
1.140 www 13033: undef %metathesekeys;
1.71 www 13034: while ($token=$parser->get_token) {
1.339 albertel 13035: if ($token->[0] eq 'S') {
13036: if (defined($token->[2]->{'package'})) {
1.172 www 13037: #
13038: # This is a package - get package info
13039: #
1.339 albertel 13040: my $package=$token->[2]->{'package'};
13041: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13042: if (defined($token->[2]->{'id'})) {
13043: $keyroot.='_'.$token->[2]->{'id'};
13044: }
1.599 albertel 13045: if ($metaentry{':packages'}) {
13046: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 13047: } else {
1.599 albertel 13048: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 13049: }
1.736 albertel 13050: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 13051: my $part=$keyroot;
13052: $part=~s/^\_//;
1.736 albertel 13053: if ($pack_entry=~/^\Q$package\E\&/ ||
13054: $pack_entry=~/^\Q$package\E_0\&/) {
13055: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 13056: # ignore package.tab specified default values
13057: # here &package_tab_default() will fetch those
13058: if ($subp eq 'default') { next; }
1.736 albertel 13059: my $value=$packagetab{$pack_entry};
1.432 albertel 13060: my $unikey;
13061: if ($pack =~ /_0$/) {
13062: $unikey='parameter_0_'.$name;
13063: $part=0;
13064: } else {
13065: $unikey='parameter'.$keyroot.'_'.$name;
13066: }
1.339 albertel 13067: if ($subp eq 'display') {
13068: $value.=' [Part: '.$part.']';
13069: }
1.599 albertel 13070: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 13071: $metathesekeys{$unikey}=1;
1.599 albertel 13072: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13073: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 13074: }
1.599 albertel 13075: if (defined($metaentry{':'.$unikey.'.default'})) {
13076: $metaentry{':'.$unikey}=
13077: $metaentry{':'.$unikey.'.default'};
1.356 albertel 13078: }
1.339 albertel 13079: }
13080: }
13081: } else {
1.172 www 13082: #
13083: # This is not a package - some other kind of start tag
1.339 albertel 13084: #
13085: my $entry=$token->[1];
1.1068 www 13086: my $unikey='';
1.175 www 13087:
1.339 albertel 13088: if ($entry eq 'import') {
1.175 www 13089: #
13090: # Importing a library here
1.339 albertel 13091: #
1.1067 www 13092: my $location=$parser->get_text('/import');
13093: my $dir=$filename;
13094: $dir=~s|[^/]*$||;
13095: $location=&filelocation($dir,$location);
1.1369 raeburn 13096:
13097: my $importid=$token->[2]->{'id'};
1.1068 www 13098: my $importmode=$token->[2]->{'importmode'};
1.1369 raeburn 13099: #
13100: # Check metadata for imported file to
13101: # see if it contained response items
13102: #
1.1372 raeburn 13103: my ($origfile,@libfilekeys);
1.1370 raeburn 13104: my %currmetaentry = %metaentry;
1.1372 raeburn 13105: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13106: $depthcount+1));
13107: if (grep(/^responseorder$/,@libfilekeys)) {
13108: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13109: undef,$depthcount+1);
13110: if ($libresponseorder ne '') {
13111: if ($#origfiletagids<0) {
13112: undef(%importedrespids);
13113: undef(%importedpartids);
13114: }
1.1373 raeburn 13115: my @respids = split(/\s*,\s*/,$libresponseorder);
13116: if (@respids) {
13117: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13118: }
13119: if ($importedrespids{$importid} ne '') {
1.1372 raeburn 13120: $importedresponses = 1;
1.1369 raeburn 13121: # We need to get the original file and the imported file to get the response order correct
13122: # Load and inspect original file
1.1372 raeburn 13123: if ($#origfiletagids<0) {
13124: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13125: $origfile=&getfile($origfilelocation);
13126: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13127: }
1.1369 raeburn 13128: }
13129: }
13130: }
1.1370 raeburn 13131: # Do not overwrite contents of %metaentry hash for resource itself with
13132: # hash populated for imported library file
13133: %metaentry = %currmetaentry;
13134: undef(%currmetaentry);
1.1374 raeburn 13135: if ($importmode eq 'part') {
1.1068 www 13136: # Import as part(s)
1.1069 www 13137: $importedparts=1;
13138: # We need to get the original file and the imported file to get the part order correct
13139: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369 raeburn 13140: # Load and inspect original file if we didn't do that already
13141: if ($#origfiletagids<0) {
13142: undef(%importedrespids);
13143: undef(%importedpartids);
13144: if ($origfile eq '') {
13145: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13146: $origfile=&getfile($origfilelocation);
13147: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13148: }
1.1070 www 13149: }
1.1372 raeburn 13150: my @impfilepartids;
13151: # If <partorder> tag is included in metadata for the imported file
13152: # get the parts in the imported file from that.
13153: if (grep(/^partorder$/,@libfilekeys)) {
13154: %currmetaentry = %metaentry;
13155: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13156: $depthcount+1);
13157: %metaentry = %currmetaentry;
13158: undef(%currmetaentry);
13159: if ($libpartorder ne '') {
13160: @impfilepartids=split(/\s*,\s*/,$libpartorder);
13161: }
13162: } else {
13163: # If no <partorder> tag available, load and inspect imported file
13164: my $impfile=&getfile($location);
13165: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13166: }
1.1069 www 13167: if ($#impfilepartids>=0) {
13168: # This problem had parts
1.1070 www 13169: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 13170: } else {
13171: # Importing by turning a single problem into a problem part
13172: # It gets the import-tags ID as part-ID
13173: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 13174: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 13175: }
1.1068 www 13176: } else {
1.1374 raeburn 13177: # Import as problem or as normal import
13178: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13179: unless ($importmode eq 'problem') {
1.1068 www 13180: # Normal import
1.1374 raeburn 13181: if (defined($token->[2]->{'id'})) {
13182: $unikey.='_'.$token->[2]->{'id'};
13183: }
13184: }
13185: # Check metadata for imported file to
13186: # see if it contained parts
13187: if (grep(/^partorder$/,@libfilekeys)) {
13188: %currmetaentry = %metaentry;
13189: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13190: $depthcount+1);
13191: %metaentry = %currmetaentry;
13192: undef(%currmetaentry);
13193: if ($libpartorder ne '') {
13194: $importedparts = 1;
13195: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13196: }
13197: }
1.1067 www 13198: }
1.339 albertel 13199: if ($depthcount<20) {
1.736 albertel 13200: my $metadata =
1.1362 raeburn 13201: &metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736 albertel 13202: $depthcount+1);
13203: foreach my $meta (split(',',$metadata)) {
13204: $metaentry{':'.$meta}=$metaentry{':'.$meta};
13205: $metathesekeys{$meta}=1;
1.339 albertel 13206: }
1.1068 www 13207: }
1.1067 www 13208: } else {
13209: #
13210: # Not importing, some other kind of non-package, non-library start tag
13211: #
13212: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13213: if (defined($token->[2]->{'id'})) {
13214: $unikey.='_'.$token->[2]->{'id'};
13215: }
1.339 albertel 13216: if (defined($token->[2]->{'name'})) {
13217: $unikey.='_'.$token->[2]->{'name'};
13218: }
13219: $metathesekeys{$unikey}=1;
1.736 albertel 13220: foreach my $param (@{$token->[3]}) {
13221: $metaentry{':'.$unikey.'.'.$param} =
13222: $token->[2]->{$param};
1.339 albertel 13223: }
13224: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 13225: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 13226: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13227: # only ws inside the tag, and not in default, so use default
13228: # as value
1.599 albertel 13229: $metaentry{':'.$unikey}=$default;
1.908 albertel 13230: } elsif ( $internaltext =~ /\S/ ) {
13231: # something interesting inside the tag
13232: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 13233: } else {
1.908 albertel 13234: # no interesting values, don't set a default
1.339 albertel 13235: }
1.172 www 13236: # end of not-a-package not-a-library import
1.339 albertel 13237: }
1.172 www 13238: # end of not-a-package start tag
1.339 albertel 13239: }
1.172 www 13240: # the next is the end of "start tag"
1.339 albertel 13241: }
13242: }
1.483 albertel 13243: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 13244: $extension = lc($extension);
13245: if ($extension eq 'htm') { $extension='html'; }
13246:
1.737 albertel 13247: foreach my $key (keys(%packagetab)) {
1.483 albertel 13248: #no specific packages #how's our extension
13249: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 13250: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 13251: \%metathesekeys);
13252: }
1.883 albertel 13253:
13254: if (!exists($metaentry{':packages'})
13255: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 13256: foreach my $key (keys(%packagetab)) {
1.483 albertel 13257: #no specific packages well let's get default then
13258: if ($key!~/^default&/) { next; }
1.488 albertel 13259: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 13260: \%metathesekeys);
13261: }
13262: }
1.338 www 13263: # are there custom rights to evaluate
1.599 albertel 13264: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 13265:
1.338 www 13266: #
13267: # Importing a rights file here
1.339 albertel 13268: #
13269: unless ($depthcount) {
1.599 albertel 13270: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 13271: my $dir=$filename;
13272: $dir=~s|[^/]*$||;
13273: $location=&filelocation($dir,$location);
1.736 albertel 13274: my $rights_metadata =
1.1362 raeburn 13275: &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736 albertel 13276: $depthcount+1);
13277: foreach my $rights (split(',',$rights_metadata)) {
13278: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13279: $metathesekeys{$rights}=1;
1.339 albertel 13280: }
13281: }
13282: }
1.737 albertel 13283: # uniqifiy package listing
13284: my %seen;
13285: my @uniq_packages =
13286: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13287: $metaentry{':packages'} = join(',',@uniq_packages);
13288:
1.1369 raeburn 13289: if (($importedresponses) || ($importedparts)) {
13290: if ($importedparts) {
1.1070 www 13291: # We had imported parts and need to rebuild partorder
1.1369 raeburn 13292: $metaentry{':partorder'}='';
13293: $metathesekeys{'partorder'}=1;
13294: }
13295: if ($importedresponses) {
13296: # We had imported responses and need to rebuil responseorder
13297: $metaentry{':responseorder'}='';
13298: $metathesekeys{'responseorder'}=1;
13299: }
13300: for (my $index=0;$index<$#origfiletagids;$index+=2) {
13301: my $origid = $origfiletagids[$index+1];
13302: if ($origfiletagids[$index] eq 'part') {
13303: # Original part, part of the problem
13304: if ($importedparts) {
13305: $metaentry{':partorder'}.=','.$origid;
13306: }
13307: } elsif ($origfiletagids[$index] eq 'import') {
13308: if ($importedparts) {
13309: # We have imported parts at this position
1.1373 raeburn 13310: if ($importedpartids{$origid} ne '') {
13311: $metaentry{':partorder'}.=','.$importedpartids{$origid};
13312: }
1.1369 raeburn 13313: }
13314: if ($importedresponses) {
13315: # We have imported responses at this position
1.1373 raeburn 13316: if ($importedrespids{$origid} ne '') {
13317: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369 raeburn 13318: }
13319: }
13320: } else {
13321: # Original response item, part of the problem
13322: if ($importedresponses) {
13323: $metaentry{':responseorder'}.=','.$origid;
13324: }
13325: }
13326: }
13327: if ($importedparts) {
13328: $metaentry{':partorder'}=~s/^\,//;
13329: }
13330: if ($importedresponses) {
13331: $metaentry{':responseorder'}=~s/^\,//;
13332: }
1.1070 www 13333: }
1.737 albertel 13334: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 13335: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 13336: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371 raeburn 13337: unless ($liburi) {
13338: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13339: }
1.177 www 13340: # this is the end of "was not already recently cached
1.71 www 13341: }
1.599 albertel 13342: return $metaentry{':'.$what};
1.261 albertel 13343: }
13344:
1.488 albertel 13345: sub metadata_create_package_def {
1.483 albertel 13346: my ($uri,$key,$package,$metathesekeys)=@_;
13347: my ($pack,$name,$subp)=split(/\&/,$key);
13348: if ($subp eq 'default') { next; }
13349:
1.599 albertel 13350: if (defined($metaentry{':packages'})) {
13351: $metaentry{':packages'}.=','.$package;
1.483 albertel 13352: } else {
1.599 albertel 13353: $metaentry{':packages'}=$package;
1.483 albertel 13354: }
13355: my $value=$packagetab{$key};
13356: my $unikey;
13357: $unikey='parameter_0_'.$name;
1.599 albertel 13358: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 13359: $$metathesekeys{$unikey}=1;
1.599 albertel 13360: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13361: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 13362: }
1.599 albertel 13363: if (defined($metaentry{':'.$unikey.'.default'})) {
13364: $metaentry{':'.$unikey}=
13365: $metaentry{':'.$unikey.'.default'};
1.483 albertel 13366: }
13367: }
13368:
1.261 albertel 13369: sub metadata_generate_part0 {
13370: my ($metadata,$metacache,$uri) = @_;
13371: my %allnames;
1.737 albertel 13372: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 13373: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 13374: my $part=$$metacache{':'.$metakey.'.part'};
13375: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 13376: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 13377: $allnames{$name}=$part;
13378: }
13379: }
13380: }
13381: foreach my $name (keys(%allnames)) {
13382: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 13383: my $key=":parameter_0_$name";
1.261 albertel 13384: $$metacache{"$key.part"}='0';
13385: $$metacache{"$key.name"}=$name;
1.428 albertel 13386: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 13387: $allnames{$name}.'_'.$name.
13388: '.type'};
1.428 albertel 13389: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 13390: '.display'};
1.644 www 13391: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 13392: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 13393: $$metacache{"$key.display"}=$olddis;
13394: }
1.71 www 13395: }
13396:
1.764 albertel 13397: # ------------------------------------------------------ Devalidate title cache
13398:
13399: sub devalidate_title_cache {
13400: my ($url)=@_;
13401: if (!$env{'request.course.id'}) { return; }
13402: my $symb=&symbread($url);
13403: if (!$symb) { return; }
13404: my $key=$env{'request.course.id'}."\0".$symb;
13405: &devalidate_cache_new('title',$key);
13406: }
13407:
1.1014 droeschl 13408: # ------------------------------------------------- Get the title of a course
13409:
13410: sub current_course_title {
13411: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13412: }
1.301 www 13413: # ------------------------------------------------- Get the title of a resource
13414:
13415: sub gettitle {
13416: my $urlsymb=shift;
13417: my $symb=&symbread($urlsymb);
1.534 albertel 13418: if ($symb) {
1.620 albertel 13419: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 13420: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 13421: if (defined($cached)) {
13422: return $result;
13423: }
1.534 albertel 13424: my ($map,$resid,$url)=&decode_symb($symb);
13425: my $title='';
1.907 albertel 13426: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13427: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13428: } else {
13429: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13430: &GDBM_READER(),0640)) {
13431: my $mapid=$bighash{'map_pc_'.&clutter($map)};
13432: $title=$bighash{'title_'.$mapid.'.'.$resid};
13433: untie(%bighash);
13434: }
1.534 albertel 13435: }
13436: $title=~s/\&colon\;/\:/gs;
13437: if ($title) {
1.1159 www 13438: # Remember both $symb and $title for dynamic metadata
13439: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 13440: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 13441: # Cache this title and then return it
1.599 albertel 13442: return &do_cache_new('title',$key,$title,600);
1.534 albertel 13443: }
13444: $urlsymb=$url;
13445: }
13446: my $title=&metadata($urlsymb,'title');
13447: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
13448: return $title;
1.301 www 13449: }
1.613 albertel 13450:
1.614 albertel 13451: sub get_slot {
13452: my ($which,$cnum,$cdom)=@_;
13453: if (!$cnum || !$cdom) {
1.790 albertel 13454: (undef,my $courseid)=&whichuser();
1.620 albertel 13455: $cdom=$env{'course.'.$courseid.'.domain'};
13456: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 13457: }
1.703 albertel 13458: my $key=join("\0",'slots',$cdom,$cnum,$which);
13459: my %slotinfo;
13460: if (exists($remembered{$key})) {
13461: $slotinfo{$which} = $remembered{$key};
13462: } else {
13463: %slotinfo=&get('slots',[$which],$cdom,$cnum);
13464: &Apache::lonhomework::showhash(%slotinfo);
13465: my ($tmp)=keys(%slotinfo);
13466: if ($tmp=~/^error:/) { return (); }
13467: $remembered{$key} = $slotinfo{$which};
13468: }
1.616 albertel 13469: if (ref($slotinfo{$which}) eq 'HASH') {
13470: return %{$slotinfo{$which}};
13471: }
13472: return $slotinfo{$which};
1.614 albertel 13473: }
1.1150 raeburn 13474:
13475: sub get_reservable_slots {
13476: my ($cnum,$cdom,$uname,$udom) = @_;
13477: my $now = time;
13478: my $reservable_info;
13479: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13480: if (exists($remembered{$key})) {
13481: $reservable_info = $remembered{$key};
13482: } else {
13483: my %resv;
13484: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13485: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13486: $reservable_info = \%resv;
13487: $remembered{$key} = $reservable_info;
13488: }
13489: return $reservable_info;
13490: }
13491:
13492: sub get_course_slots {
13493: my ($cnum,$cdom) = @_;
13494: my $hashid=$cnum.':'.$cdom;
13495: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13496: if (defined($cached)) {
13497: if (ref($result) eq 'HASH') {
13498: return %{$result};
13499: }
13500: } else {
13501: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13502: my ($tmp) = keys(%slots);
13503: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 13504: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 13505: return %slots;
13506: }
13507: }
13508: return;
13509: }
13510:
13511: sub devalidate_slots_cache {
13512: my ($cnum,$cdom)=@_;
13513: my $hashid=$cnum.':'.$cdom;
13514: &devalidate_cache_new('allslots',$hashid);
13515: }
13516:
1.1181 raeburn 13517: sub get_coursechange {
13518: my ($cdom,$cnum) = @_;
13519: if ($cdom eq '' || $cnum eq '') {
13520: return unless ($env{'request.course.id'});
13521: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13522: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13523: }
13524: my $hashid=$cdom.'_'.$cnum;
13525: my ($change,$cached)=&is_cached_new('crschange',$hashid);
13526: if ((defined($cached)) && ($change ne '')) {
13527: return $change;
13528: } else {
13529: my %crshash;
13530: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13531: if ($crshash{'internal.contentchange'} eq '') {
13532: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13533: if ($change eq '') {
13534: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13535: $change = $crshash{'internal.created'};
13536: }
13537: } else {
13538: $change = $crshash{'internal.contentchange'};
13539: }
13540: my $cachetime = 600;
13541: &do_cache_new('crschange',$hashid,$change,$cachetime);
13542: }
13543: return $change;
13544: }
13545:
13546: sub devalidate_coursechange_cache {
13547: my ($cnum,$cdom)=@_;
13548: my $hashid=$cnum.':'.$cdom;
13549: &devalidate_cache_new('crschange',$hashid);
13550: }
13551:
1.31 www 13552: # ------------------------------------------------- Update symbolic store links
13553:
13554: sub symblist {
13555: my ($mapname,%newhash)=@_;
1.438 www 13556: $mapname=&deversion(&declutter($mapname));
1.31 www 13557: my %hash;
1.620 albertel 13558: if (($env{'request.course.fn'}) && (%newhash)) {
13559: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 13560: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 13561: foreach my $url (keys(%newhash)) {
1.711 albertel 13562: next if ($url eq 'last_known'
13563: && $env{'form.no_update_last_known'});
13564: $hash{declutter($url)}=&encode_symb($mapname,
13565: $newhash{$url}->[1],
13566: $newhash{$url}->[0]);
1.191 harris41 13567: }
1.31 www 13568: if (untie(%hash)) {
13569: return 'ok';
13570: }
13571: }
13572: }
13573: return 'error';
1.212 www 13574: }
13575:
13576: # --------------------------------------------------------------- Verify a symb
13577:
13578: sub symbverify {
1.1190 raeburn 13579: my ($symb,$thisurl,$encstate)=@_;
1.510 www 13580: my $thisfn=$thisurl;
1.439 www 13581: $thisfn=&declutter($thisfn);
1.215 www 13582: # direct jump to resource in page or to a sequence - will construct own symbs
13583: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13584: # check URL part
1.409 www 13585: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 13586:
1.431 www 13587: unless ($url eq $thisfn) { return 0; }
1.213 www 13588:
1.216 www 13589: $symb=&symbclean($symb);
1.510 www 13590: $thisurl=&deversion($thisurl);
1.439 www 13591: $thisfn=&deversion($thisfn);
1.213 www 13592:
13593: my %bighash;
13594: my $okay=0;
1.431 www 13595:
1.620 albertel 13596: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13597: &GDBM_READER(),0640)) {
1.1032 raeburn 13598: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13599: $thisurl =~ s/\?.+$//;
1.1204 raeburn 13600: if ($map =~ m{^uploaded/.+\.page$}) {
13601: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13602: $thisurl =~ s{^\Qhttp://https://\E}{https://};
13603: }
13604: }
13605: my $ids;
1.1419 raeburn 13606: if ($map =~ m{^uploaded/.+\.page$}) {
13607: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204 raeburn 13608: } else {
13609: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 13610: }
1.1102 raeburn 13611: unless ($ids) {
13612: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
13613: $ids=$bighash{$idkey};
1.216 www 13614: }
13615: if ($ids) {
13616: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 13617: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 13618: $symb =~ s/\?.+$//;
1.1202 raeburn 13619: }
1.800 albertel 13620: foreach my $id (split(/\,/,$ids)) {
13621: my ($mapid,$resid)=split(/\./,$id);
1.216 www 13622: if (
13623: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 13624: eq $symb) {
13625: if (ref($encstate)) {
13626: $$encstate = $bighash{'encrypted_'.$id};
13627: }
1.620 albertel 13628: if (($env{'request.role.adv'}) ||
1.1101 raeburn 13629: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13630: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 13631: $okay=1;
1.1202 raeburn 13632: last;
1.582 albertel 13633: }
13634: }
1.216 www 13635: }
13636: }
1.213 www 13637: untie(%bighash);
13638: }
13639: return $okay;
1.31 www 13640: }
13641:
1.210 www 13642: # --------------------------------------------------------------- Clean-up symb
13643:
13644: sub symbclean {
13645: my $symb=shift;
1.568 albertel 13646: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 13647: # remove version from map
13648: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 13649:
1.210 www 13650: # remove version from URL
13651: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 13652:
1.507 www 13653: # remove wrapper
13654:
1.510 www 13655: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 13656: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 13657: return $symb;
1.409 www 13658: }
13659:
13660: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 13661:
13662: sub encode_symb {
13663: my ($map,$resid,$url)=@_;
13664: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13665: }
1.409 www 13666:
13667: sub decode_symb {
1.568 albertel 13668: my $symb=shift;
13669: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13670: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 13671: return (&fixversion($map),$resid,&fixversion($url));
13672: }
13673:
13674: sub fixversion {
13675: my $fn=shift;
1.609 banghart 13676: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 13677: my %bighash;
13678: my $uri=&clutter($fn);
1.620 albertel 13679: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 13680: # is this cached?
1.599 albertel 13681: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 13682: if (defined($cached)) { return $result; }
13683: # unfortunately not cached, or expired
1.620 albertel 13684: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 13685: &GDBM_READER(),0640)) {
13686: if ($bighash{'version_'.$uri}) {
13687: my $version=$bighash{'version_'.$uri};
1.444 www 13688: unless (($version eq 'mostrecent') ||
13689: ($version==&getversion($uri))) {
1.440 www 13690: $uri=~s/\.(\w+)$/\.$version\.$1/;
13691: }
13692: }
13693: untie %bighash;
1.413 www 13694: }
1.599 albertel 13695: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 13696: }
13697:
13698: sub deversion {
13699: my $url=shift;
13700: $url=~s/\.\d+\.(\w+)$/\.$1/;
13701: return $url;
1.210 www 13702: }
13703:
1.31 www 13704: # ------------------------------------------------------ Return symb list entry
13705:
13706: sub symbread {
1.1424 raeburn 13707: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427 raeburn 13708: $ignoresymbdb,$noenccheck)=@_;
1.1265 raeburn 13709: my $cache_str='request.symbread.cached.'.$thisfn;
1.1427 raeburn 13710: if (defined($env{$cache_str})) {
1.1424 raeburn 13711: unless (ref($possibles) eq 'HASH') {
13712: if ($ignorecachednull) {
13713: return $env{$cache_str} unless ($env{$cache_str} eq '');
13714: } else {
13715: return $env{$cache_str};
13716: }
1.1282 raeburn 13717: }
13718: }
1.242 www 13719: # no filename provided? try from environment
1.1265 raeburn 13720: unless ($thisfn) {
1.620 albertel 13721: if ($env{'request.symb'}) {
1.1427 raeburn 13722: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 13723: }
1.620 albertel 13724: $thisfn=$env{'request.filename'};
1.44 www 13725: }
1.569 albertel 13726: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 13727: # is that filename actually a symb? Verify, clean, and return
13728: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 13729: if (&symbverify($thisfn,$1)) {
1.1427 raeburn 13730: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 13731: }
1.242 www 13732: }
1.44 www 13733: $thisfn=declutter($thisfn);
1.31 www 13734: my %hash;
1.37 www 13735: my %bighash;
13736: my $syval='';
1.620 albertel 13737: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 13738: my $targetfn = $thisfn;
1.609 banghart 13739: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 13740: $targetfn = 'adm/wrapper/'.$thisfn;
13741: }
1.687 albertel 13742: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13743: $targetfn=$1;
13744: }
1.1427 raeburn 13745: unless ($ignoresymbdb) {
1.1424 raeburn 13746: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13747: &GDBM_READER(),0640)) {
13748: $syval=$hash{$targetfn};
13749: untie(%hash);
13750: }
1.1427 raeburn 13751: if ($syval && $checkforblock) {
13752: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424 raeburn 13753: if (@blockers) {
13754: $syval='';
13755: }
13756: }
1.37 www 13757: }
13758: # ---------------------------------------------------------- There was an entry
13759: if ($syval) {
1.601 albertel 13760: #unless ($syval=~/\_\d+$/) {
1.620 albertel 13761: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 13762: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13763: #return $env{$cache_str}='';
1.601 albertel 13764: #}
13765: #$syval.=$1;
13766: #}
1.37 www 13767: } else {
13768: # ------------------------------------------------------- Was not in symb table
1.620 albertel 13769: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13770: &GDBM_READER(),0640)) {
1.37 www 13771: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 13772: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 13773: unless ($ids) {
13774: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 13775: }
13776: unless ($ids) {
13777: # alias?
13778: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 13779: }
1.37 www 13780: if ($ids) {
13781: # ------------------------------------------------------------------- Has ID(s)
13782: my @possibilities=split(/\,/,$ids);
1.39 www 13783: if ($#possibilities==0) {
13784: # ----------------------------------------------- There is only one possibility
1.37 www 13785: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 13786: $syval=&encode_symb($bighash{'map_id_'.$mapid},
13787: $resid,$thisfn);
1.1282 raeburn 13788: if (ref($possibles) eq 'HASH') {
1.1424 raeburn 13789: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13790: $possibles->{$syval} = 1;
13791: }
1.1282 raeburn 13792: }
13793: if ($checkforblock) {
1.1424 raeburn 13794: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426 raeburn 13795: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424 raeburn 13796: if (@blockers) {
13797: $syval = '';
1.1425 raeburn 13798: untie(%bighash);
13799: return $env{$cache_str}='';
1.1424 raeburn 13800: }
1.1282 raeburn 13801: }
13802: }
13803: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 13804: # ------------------------------------------ There is more than one possibility
13805: my $realpossible=0;
1.800 albertel 13806: foreach my $id (@possibilities) {
13807: my $file=$bighash{'src_'.$id};
1.1282 raeburn 13808: my $canaccess;
13809: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13810: $canaccess = 1;
13811: } else {
13812: $canaccess = &allowed('bre',$file);
13813: }
13814: if ($canaccess) {
13815: my ($mapid,$resid)=split(/\./,$id);
13816: if ($bighash{'map_type_'.$mapid} ne 'page') {
13817: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13818: $resid,$thisfn);
1.1424 raeburn 13819: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426 raeburn 13820: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282 raeburn 13821: if ($checkforblock) {
1.1426 raeburn 13822: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424 raeburn 13823: if (@blockers > 0) {
13824: $syval = '';
13825: } else {
1.1282 raeburn 13826: $syval = $poss_syval;
13827: $realpossible++;
13828: }
13829: } else {
13830: $syval = $poss_syval;
13831: $realpossible++;
13832: }
1.1424 raeburn 13833: if ($syval) {
13834: if (ref($possibles) eq 'HASH') {
13835: $possibles->{$syval} = 1;
13836: }
13837: }
1.1282 raeburn 13838: }
1.39 www 13839: }
1.191 harris41 13840: }
1.39 www 13841: if ($realpossible!=1) { $syval=''; }
1.249 www 13842: } else {
13843: $syval='';
1.37 www 13844: }
13845: }
1.1282 raeburn 13846: untie(%bighash);
1.481 raeburn 13847: }
1.31 www 13848: }
1.62 www 13849: if ($syval) {
1.1427 raeburn 13850: return $env{$cache_str}=$syval;
1.62 www 13851: }
1.31 www 13852: }
1.949 raeburn 13853: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13854: return $env{$cache_str}='';
1.31 www 13855: }
13856:
13857: # ---------------------------------------------------------- Return random seed
13858:
1.32 www 13859: sub numval {
13860: my $txt=shift;
13861: $txt=~tr/A-J/0-9/;
13862: $txt=~tr/a-j/0-9/;
13863: $txt=~tr/K-T/0-9/;
13864: $txt=~tr/k-t/0-9/;
13865: $txt=~tr/U-Z/0-5/;
13866: $txt=~tr/u-z/0-5/;
13867: $txt=~s/\D//g;
1.564 albertel 13868: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 13869: return int($txt);
1.368 albertel 13870: }
13871:
1.484 albertel 13872: sub numval2 {
13873: my $txt=shift;
13874: $txt=~tr/A-J/0-9/;
13875: $txt=~tr/a-j/0-9/;
13876: $txt=~tr/K-T/0-9/;
13877: $txt=~tr/k-t/0-9/;
13878: $txt=~tr/U-Z/0-5/;
13879: $txt=~tr/u-z/0-5/;
13880: $txt=~s/\D//g;
13881: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13882: my $total;
13883: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 13884: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 13885: return int($total);
13886: }
13887:
1.575 albertel 13888: sub numval3 {
13889: use integer;
13890: my $txt=shift;
13891: $txt=~tr/A-J/0-9/;
13892: $txt=~tr/a-j/0-9/;
13893: $txt=~tr/K-T/0-9/;
13894: $txt=~tr/k-t/0-9/;
13895: $txt=~tr/U-Z/0-5/;
13896: $txt=~tr/u-z/0-5/;
13897: $txt=~s/\D//g;
13898: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13899: my $total;
13900: foreach my $val (@txts) { $total+=$val; }
13901: if ($_64bit) { $total=(($total<<32)>>32); }
13902: return $total;
13903: }
13904:
1.675 albertel 13905: sub digest {
13906: my ($data)=@_;
13907: my $digest=&Digest::MD5::md5($data);
13908: my ($a,$b,$c,$d)=unpack("iiii",$digest);
13909: my ($e,$f);
13910: {
13911: use integer;
13912: $e=($a+$b);
13913: $f=($c+$d);
13914: if ($_64bit) {
13915: $e=(($e<<32)>>32);
13916: $f=(($f<<32)>>32);
13917: }
13918: }
13919: if (wantarray) {
13920: return ($e,$f);
13921: } else {
13922: my $g;
13923: {
13924: use integer;
13925: $g=($e+$f);
13926: if ($_64bit) {
13927: $g=(($g<<32)>>32);
13928: }
13929: }
13930: return $g;
13931: }
13932: }
13933:
1.368 albertel 13934: sub latest_rnd_algorithm_id {
1.675 albertel 13935: return '64bit5';
1.366 albertel 13936: }
1.32 www 13937:
1.503 albertel 13938: sub get_rand_alg {
13939: my ($courseid)=@_;
1.790 albertel 13940: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 13941: if ($courseid) {
1.620 albertel 13942: return $env{"course.$courseid.rndseed"};
1.503 albertel 13943: }
13944: return &latest_rnd_algorithm_id();
13945: }
13946:
1.562 albertel 13947: sub validCODE {
13948: my ($CODE)=@_;
13949: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13950: return 0;
13951: }
13952:
1.491 albertel 13953: sub getCODE {
1.620 albertel 13954: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 13955: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13956: defined($Apache::lonhomework::parsing_a_task) ) &&
13957: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 13958: return $Apache::lonhomework::history{'resource.CODE'};
13959: }
13960: return undef;
13961: }
1.1133 foxr 13962: #
13963: # Determines the random seed for a specific context:
13964: #
13965: # parameters:
13966: # symb - in course context the symb for the seed.
13967: # course_id - The course id of the form domain_coursenum.
13968: # domain - Domain for the user.
13969: # course - Course for the user.
13970: # cenv - environment of the course.
13971: #
13972: # NOTE:
13973: # All parameters are picked out of the environment if missing
13974: # or not defined.
13975: # If a symb cannot be determined the current time is used instead.
13976: #
13977: # For a given well defined symb, courside, domain, username,
13978: # and course environment, the seed is reproducible.
13979: #
1.31 www 13980: sub rndseed {
1.1133 foxr 13981: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 13982: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 13983: if (!defined($symb)) {
1.366 albertel 13984: unless ($symb=$wsymb) { return time; }
13985: }
1.1146 foxr 13986: if (!defined $courseid) {
13987: $courseid=$wcourseid;
13988: }
13989: if (!defined $domain) { $domain=$wdomain; }
13990: if (!defined $username) { $username=$wusername }
1.1133 foxr 13991:
13992: my $which;
13993: if (defined($cenv->{'rndseed'})) {
13994: $which = $cenv->{'rndseed'};
13995: } else {
13996: $which =&get_rand_alg($courseid);
13997: }
1.491 albertel 13998: if (defined(&getCODE())) {
1.1133 foxr 13999:
1.675 albertel 14000: if ($which eq '64bit5') {
14001: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14002: } elsif ($which eq '64bit4') {
1.575 albertel 14003: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14004: } else {
14005: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14006: }
1.675 albertel 14007: } elsif ($which eq '64bit5') {
14008: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 14009: } elsif ($which eq '64bit4') {
14010: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 14011: } elsif ($which eq '64bit3') {
14012: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 14013: } elsif ($which eq '64bit2') {
14014: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 14015: } elsif ($which eq '64bit') {
14016: return &rndseed_64bit($symb,$courseid,$domain,$username);
14017: }
14018: return &rndseed_32bit($symb,$courseid,$domain,$username);
14019: }
14020:
14021: sub rndseed_32bit {
14022: my ($symb,$courseid,$domain,$username)=@_;
14023: {
14024: use integer;
14025: my $symbchck=unpack("%32C*",$symb) << 27;
14026: my $symbseed=numval($symb) << 22;
14027: my $namechck=unpack("%32C*",$username) << 17;
14028: my $nameseed=numval($username) << 12;
14029: my $domainseed=unpack("%32C*",$domain) << 7;
14030: my $courseseed=unpack("%32C*",$courseid);
14031: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 14032: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14033: #&logthis("rndseed :$num:$symb");
1.564 albertel 14034: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 14035: return $num;
14036: }
14037: }
14038:
14039: sub rndseed_64bit {
14040: my ($symb,$courseid,$domain,$username)=@_;
14041: {
14042: use integer;
14043: my $symbchck=unpack("%32S*",$symb) << 21;
14044: my $symbseed=numval($symb) << 10;
14045: my $namechck=unpack("%32S*",$username);
14046:
14047: my $nameseed=numval($username) << 21;
14048: my $domainseed=unpack("%32S*",$domain) << 10;
14049: my $courseseed=unpack("%32S*",$courseid);
14050:
14051: my $num1=$symbchck+$symbseed+$namechck;
14052: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14053: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14054: #&logthis("rndseed :$num:$symb");
1.564 albertel 14055: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 14056: return "$num1,$num2";
1.155 albertel 14057: }
1.366 albertel 14058: }
14059:
1.443 albertel 14060: sub rndseed_64bit2 {
14061: my ($symb,$courseid,$domain,$username)=@_;
14062: {
14063: use integer;
14064: # strings need to be an even # of cahracters long, it it is odd the
14065: # last characters gets thrown away
14066: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14067: my $symbseed=numval($symb) << 10;
14068: my $namechck=unpack("%32S*",$username.' ');
14069:
14070: my $nameseed=numval($username) << 21;
1.501 albertel 14071: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14072: my $courseseed=unpack("%32S*",$courseid.' ');
14073:
14074: my $num1=$symbchck+$symbseed+$namechck;
14075: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14076: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14077: #&logthis("rndseed :$num:$symb");
1.803 albertel 14078: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 14079: return "$num1,$num2";
14080: }
14081: }
14082:
14083: sub rndseed_64bit3 {
14084: my ($symb,$courseid,$domain,$username)=@_;
14085: {
14086: use integer;
14087: # strings need to be an even # of cahracters long, it it is odd the
14088: # last characters gets thrown away
14089: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14090: my $symbseed=numval2($symb) << 10;
14091: my $namechck=unpack("%32S*",$username.' ');
14092:
14093: my $nameseed=numval2($username) << 21;
1.443 albertel 14094: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14095: my $courseseed=unpack("%32S*",$courseid.' ');
14096:
14097: my $num1=$symbchck+$symbseed+$namechck;
14098: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14099: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14100: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 14101: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14102:
1.503 albertel 14103: return "$num1:$num2";
1.443 albertel 14104: }
14105: }
14106:
1.575 albertel 14107: sub rndseed_64bit4 {
14108: my ($symb,$courseid,$domain,$username)=@_;
14109: {
14110: use integer;
14111: # strings need to be an even # of cahracters long, it it is odd the
14112: # last characters gets thrown away
14113: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14114: my $symbseed=numval3($symb) << 10;
14115: my $namechck=unpack("%32S*",$username.' ');
14116:
14117: my $nameseed=numval3($username) << 21;
14118: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14119: my $courseseed=unpack("%32S*",$courseid.' ');
14120:
14121: my $num1=$symbchck+$symbseed+$namechck;
14122: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14123: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14124: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 14125: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14126:
1.575 albertel 14127: return "$num1:$num2";
14128: }
14129: }
14130:
1.675 albertel 14131: sub rndseed_64bit5 {
14132: my ($symb,$courseid,$domain,$username)=@_;
14133: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14134: return "$num1:$num2";
14135: }
14136:
1.366 albertel 14137: sub rndseed_CODE_64bit {
14138: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 14139: {
1.366 albertel 14140: use integer;
1.443 albertel 14141: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 14142: my $symbseed=numval2($symb);
1.491 albertel 14143: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14144: my $CODEseed=numval(&getCODE());
1.443 albertel 14145: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 14146: my $num1=$symbseed+$CODEchck;
14147: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14148: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14149: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 14150: if ($_64bit) { $num1=(($num1<<32)>>32); }
14151: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 14152: return "$num1:$num2";
1.366 albertel 14153: }
14154: }
14155:
1.575 albertel 14156: sub rndseed_CODE_64bit4 {
14157: my ($symb,$courseid,$domain,$username)=@_;
14158: {
14159: use integer;
14160: my $symbchck=unpack("%32S*",$symb.' ') << 16;
14161: my $symbseed=numval3($symb);
14162: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14163: my $CODEseed=numval3(&getCODE());
14164: my $courseseed=unpack("%32S*",$courseid.' ');
14165: my $num1=$symbseed+$CODEchck;
14166: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14167: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14168: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 14169: if ($_64bit) { $num1=(($num1<<32)>>32); }
14170: if ($_64bit) { $num2=(($num2<<32)>>32); }
14171: return "$num1:$num2";
14172: }
14173: }
14174:
1.675 albertel 14175: sub rndseed_CODE_64bit5 {
14176: my ($symb,$courseid,$domain,$username)=@_;
14177: my $code = &getCODE();
14178: my ($num1,$num2)=&digest("$symb,$courseid,$code");
14179: return "$num1:$num2";
14180: }
14181:
1.366 albertel 14182: sub setup_random_from_rndseed {
14183: my ($rndseed)=@_;
1.503 albertel 14184: if ($rndseed =~/([,:])/) {
1.1262 raeburn 14185: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14186: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14187: &Math::Random::random_set_seed_from_phrase($rndseed);
14188: } else {
14189: &Math::Random::random_set_seed($num1,$num2);
14190: }
1.366 albertel 14191: } else {
14192: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 14193: }
1.36 albertel 14194: }
14195:
1.474 albertel 14196: sub latest_receipt_algorithm_id {
1.835 albertel 14197: return 'receipt3';
1.474 albertel 14198: }
14199:
1.480 www 14200: sub recunique {
14201: my $fucourseid=shift;
14202: my $unique;
1.835 albertel 14203: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14204: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14205: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 14206: } else {
14207: $unique=$perlvar{'lonReceipt'};
14208: }
14209: return unpack("%32C*",$unique);
14210: }
14211:
14212: sub recprefix {
14213: my $fucourseid=shift;
14214: my $prefix;
1.835 albertel 14215: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14216: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14217: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 14218: } else {
14219: $prefix=$perlvar{'lonHostID'};
14220: }
14221: return unpack("%32C*",$prefix);
14222: }
14223:
1.76 www 14224: sub ireceipt {
1.474 albertel 14225: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 14226:
14227: my $return =&recprefix($fucourseid).'-';
14228:
14229: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14230: $env{'request.state'} eq 'construct') {
14231: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14232: return $return;
14233: }
14234:
1.76 www 14235: my $cuname=unpack("%32C*",$funame);
14236: my $cudom=unpack("%32C*",$fudom);
14237: my $cucourseid=unpack("%32C*",$fucourseid);
14238: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 14239: my $cunique=&recunique($fucourseid);
1.474 albertel 14240: my $cpart=unpack("%32S*",$part);
1.835 albertel 14241: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14242:
1.790 albertel 14243: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 14244:
14245: $return.= ($cunique%$cuname+
14246: $cunique%$cudom+
14247: $cusymb%$cuname+
14248: $cusymb%$cudom+
14249: $cucourseid%$cuname+
14250: $cucourseid%$cudom+
14251: $cpart%$cuname+
14252: $cpart%$cudom);
14253: } else {
14254: $return.= ($cunique%$cuname+
14255: $cunique%$cudom+
14256: $cusymb%$cuname+
14257: $cusymb%$cudom+
14258: $cucourseid%$cuname+
14259: $cucourseid%$cudom);
14260: }
14261: return $return;
1.76 www 14262: }
14263:
14264: sub receipt {
1.474 albertel 14265: my ($part)=@_;
1.790 albertel 14266: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 14267: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 14268: }
1.260 ng 14269:
1.790 albertel 14270: sub whichuser {
14271: my ($passedsymb)=@_;
14272: my ($symb,$courseid,$domain,$name,$publicuser);
14273: if (defined($env{'form.grade_symb'})) {
14274: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14275: my $allowed=&allowed('vgr',$tmp_courseid);
14276: if (!$allowed &&
14277: exists($env{'request.course.sec'}) &&
14278: $env{'request.course.sec'} !~ /^\s*$/) {
14279: $allowed=&allowed('vgr',$tmp_courseid.
14280: '/'.$env{'request.course.sec'});
14281: }
14282: if ($allowed) {
14283: ($symb)=&get_env_multiple('form.grade_symb');
14284: $courseid=$tmp_courseid;
14285: ($domain)=&get_env_multiple('form.grade_domain');
14286: ($name)=&get_env_multiple('form.grade_username');
14287: return ($symb,$courseid,$domain,$name,$publicuser);
14288: }
14289: }
14290: if (!$passedsymb) {
14291: $symb=&symbread();
14292: } else {
14293: $symb=$passedsymb;
14294: }
14295: $courseid=$env{'request.course.id'};
14296: $domain=$env{'user.domain'};
14297: $name=$env{'user.name'};
14298: if ($name eq 'public' && $domain eq 'public') {
14299: if (!defined($env{'form.username'})) {
14300: $env{'form.username'}.=time.rand(10000000);
14301: }
14302: $name.=$env{'form.username'};
14303: }
14304: return ($symb,$courseid,$domain,$name,$publicuser);
14305:
14306: }
14307:
1.36 albertel 14308: # ------------------------------------------------------------ Serves up a file
1.472 albertel 14309: # returns either the contents of the file or
14310: # -1 if the file doesn't exist
1.481 raeburn 14311: #
14312: # if the target is a file that was uploaded via DOCS,
14313: # a check will be made to see if a current copy exists on the local server,
14314: # if it does this will be served, otherwise a copy will be retrieved from
14315: # the home server for the course and stored in /home/httpd/html/userfiles on
14316: # the local server.
1.472 albertel 14317:
1.36 albertel 14318: sub getfile {
1.538 albertel 14319: my ($file) = @_;
1.609 banghart 14320: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 14321: &repcopy($file);
14322: return &readfile($file);
14323: }
14324:
14325: sub repcopy_userfile {
14326: my ($file)=@_;
1.1142 raeburn 14327: my $londocroot = $perlvar{'lonDocRoot'};
14328: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 14329: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 14330: my ($cdom,$cnum,$filename) =
1.811 albertel 14331: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 14332: my $uri="/uploaded/$cdom/$cnum/$filename";
14333: if (-e "$file") {
1.828 www 14334: # we already have a local copy, check it out
1.538 albertel 14335: my @fileinfo = stat($file);
1.828 www 14336: my $rtncode;
14337: my $info;
1.538 albertel 14338: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 14339: if ($lwpresp ne 'ok') {
1.828 www 14340: # there is no such file anymore, even though we had a local copy
1.482 albertel 14341: if ($rtncode eq '404') {
1.538 albertel 14342: unlink($file);
1.482 albertel 14343: }
14344: return -1;
14345: }
14346: if ($info < $fileinfo[9]) {
1.828 www 14347: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 14348: return 'ok';
1.828 www 14349: } else {
14350: # the file is outdated, get rid of it
14351: unlink($file);
1.482 albertel 14352: }
1.828 www 14353: }
14354: # one way or the other, at this point, we don't have the file
14355: # construct the correct path for the file
14356: my @parts = ($cdom,$cnum);
14357: if ($filename =~ m|^(.+)/[^/]+$|) {
14358: push @parts, split(/\//,$1);
14359: }
14360: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14361: foreach my $part (@parts) {
14362: $path .= '/'.$part;
14363: if (!-e $path) {
14364: mkdir($path,0770);
1.482 albertel 14365: }
14366: }
1.828 www 14367: # now the path exists for sure
14368: # get a user agent
14369: my $transferfile=$file.'.in.transfer';
14370: # FIXME: this should flock
14371: if (-e $transferfile) { return 'ok'; }
14372: my $request;
14373: $uri=~s/^\///;
1.980 raeburn 14374: my $homeserver = &homeserver($cnum,$cdom);
1.1398 raeburn 14375: my $hostname = &hostname($homeserver);
1.980 raeburn 14376: my $protocol = $protocol{$homeserver};
14377: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14378: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345 raeburn 14379: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828 www 14380: # did it work?
14381: if ($response->is_error()) {
14382: unlink($transferfile);
14383: &logthis("Userfile repcopy failed for $uri");
14384: return -1;
14385: }
14386: # worked, rename the transfer file
14387: rename($transferfile,$file);
1.607 raeburn 14388: return 'ok';
1.481 raeburn 14389: }
14390:
1.517 albertel 14391: sub tokenwrapper {
14392: my $uri=shift;
1.980 raeburn 14393: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 14394: $uri=~s|^/||;
1.620 albertel 14395: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 14396: my $token=$1;
1.552 albertel 14397: my (undef,$udom,$uname,$file)=split('/',$uri,4);
14398: if ($udom && $uname && $file) {
14399: $file=~s|(\?\.*)*$||;
1.949 raeburn 14400: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 14401: my $homeserver = &homeserver($uname,$udom);
1.1397 raeburn 14402: my $hostname = &hostname($homeserver);
1.980 raeburn 14403: my $protocol = $protocol{$homeserver};
14404: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14405: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 14406: (($uri=~/\?/)?'&':'?').'token='.$token.
14407: '&tokenissued='.$perlvar{'lonHostID'};
14408: } else {
14409: return '/adm/notfound.html';
14410: }
14411: }
14412:
1.828 www 14413: # call with reqtype HEAD: get last modification time
14414: # call with reqtype GET: get the file contents
14415: # Do not call this with reqtype GET for large files! It loads everything into memory
14416: #
1.481 raeburn 14417: sub getuploaded {
14418: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14419: $uri=~s/^\///;
1.980 raeburn 14420: my $homeserver = &homeserver($cnum,$cdom);
1.1397 raeburn 14421: my $hostname = &hostname($homeserver);
1.980 raeburn 14422: my $protocol = $protocol{$homeserver};
14423: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14424: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 14425: my $request=new HTTP::Request($reqtype,$uri);
1.1345 raeburn 14426: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481 raeburn 14427: $$rtncode = $response->code;
1.482 albertel 14428: if (! $response->is_success()) {
14429: return 'failed';
14430: }
14431: if ($reqtype eq 'HEAD') {
1.486 www 14432: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 14433: } elsif ($reqtype eq 'GET') {
14434: $$info = $response->content;
1.472 albertel 14435: }
1.482 albertel 14436: return 'ok';
1.36 albertel 14437: }
14438:
1.481 raeburn 14439: sub readfile {
14440: my $file = shift;
14441: if ( (! -e $file ) || ($file eq '') ) { return -1; };
14442: my $fh;
1.1359 raeburn 14443: open($fh,"<",$file);
1.481 raeburn 14444: my $a='';
1.800 albertel 14445: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 14446: return $a;
14447: }
14448:
1.36 albertel 14449: sub filelocation {
1.590 banghart 14450: my ($dir,$file) = @_;
14451: my $location;
14452: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 14453:
14454: if ($file =~ m-^/adm/-) {
14455: $file=~s-^/adm/wrapper/-/-;
14456: $file=~s-^/adm/coursedocs/showdoc/-/-;
14457: }
1.882 albertel 14458:
1.1139 www 14459: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 14460: $location = $file;
1.609 banghart 14461: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 14462: my ($udom,$uname,$filename)=
1.811 albertel 14463: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 14464: my $home=&homeserver($uname,$udom);
14465: my $is_me=0;
14466: my @ids=¤t_machine_ids();
14467: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14468: if ($is_me) {
1.1117 foxr 14469: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 14470: } else {
14471: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14472: $udom.'/'.$uname.'/'.$filename;
14473: }
1.882 albertel 14474: } elsif ($file =~ m-^/adm/-) {
14475: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 14476: } else {
14477: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 14478: $file=~s:^/(res|priv)/:/:;
14479: my $space=$1;
1.590 banghart 14480: if ( !( $file =~ m:^/:) ) {
14481: $location = $dir. '/'.$file;
14482: } else {
1.1142 raeburn 14483: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 14484: }
1.59 albertel 14485: }
1.590 banghart 14486: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 14487: while ($location=~m{/\.\./}) {
14488: if ($location =~ m{/[^/]+/\.\./}) {
14489: $location=~ s{/[^/]+/\.\./}{/}g;
14490: } else {
14491: $location=~ s{/\.\./}{/}g;
14492: }
14493: } #remove dir/..
1.590 banghart 14494: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14495: return $location;
1.46 www 14496: }
1.36 albertel 14497:
1.46 www 14498: sub hreflocation {
14499: my ($dir,$file)=@_;
1.980 raeburn 14500: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 14501: $file=filelocation($dir,$file);
1.700 albertel 14502: } elsif ($file=~m-^/adm/-) {
14503: $file=~s-^/adm/wrapper/-/-;
14504: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 14505: }
14506: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14507: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14508: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 14509: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14510: {/uploaded/$1/$2/}x;
1.46 www 14511: }
1.913 albertel 14512: if ($file=~ m{^/userfiles/}) {
14513: $file =~ s{^/userfiles/}{/uploaded/};
14514: }
1.462 albertel 14515: return $file;
1.465 albertel 14516: }
14517:
1.1139 www 14518:
14519:
14520:
14521:
1.465 albertel 14522: sub current_machine_domains {
1.853 albertel 14523: return &machine_domains(&hostname($perlvar{'lonHostID'}));
14524: }
14525:
14526: sub machine_domains {
14527: my ($hostname) = @_;
1.465 albertel 14528: my @domains;
1.838 albertel 14529: my %hostname = &all_hostnames();
1.465 albertel 14530: while( my($id, $name) = each(%hostname)) {
1.467 matthew 14531: # &logthis("-$id-$name-$hostname-");
1.465 albertel 14532: if ($hostname eq $name) {
1.844 albertel 14533: push(@domains,&host_domain($id));
1.465 albertel 14534: }
14535: }
14536: return @domains;
14537: }
14538:
14539: sub current_machine_ids {
1.853 albertel 14540: return &machine_ids(&hostname($perlvar{'lonHostID'}));
14541: }
14542:
14543: sub machine_ids {
14544: my ($hostname) = @_;
14545: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 14546: my @ids;
1.888 albertel 14547: my %name_to_host = &all_names();
1.889 albertel 14548: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14549: return @{ $name_to_host{$hostname} };
14550: }
14551: return;
1.31 www 14552: }
14553:
1.824 raeburn 14554: sub additional_machine_domains {
14555: my @domains;
1.1466 raeburn 14556: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14557: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14558: while (my $line = <$fh>) {
14559: chomp($line);
14560: $line =~ s/\s//g;
14561: push(@domains,$line);
14562: }
14563: close($fh);
14564: }
1.824 raeburn 14565: }
14566: return @domains;
14567: }
14568:
14569: sub default_login_domain {
14570: my $domain = $perlvar{'lonDefDomain'};
14571: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14572: foreach my $posdom (¤t_machine_domains(),
14573: &additional_machine_domains()) {
14574: if (lc($posdom) eq lc($testdomain)) {
14575: $domain=$posdom;
14576: last;
14577: }
14578: }
14579: return $domain;
14580: }
14581:
1.1414 raeburn 14582: sub shared_institution {
1.1439 raeburn 14583: my ($dom,$lonhost) = @_;
14584: if ($lonhost eq '') {
14585: $lonhost = $perlvar{'lonHostID'};
14586: }
1.1414 raeburn 14587: my $same_intdom;
1.1439 raeburn 14588: my $hostintdom = &internet_dom($lonhost);
1.1414 raeburn 14589: if ($hostintdom ne '') {
14590: my %iphost = &get_iphost();
14591: my $primary_id = &domain($dom,'primary');
14592: my $primary_ip = &get_host_ip($primary_id);
14593: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14594: foreach my $id (@{$iphost{$primary_ip}}) {
14595: my $intdom = &internet_dom($id);
14596: if ($intdom eq $hostintdom) {
14597: $same_intdom = 1;
14598: last;
14599: }
14600: }
14601: }
14602: }
14603: return $same_intdom;
14604: }
14605:
1.1398 raeburn 14606: sub uses_sts {
14607: my ($ignore_cache) = @_;
14608: my $lonhost = $perlvar{'lonHostID'};
14609: my $hostname = &hostname($lonhost);
14610: my $sts_on;
14611: if ($protocol{$lonhost} eq 'https') {
14612: my $cachetime = 12*3600;
14613: if (!$ignore_cache) {
14614: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14615: if (defined($cached)) {
14616: return $sts_on;
14617: }
14618: }
14619: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14620: my $request=new HTTP::Request('HEAD',$url);
14621: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14622: if ($response->is_success) {
14623: my $has_sts = $response->header('Strict-Transport-Security');
14624: if ($has_sts eq '') {
14625: $sts_on = 0;
14626: } else {
14627: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14628: my $maxage = $1;
14629: if ($maxage) {
14630: $sts_on = 1;
14631: } else {
14632: $sts_on = 0;
14633: }
14634: } else {
14635: $sts_on = 0;
14636: }
14637: }
14638: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14639: }
14640: }
14641: return;
14642: }
14643:
1.1449 raeburn 14644: sub waf_allssl {
14645: my ($host_name) = @_;
14646: my $alias = &get_proxy_alias();
14647: if ($host_name eq '') {
14648: $host_name = $ENV{'SERVER_NAME'};
14649: }
14650: if (($host_name ne '') && ($alias eq $host_name)) {
14651: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14652: my %defdomdefaults = &get_domain_defaults($serverhomedom);
14653: if ($defdomdefaults{'waf_sslopt'}) {
14654: return $defdomdefaults{'waf_sslopt'};
14655: }
14656: }
14657: return;
14658: }
14659:
1.1434 raeburn 14660: sub get_requestor_ip {
14661: my ($r,$nolookup,$noproxy) = @_;
14662: my $from_ip;
14663: if (ref($r)) {
1.1447 raeburn 14664: if ($r->can('useragent_ip')) {
14665: if ($noproxy && $r->can('client_ip')) {
14666: $from_ip = $r->client_ip();
14667: } else {
14668: $from_ip = $r->useragent_ip();
14669: }
14670: } elsif ($r->connection->can('remote_ip')) {
14671: $from_ip = $r->connection->remote_ip();
14672: } else {
14673: $from_ip = $r->get_remote_host($nolookup);
14674: }
1.1434 raeburn 14675: } else {
14676: $from_ip = $ENV{'REMOTE_ADDR'};
14677: }
14678: return $from_ip if ($noproxy);
14679: # Who controls proxy settings for server
14680: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14681: my $proxyinfo = &get_proxy_settings($dom_in_use);
14682: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437 raeburn 14683: if ($proxyinfo->{'vpnint'}) {
14684: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434 raeburn 14685: return $from_ip;
14686: }
14687: }
14688: if ($proxyinfo->{'trusted'}) {
14689: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14690: my $ipheader = $proxyinfo->{'ipheader'};
14691: my ($ip,$xfor);
14692: if (ref($r)) {
14693: if ($ipheader) {
14694: $ip = $r->headers_in->{$ipheader};
14695: }
14696: $xfor = $r->headers_in->{'X-Forwarded-For'};
14697: } else {
14698: if ($ipheader) {
14699: $ip = $ENV{'HTTP_'.uc($ipheader)};
14700: }
14701: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14702: }
14703: if (($ip eq '') && ($xfor ne '')) {
14704: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14705: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14706: $ip = $poss_ip;
1.1435 raeburn 14707: last;
1.1434 raeburn 14708: }
14709: }
14710: }
14711: if ($ip ne '') {
14712: return $ip;
14713: }
14714: }
14715: }
14716: }
14717: return $from_ip;
14718: }
14719:
14720: sub get_proxy_settings {
14721: my ($dom_in_use) = @_;
14722: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14723: my $proxyinfo = {
14724: ipheader => $domdefaults{'waf_ipheader'},
14725: trusted => $domdefaults{'waf_trusted'},
1.1437 raeburn 14726: vpnint => $domdefaults{'waf_vpnint'},
1.1438 raeburn 14727: vpnext => $domdefaults{'waf_vpnext'},
1.1449 raeburn 14728: sslopt => $domdefaults{'waf_sslopt'},
1.1434 raeburn 14729: };
14730: return $proxyinfo;
14731: }
14732:
14733: sub ip_match {
14734: my ($ip,$pattern_str) = @_;
14735: $ip=Net::CIDR::cidrvalidate($ip);
14736: if ($ip) {
14737: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14738: }
14739: return;
14740: }
14741:
14742: sub get_proxy_alias {
1.1450 raeburn 14743: my ($lonid) = @_;
14744: if ($lonid eq '') {
14745: $lonid = $perlvar{'lonHostID'};
14746: }
14747: if (!defined(&hostname($lonid))) {
14748: return;
14749: }
14750: if ($lonid ne '') {
14751: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434 raeburn 14752: if ($cached) {
14753: return $alias;
14754: }
1.1450 raeburn 14755: my $dom = &Apache::lonnet::host_domain($lonid);
1.1434 raeburn 14756: if ($dom ne '') {
14757: my $cachetime = 60*60*24;
14758: my %domconfig =
1.1437 raeburn 14759: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14760: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14761: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450 raeburn 14762: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
14763: }
14764: }
14765: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
14766: }
14767: }
14768: return;
14769: }
14770:
14771: sub use_proxy_alias {
14772: my ($r,$lonid) = @_;
14773: my $alias = &get_proxy_alias($lonid);
14774: if ($alias) {
14775: my $dom = &host_domain($lonid);
14776: if ($dom ne '') {
1.1467 raeburn 14777: my $proxyinfo = &get_proxy_settings($dom);
1.1450 raeburn 14778: my ($vpnint,$remote_ip);
14779: if (ref($proxyinfo) eq 'HASH') {
14780: $vpnint = $proxyinfo->{'vpnint'};
14781: if ($vpnint) {
14782: $remote_ip = &get_requestor_ip($r,1,1);
1.1434 raeburn 14783: }
14784: }
1.1450 raeburn 14785: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14786: return $alias;
14787: }
1.1434 raeburn 14788: }
14789: }
14790: return;
14791: }
14792:
1.1474 raeburn 14793: sub alias_sso {
1.1467 raeburn 14794: my ($lonid) = @_;
14795: if ($lonid eq '') {
14796: $lonid = $perlvar{'lonHostID'};
14797: }
14798: if (!defined(&hostname($lonid))) {
14799: return;
14800: }
14801: if ($lonid ne '') {
14802: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
14803: if ($cached) {
14804: return $use_alias;
14805: }
14806: my $dom = &Apache::lonnet::host_domain($lonid);
14807: if ($dom ne '') {
14808: my $cachetime = 60*60*24;
14809: my %domconfig =
14810: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14811: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14812: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
14813: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
14814: }
14815: }
14816: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
14817: }
14818: }
14819: return;
14820: }
14821:
1.1465 raeburn 14822: sub get_saml_landing {
14823: my ($lonid) = @_;
14824: if ($lonid eq '') {
14825: my $defdom = &default_login_domain();
14826: my @hosts = ¤t_machine_ids();
14827: if (@hosts > 1) {
14828: foreach my $hostid (@hosts) {
14829: if (&host_domain($hostid) eq $defdom) {
14830: $lonid = $hostid;
14831: last;
14832: }
14833: }
14834: } else {
14835: $lonid = $perlvar{'lonHostID'};
14836: }
14837: if ($lonid) {
14838: unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
14839: return;
14840: }
14841: } else {
14842: return;
14843: }
14844: } elsif (!defined(&hostname($lonid))) {
14845: return;
14846: }
14847: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
14848: if ($cached) {
14849: return $landing;
14850: }
14851: my $dom = &Apache::lonnet::host_domain($lonid);
14852: if ($dom ne '') {
14853: my $cachetime = 60*60*24;
14854: my %domconfig =
14855: &Apache::lonnet::get_dom('configuration',['login'],$dom);
14856: if (ref($domconfig{'login'}) eq 'HASH') {
14857: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
14858: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
14859: $landing = 1;
14860: }
14861: }
14862: }
14863: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
14864: }
14865: return;
14866: }
14867:
1.31 www 14868: # ------------------------------------------------------------- Declutters URLs
14869:
14870: sub declutter {
14871: my $thisfn=shift;
1.569 albertel 14872: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 14873: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14874: $thisfn=~s{^/home/httpd/html}{};
14875: }
1.31 www 14876: $thisfn=~s/^\///;
1.697 albertel 14877: $thisfn=~s|^adm/wrapper/||;
14878: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 14879: $thisfn=~s/^res\///;
1.1172 bisitz 14880: $thisfn=~s/^priv\///;
1.1032 raeburn 14881: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14882: $thisfn=~s/\?.+$//;
14883: }
1.268 www 14884: return $thisfn;
14885: }
14886:
14887: # ------------------------------------------------------------- Clutter up URLs
14888:
14889: sub clutter {
14890: my $thisfn='/'.&declutter(shift);
1.887 albertel 14891: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 14892: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 14893: $thisfn='/res'.$thisfn;
14894: }
1.1031 raeburn 14895: if ($thisfn !~m|^/adm|) {
14896: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 14897: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 14898: } else {
14899: my ($ext) = ($thisfn =~ /\.(\w+)$/);
14900: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 14901: if ($embstyle eq 'ssi'
14902: || ($embstyle eq 'hdn')
14903: || ($embstyle eq 'rat')
14904: || ($embstyle eq 'prv')
14905: || ($embstyle eq 'ign')) {
14906: #do nothing with these
14907: } elsif (($embstyle eq 'img')
1.695 albertel 14908: || ($embstyle eq 'emb')
14909: || ($embstyle eq 'wrp')) {
14910: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 14911: } elsif ($embstyle eq 'unk'
14912: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 14913: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 14914: } else {
1.718 www 14915: # &logthis("Got a blank emb style");
1.695 albertel 14916: }
1.694 albertel 14917: }
1.1343 raeburn 14918: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 14919: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 14920: }
1.31 www 14921: return $thisfn;
1.12 www 14922: }
14923:
1.787 albertel 14924: sub clutter_with_no_wrapper {
14925: my $uri = &clutter(shift);
14926: if ($uri =~ m-^/adm/-) {
14927: $uri =~ s-^/adm/wrapper/-/-;
14928: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
14929: }
14930: return $uri;
14931: }
14932:
1.557 albertel 14933: sub freeze_escape {
14934: my ($value)=@_;
14935: if (ref($value)) {
14936: $value=&nfreeze($value);
14937: return '__FROZEN__'.&escape($value);
14938: }
14939: return &escape($value);
14940: }
14941:
1.11 www 14942:
1.557 albertel 14943: sub thaw_unescape {
14944: my ($value)=@_;
14945: if ($value =~ /^__FROZEN__/) {
14946: substr($value,0,10,undef);
14947: $value=&unescape($value);
14948: return &thaw($value);
14949: }
14950: return &unescape($value);
14951: }
14952:
1.436 albertel 14953: sub correct_line_ends {
14954: my ($result)=@_;
14955: $$result =~s/\r\n/\n/mg;
14956: $$result =~s/\r/\n/mg;
1.415 albertel 14957: }
1.1 albertel 14958: # ================================================================ Main Program
14959:
1.184 www 14960: sub goodbye {
1.204 albertel 14961: &logthis("Starting Shut down");
1.443 albertel 14962: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 14963: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 14964: #converted
1.599 albertel 14965: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 14966: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14967: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14968: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 14969: #1.1 only
1.870 albertel 14970: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14971: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14972: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14973: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14974: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 14975: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14976: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 14977: &flushcourselogs();
14978: &logthis("Shutting down");
14979: }
14980:
1.852 albertel 14981: sub get_dns {
1.1210 raeburn 14982: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 14983: if (!$ignore_cache) {
14984: my ($content,$cached)=
14985: &Apache::lonnet::is_cached_new('dns',$url);
14986: if ($cached) {
1.1210 raeburn 14987: &$func($content,$hashref);
1.869 albertel 14988: return;
14989: }
14990: }
14991:
14992: my %alldns;
1.1379 raeburn 14993: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14994: foreach my $dns (<$config>) {
14995: next if ($dns !~ /^\^(\S*)/x);
14996: my $line = $1;
14997: my ($host,$protocol) = split(/:/,$line);
14998: if ($protocol ne 'https') {
14999: $protocol = 'http';
15000: }
15001: $alldns{$host} = $protocol;
1.979 raeburn 15002: }
1.1379 raeburn 15003: close($config);
1.869 albertel 15004: }
15005: while (%alldns) {
1.1263 raeburn 15006: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456 raeburn 15007: my ($contents,@content);
15008: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15009: my $command = (split('/',$url))[3];
15010: my ($dir,$file) = &parse_getdns_url($command,$url);
15011: delete($alldns{$dns});
15012: next if (($dir eq '') || ($file eq ''));
15013: if (open(my $config,'<',"$dir/$file")) {
1.1457 raeburn 15014: @content = <$config>;
1.1456 raeburn 15015: close($config);
15016: }
15017: if ($url eq '/adm/dns/loncapaCRL') {
15018: $contents = join('',@content);
15019: }
15020: } else {
15021: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15022: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15023: delete($alldns{$dns});
15024: next if ($response->is_error());
15025: if ($url eq '/adm/dns/loncapaCRL') {
15026: $contents = $response->content;
15027: } else {
15028: @content = split("\n",$response->content);
15029: }
15030: }
1.1379 raeburn 15031: if ($url eq '/adm/dns/loncapaCRL') {
1.1456 raeburn 15032: return &$func($contents);
1.1379 raeburn 15033: } else {
15034: unless ($nocache) {
15035: &do_cache_new('dns',$url,\@content,30*24*60*60);
15036: }
15037: &$func(\@content,$hashref);
15038: return;
15039: }
15040: }
15041: my $which = (split('/',$url,4))[3];
15042: if ($which eq 'loncapaCRL') {
15043: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15044: if (-e $diskfile) {
15045: &logthis("unable to contact DNS, on disk file $diskfile not updated");
15046: } else {
15047: &logthis("unable to contact DNS, no on disk file $diskfile available");
15048: }
15049: } else {
15050: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15051: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15052: my @content = <$config>;
15053: close($config);
15054: &$func(\@content,$hashref);
15055: }
1.852 albertel 15056: }
1.1210 raeburn 15057: return;
15058: }
15059:
15060: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 15061: sub parse_dns_checksums_tab {
1.1210 raeburn 15062: my ($lines,$hashref) = @_;
1.1264 raeburn 15063: my $lonhost = $perlvar{'lonHostID'};
15064: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 15065: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 15066: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15067: my $webconfdir = '/etc/httpd/conf';
15068: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15069: $webconfdir = '/etc/apache2';
15070: } elsif ($distro =~ /^sles(\d+)$/) {
15071: if ($1 >= 10) {
15072: $webconfdir = '/etc/apache2';
15073: }
15074: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15075: if ($1 >= 10.0) {
15076: $webconfdir = '/etc/apache2';
15077: }
15078: }
1.1210 raeburn 15079: my ($release,$timestamp) = split(/\-/,$loncaparev);
15080: my (%chksum,%revnum);
15081: if (ref($lines) eq 'ARRAY') {
15082: chomp(@{$lines});
1.1238 raeburn 15083: my $version = shift(@{$lines});
15084: if ($version eq $release) {
1.1210 raeburn 15085: foreach my $line (@{$lines}) {
1.1238 raeburn 15086: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 15087: if ($file =~ m{^/etc/httpd/conf}) {
15088: if ($webconfdir eq '/etc/apache2') {
15089: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15090: }
15091: }
1.1238 raeburn 15092: $chksum{$file} = $shasum;
15093: $revnum{$file} = $version;
1.1210 raeburn 15094: }
15095: if (ref($hashref) eq 'HASH') {
15096: %{$hashref} = (
15097: sums => \%chksum,
15098: versions => \%revnum,
15099: );
15100: }
15101: }
15102: }
1.869 albertel 15103: return;
1.852 albertel 15104: }
1.1210 raeburn 15105:
15106: sub fetch_dns_checksums {
1.1238 raeburn 15107: my %checksums;
15108: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 15109: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 15110: my ($release,$timestamp) = split(/\-/,$loncaparev);
15111: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 15112: \%checksums);
1.1210 raeburn 15113: return \%checksums;
15114: }
15115:
1.1379 raeburn 15116: sub fetch_crl_pemfile {
15117: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15118: }
15119:
15120: sub save_crl_pem {
1.1456 raeburn 15121: my ($content) = @_;
1.1380 raeburn 15122: my ($msg,$hadchanges);
1.1456 raeburn 15123: if ($content ne '') {
1.1379 raeburn 15124: my $now = time;
15125: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15126: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15127: if (open(my $fh,'>',"$tmpcrl")) {
1.1456 raeburn 15128: print $fh $content;
1.1379 raeburn 15129: close($fh);
15130: if (-e $lonca) {
15131: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15132: my $check = <PIPE>;
15133: close(PIPE);
15134: chomp($check);
15135: if ($check eq 'verify OK') {
15136: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380 raeburn 15137: my $backup;
1.1379 raeburn 15138: if (-e $dest) {
1.1380 raeburn 15139: if (&File::Copy::move($dest,"$dest.bak")) {
15140: $backup = 'ok';
15141: }
1.1379 raeburn 15142: }
15143: if (&File::Copy::move($tmpcrl,$dest)) {
15144: $msg = 'ok';
1.1380 raeburn 15145: if ($backup) {
15146: my (%oldnums,%newnums);
15147: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15148: while (<PIPE>) {
15149: $oldnums{(split(/:/))[1]} = 1;
15150: }
15151: close(PIPE);
15152: }
15153: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15154: while(<PIPE>) {
15155: $newnums{(split(/:/))[1]} = 1;
15156: }
15157: close(PIPE);
15158: }
15159: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15160: unless (exists($oldnums{$key})) {
15161: $hadchanges = 1;
15162: last;
15163: }
15164: }
15165: unless ($hadchanges) {
15166: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15167: unless (exists($newnums{$key})) {
15168: $hadchanges = 1;
15169: last;
15170: }
15171: }
15172: }
15173: }
1.1379 raeburn 15174: }
15175: } else {
15176: unlink($tmpcrl);
15177: }
15178: } else {
15179: unlink($tmpcrl);
15180: }
15181: } else {
15182: unlink($tmpcrl);
15183: }
15184: }
15185: }
1.1380 raeburn 15186: return ($msg,$hadchanges);
1.1379 raeburn 15187: }
15188:
1.1456 raeburn 15189: sub parse_getdns_url {
15190: my ($command,$url) = @_;
15191: my $dir = $perlvar{'lonTabDir'};
15192: my $file;
15193: if ($command eq 'hosts') {
15194: $file = 'dns_hosts.tab';
15195: } elsif ($command eq 'domain') {
15196: $file = 'dns_domain.tab';
15197: } elsif ($command eq 'checksums') {
15198: my $version = (split('/',$url))[4];
15199: $file = "dns_checksums/$version.tab",
15200: } elsif ($command eq 'loncapaCRL') {
15201: $dir = $perlvar{'lonCertificateDirectory'};
15202: $file = $perlvar{'lonnetCertRevocationList'};
15203: }
15204: return ($dir,$file);
15205: }
15206:
1.327 albertel 15207: # ------------------------------------------------------------ Read domain file
15208: {
1.852 albertel 15209: my $loaded;
1.846 albertel 15210: my %domain;
15211:
1.852 albertel 15212: sub parse_domain_tab {
15213: my ($lines) = @_;
15214: foreach my $line (@$lines) {
15215: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 15216:
1.846 albertel 15217: chomp($line);
1.852 albertel 15218: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 15219: my %this_domain;
15220: foreach my $field ('description', 'auth_def', 'auth_arg_def',
15221: 'lang_def', 'city', 'longi', 'lati',
15222: 'primary') {
15223: $this_domain{$field} = shift(@elements);
15224: }
15225: $domain{$name} = \%this_domain;
1.852 albertel 15226: }
15227: }
1.864 albertel 15228:
15229: sub reset_domain_info {
15230: undef($loaded);
15231: undef(%domain);
15232: }
15233:
1.852 albertel 15234: sub load_domain_tab {
1.1293 raeburn 15235: my ($ignore_cache,$nocache) = @_;
15236: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 15237: my $fh;
1.1359 raeburn 15238: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 15239: my @lines = <$fh>;
15240: &parse_domain_tab(\@lines);
1.448 albertel 15241: }
1.852 albertel 15242: close($fh);
15243: $loaded = 1;
1.327 albertel 15244: }
1.846 albertel 15245:
15246: sub domain {
1.852 albertel 15247: &load_domain_tab() if (!$loaded);
15248:
1.846 albertel 15249: my ($name,$what) = @_;
15250: return if ( !exists($domain{$name}) );
15251:
15252: if (!$what) {
15253: return $domain{$name}{'description'};
15254: }
15255: return $domain{$name}{$what};
15256: }
1.974 raeburn 15257:
15258: sub domain_info {
15259: &load_domain_tab() if (!$loaded);
15260: return %domain;
15261: }
15262:
1.327 albertel 15263: }
15264:
15265:
1.1 albertel 15266: # ------------------------------------------------------------- Read hosts file
15267: {
1.838 albertel 15268: my %hostname;
1.844 albertel 15269: my %hostdom;
1.845 albertel 15270: my %libserv;
1.852 albertel 15271: my $loaded;
1.888 albertel 15272: my %name_to_host;
1.1074 raeburn 15273: my %internetdom;
1.1107 raeburn 15274: my %LC_dns_serv;
1.852 albertel 15275:
15276: sub parse_hosts_tab {
15277: my ($file) = @_;
15278: foreach my $configline (@$file) {
15279: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 15280: chomp($configline);
15281: if ($configline =~ /^\^/) {
15282: if ($configline =~ /^\^([\w.\-]+)/) {
15283: $LC_dns_serv{$1} = 1;
15284: }
15285: next;
15286: }
1.1074 raeburn 15287: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 15288: $name=~s/\s//g;
15289: if ($id && $domain && $role && $name) {
1.1351 raeburn 15290: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15291: my $curr = $hostname{$id};
15292: my $skip;
15293: if (ref($name_to_host{$curr}) eq 'ARRAY') {
15294: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15295: $skip = 1;
15296: } else {
15297: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15298: }
15299: }
15300: unless ($skip) {
15301: push(@{$name_to_host{$name}},$id);
15302: }
15303: } else {
15304: push(@{$name_to_host{$name}},$id);
15305: }
1.852 albertel 15306: $hostname{$id}=$name;
15307: $hostdom{$id}=$domain;
15308: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 15309: if (defined($protocol)) {
15310: if ($protocol eq 'https') {
15311: $protocol{$id} = $protocol;
15312: } else {
15313: $protocol{$id} = 'http';
15314: }
1.968 raeburn 15315: } else {
1.969 raeburn 15316: $protocol{$id} = 'http';
1.968 raeburn 15317: }
1.1074 raeburn 15318: if (defined($intdom)) {
15319: $internetdom{$id} = $intdom;
15320: }
1.852 albertel 15321: }
15322: }
15323: }
1.864 albertel 15324:
15325: sub reset_hosts_info {
1.897 albertel 15326: &purge_remembered();
1.864 albertel 15327: &reset_domain_info();
15328: &reset_hosts_ip_info();
1.1339 raeburn 15329: undef(%internetdom);
1.892 albertel 15330: undef(%name_to_host);
1.864 albertel 15331: undef(%hostname);
15332: undef(%hostdom);
15333: undef(%libserv);
15334: undef($loaded);
15335: }
1.1 albertel 15336:
1.852 albertel 15337: sub load_hosts_tab {
1.1293 raeburn 15338: my ($ignore_cache,$nocache) = @_;
15339: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359 raeburn 15340: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 15341: my @config = <$config>;
15342: &parse_hosts_tab(\@config);
15343: close($config);
15344: $loaded=1;
1.1 albertel 15345: }
1.852 albertel 15346:
1.838 albertel 15347: sub hostname {
1.852 albertel 15348: &load_hosts_tab() if (!$loaded);
15349:
1.838 albertel 15350: my ($lonid) = @_;
15351: return $hostname{$lonid};
15352: }
1.845 albertel 15353:
1.838 albertel 15354: sub all_hostnames {
1.852 albertel 15355: &load_hosts_tab() if (!$loaded);
15356:
1.838 albertel 15357: return %hostname;
15358: }
1.845 albertel 15359:
1.888 albertel 15360: sub all_names {
1.1293 raeburn 15361: my ($ignore_cache,$nocache) = @_;
15362: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 15363:
15364: return %name_to_host;
15365: }
15366:
1.974 raeburn 15367: sub all_host_domain {
15368: &load_hosts_tab() if (!$loaded);
15369: return %hostdom;
15370: }
15371:
1.1339 raeburn 15372: sub all_host_intdom {
15373: &load_hosts_tab() if (!$loaded);
15374: return %internetdom;
15375: }
15376:
1.845 albertel 15377: sub is_library {
1.852 albertel 15378: &load_hosts_tab() if (!$loaded);
15379:
1.845 albertel 15380: return exists($libserv{$_[0]});
15381: }
15382:
15383: sub all_library {
1.852 albertel 15384: &load_hosts_tab() if (!$loaded);
15385:
1.845 albertel 15386: return %libserv;
15387: }
15388:
1.1062 droeschl 15389: sub unique_library {
15390: #2x reverse removes all hostnames that appear more than once
15391: my %unique = reverse &all_library();
15392: return reverse %unique;
15393: }
15394:
1.841 albertel 15395: sub get_servers {
1.852 albertel 15396: &load_hosts_tab() if (!$loaded);
15397:
1.841 albertel 15398: my ($domain,$type) = @_;
15399: my %possible_hosts = ($type eq 'library') ? %libserv
15400: : %hostname;
15401: my %result;
1.842 albertel 15402: if (ref($domain) eq 'ARRAY') {
15403: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 15404: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 15405: $result{$host} = $hostname;
15406: }
15407: }
15408: } else {
15409: while ( my ($host,$hostname) = each(%possible_hosts)) {
15410: if ($hostdom{$host} eq $domain) {
15411: $result{$host} = $hostname;
15412: }
1.841 albertel 15413: }
15414: }
15415: return %result;
15416: }
1.845 albertel 15417:
1.1062 droeschl 15418: sub get_unique_servers {
15419: my %unique = reverse &get_servers(@_);
15420: return reverse %unique;
15421: }
15422:
1.844 albertel 15423: sub host_domain {
1.852 albertel 15424: &load_hosts_tab() if (!$loaded);
15425:
1.844 albertel 15426: my ($lonid) = @_;
15427: return $hostdom{$lonid};
15428: }
15429:
1.841 albertel 15430: sub all_domains {
1.852 albertel 15431: &load_hosts_tab() if (!$loaded);
15432:
1.841 albertel 15433: my %seen;
15434: my @uniq = grep(!$seen{$_}++, values(%hostdom));
15435: return @uniq;
15436: }
1.1074 raeburn 15437:
15438: sub internet_dom {
15439: &load_hosts_tab() if (!$loaded);
15440:
15441: my ($lonid) = @_;
15442: return $internetdom{$lonid};
15443: }
1.1107 raeburn 15444:
15445: sub is_LC_dns {
15446: &load_hosts_tab() if (!$loaded);
15447:
15448: my ($hostname) = @_;
15449: return exists($LC_dns_serv{$hostname});
15450: }
15451:
1.1 albertel 15452: }
15453:
1.847 albertel 15454: {
15455: my %iphost;
1.856 albertel 15456: my %name_to_ip;
15457: my %lonid_to_ip;
1.869 albertel 15458:
1.847 albertel 15459: sub get_hosts_from_ip {
15460: my ($ip) = @_;
15461: my %iphosts = &get_iphost();
15462: if (ref($iphosts{$ip})) {
15463: return @{$iphosts{$ip}};
15464: }
15465: return;
1.839 albertel 15466: }
1.864 albertel 15467:
15468: sub reset_hosts_ip_info {
15469: undef(%iphost);
15470: undef(%name_to_ip);
15471: undef(%lonid_to_ip);
15472: }
1.856 albertel 15473:
15474: sub get_host_ip {
15475: my ($lonid) = @_;
15476: if (exists($lonid_to_ip{$lonid})) {
15477: return $lonid_to_ip{$lonid};
15478: }
15479: my $name=&hostname($lonid);
15480: my $ip = gethostbyname($name);
15481: return if (!$ip || length($ip) ne 4);
15482: $ip=inet_ntoa($ip);
15483: $name_to_ip{$name} = $ip;
15484: $lonid_to_ip{$lonid} = $ip;
15485: return $ip;
15486: }
1.847 albertel 15487:
15488: sub get_iphost {
1.1293 raeburn 15489: my ($ignore_cache,$nocache) = @_;
1.894 albertel 15490:
1.869 albertel 15491: if (!$ignore_cache) {
15492: if (%iphost) {
15493: return %iphost;
15494: }
15495: my ($ip_info,$cached)=
15496: &Apache::lonnet::is_cached_new('iphost','iphost');
15497: if ($cached) {
15498: %iphost = %{$ip_info->[0]};
15499: %name_to_ip = %{$ip_info->[1]};
15500: %lonid_to_ip = %{$ip_info->[2]};
15501: return %iphost;
15502: }
15503: }
1.894 albertel 15504:
15505: # get yesterday's info for fallback
15506: my %old_name_to_ip;
15507: my ($ip_info,$cached)=
15508: &Apache::lonnet::is_cached_new('iphost','iphost');
15509: if ($cached) {
15510: %old_name_to_ip = %{$ip_info->[1]};
15511: }
15512:
1.1293 raeburn 15513: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 15514: foreach my $name (keys(%name_to_host)) {
1.847 albertel 15515: my $ip;
15516: if (!exists($name_to_ip{$name})) {
15517: $ip = gethostbyname($name);
15518: if (!$ip || length($ip) ne 4) {
1.894 albertel 15519: if (defined($old_name_to_ip{$name})) {
15520: $ip = $old_name_to_ip{$name};
15521: &logthis("Can't find $name defaulting to old $ip");
15522: } else {
15523: &logthis("Name $name no IP found");
15524: next;
15525: }
15526: } else {
15527: $ip=inet_ntoa($ip);
1.847 albertel 15528: }
15529: $name_to_ip{$name} = $ip;
15530: } else {
15531: $ip = $name_to_ip{$name};
1.653 albertel 15532: }
1.888 albertel 15533: foreach my $id (@{ $name_to_host{$name} }) {
15534: $lonid_to_ip{$id} = $ip;
15535: }
15536: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 15537: }
1.1293 raeburn 15538: unless ($nocache) {
15539: &do_cache_new('iphost','iphost',
15540: [\%iphost,\%name_to_ip,\%lonid_to_ip],
15541: 48*60*60);
15542: }
1.869 albertel 15543:
1.847 albertel 15544: return %iphost;
1.598 albertel 15545: }
15546:
1.992 raeburn 15547: #
15548: # Given a DNS returns the loncapa host name for that DNS
15549: #
15550: sub host_from_dns {
15551: my ($dns) = @_;
15552: my @hosts;
15553: my $ip;
15554:
1.993 raeburn 15555: if (exists($name_to_ip{$dns})) {
1.992 raeburn 15556: $ip = $name_to_ip{$dns};
15557: }
15558: if (!$ip) {
15559: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15560: if (length($ip) == 4) {
15561: $ip = &IO::Socket::inet_ntoa($ip);
15562: }
15563: }
15564: if ($ip) {
15565: @hosts = get_hosts_from_ip($ip);
15566: return $hosts[0];
15567: }
15568: return undef;
1.986 foxr 15569: }
1.992 raeburn 15570:
1.1074 raeburn 15571: sub get_internet_names {
15572: my ($lonid) = @_;
15573: return if ($lonid eq '');
15574: my ($idnref,$cached)=
15575: &Apache::lonnet::is_cached_new('internetnames',$lonid);
15576: if ($cached) {
15577: return $idnref;
15578: }
15579: my $ip = &get_host_ip($lonid);
15580: my @hosts = &get_hosts_from_ip($ip);
15581: my %iphost = &get_iphost();
15582: my (@idns,%seen);
15583: foreach my $id (@hosts) {
15584: my $dom = &host_domain($id);
15585: my $prim_id = &domain($dom,'primary');
15586: my $prim_ip = &get_host_ip($prim_id);
15587: next if ($seen{$prim_ip});
15588: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15589: foreach my $id (@{$iphost{$prim_ip}}) {
15590: my $intdom = &internet_dom($id);
15591: unless (grep(/^\Q$intdom\E$/,@idns)) {
15592: push(@idns,$intdom);
15593: }
15594: }
15595: }
15596: $seen{$prim_ip} = 1;
15597: }
1.1219 raeburn 15598: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 15599: }
15600:
1.986 foxr 15601: }
15602:
1.1079 raeburn 15603: sub all_loncaparevs {
1.1249 raeburn 15604: 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 15605: }
15606:
1.1227 raeburn 15607: # ---------------------------------------------------------- Read loncaparev table
15608: {
15609: sub load_loncaparevs {
15610: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359 raeburn 15611: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227 raeburn 15612: while (my $configline=<$config>) {
15613: chomp($configline);
15614: my ($hostid,$loncaparev)=split(/:/,$configline);
15615: $loncaparevs{$hostid}=$loncaparev;
15616: }
15617: close($config);
15618: }
15619: }
15620: }
15621: }
15622:
15623: # ---------------------------------------------------------- Read serverhostID table
15624: {
15625: sub load_serverhomeIDs {
15626: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359 raeburn 15627: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227 raeburn 15628: while (my $configline=<$config>) {
15629: chomp($configline);
15630: my ($name,$id)=split(/:/,$configline);
15631: $serverhomeIDs{$name}=$id;
15632: }
15633: close($config);
15634: }
15635: }
15636: }
15637: }
15638:
15639:
1.862 albertel 15640: BEGIN {
15641:
15642: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15643: unless ($readit) {
15644: {
15645: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15646: %perlvar = (%perlvar,%{$configvars});
15647: }
15648:
15649:
1.1 albertel 15650: # ------------------------------------------------------ Read spare server file
15651: {
1.1359 raeburn 15652: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 15653:
15654: while (my $configline=<$config>) {
15655: chomp($configline);
1.284 matthew 15656: if ($configline) {
1.784 albertel 15657: my ($host,$type) = split(':',$configline,2);
1.785 albertel 15658: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 15659: push(@{ $spareid{$type} }, $host);
1.1 albertel 15660: }
15661: }
1.448 albertel 15662: close($config);
1.1 albertel 15663: }
1.11 www 15664: # ------------------------------------------------------------ Read permissions
15665: {
1.1359 raeburn 15666: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 15667:
15668: while (my $configline=<$config>) {
1.448 albertel 15669: chomp($configline);
15670: if ($configline) {
15671: my ($role,$perm)=split(/ /,$configline);
15672: if ($perm ne '') { $pr{$role}=$perm; }
15673: }
1.11 www 15674: }
1.448 albertel 15675: close($config);
1.11 www 15676: }
15677:
15678: # -------------------------------------------- Read plain texts for permissions
15679: {
1.1359 raeburn 15680: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 15681:
15682: while (my $configline=<$config>) {
1.448 albertel 15683: chomp($configline);
15684: if ($configline) {
1.742 raeburn 15685: my ($short,@plain)=split(/:/,$configline);
15686: %{$prp{$short}} = ();
15687: if (@plain > 0) {
15688: $prp{$short}{'std'} = $plain[0];
15689: for (my $i=1; $i<@plain; $i++) {
15690: $prp{$short}{'alt'.$i} = $plain[$i];
15691: }
15692: }
1.448 albertel 15693: }
1.135 www 15694: }
1.448 albertel 15695: close($config);
1.135 www 15696: }
15697:
15698: # ---------------------------------------------------------- Read package table
15699: {
1.1359 raeburn 15700: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 15701:
15702: while (my $configline=<$config>) {
1.483 albertel 15703: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 15704: chomp($configline);
15705: my ($short,$plain)=split(/:/,$configline);
15706: my ($pack,$name)=split(/\&/,$short);
15707: if ($plain ne '') {
15708: $packagetab{$pack.'&'.$name.'&name'}=$name;
15709: $packagetab{$short}=$plain;
15710: }
1.11 www 15711: }
1.448 albertel 15712: close($config);
1.329 matthew 15713: }
15714:
1.1073 raeburn 15715: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 15716:
15717: &load_loncaparevs();
1.1073 raeburn 15718:
1.1074 raeburn 15719: # ---------------------------------------------------------- Read serverhostID table
15720:
1.1227 raeburn 15721: &load_serverhomeIDs();
15722:
15723: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 15724: {
15725: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15726: if (-e $file) {
15727: my $parser = HTML::LCParser->new($file);
15728: while (my $token = $parser->get_token()) {
15729: if ($token->[0] eq 'S') {
15730: my $item = $token->[1];
15731: my $name = $token->[2]{'name'};
15732: my $value = $token->[2]{'value'};
1.1285 raeburn 15733: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 15734: my $namematch = $token->[2]{'namematch'};
15735: if ($item eq 'parameter') {
15736: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15737: my $release = $parser->get_text();
15738: $release =~ s/(^\s*|\s*$ )//gx;
15739: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15740: }
15741: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 15742: my $release = $parser->get_text();
15743: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 15744: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 15745: }
15746: }
15747: }
15748: }
1.1073 raeburn 15749: }
15750:
1.1138 raeburn 15751: # ---------------------------------------------------------- Read managers table
15752: {
15753: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359 raeburn 15754: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 15755: while (my $configline=<$config>) {
15756: chomp($configline);
15757: next if ($configline =~ /^\#/);
15758: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15759: $managerstab{$configline} = 1;
15760: }
15761: }
15762: close($config);
15763: }
15764: }
15765: }
15766:
1.329 matthew 15767: # ------------- set up temporary directory
15768: {
1.1117 foxr 15769: $tmpdir = LONCAPA::tempdir();
1.329 matthew 15770:
1.11 www 15771: }
15772:
1.1405 raeburn 15773: # ------------- set default texengine (domain default overrides this)
15774: {
15775: $deftex = LONCAPA::texengine();
15776: }
15777:
1.1416 raeburn 15778: # ------------- set default minimum length for passwords for internal auth users
15779: {
15780: $passwdmin = LONCAPA::passwd_min();
15781: }
15782:
1.794 albertel 15783: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
15784: 'compress_threshold'=> 20_000,
15785: });
1.185 www 15786:
1.281 www 15787: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 15788: $dumpcount=0;
1.958 www 15789: $locknum=0;
1.22 www 15790:
1.163 harris41 15791: &logtouch();
1.672 albertel 15792: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 15793: $readit=1;
1.564 albertel 15794: {
15795: use integer;
15796: my $test=(2**32)+1;
1.568 albertel 15797: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 15798: &logthis(" Detected 64bit platform ($_64bit)");
15799: }
1.195 www 15800: }
1.1 albertel 15801: }
1.179 www 15802:
1.1 albertel 15803: 1;
1.191 harris41 15804: __END__
15805:
1.243 albertel 15806: =pod
15807:
1.191 harris41 15808: =head1 NAME
15809:
1.243 albertel 15810: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 15811:
15812: =head1 SYNOPSIS
15813:
1.243 albertel 15814: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 15815:
15816: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15817:
1.243 albertel 15818: Common parameters:
15819:
15820: =over 4
15821:
15822: =item *
15823:
15824: $uname : an internal username (if $cname expecting a course Id specifically)
15825:
15826: =item *
15827:
15828: $udom : a domain (if $cdom expecting a course's domain specifically)
15829:
15830: =item *
15831:
15832: $symb : a resource instance identifier
15833:
15834: =item *
15835:
15836: $namespace : the name of a .db file that contains the data needed or
15837: being set.
15838:
15839: =back
15840:
1.394 bowersj2 15841: =head1 OVERVIEW
1.191 harris41 15842:
1.394 bowersj2 15843: lonnet provides subroutines which interact with the
15844: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15845: about classes, users, and resources.
1.243 albertel 15846:
15847: For many of these objects you can also use this to store data about
15848: them or modify them in various ways.
1.191 harris41 15849:
1.394 bowersj2 15850: =head2 Symbs
1.191 harris41 15851:
1.394 bowersj2 15852: To identify a specific instance of a resource, LON-CAPA uses symbols
15853: or "symbs"X<symb>. These identifiers are built from the URL of the
15854: map, the resource number of the resource in the map, and the URL of
15855: the resource itself. The latter is somewhat redundant, but might help
15856: if maps change.
15857:
15858: An example is
15859:
15860: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15861:
15862: The respective map entry is
15863:
15864: <resource id="19" src="/res/msu/korte/tests/part12.problem"
15865: title="Problem 2">
15866: </resource>
15867:
15868: Symbs are used by the random number generator, as well as to store and
15869: restore data specific to a certain instance of for example a problem.
15870:
15871: =head2 Storing And Retrieving Data
15872:
15873: X<store()>X<cstore()>X<restore()>Three of the most important functions
15874: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15875: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15876: is is the non-critical message twin of cstore. These functions are for
15877: handlers to store a perl hash to a user's permanent data space in an
15878: easy manner, and to retrieve it again on another call. It is expected
15879: that a handler would use this once at the beginning to retrieve data,
15880: and then again once at the end to send only the new data back.
15881:
15882: The data is stored in the user's data directory on the user's
15883: homeserver under the ID of the course.
15884:
15885: The hash that is returned by restore will have all of the previous
15886: value for all of the elements of the hash.
15887:
15888: Example:
15889:
15890: #creating a hash
15891: my %hash;
15892: $hash{'foo'}='bar';
15893:
15894: #storing it
15895: &Apache::lonnet::cstore(\%hash);
15896:
15897: #changing a value
15898: $hash{'foo'}='notbar';
15899:
15900: #adding a new value
15901: $hash{'bar'}='foo';
15902: &Apache::lonnet::cstore(\%hash);
15903:
15904: #retrieving the hash
15905: my %history=&Apache::lonnet::restore();
15906:
15907: #print the hash
15908: foreach my $key (sort(keys(%history))) {
15909: print("\%history{$key} = $history{$key}");
15910: }
15911:
15912: Will print out:
1.191 harris41 15913:
1.394 bowersj2 15914: %history{1:foo} = bar
15915: %history{1:keys} = foo:timestamp
15916: %history{1:timestamp} = 990455579
15917: %history{2:bar} = foo
15918: %history{2:foo} = notbar
15919: %history{2:keys} = foo:bar:timestamp
15920: %history{2:timestamp} = 990455580
15921: %history{bar} = foo
15922: %history{foo} = notbar
15923: %history{timestamp} = 990455580
15924: %history{version} = 2
15925:
15926: Note that the special hash entries C<keys>, C<version> and
15927: C<timestamp> were added to the hash. C<version> will be equal to the
15928: total number of versions of the data that have been stored. The
15929: C<timestamp> attribute will be the UNIX time the hash was
15930: stored. C<keys> is available in every historical section to list which
15931: keys were added or changed at a specific historical revision of a
15932: hash.
15933:
15934: B<Warning>: do not store the hash that restore returns directly. This
15935: will cause a mess since it will restore the historical keys as if the
15936: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 15937:
1.394 bowersj2 15938: Calling convention:
1.191 harris41 15939:
1.1225 raeburn 15940: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 15941: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 15942:
1.394 bowersj2 15943: For more detailed information, see lonnet specific documentation.
1.191 harris41 15944:
1.394 bowersj2 15945: =head1 RETURN MESSAGES
1.191 harris41 15946:
1.394 bowersj2 15947: =over 4
1.191 harris41 15948:
1.394 bowersj2 15949: =item * B<con_lost>: unable to contact remote host
1.191 harris41 15950:
1.394 bowersj2 15951: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15952: when the connection is brought back up
1.191 harris41 15953:
1.394 bowersj2 15954: =item * B<con_failed>: unable to contact remote host and unable to save message
15955: for later delivery
1.191 harris41 15956:
1.967 bisitz 15957: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 15958:
1.394 bowersj2 15959: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 15960: that was requested
1.191 harris41 15961:
1.243 albertel 15962: =back
1.191 harris41 15963:
1.243 albertel 15964: =head1 PUBLIC SUBROUTINES
1.191 harris41 15965:
1.243 albertel 15966: =head2 Session Environment Functions
1.191 harris41 15967:
1.243 albertel 15968: =over 4
1.191 harris41 15969:
1.394 bowersj2 15970: =item *
15971: X<appenv()>
1.949 raeburn 15972: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 15973: the user envirnoment file, and will be restored for each access this
1.620 albertel 15974: user makes during this session, also modifies the %env for the current
1.949 raeburn 15975: process. Optional rolesarrayref - if defined contains a reference to an array
15976: of roles which are exempt from the restriction on modifying user.role entries
15977: in the user's environment.db and in %env.
1.191 harris41 15978:
15979: =item *
1.394 bowersj2 15980: X<delenv()>
1.987 raeburn 15981: B<delenv($delthis,$regexp)>: removes all items from the session
15982: environment file that begin with $delthis. If the
15983: optional second arg - $regexp - is true, $delthis is treated as a
15984: regular expression, otherwise \Q$delthis\E is used.
15985: The values are also deleted from the current processes %env.
1.191 harris41 15986:
1.795 albertel 15987: =item * get_env_multiple($name)
15988:
15989: gets $name from the %env hash, it seemlessly handles the cases where multiple
15990: values may be defined and end up as an array ref.
15991:
15992: returns an array of values
15993:
1.243 albertel 15994: =back
15995:
15996: =head2 User Information
1.191 harris41 15997:
1.243 albertel 15998: =over 4
1.191 harris41 15999:
16000: =item *
1.394 bowersj2 16001: X<queryauthenticate()>
16002: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 16003: authentication scheme
16004:
16005: =item *
1.394 bowersj2 16006: X<authenticate()>
1.1073 raeburn 16007: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 16008: authenticate user from domain's lib servers (first use the current
16009: one). C<$upass> should be the users password.
1.1073 raeburn 16010: $checkdefauth is optional (value is 1 if a check should be made to
16011: authenticate user using default authentication method, and allow
16012: account creation if username does not have account in the domain).
16013: $clientcancheckhost is optional (value is 1 if checking whether the
16014: server can host will occur on the client side in lonauth.pm).
1.191 harris41 16015:
16016: =item *
1.394 bowersj2 16017: X<homeserver()>
16018: B<homeserver($uname,$udom)>: find the server which has
16019: the user's directory and files (there must be only one), this caches
16020: the answer, and also caches if there is a borken connection.
1.191 harris41 16021:
16022: =item *
1.394 bowersj2 16023: X<idget()>
1.1300 raeburn 16024: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
16025: a list of student/employee IDs or clicker IDs
16026: (student/employee IDs are a unique resource in a domain, there must be
16027: only 1 ID per username, and only 1 username per ID in a specific domain).
16028: clickerIDs are not necessarily unique, as students might share clickers.
16029: (returns hash: id=>name,id=>name)
1.191 harris41 16030:
16031: =item *
1.394 bowersj2 16032: X<idrget()>
16033: B<idrget($udom,@unames)>: find the IDs behind a list of
16034: usernames (returns hash: name=>id,name=>id)
1.191 harris41 16035:
16036: =item *
1.394 bowersj2 16037: X<idput()>
1.1300 raeburn 16038: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
16039: names and associated student/employee IDs or clicker IDs.
16040:
16041: =item *
16042: X<iddel()>
16043: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
16044: student/employee ID or clicker ID username look-ups from domain.
16045: The homeserver ($uhome) and namespace ($namespace) are optional.
16046: If no $uhome is provided, it will be determined usig &homeserver()
16047: for each user. If no $namespace is provided, the default is ids.
16048:
16049: =item *
16050: X<updateclickers()>
16051: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
16052: clicker ID-to-username look-ups in clickers.db on library server.
16053: Permitted actions are add or del (i.e., add or delete). The
16054: clickers.db contains clickerID as keys (escaped), and each corresponding
16055: value is an escaped comma-separated list of usernames (for whom the
16056: library server is the homeserver), who registered that particular ID.
16057: If $critical is true, the update will be sent via &critical, otherwise
16058: &reply() will be used.
1.191 harris41 16059:
16060: =item *
1.394 bowersj2 16061: X<rolesinit()>
1.1169 droeschl 16062: B<rolesinit($udom,$username)>: get user privileges.
16063: returns user role, first access and timer interval hashes
1.243 albertel 16064:
16065: =item *
1.1171 droeschl 16066: X<privileged()>
16067: B<privileged($username,$domain)>: returns a true if user has a
16068: privileged and active role (i.e. su or dc), false otherwise.
16069:
16070: =item *
1.551 albertel 16071: X<getsection()>
16072: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 16073: course $cname, return section name/number or '' for "not in course"
16074: and '-1' for "no section"
16075:
16076: =item *
1.394 bowersj2 16077: X<userenvironment()>
16078: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 16079: passed in @what from the requested user's environment, returns a hash
16080:
1.858 raeburn 16081: =item *
16082: X<userlog_query()>
1.859 albertel 16083: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16084: activity.log file. %filters defines filters applied when parsing the
16085: log file. These can be start or end timestamps, or the type of action
16086: - log to look for Login or Logout events, check for Checkin or
16087: Checkout, role for role selection. The response is in the form
16088: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
16089: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 16090:
1.243 albertel 16091: =back
16092:
16093: =head2 User Roles
16094:
16095: =over 4
16096:
16097: =item *
16098:
1.1284 raeburn 16099: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
16100: returns codes for allowed actions.
16101:
16102: The first argument is required, all others are optional.
16103:
16104: $priv is the privilege being checked.
16105: $uri contains additional information about what is being checked for access (e.g.,
16106: URL, course ID etc.).
16107: $symb is the unique resource instance identifier in a course; if needed,
16108: but not provided, it will be retrieved via a call to &symbread().
16109: $role is the role for which a priv is being checked (only used if priv is evb).
16110: $clientip is the user's IP address (only used when checking for access to portfolio
16111: files).
16112: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
16113: prevents recursive calls to &allowed.
16114:
1.243 albertel 16115: F: full access
16116: U,I,K: authentication modes (cxx only)
16117: '': forbidden
16118: 1: user needs to choose course
16119: 2: browse allowed
1.766 albertel 16120: A: passphrase authentication needed
1.1284 raeburn 16121: B: access temporarily blocked because of a blocking event in a course.
1.1402 raeburn 16122: D: access blocked because access is required via session initiated via deep-link
1.243 albertel 16123:
16124: =item *
16125:
1.1192 raeburn 16126: constructaccess($url,$setpriv) : check for access to construction space URL
16127:
16128: See if the owner domain and name in the URL match those in the
16129: expected environment. If so, return three element list
16130: ($ownername,$ownerdomain,$ownerhome).
16131:
16132: Otherwise return the null string.
16133:
16134: If second argument 'setpriv' is true, it assigns the privileges,
16135: and returns the same three element list, unless the owner has
16136: blocked "ad hoc" Domain Coordinator access to the Author Space,
16137: in which case the null string is returned.
16138:
16139: =item *
16140:
1.1326 raeburn 16141: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16142: define a custom role rolename set privileges in format of lonTabs/roles.tab
16143: for system, domain, and course level. $uname and $udom are optional (current
16144: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 16145:
16146: =item *
16147:
1.988 raeburn 16148: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
16149: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 16150: $type is Course (default) or Community.
1.988 raeburn 16151: If $forcedefault evaluates to true, text returned will be default
16152: text for $type. Otherwise, if this is a course, the text returned
16153: will be a custom name for the role (if defined in the course's
16154: environment). If no custom name is defined the default is returned.
16155:
1.832 raeburn 16156: =item *
16157:
1.1219 raeburn 16158: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 16159: All arguments are optional. Returns a hash of a roles, either for
16160: co-author/assistant author roles for a user's Construction Space
1.906 albertel 16161: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 16162: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16163: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16164: For each key, value is set to colon-separated start and end times for
16165: the role. If no username and domain are specified, will default to
1.934 raeburn 16166: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 16167: of role statuses (active, future or previous), roles
16168: (e.g., cc,in, st etc.) and domains of the roles which can be used
16169: to restrict the list of roles reported. If no array ref is
16170: provided for types, will default to return only active roles.
1.834 albertel 16171:
1.1195 raeburn 16172: =item *
16173:
16174: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 16175: user: $uname:$udom has a role in the course: $cdom_$cnum.
16176:
16177: Additional optional arguments are: $type (if role checking is to be restricted
16178: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 16179: available roles) or future (roles available in the future), and
16180: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 16181: have active Domain Coordinator role in course's domain or in additional
16182: domains (specified in 'Domains to check for privileged users' in course
16183: environment -- set via: Course Settings -> Classlists and staff listing).
16184:
16185: =item *
16186:
16187: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16188: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16189: $possdomains and $possroles are optional array refs -- to domains to check and
16190: roles to check. If $possdomains is not specified, a dump will be done of the
16191: users' roles.db to check for a dc or su role in any domain. This can be
16192: time consuming if &privileged is called repeatedly (e.g., when displaying a
16193: classlist), so in such cases, supplying a $possdomains array is preferred, as
16194: this then allows &privileged_by_domain() to be used, which caches the identity
16195: of privileged users, eliminating the need for repeated calls to &dump().
16196:
16197: =item *
16198:
16199: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16200: where the outer hash keys are domains specified in the $possdomains array ref,
16201: next inner hash keys are privileged roles specified in the $roles array ref,
16202: and the innermost hash contains key = value pairs for username:domain = end:start
16203: for active or future "privileged" users with that role in that domain. To avoid
16204: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16205: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 16206:
1.243 albertel 16207: =back
16208:
16209: =head2 User Modification
16210:
16211: =over 4
16212:
16213: =item *
16214:
1.957 raeburn 16215: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 16216: user for the level given by URL. Optional start and end dates (leave empty
16217: string or zero for "no date")
1.191 harris41 16218:
16219: =item *
16220:
1.243 albertel 16221: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16222: change a users, password, possible return values are: ok,
16223: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16224: refused
1.191 harris41 16225:
16226: =item *
16227:
1.243 albertel 16228: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 16229:
16230: =item *
16231:
1.1058 raeburn 16232: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16233: $forceid,$desiredhome,$email,$inststatus,$candelete) :
16234:
16235: will update user information (firstname,middlename,lastname,generation,
16236: permanentemail), and if forceid is true, student/employee ID also.
16237: A user's institutional affiliation(s) can also be updated.
16238: User information fields will not be overwritten with empty entries
16239: unless the field is included in the $candelete array reference.
16240: This array is included when a single user is modified via "Manage Users",
16241: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 16242:
16243: =item *
16244:
1.286 matthew 16245: modifystudent
16246:
1.957 raeburn 16247: modify a student's enrollment and identification information.
1.1235 raeburn 16248: The course id is resolved based on the current user's environment.
16249: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 16250: associated with a course.
16251:
1.297 matthew 16252: This call is essentially a wrapper for lonnet::modifyuser and
16253: lonnet::modify_student_enrollment
1.286 matthew 16254:
16255: Inputs:
16256:
16257: =over 4
16258:
1.957 raeburn 16259: =item B<$udom> Student's loncapa domain
1.286 matthew 16260:
1.957 raeburn 16261: =item B<$uname> Student's loncapa login name
1.286 matthew 16262:
1.964 bisitz 16263: =item B<$uid> Student/Employee ID
1.286 matthew 16264:
1.957 raeburn 16265: =item B<$umode> Student's authentication mode
1.286 matthew 16266:
1.957 raeburn 16267: =item B<$upass> Student's password
1.286 matthew 16268:
1.957 raeburn 16269: =item B<$first> Student's first name
1.286 matthew 16270:
1.957 raeburn 16271: =item B<$middle> Student's middle name
1.286 matthew 16272:
1.957 raeburn 16273: =item B<$last> Student's last name
1.286 matthew 16274:
1.957 raeburn 16275: =item B<$gene> Student's generation
1.286 matthew 16276:
1.957 raeburn 16277: =item B<$usec> Student's section in course
1.286 matthew 16278:
16279: =item B<$end> Unix time of the roles expiration
16280:
16281: =item B<$start> Unix time of the roles start date
16282:
16283: =item B<$forceid> If defined, allow $uid to be changed
16284:
16285: =item B<$desiredhome> server to use as home server for student
16286:
1.957 raeburn 16287: =item B<$email> Student's permanent e-mail address
16288:
16289: =item B<$type> Type of enrollment (auto or manual)
16290:
1.963 raeburn 16291: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
16292:
16293: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 16294:
1.963 raeburn 16295: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 16296:
1.963 raeburn 16297: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 16298:
1.1216 raeburn 16299: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16300:
16301: =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 16302:
1.286 matthew 16303: =back
1.297 matthew 16304:
16305: =item *
16306:
16307: modify_student_enrollment
16308:
1.1235 raeburn 16309: Change a student's enrollment status in a class. The environment variable
1.297 matthew 16310: 'role.request.course' must be defined for this function to proceed.
16311:
16312: Inputs:
16313:
16314: =over 4
16315:
1.1235 raeburn 16316: =item $udom, student's domain
1.297 matthew 16317:
1.1235 raeburn 16318: =item $uname, student's name
1.297 matthew 16319:
1.1235 raeburn 16320: =item $uid, student's user id
1.297 matthew 16321:
1.1235 raeburn 16322: =item $first, student's first name
1.297 matthew 16323:
16324: =item $middle
16325:
16326: =item $last
16327:
16328: =item $gene
16329:
16330: =item $usec
16331:
16332: =item $end
16333:
16334: =item $start
16335:
1.957 raeburn 16336: =item $type
16337:
16338: =item $locktype
16339:
16340: =item $cid
16341:
16342: =item $selfenroll
16343:
16344: =item $context
16345:
1.1216 raeburn 16346: =item $credits, number of credits student will earn from this class
16347:
1.1314 raeburn 16348: =item $instsec, institutional course section code for student
16349:
1.297 matthew 16350: =back
16351:
1.191 harris41 16352:
16353: =item *
16354:
1.243 albertel 16355: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16356: custom role; give a custom role to a user for the level given by URL. Specify
16357: name and domain of role author, and role name
1.191 harris41 16358:
16359: =item *
16360:
1.243 albertel 16361: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 16362:
16363: =item *
16364:
1.243 albertel 16365: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16366:
16367: =back
16368:
16369: =head2 Course Infomation
16370:
16371: =over 4
1.191 harris41 16372:
16373: =item *
16374:
1.1118 foxr 16375: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 16376: specified course id, including all environment settings for the
16377: course, the description of the course will be in the hash under the
16378: key 'description'
1.191 harris41 16379:
1.1118 foxr 16380: $options is an optional parameter that if supplied is a hash reference that controls
16381: what how this function works. It has the following key/values:
16382:
16383: =over 4
16384:
16385: =item freshen_cache
16386:
16387: If defined, and the environment cache for the course is valid, it is
16388: returned in the returned hash.
16389:
16390: =item one_time
16391:
16392: If defined, the last cache time is set to _now_
16393:
16394: =item user
16395:
16396: If defined, the supplied username is used instead of the current user.
16397:
16398:
16399: =back
16400:
1.191 harris41 16401: =item *
16402:
1.624 albertel 16403: resdata($name,$domain,$type,@which) : request for current parameter
16404: setting for a specific $type, where $type is either 'course' or 'user',
16405: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 16406: answers for 10 minutes.
1.243 albertel 16407:
1.877 foxr 16408: =item *
16409:
16410: get_courseresdata($courseid, $domain) : dump the entire course resource
16411: data base, returning a hash that is keyed by the resource name and has
16412: values that are the resource value. I believe that the timestamps and
16413: versions are also returned.
16414:
1.1236 raeburn 16415: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
16416: supplemental content area. This routine caches the number of files for
16417: 10 minutes.
16418:
1.243 albertel 16419: =back
16420:
16421: =head2 Course Modification
16422:
16423: =over 4
1.191 harris41 16424:
16425: =item *
16426:
1.243 albertel 16427: writecoursepref($courseid,%prefs) : write preferences (environment
16428: database) for a course
1.191 harris41 16429:
16430: =item *
16431:
1.1011 raeburn 16432: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16433:
16434: =item *
16435:
1.1038 raeburn 16436: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 16437:
1.1167 droeschl 16438: =item *
16439:
16440: is_course($courseid), is_course($cdom, $cnum)
16441:
16442: Accepts either a combined $courseid (in the form of domain_courseid) or the
16443: two component version $cdom, $cnum. It checks if the specified course exists.
16444:
16445: Returns:
16446: undef if the course doesn't exist, otherwise
16447: in scalar context the combined courseid.
16448: in list context the two components of the course identifier, domain and
16449: courseid.
16450:
1.243 albertel 16451: =back
16452:
1.1401 raeburn 16453: =head2 Bubblesheet Configuration
16454:
16455: =over 4
16456:
16457: =item *
16458:
16459: get_scantron_config($which)
16460:
16461: $which - the name of the configuration to parse from the file.
16462:
16463: Parses and returns the bubblesheet configuration line selected as a
16464: hash of configuration file fields.
16465:
16466:
16467: Returns:
16468: If the named configuration is not in the file, an empty
16469: hash is returned.
16470:
16471: a hash with the fields
16472: name - internal name for the this configuration setup
16473: description - text to display to operator that describes this config
16474: CODElocation - if 0 or the string 'none'
16475: - no CODE exists for this config
16476: if -1 || the string 'letter'
16477: - a CODE exists for this config and is
16478: a string of letters
16479: Unsupported value (but planned for future support)
16480: if a positive integer
16481: - The CODE exists as the first n items from
16482: the question section of the form
16483: if the string 'number'
16484: - The CODE exists for this config and is
16485: a string of numbers
16486: CODEstart - (only matter if a CODE exists) column in the line where
16487: the CODE starts
16488: CODElength - length of the CODE
16489: IDstart - column where the student/employee ID starts
16490: IDlength - length of the student/employee ID info
16491: Qstart - column where the information from the bubbled
16492: 'questions' start
16493: Qlength - number of columns comprising a single bubble line from
16494: the sheet. (usually either 1 or 10)
16495: Qon - either a single character representing the character used
16496: to signal a bubble was chosen in the positional setup, or
16497: the string 'letter' if the letter of the chosen bubble is
16498: in the final, or 'number' if a number representing the
16499: chosen bubble is in the file (1->A 0->J)
16500: Qoff - the character used to represent that a bubble was
16501: left blank
16502: PaperID - if the scanning process generates a unique number for each
16503: sheet scanned the column that this ID number starts in
16504: PaperIDlength - number of columns that comprise the unique ID number
16505: for the sheet of paper
16506: FirstName - column that the first name starts in
16507: FirstNameLength - number of columns that the first name spans
16508: LastName - column that the last name starts in
16509: LastNameLength - number of columns that the last name spans
16510: BubblesPerRow - number of bubbles available in each row used to
16511: bubble an answer. (If not specified, 10 assumed).
16512:
16513:
16514: =item *
16515:
16516: get_scantronformat_file($cdom)
16517:
16518: $cdom - the course's domain (optional); if not supplied, uses
16519: domain for current $env{'request.course.id'}.
16520:
16521: Returns an array containing lines from the scantron format file for
16522: the domain of the course.
16523:
16524: If a url for a custom.tab file is listed in domain's configuration.db,
16525: lines are from this file.
16526:
16527: Otherwise, if a default.tab has been published in RES space by the
16528: domainconfig user, lines are from this file.
16529:
16530: Otherwise, fall back to getting lines from the legacy file on the
16531: local server: /home/httpd/lonTabs/default_scantronformat.tab
16532:
16533: =back
16534:
1.243 albertel 16535: =head2 Resource Subroutines
16536:
16537: =over 4
1.191 harris41 16538:
16539: =item *
16540:
1.243 albertel 16541: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 16542:
16543: =item *
16544:
1.243 albertel 16545: repcopy($filename) : subscribes to the requested file, and attempts to
16546: replicate from the owning library server, Might return
1.607 raeburn 16547: 'unavailable', 'not_found', 'forbidden', 'ok', or
16548: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 16549: resource. Expects the local filesystem pathname
16550: (/home/httpd/html/res/....)
16551:
16552: =back
16553:
16554: =head2 Resource Information
16555:
16556: =over 4
1.191 harris41 16557:
16558: =item *
16559:
1.1228 raeburn 16560: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
16561: and returns the value of a variety of different possible values,
16562: $varname should be a request string, and the other parameters can be
16563: used to specify who and what one is asking about. Ordinarily, $cid
16564: does not need to be specified, as it is retrived from
16565: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16566: within lonuserstate::loadmap() when initializing a course, before
16567: $env{'request.course.id'} has been set, so it needs to be provided
16568: in that one case.
1.243 albertel 16569:
16570: Possible values for $varname are environment.lastname (or other item
16571: from the envirnment hash), user.name (or someother aspect about the
16572: user), resource.0.maxtries (or some other part and parameter of a
16573: resource)
1.204 albertel 16574:
16575: =item *
16576:
1.243 albertel 16577: directcondval($number) : get current value of a condition; reads from a state
16578: string
1.204 albertel 16579:
16580: =item *
16581:
1.243 albertel 16582: condval($condidx) : value of condition index based on state
1.204 albertel 16583:
16584: =item *
16585:
1.1362 raeburn 16586: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243 albertel 16587: resource's metadata, $what should be either a specific key, or either
16588: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362 raeburn 16589: packages that this resource currently uses, the last 3 arguments are
16590: only used internally for recursive metadata.
16591:
16592: the toolsymb is only used where the uri is for an external tool (for which
16593: the uri as well as the symb are guaranteed to be unique).
1.243 albertel 16594:
1.1371 raeburn 16595: this function automatically caches all requests except any made recursively
16596: to retrieve a list of metadata keys for an imported library file ($liburi is
16597: defined).
1.191 harris41 16598:
16599: =item *
16600:
1.243 albertel 16601: metadata_query($query,$custom,$customshow) : make a metadata query against the
16602: network of library servers; returns file handle of where SQL and regex results
16603: will be stored for query
1.191 harris41 16604:
16605: =item *
16606:
1.1282 raeburn 16607: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
16608: return symbolic list entry (all arguments optional).
16609:
16610: Args: filename is the filename (including path) for the file for which a symb
16611: is required; donotrecurse, if true will prevent calls to allowed() being made
16612: to check access status if more than one resource was found in the bighash
16613: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
16614: a randompick); ignorecachednull, if true will prevent a symb of '' being
16615: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16616: cause possible symbs to be checked to determine if they are subject to content
16617: blocking, if so they will not be included as possible symbs; possibles is a
16618: ref to a hash, which, as a side effect, will be populated with all possible
16619: symbs (content blocking not tested).
16620:
1.243 albertel 16621: returns the data handle
1.191 harris41 16622:
16623: =item *
16624:
1.1190 raeburn 16625: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16626: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 16627: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 16628: on failure, user must be in a course, as it assumes the existence of
16629: the course initial hash, and uses $env('request.course.id'}. The third
16630: arg is an optional reference to a scalar. If this arg is passed in the
16631: call to symbverify, it will be set to 1 if the symb has been set to be
16632: encrypted; otherwise it will be null.
1.191 harris41 16633:
16634: =item *
16635:
1.243 albertel 16636: symbclean($symb) : removes versions numbers from a symb, returns the
16637: cleaned symb
1.191 harris41 16638:
16639: =item *
16640:
1.243 albertel 16641: is_on_map($uri) : checks if the $uri is somewhere on the current
16642: course map, user must be in a course for it to work.
1.191 harris41 16643:
16644: =item *
16645:
1.243 albertel 16646: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 16647:
16648: =item *
16649:
1.243 albertel 16650: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16651: a random seed, all arguments are optional, if they aren't sent it uses the
16652: environment to derive them. Note: if symb isn't sent and it can't get one
16653: from &symbread it will use the current time as its return value
1.191 harris41 16654:
16655: =item *
16656:
1.243 albertel 16657: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16658: unfakeable, receipt
1.191 harris41 16659:
16660: =item *
16661:
1.620 albertel 16662: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 16663:
16664: =item *
16665:
1.243 albertel 16666: countacc($url) : count the number of accesses to a given URL
1.191 harris41 16667:
16668: =item *
16669:
1.243 albertel 16670: 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 16671:
16672: =item *
16673:
1.243 albertel 16674: 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 16675:
16676: =item *
16677:
1.243 albertel 16678: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 16679:
16680: =item *
16681:
1.243 albertel 16682: devalidate($symb) : devalidate temporary spreadsheet calculations,
16683: forcing spreadsheet to reevaluate the resource scores next time.
16684:
1.1195 raeburn 16685: =item *
16686:
1.1196 raeburn 16687: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16688: when viewing in course context.
1.1195 raeburn 16689:
1.1196 raeburn 16690: input: six args -- filename (decluttered), course number, course domain,
16691: url, symb (if registered) and group (if this is a
16692: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 16693:
1.1196 raeburn 16694: output: array of five scalars --
1.1195 raeburn 16695: $cfile -- url for file editing if editable on current server
16696: $home -- homeserver of resource (i.e., for author if published,
16697: or course if uploaded.).
16698: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 16699: $forceedit -- 1 if icon/link should be to go to edit mode
16700: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 16701:
16702: =item *
16703:
16704: is_course_upload($file,$cnum,$cdom)
16705:
16706: Used in course context to determine if current file was uploaded to
16707: the course (i.e., would be found in /userfiles/docs on the course's
16708: homeserver.
16709:
16710: input: 3 args -- filename (decluttered), course number and course domain.
16711: output: boolean -- 1 if file was uploaded.
16712:
1.243 albertel 16713: =back
16714:
16715: =head2 Storing/Retreiving Data
16716:
16717: =over 4
1.191 harris41 16718:
16719: =item *
16720:
1.1269 raeburn 16721: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16722: permanently for this url; hashref needs to be given and should be a \%hashname;
16723: the remaining args aren't required and if they aren't passed or are '' they will
16724: be derived from the env (with the exception of $laststore, which is an
16725: optional arg used when a user's submission is stored in grading).
16726: $laststore is $version=$timestamp, where $version is the most recent version
16727: number retrieved for the corresponding $symb in the $namespace db file, and
16728: $timestamp is the timestamp for that transaction (UNIX time).
16729: $laststore is currently only passed when cstore() is called by
16730: structuretags::finalize_storage().
1.191 harris41 16731:
16732: =item *
16733:
1.1269 raeburn 16734: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16735: but uses critical subroutine
1.191 harris41 16736:
16737: =item *
16738:
1.243 albertel 16739: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16740: all args are optional
1.191 harris41 16741:
16742: =item *
16743:
1.717 albertel 16744: dumpstore($namespace,$udom,$uname,$regexp,$range) :
16745: dumps the complete (or key matching regexp) namespace into a hash
16746: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16747: normally &store()ed into
16748:
16749: $range should be either an integer '100' (give me the first 100
16750: matching records)
16751: or be two integers sperated by a - with no spaces
16752: '30-50' (give me the 30th through the 50th matching
16753: records)
16754:
16755:
16756: =item *
16757:
1.1269 raeburn 16758: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 16759: replaces a &store() version of data with a replacement set of data
16760: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 16761: reference. If $tolog is true, the transaction is logged in the courselog
16762: with an action=PUTSTORE.
1.717 albertel 16763:
16764: =item *
16765:
1.243 albertel 16766: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16767: works very similar to store/cstore, but all data is stored in a
16768: temporary location and can be reset using tmpreset, $storehash should
16769: be a hash reference, returns nothing on success
1.191 harris41 16770:
16771: =item *
16772:
1.243 albertel 16773: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16774: similar to restore, but all data is stored in a temporary location and
16775: can be reset using tmpreset. Returns a hash of values on success,
16776: error string otherwise.
1.191 harris41 16777:
16778: =item *
16779:
1.243 albertel 16780: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16781: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 16782:
16783: =item *
16784:
1.243 albertel 16785: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16786: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 16787:
16788: =item *
16789:
1.243 albertel 16790: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16791: namesp ($udom and $uname are optional)
1.191 harris41 16792:
16793: =item *
16794:
1.702 albertel 16795: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 16796: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 16797: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 16798:
1.702 albertel 16799: $range should be either an integer '100' (give me the first 100
16800: matching records)
16801: or be two integers sperated by a - with no spaces
16802: '30-50' (give me the 30th through the 50th matching
16803: records)
1.449 matthew 16804: =item *
16805:
16806: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16807: $store can be a scalar, an array reference, or if the amount to be
16808: incremented is > 1, a hash reference.
16809:
16810: ($udom and $uname are optional)
1.191 harris41 16811:
16812: =item *
16813:
1.243 albertel 16814: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16815: ($udom and $uname are optional)
1.191 harris41 16816:
16817: =item *
16818:
1.243 albertel 16819: cput($namespace,$storehash,$udom,$uname) : critical put
16820: ($udom and $uname are optional)
1.191 harris41 16821:
16822: =item *
16823:
1.748 albertel 16824: newput($namespace,$storehash,$udom,$uname) :
16825:
16826: Attempts to store the items in the $storehash, but only if they don't
16827: currently exist, if this succeeds you can be certain that you have
16828: successfully created a new key value pair in the $namespace db.
16829:
16830:
16831: Args:
16832: $namespace: name of database to store values to
16833: $storehash: hashref to store to the db
16834: $udom: (optional) domain of user containing the db
16835: $uname: (optional) name of user caontaining the db
16836:
16837: Returns:
16838: 'ok' -> succeeded in storing all keys of $storehash
16839: 'key_exists: <key>' -> failed to anything out of $storehash, as at
16840: least <key> already existed in the db (other
16841: requested keys may also already exist)
1.967 bisitz 16842: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 16843: 'con_lost' -> unable to contact request server
16844: 'refused' -> action was not allowed by remote machine
16845:
16846:
16847: =item *
16848:
1.243 albertel 16849: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16850: reference filled in from namesp (encrypts the return communication)
16851: ($udom and $uname are optional)
1.191 harris41 16852:
16853: =item *
16854:
1.243 albertel 16855: log($udom,$name,$home,$message) : write to permanent log for user; use
16856: critical subroutine
16857:
1.806 raeburn 16858: =item *
16859:
1.860 raeburn 16860: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16861: array reference filled in from namespace found in domain level on either
16862: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 16863:
16864: =item *
16865:
1.860 raeburn 16866: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
16867: domain level either on specified domain server ($uhome) or primary domain
16868: server ($udom and $uhome are optional)
1.806 raeburn 16869:
1.943 raeburn 16870: =item *
16871:
1.1240 raeburn 16872: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
16873: for: authentication, language, quotas, timezone, date locale, and portal URL in
16874: the target domain.
16875:
16876: May also include additional key => value pairs for the following groups:
16877:
16878: =over
16879:
16880: =item
16881: disk quotas (MB allocated by default to portfolios and authoring spaces).
16882:
16883: =over
16884:
16885: =item defaultquota, authorquota
16886:
16887: =back
16888:
16889: =item
16890: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16891: portfolio for users).
16892:
16893: =over
16894:
16895: =item
16896: aboutme, blog, webdav, portfolio
16897:
16898: =back
16899:
16900: =item
16901: requestcourses: ability to request courses, and how requests are processed.
16902:
16903: =over
16904:
16905: =item
1.1305 raeburn 16906: official, unofficial, community, textbook, placement
1.1240 raeburn 16907:
16908: =back
16909:
16910: =item
16911: inststatus: types of institutional affiliation, and order in which they are displayed.
16912:
16913: =over
16914:
16915: =item
1.1256 raeburn 16916: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 16917:
16918: =back
16919:
16920: =item
16921: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16922: for course's uploaded content.
16923:
16924: =over
16925:
16926: =item
1.1246 raeburn 16927: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 16928: communityquota, textbookquota, placementquota
1.1240 raeburn 16929:
16930: =back
16931:
16932: =item
16933: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16934: on your servers.
16935:
16936: =over
16937:
16938: =item
16939: remotesessions, hostedsessions
16940:
16941: =back
16942:
16943: =back
16944:
16945: In cases where a domain coordinator has never used the "Set Domain Configuration"
16946: utility to create a configuration.db file on a domain's primary library server
16947: only the following domain defaults: auth_def, auth_arg_def, lang_def
16948: -- corresponding values are authentication type (internal, krb4, krb5,
16949: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
16950: will be available. Values are retrieved from cache (if current), unless the
16951: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16952: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16953:
16954: Typical usage:
1.943 raeburn 16955:
1.1240 raeburn 16956: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 16957:
1.243 albertel 16958: =back
16959:
16960: =head2 Network Status Functions
16961:
16962: =over 4
1.191 harris41 16963:
16964: =item *
16965:
1.1137 raeburn 16966: dirlist() : return directory list based on URI (first arg).
16967:
16968: Inputs: 1 required, 5 optional.
16969:
16970: =over
16971:
16972: =item
16973: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16974:
16975: =item
16976: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
16977:
16978: =item
16979: $username - username of user/course to be listed. Extracted from $uri if absent.
16980:
16981: =item
16982: $getpropath - boolean: 1 if prepend path using &propath().
16983:
16984: =item
16985: $getuserdir - boolean: 1 if prepend path for "userfiles".
16986:
16987: =item
16988: $alternateRoot - path to prepend in place of path from $uri.
16989:
16990: =back
16991:
16992: Returns: Array of up to two items.
16993:
16994: =over
16995:
16996: a reference to an array of files/subdirectories
16997:
16998: =over
16999:
17000: Each element in the array of files/subdirectories is a & separated list of
17001: item name and the result of running stat on the item. If dirlist was requested
17002: for a file instead of a directory, the item name will be ''. For a directory
17003: listing, if the item is a metadata file, the element will end &N&M
17004: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17005: default copyright set (1).
17006:
17007: =back
17008:
17009: a scalar containing error condition (if encountered).
17010:
17011: =over
17012:
17013: =item
17014: no_host (no homeserver identified for $username:$domain).
17015:
17016: =item
17017: no_such_host (server contacted for listing not identified as valid host).
17018:
17019: =item
17020: con_lost (connection to remote server failed).
17021:
17022: =item
17023: refused (invalid $username:$domain received on lond side).
17024:
17025: =item
17026: no_such_dir (directory at specified path on lond side does not exist).
17027:
17028: =item
17029: empty (directory at specified path on lond side is empty).
17030:
17031: =over
17032:
17033: This is currently not encountered because the &ls3, &ls2,
17034: &ls (_handler) routines on the lond side do not filter out
17035: . and .. from a directory listing.
17036:
17037: =back
17038:
17039: =back
17040:
17041: =back
1.191 harris41 17042:
17043: =item *
17044:
1.243 albertel 17045: spareserver() : find server with least workload from spare.tab
17046:
1.986 foxr 17047:
17048: =item *
17049:
17050: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17051: if there is no corresponding loncapa host.
17052:
1.243 albertel 17053: =back
17054:
1.986 foxr 17055:
1.243 albertel 17056: =head2 Apache Request
17057:
17058: =over 4
1.191 harris41 17059:
17060: =item *
17061:
1.243 albertel 17062: ssi($url,%hash) : server side include, does a complete request cycle on url to
17063: localhost, posts hash
17064:
17065: =back
17066:
17067: =head2 Data to String to Data
17068:
17069: =over 4
1.191 harris41 17070:
17071: =item *
17072:
1.243 albertel 17073: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17074: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 17075:
17076: =item *
17077:
1.243 albertel 17078: hashref2str($hashref) : convert a hashref into a string complete with
17079: escaping and '=' and '&' separators, supports elements that are
17080: arrayrefs and hashrefs
1.191 harris41 17081:
17082: =item *
17083:
1.243 albertel 17084: arrayref2str($arrayref) : convert an arrayref into a string complete
17085: with escaping and '&' separators, supports elements that are arrayrefs
17086: and hashrefs
1.191 harris41 17087:
17088: =item *
17089:
1.243 albertel 17090: str2hash($string) : convert string to hash using unescaping and
17091: splitting on '=' and '&', supports elements that are arrayrefs and
17092: hashrefs
1.191 harris41 17093:
17094: =item *
17095:
1.243 albertel 17096: str2array($string) : convert string to hash using unescaping and
17097: splitting on '&', supports elements that are arrayrefs and hashrefs
17098:
17099: =back
17100:
17101: =head2 Logging Routines
17102:
17103:
17104: These routines allow one to make log messages in the lonnet.log and
17105: lonnet.perm logfiles.
1.191 harris41 17106:
1.1119 foxr 17107: =over 4
17108:
1.191 harris41 17109: =item *
17110:
1.243 albertel 17111: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 17112:
17113: =item *
17114:
1.243 albertel 17115: logthis() : append message to the normal lonnet.log file, it gets
17116: preiodically rolled over and deleted.
1.191 harris41 17117:
17118: =item *
17119:
1.243 albertel 17120: logperm() : append a permanent message to lonnet.perm.log, this log
17121: file never gets deleted by any automated portion of the system, only
17122: messages of critical importance should go in here.
17123:
1.1119 foxr 17124:
1.243 albertel 17125: =back
17126:
17127: =head2 General File Helper Routines
17128:
17129: =over 4
1.191 harris41 17130:
17131: =item *
17132:
1.481 raeburn 17133: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17134: (a) files in /uploaded
17135: (i) If a local copy of the file exists -
17136: compares modification date of local copy with last-modified date for
17137: definitive version stored on home server for course. If local copy is
17138: stale, requests a new version from the home server and stores it.
17139: If the original has been removed from the home server, then local copy
17140: is unlinked.
17141: (ii) If local copy does not exist -
17142: requests the file from the home server and stores it.
17143:
17144: If $caller is 'uploadrep':
17145: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17146: for request for files originally uploaded via DOCS.
17147: - returns 'ok' if fresh local copy now available, -1 otherwise.
17148:
17149: Otherwise:
17150: This indicates a call from the content generation phase of the request.
17151: - returns the entire contents of the file or -1.
17152:
17153: (b) files in /res
17154: - returns the entire contents of a file or -1;
17155: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 17156:
1.712 albertel 17157:
17158: =item *
17159:
17160: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17161: reference
17162:
17163: returns either a stat() list of data about the file or an empty list
17164: if the file doesn't exist or couldn't find out about it (connection
17165: problems or user unknown)
17166:
1.191 harris41 17167: =item *
17168:
1.243 albertel 17169: filelocation($dir,$file) : returns file system location of a file
17170: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17171: directory that relative $file lookups are to looked in ($dir of /a/dir
17172: and a file of ../bob will become /a/bob)
1.191 harris41 17173:
17174: =item *
17175:
17176: hreflocation($dir,$file) : returns file system location or a URL; same as
17177: filelocation except for hrefs
17178:
17179: =item *
17180:
1.1261 raeburn 17181: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17182: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 17183:
1.243 albertel 17184: =back
17185:
1.608 albertel 17186: =head2 Usererfile file routines (/uploaded*)
17187:
17188: =over 4
17189:
17190: =item *
17191:
17192: userfileupload(): main rotine for putting a file in a user or course's
17193: filespace, arguments are,
17194:
1.620 albertel 17195: formname - required - this is the name of the element in $env where the
1.608 albertel 17196: filename, and the contents of the file to create/modifed exist
1.620 albertel 17197: the filename is in $env{'form.'.$formname.'.filename'} and the
17198: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 17199: context - if coursedoc, store the file in the course of the active role
17200: of the current user;
17201: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17202: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 17203: subdir - required - subdirectory to put the file in under ../userfiles/
17204: if undefined, it will be placed in "unknown"
17205:
17206: (This routine calls clean_filename() to remove any dangerous
17207: characters from the filename, and then calls finuserfileupload() to
17208: complete the transaction)
17209:
17210: returns either the url of the uploaded file (/uploaded/....) if successful
17211: and /adm/notfound.html if unsuccessful
17212:
17213: =item *
17214:
17215: clean_filename(): routine for cleaing a filename up for storage in
17216: userfile space, argument is:
17217:
17218: filename - proposed filename
17219:
17220: returns: the new clean filename
17221:
17222: =item *
17223:
1.1090 raeburn 17224: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 17225: userspace, probably shouldn't be called directly
17226:
17227: docuname: username or courseid of destination for the file
17228: docudom: domain of user/course of destination for the file
17229: formname: same as for userfileupload()
1.1090 raeburn 17230: fname: filename (including subdirectories) for the file
17231: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401 raeburn 17232: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 17233: allfiles: reference to hash used to store objects found by parser
17234: codebase: reference to hash used for codebases of java objects found by parser
17235: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17236: thumbheight: height (pixels) of thumbnail to be created for uploaded image
17237: resizewidth: width to be used to resize image using resizeImage from ImageMagick
17238: resizeheight: height to be used to resize image using resizeImage from ImageMagick
17239: context: if 'overwrite', will move the uploaded file from its temporary location to
17240: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 17241: mimetype: reference to scalar to accommodate mime type determined
17242: from File::MMagic if $parser = parse.
1.608 albertel 17243:
17244: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 17245: and /adm/notfound.html if unsuccessful (or an error message if context
17246: was 'overwrite').
17247:
1.608 albertel 17248:
17249: =item *
17250:
17251: renameuserfile(): renames an existing userfile to a new name
17252:
17253: Args:
17254: docuname: username or courseid of destination for the file
17255: docudom: domain of user/course of destination for the file
17256: old: current file name (including any subdirs under userfiles)
17257: new: desired file name (including any subdirs under userfiles)
17258:
17259: =item *
17260:
17261: mkdiruserfile(): creates a directory is a userfiles dir
17262:
17263: Args:
17264: docuname: username or courseid of destination for the file
17265: docudom: domain of user/course of destination for the file
17266: dir: dir to create (including any subdirs under userfiles)
17267:
17268: =item *
17269:
17270: removeuserfile(): removes a file that exists in userfiles
17271:
17272: Args:
17273: docuname: username or courseid of destination for the file
17274: docudom: domain of user/course of destination for the file
17275: fname: filname to delete (including any subdirs under userfiles)
17276:
17277: =item *
17278:
17279: removeuploadedurl(): convience function for removeuserfile()
17280:
17281: Args:
17282: url: a full /uploaded/... url to delete
17283:
1.747 albertel 17284: =item *
17285:
17286: get_portfile_permissions():
17287: Args:
17288: domain: domain of user or course contain the portfolio files
17289: user: name of user or num of course contain the portfolio files
17290: Returns:
17291: hashref of a dump of the proper file_permissions.db
17292:
17293:
17294: =item *
17295:
17296: get_access_controls():
17297:
17298: Args:
17299: current_permissions: the hash ref returned from get_portfile_permissions()
17300: group: (optional) the group you want the files associated with
17301: file: (optional) the file you want access info on
17302:
17303: Returns:
1.749 raeburn 17304: a hash (keys are file names) of hashes containing
17305: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17306: values are XML containing access control settings (see below)
1.747 albertel 17307:
17308: Internal notes:
17309:
1.749 raeburn 17310: access controls are stored in file_permissions.db as key=value pairs.
17311: key -> path to file/file_name\0uniqueID:scope_end_start
17312: where scope -> public,guest,course,group,domains or users.
17313: end -> UNIX time for end of access (0 -> no end date)
17314: start -> UNIX time for start of access
17315:
17316: value -> XML description of access control
17317: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17318: <start></start>
17319: <end></end>
17320:
17321: <password></password> for scope type = guest
17322:
17323: <domain></domain> for scope type = course or group
17324: <number></number>
17325: <roles id="">
17326: <role></role>
17327: <access></access>
17328: <section></section>
17329: <group></group>
17330: </roles>
17331:
17332: <dom></dom> for scope type = domains
17333:
17334: <users> for scope type = users
17335: <user>
17336: <uname></uname>
17337: <udom></udom>
17338: </user>
17339: </users>
17340: </scope>
17341:
17342: Access data is also aggregated for each file in an additional key=value pair:
17343: key -> path to file/file_name\0accesscontrol
17344: value -> reference to hash
17345: hash contains key = value pairs
17346: where key = uniqueID:scope_end_start
17347: value = UNIX time record was last updated
17348:
17349: Used to improve speed of look-ups of access controls for each file.
17350:
17351: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17352:
1.1198 raeburn 17353: =item *
17354:
1.749 raeburn 17355: modify_access_controls():
17356:
17357: Modifies access controls for a portfolio file
17358: Args
17359: 1. file name
17360: 2. reference to hash of required changes,
17361: 3. domain
17362: 4. username
17363: where domain,username are the domain of the portfolio owner
17364: (either a user or a course)
17365:
17366: Returns:
17367: 1. result of additions or updates ('ok' or 'error', with error message).
17368: 2. result of deletions ('ok' or 'error', with error message).
17369: 3. reference to hash of any new or updated access controls.
17370: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17371: key = integer (inbound ID)
1.1198 raeburn 17372: value = uniqueID
17373:
17374: =item *
17375:
17376: get_timebased_id():
17377:
17378: Attempts to get a unique timestamp-based suffix for use with items added to a
17379: course via the Course Editor (e.g., folders, composite pages,
17380: group bulletin boards).
17381:
17382: Args: (first three required; six others optional)
17383:
17384: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17385: docssequence, or name of group
17386:
17387: 2. keyid (alphanumeric): name of temporary locking key in hash,
17388: e.g., num, boardids
17389:
17390: 3. namespace: name of gdbm file used to store suffixes already assigned;
17391: file will be named nohist_namespace.db
17392:
17393: 4. cdom: domain of course; default is current course domain from %env
17394:
17395: 5. cnum: course number; default is current course number from %env
17396:
17397: 6. idtype: set to concat if an additional digit is to be appended to the
17398: unix timestamp to form the suffix, if the plain timestamp is already
17399: in use. Default is to not do this, but simply increment the unix
17400: timestamp by 1 until a unique key is obtained.
17401:
17402: 7. who: holder of locking key; defaults to user:domain for user.
17403:
17404: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
17405: retrying); default is 3.
17406:
17407: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
17408:
17409: Returns:
17410:
17411: 1. suffix obtained (numeric)
17412:
17413: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17414:
17415: 3. error: contains (localized) error message if an error occurred.
17416:
1.747 albertel 17417:
1.608 albertel 17418: =back
17419:
1.243 albertel 17420: =head2 HTTP Helper Routines
17421:
17422: =over 4
17423:
1.191 harris41 17424: =item *
17425:
17426: escape() : unpack non-word characters into CGI-compatible hex codes
17427:
17428: =item *
17429:
17430: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17431:
1.243 albertel 17432: =back
17433:
17434: =head1 PRIVATE SUBROUTINES
17435:
17436: =head2 Underlying communication routines (Shouldn't call)
17437:
17438: =over 4
17439:
17440: =item *
17441:
17442: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17443:
17444: =item *
17445:
17446: reply() : uses subreply to send a message to remote machine, logs all failures
17447:
17448: =item *
17449:
17450: critical() : passes a critical message to another server; if cannot
17451: get through then place message in connection buffer directory and
17452: returns con_delayed, if incapable of saving message, returns
17453: con_failed
17454:
17455: =item *
17456:
17457: reconlonc() : tries to reconnect lonc client processes.
17458:
17459: =back
17460:
17461: =head2 Resource Access Logging
17462:
17463: =over 4
17464:
17465: =item *
17466:
17467: flushcourselogs() : flush (save) buffer logs and access logs
17468:
17469: =item *
17470:
17471: courselog($what) : save message for course in hash
17472:
17473: =item *
17474:
17475: courseacclog($what) : save message for course using &courselog(). Perform
17476: special processing for specific resource types (problems, exams, quizzes, etc).
17477:
1.191 harris41 17478: =item *
17479:
17480: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17481: as a PerlChildExitHandler
1.243 albertel 17482:
17483: =back
17484:
17485: =head2 Other
17486:
17487: =over 4
17488:
17489: =item *
17490:
17491: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 17492:
17493: =back
17494:
17495: =cut
1.877 foxr 17496:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>