Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1503
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1503 ! raeburn 4: # $Id: lonnet.pm,v 1.1502 2022/11/23 02:55:37 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.486 www 74: use HTTP::Date;
1.977 amueller 75: use Image::Magick;
1.1389 raeburn 76: use CGI::Cookie;
1.1182 foxr 77:
1.1173 foxr 78: use Encode;
79:
1.1405 raeburn 80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138 raeburn 81: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1416 raeburn 82: %managerstab $passwdmin);
1.871 albertel 83:
84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
85: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
86: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 87: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 88:
1.1 albertel 89: use IO::Socket;
1.31 www 90: use GDBM_File;
1.208 albertel 91: use HTML::LCParser;
1.88 www 92: use Fcntl qw(:flock);
1.870 albertel 93: use Storable qw(thaw nfreeze);
1.1289 damieng 94: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 95: use Cache::Memcached;
1.676 albertel 96: use Digest::MD5;
1.790 albertel 97: use Math::Random;
1.1024 raeburn 98: use File::MMagic;
1.1434 raeburn 99: use Net::CIDR;
1.1456 raeburn 100: use Sys::Hostname::FQDN();
1.807 albertel 101: use LONCAPA qw(:DEFAULT :match);
1.740 www 102: use LONCAPA::Configuration;
1.1160 www 103: use LONCAPA::lonmetadata;
1.1167 droeschl 104: use LONCAPA::Lond;
1.1345 raeburn 105: use LONCAPA::LWPReq;
1.1406 raeburn 106: use LONCAPA::transliterate;
1.1117 foxr 107:
1.1090 raeburn 108: use File::Copy;
1.676 albertel 109:
1.195 www 110: my $readit;
1.1288 damieng 111: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 112:
1.619 albertel 113: require Exporter;
114:
115: our @ISA = qw (Exporter);
116: our @EXPORT = qw(%env);
117:
1.449 matthew 118:
1.1187 raeburn 119: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 120: {
121: my $logid;
1.1187 raeburn 122: sub write_log {
1.1188 raeburn 123: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 124: if ($context eq 'course') {
125: if (($cnum eq '') || ($cdom eq '')) {
126: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
127: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
128: }
1.957 raeburn 129: }
1.1184 raeburn 130: $logid ++;
1.957 raeburn 131: my $now = time();
132: my $id=$now.'00000'.$$.'00000'.$logid;
1.1434 raeburn 133: my $ip = &get_requestor_ip();
1.1184 raeburn 134: my $logentry = {
135: $id => {
136: 'exe_uname' => $env{'user.name'},
137: 'exe_udom' => $env{'user.domain'},
138: 'exe_time' => $now,
1.1434 raeburn 139: 'exe_ip' => $ip,
1.1184 raeburn 140: 'delflag' => $delflag,
141: 'logentry' => $storehash,
142: 'uname' => $uname,
143: 'udom' => $udom,
144: }
145: };
146: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 147: }
148: }
1.1 albertel 149:
1.163 harris41 150: sub logtouch {
151: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 152: unless (-e "$execdir/logs/lonnet.log") {
1.1359 raeburn 153: open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 154: close $fh;
155: }
156: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
157: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
158: }
159:
1.1 albertel 160: sub logthis {
161: my $message=shift;
162: my $execdir=$perlvar{'lonDaemons'};
163: my $now=time;
164: my $local=localtime($now);
1.1359 raeburn 165: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 166: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
167: print $fh $logstring;
1.448 albertel 168: close($fh);
169: }
1.1 albertel 170: return 1;
171: }
172:
173: sub logperm {
174: my $message=shift;
175: my $execdir=$perlvar{'lonDaemons'};
176: my $now=time;
177: my $local=localtime($now);
1.1359 raeburn 178: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 179: print $fh "$now:$message:$local\n";
180: close($fh);
181: }
1.1 albertel 182: return 1;
183: }
184:
1.850 albertel 185: sub create_connection {
1.853 albertel 186: my ($hostname,$lonid) = @_;
1.851 albertel 187: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 188: Type => SOCK_STREAM,
189: Timeout => 10);
190: return 0 if (!$client);
1.1399 raeburn 191: print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
1.850 albertel 192: my $result = <$client>;
193: chomp($result);
194: return 1 if ($result eq 'done');
195: return 0;
196: }
197:
1.983 raeburn 198: sub get_server_timezone {
199: my ($cnum,$cdom) = @_;
200: my $home=&homeserver($cnum,$cdom);
201: if ($home ne 'no_host') {
202: my $cachetime = 24*3600;
203: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
204: if (defined($cached)) {
205: return $timezone;
206: } else {
207: my $timezone = &reply('servertimezone',$home);
208: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
209: }
210: }
211: }
1.850 albertel 212:
1.1106 raeburn 213: sub get_server_distarch {
214: my ($lonhost,$ignore_cache) = @_;
215: if (defined($lonhost)) {
216: if (!defined(&hostname($lonhost))) {
217: return;
218: }
219: my $cachetime = 12*3600;
220: if (!$ignore_cache) {
221: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
222: if (defined($cached)) {
223: return $distarch;
224: }
225: }
226: my $rep = &reply('serverdistarch',$lonhost);
227: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
228: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
229: $rep eq '') {
230: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
231: }
232: }
233: return;
234: }
235:
1.1315 raeburn 236: sub get_servercerts_info {
1.1383 raeburn 237: my ($lonhost,$hostname,$context) = @_;
238: return if ($lonhost eq '');
239: if ($hostname eq '') {
240: $hostname = &hostname($lonhost);
241: }
242: return if ($hostname eq '');
1.1315 raeburn 243: my ($rep,$uselocal);
1.1388 raeburn 244: if ($context eq 'install') {
1.1387 raeburn 245: $uselocal = 1;
246: } elsif (grep { $_ eq $lonhost } ¤t_machine_ids()) {
1.1315 raeburn 247: $uselocal = 1;
248: }
1.1387 raeburn 249: if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315 raeburn 250: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323 raeburn 251: if ($distro eq '') {
252: $uselocal = 0;
253: } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315 raeburn 254: if ($1 < 6) {
255: $uselocal = 0;
256: }
1.1346 raeburn 257: } elsif ($distro =~ /^(?:sles)(\d+)$/) {
258: if ($1 < 12) {
259: $uselocal = 0;
260: }
1.1315 raeburn 261: }
262: }
263: if ($uselocal) {
1.1383 raeburn 264: $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315 raeburn 265: } else {
266: $rep=&reply('servercerts',$lonhost);
267: }
268: my ($result,%returnhash);
269: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
270: ($rep eq 'unknown_cmd')) {
271: $result = $rep;
272: } else {
273: $result = 'ok';
274: my @pairs=split(/\&/,$rep);
275: foreach my $item (@pairs) {
276: my ($key,$value)=split(/=/,$item,2);
277: my $what = &unescape($key);
278: $returnhash{$what}=&thaw_unescape($value);
279: }
280: }
281: return ($result,\%returnhash);
282: }
283:
1.993 raeburn 284: sub get_server_loncaparev {
1.1073 raeburn 285: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 286: if (defined($lonhost)) {
287: if (!defined(&hostname($lonhost))) {
288: undef($lonhost);
289: }
290: }
291: if (!defined($lonhost)) {
292: if (defined(&domain($dom,'primary'))) {
293: $lonhost=&domain($dom,'primary');
294: if ($lonhost eq 'no_host') {
295: undef($lonhost);
296: }
297: }
298: }
299: if (defined($lonhost)) {
1.1073 raeburn 300: my $cachetime = 12*3600;
301: if (!$ignore_cache) {
302: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
303: if (defined($cached)) {
304: return $loncaparev;
305: }
306: }
307: my ($answer,$loncaparev);
308: my @ids=¤t_machine_ids();
309: if (grep(/^\Q$lonhost\E$/,@ids)) {
310: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 311: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 312: $loncaparev = $1;
313: }
314: } else {
315: $answer = &reply('serverloncaparev',$lonhost);
316: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
317: if ($caller eq 'loncron') {
1.1397 raeburn 318: my $hostname = &hostname($lonhost);
1.1073 raeburn 319: my $protocol = $protocol{$lonhost};
320: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 321: my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073 raeburn 322: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 323: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073 raeburn 324: unless ($response->is_error()) {
325: my $content = $response->content;
1.1081 raeburn 326: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 327: $loncaparev = $1;
328: }
329: }
330: } else {
331: $loncaparev = $loncaparevs{$lonhost};
332: }
1.1081 raeburn 333: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 334: $loncaparev = $1;
335: }
1.993 raeburn 336: }
1.1073 raeburn 337: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 338: }
339: }
340:
1.1074 raeburn 341: sub get_server_homeID {
342: my ($hostname,$ignore_cache,$caller) = @_;
343: unless ($ignore_cache) {
344: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
345: if (defined($cached)) {
346: return $serverhomeID;
347: }
348: }
349: my $cachetime = 12*3600;
350: my $serverhomeID;
351: if ($caller eq 'loncron') {
352: my @machine_ids = &machine_ids($hostname);
353: foreach my $id (@machine_ids) {
354: my $response = &reply('serverhomeID',$id);
355: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
356: $serverhomeID = $response;
357: last;
358: }
359: }
360: if ($serverhomeID eq '') {
361: $serverhomeID = $machine_ids[-1];
362: }
363: } else {
364: $serverhomeID = $serverhomeIDs{$hostname};
365: }
366: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
367: }
368:
1.1121 raeburn 369: sub get_remote_globals {
370: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 371: my ($result,%returnhash,%whatneeded);
372: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 373: foreach my $what (sort(keys(%{$whathash}))) {
374: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 375: my ($response,$cached);
1.1121 raeburn 376: unless ($ignore_cache) {
1.1125 raeburn 377: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 378: }
379: if (defined($cached)) {
1.1125 raeburn 380: $returnhash{$what} = $response;
1.1121 raeburn 381: } else {
1.1125 raeburn 382: $whatneeded{$what} = 1;
1.1121 raeburn 383: }
384: }
1.1125 raeburn 385: if (keys(%whatneeded) == 0) {
386: $result = 'ok';
387: } else {
1.1121 raeburn 388: my $requested = &freeze_escape(\%whatneeded);
389: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 390: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
391: ($rep eq 'unknown_cmd')) {
392: $result = $rep;
393: } else {
394: $result = 'ok';
1.1121 raeburn 395: my @pairs=split(/\&/,$rep);
1.1125 raeburn 396: foreach my $item (@pairs) {
397: my ($key,$value)=split(/=/,$item,2);
398: my $what = &unescape($key);
399: my $hashid = $lonhost.'-'.$what;
400: $returnhash{$what}=&thaw_unescape($value);
401: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 402: }
403: }
404: }
405: }
1.1125 raeburn 406: return ($result,\%returnhash);
1.1121 raeburn 407: }
408:
1.1124 raeburn 409: sub remote_devalidate_cache {
1.1241 raeburn 410: my ($lonhost,$cachekeys) = @_;
411: my $items;
412: return unless (ref($cachekeys) eq 'ARRAY');
413: my $cachestr = join('&',@{$cachekeys});
414: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 415: return $response;
416: }
417:
1.1 albertel 418: # -------------------------------------------------- Non-critical communication
419: sub subreply {
420: my ($cmd,$server)=@_;
1.838 albertel 421: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 422: #
423: # With loncnew process trimming, there's a timing hole between lonc server
424: # process exit and the master server picking up the listen on the AF_UNIX
425: # socket. In that time interval, a lock file will exist:
426:
427: my $lockfile=$peerfile.".lock";
428: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1289 damieng 429: sleep(0.1);
1.549 foxr 430: }
431: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 432: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 433: #
1.550 foxr 434: # We'll give the connection a few tries before abandoning it. If
435: # connection is not possible, we'll con_lost back to the client.
436: #
437: my $client;
438: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
439: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
440: Type => SOCK_STREAM,
441: Timeout => 10);
1.869 albertel 442: if ($client) {
1.550 foxr 443: last; # Connected!
1.850 albertel 444: } else {
1.853 albertel 445: &create_connection(&hostname($server),$server);
1.550 foxr 446: }
1.1289 damieng 447: sleep(0.1); # Try again later if failed connection.
1.550 foxr 448: }
449: my $answer;
450: if ($client) {
1.704 albertel 451: print $client "sethost:$server:$cmd\n";
1.550 foxr 452: $answer=<$client>;
453: if (!$answer) { $answer="con_lost"; }
454: chomp($answer);
455: } else {
456: $answer = 'con_lost'; # Failed connection.
457: }
1.1 albertel 458: return $answer;
459: }
460:
461: sub reply {
462: my ($cmd,$server)=@_;
1.838 albertel 463: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 464: my $answer=subreply($cmd,$server);
1.65 www 465: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396 raeburn 466: my $logged = $cmd;
467: if ($cmd =~ /^encrypt:([^:]+):/) {
468: my $subcmd = $1;
469: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
470: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462 raeburn 471: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
472: ($subcmd eq 'put')) {
1.1396 raeburn 473: (undef,undef,my @rest) = split(/:/,$cmd);
474: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
475: splice(@rest,2,1,'Hidden');
476: } elsif ($subcmd eq 'passwd') {
477: splice(@rest,2,2,('Hidden','Hidden'));
478: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462 raeburn 479: ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
1.1396 raeburn 480: splice(@rest,3,1,'Hidden');
481: }
482: $logged = join(':',('encrypt:'.$subcmd,@rest));
483: }
484: }
485: &logthis("<font color=\"blue\">WARNING:".
486: " $logged to $server returned $answer</font>");
1.12 www 487: }
1.1 albertel 488: return $answer;
489: }
490:
491: # ----------------------------------------------------------- Send USR1 to lonc
492:
493: sub reconlonc {
1.891 albertel 494: my ($lonid) = @_;
495: if ($lonid) {
1.1295 raeburn 496: my $hostname = &hostname($lonid);
1.891 albertel 497: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
498: if ($hostname && -e $peerfile) {
499: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
500: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
501: Type => SOCK_STREAM,
502: Timeout => 10);
503: if ($client) {
504: print $client ("reset_retries\n");
505: my $answer=<$client>;
506: #reset just this one.
507: }
508: }
509: return;
510: }
511:
1.836 www 512: &logthis("Trying to reconnect lonc");
1.1 albertel 513: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359 raeburn 514: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 515: my $loncpid=<$fh>;
516: chomp($loncpid);
517: if (kill 0 => $loncpid) {
518: &logthis("lonc at pid $loncpid responding, sending USR1");
519: kill USR1 => $loncpid;
520: sleep 1;
1.1295 raeburn 521: } else {
1.12 www 522: &logthis(
1.672 albertel 523: "<font color=\"blue\">WARNING:".
1.12 www 524: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 525: }
526: } else {
1.836 www 527: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 528: }
529: }
530:
531: # ------------------------------------------------------ Critical communication
1.12 www 532:
1.1 albertel 533: sub critical {
534: my ($cmd,$server)=@_;
1.838 albertel 535: unless (&hostname($server)) {
1.672 albertel 536: &logthis("<font color=\"blue\">WARNING:".
1.89 www 537: " Critical message to unknown server ($server)</font>");
538: return 'no_such_host';
539: }
1.1 albertel 540: my $answer=reply($cmd,$server);
541: if ($answer eq 'con_lost') {
1.1295 raeburn 542: &reconlonc($server);
1.589 albertel 543: my $answer=reply($cmd,$server);
1.1 albertel 544: if ($answer eq 'con_lost') {
545: my $now=time;
546: my $middlename=$cmd;
1.5 www 547: $middlename=substr($middlename,0,16);
1.1 albertel 548: $middlename=~s/\W//g;
549: my $dfilename=
1.305 www 550: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
551: $dumpcount++;
1.1 albertel 552: {
1.448 albertel 553: my $dfh;
1.1359 raeburn 554: if (open($dfh,">",$dfilename)) {
1.448 albertel 555: print $dfh "$cmd\n";
556: close($dfh);
557: }
1.1 albertel 558: }
1.1288 damieng 559: sleep 1;
1.1 albertel 560: my $wcmd='';
561: {
1.448 albertel 562: my $dfh;
1.1359 raeburn 563: if (open($dfh,"<",$dfilename)) {
1.448 albertel 564: $wcmd=<$dfh>;
565: close($dfh);
566: }
1.1 albertel 567: }
568: chomp($wcmd);
1.7 www 569: if ($wcmd eq $cmd) {
1.672 albertel 570: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 571: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 572: &logperm("D:$server:$cmd");
573: return 'con_delayed';
574: } else {
1.672 albertel 575: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 576: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 577: &logperm("F:$server:$cmd");
578: return 'con_failed';
579: }
580: }
581: }
582: return $answer;
1.405 albertel 583: }
584:
1.755 albertel 585: # ------------------------------------------- check if return value is an error
586:
587: sub error {
588: my ($result) = @_;
1.756 albertel 589: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 590: if ($2 == 2) { return undef; }
591: return $1;
592: }
593: return undef;
594: }
595:
1.783 albertel 596: sub convert_and_load_session_env {
597: my ($lonidsdir,$handle)=@_;
598: my @profile;
599: {
1.917 albertel 600: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
601: if (!$opened) {
1.915 albertel 602: return 0;
603: }
1.783 albertel 604: flock($idf,LOCK_SH);
605: @profile=<$idf>;
606: close($idf);
607: }
608: my %temp_env;
609: foreach my $line (@profile) {
1.786 albertel 610: if ($line !~ m/=/) {
611: return 0;
612: }
1.783 albertel 613: chomp($line);
614: my ($envname,$envvalue)=split(/=/,$line,2);
615: $temp_env{&unescape($envname)} = &unescape($envvalue);
616: }
617: unlink("$lonidsdir/$handle.id");
618: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
619: 0640)) {
620: %disk_env = %temp_env;
621: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
622: untie(%disk_env);
623: }
1.786 albertel 624: return 1;
1.783 albertel 625: }
626:
1.374 www 627: # ------------------------------------------- Transfer profile into environment
1.780 albertel 628: my $env_loaded;
629: sub transfer_profile_to_env {
1.788 albertel 630: my ($lonidsdir,$handle,$force_transfer) = @_;
631: if (!$force_transfer && $env_loaded) { return; }
1.374 www 632:
1.720 albertel 633: if (!defined($lonidsdir)) {
634: $lonidsdir = $perlvar{'lonIDsDir'};
635: }
636: if (!defined($handle)) {
637: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
638: }
639:
1.786 albertel 640: my $convert;
641: {
1.917 albertel 642: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
643: if (!$opened) {
1.915 albertel 644: return;
645: }
1.786 albertel 646: flock($idf,LOCK_SH);
647: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
648: &GDBM_READER(),0640)) {
649: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
650: untie(%disk_env);
651: } else {
652: $convert = 1;
653: }
654: }
655: if ($convert) {
656: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
657: &logthis("Failed to load session, or convert session.");
658: }
1.374 www 659: }
1.783 albertel 660:
1.786 albertel 661: my %remove;
1.783 albertel 662: while ( my $envname = each(%env) ) {
1.433 matthew 663: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
664: if ($time < time-300) {
1.783 albertel 665: $remove{$key}++;
1.433 matthew 666: }
667: }
668: }
1.783 albertel 669:
1.619 albertel 670: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 671: $env_loaded=1;
1.783 albertel 672: foreach my $expired_key (keys(%remove)) {
1.433 matthew 673: &delenv($expired_key);
1.374 www 674: }
1.1 albertel 675: }
676:
1.916 albertel 677: # ---------------------------------------------------- Check for valid session
678: sub check_for_valid_session {
1.1355 raeburn 679: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 680: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378 raeburn 681: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
682: if ($name eq 'lonDAV') {
683: $lonidsdir=$r->dir_config('lonDAVsessDir');
684: } else {
685: $lonidsdir=$r->dir_config('lonIDsDir');
686: if ($name eq '') {
687: $name = 'lonID';
688: }
689: }
690: if ($name eq 'lonID') {
691: $secure = 'lonSID';
1.1337 raeburn 692: $linkname = 'lonLinkID';
693: $pubname = 'lonPubID';
1.1378 raeburn 694: if (exists($cookies{$secure})) {
695: $lonid=$cookies{$secure};
696: } elsif (exists($cookies{$name})) {
697: $lonid=$cookies{$name};
1.1400 raeburn 698: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337 raeburn 699: $lonid=$cookies{$linkname};
1.1378 raeburn 700: } elsif (exists($cookies{$pubname})) {
701: $lonid=$cookies{$pubname};
1.1337 raeburn 702: }
1.1378 raeburn 703: } else {
704: $lonid=$cookies{$name};
1.1337 raeburn 705: }
1.916 albertel 706: return undef if (!$lonid);
707:
708: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378 raeburn 709: if (-l "$lonidsdir/$handle.id") {
710: my $link = readlink("$lonidsdir/$handle.id");
711: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
712: $handle = $1;
713: }
1.1155 raeburn 714: }
1.1355 raeburn 715: if (!-e "$lonidsdir/$handle.id") {
716: if ((ref($domref)) && ($name eq 'lonID') &&
717: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
718: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
719: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
720: $$domref = $possudom;
721: }
722: }
723: return undef;
724: }
1.916 albertel 725:
1.917 albertel 726: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
727: return undef if (!$opened);
1.916 albertel 728:
729: flock($idf,LOCK_SH);
730: my %disk_env;
731: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
732: &GDBM_READER(),0640)) {
733: return undef;
734: }
735:
736: if (!defined($disk_env{'user.name'})
737: || !defined($disk_env{'user.domain'})) {
1.1394 raeburn 738: untie(%disk_env);
1.916 albertel 739: return undef;
740: }
1.1245 raeburn 741:
742: if (ref($userhashref) eq 'HASH') {
743: $userhashref->{'name'} = $disk_env{'user.name'};
744: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1448 raeburn 745: if ($disk_env{'request.role'}) {
746: $userhashref->{'role'} = $disk_env{'request.role'};
747: }
1.1361 raeburn 748: $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375 raeburn 749: if ($userhashref->{'lti'}) {
750: $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
751: $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
752: }
1.1212 raeburn 753: }
1.1394 raeburn 754: untie(%disk_env);
1.1245 raeburn 755:
1.916 albertel 756: return $handle;
757: }
758:
1.830 albertel 759: sub timed_flock {
760: my ($file,$lock_type) = @_;
761: my $failed=0;
762: eval {
763: local $SIG{__DIE__}='DEFAULT';
764: local $SIG{ALRM}=sub {
765: $failed=1;
766: die("failed lock");
767: };
768: alarm(13);
769: flock($file,$lock_type);
770: alarm(0);
771: };
772: if ($failed) {
773: return undef;
774: } else {
775: return 1;
776: }
777: }
778:
1.1392 raeburn 779: sub get_sessionfile_vars {
780: my ($handle,$lonidsdir,$storearr) = @_;
781: my %returnhash;
782: unless (ref($storearr) eq 'ARRAY') {
783: return %returnhash;
784: }
785: if (-l "$lonidsdir/$handle.id") {
786: my $link = readlink("$lonidsdir/$handle.id");
787: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
788: $handle = $1;
789: }
790: }
791: if ((-e "$lonidsdir/$handle.id") &&
792: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
793: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
794: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
795: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
796: flock($idf,LOCK_SH);
797: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
798: &GDBM_READER(),0640)) {
799: foreach my $item (@{$storearr}) {
800: $returnhash{$item} = $disk_env{$item};
801: }
802: untie(%disk_env);
803: }
804: }
805: }
806: }
807: return %returnhash;
808: }
809:
1.5 www 810: # ---------------------------------------------------------- Append Environment
811:
812: sub appenv {
1.949 raeburn 813: my ($newenv,$roles) = @_;
814: if (ref($newenv) eq 'HASH') {
815: foreach my $key (keys(%{$newenv})) {
816: my $refused = 0;
817: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
818: $refused = 1;
819: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 820: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 821: if (grep(/^\Q$role\E$/,@{$roles})) {
822: $refused = 0;
823: }
824: }
825: }
826: if ($refused) {
827: &logthis("<font color=\"blue\">WARNING: ".
828: "Attempt to modify environment ".$key." to ".$newenv->{$key}
829: .'</font>');
830: delete($newenv->{$key});
831: } else {
832: $env{$key}=$newenv->{$key};
833: }
834: }
1.1376 raeburn 835: my $lonids = $perlvar{'lonIDsDir'};
836: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
837: my $opened = open(my $env_file,'+<',$env{'user.environment'});
838: if ($opened
839: && &timed_flock($env_file,LOCK_EX)
840: &&
841: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
842: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
843: while (my ($key,$value) = each(%{$newenv})) {
844: $disk_env{$key} = $value;
845: }
846: untie(%disk_env);
847: }
1.35 www 848: }
1.191 harris41 849: }
1.56 www 850: return 'ok';
851: }
852: # ----------------------------------------------------- Delete from Environment
853:
854: sub delenv {
1.1104 raeburn 855: my ($delthis,$regexp,$roles) = @_;
856: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
857: my $refused = 1;
858: if (ref($roles) eq 'ARRAY') {
859: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
860: if (grep(/^\Q$role\E$/,@{$roles})) {
861: $refused = 0;
862: }
863: }
864: if ($refused) {
865: &logthis("<font color=\"blue\">WARNING: ".
866: "Attempt to delete from environment ".$delthis);
867: return 'error';
868: }
1.56 www 869: }
1.917 albertel 870: my $opened = open(my $env_file,'+<',$env{'user.environment'});
871: if ($opened
1.915 albertel 872: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 873: &&
874: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
875: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 876: foreach my $key (keys(%disk_env)) {
1.987 raeburn 877: if ($regexp) {
878: if ($key=~/^$delthis/) {
879: delete($env{$key});
880: delete($disk_env{$key});
881: }
882: } else {
883: if ($key=~/^\Q$delthis\E/) {
884: delete($env{$key});
885: delete($disk_env{$key});
886: }
887: }
1.448 albertel 888: }
1.783 albertel 889: untie(%disk_env);
1.5 www 890: }
891: return 'ok';
1.369 albertel 892: }
893:
1.790 albertel 894: sub get_env_multiple {
895: my ($name) = @_;
896: my @values;
897: if (defined($env{$name})) {
898: # exists is it an array
899: if (ref($env{$name})) {
900: @values=@{ $env{$name} };
901: } else {
902: $values[0]=$env{$name};
903: }
904: }
905: return(@values);
906: }
907:
1.958 www 908: # ------------------------------------------------------------------- Locking
909:
910: sub set_lock {
911: my ($text)=@_;
912: $locknum++;
913: my $id=$$.'-'.$locknum;
914: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
915: 'session.lock.'.$id => $text});
916: return $id;
917: }
918:
919: sub get_locks {
920: my $num=0;
921: my %texts=();
922: foreach my $lock (split(/\,/,$env{'session.locks'})) {
923: if ($lock=~/\w/) {
924: $num++;
925: $texts{$lock}=$env{'session.lock.'.$lock};
926: }
927: }
928: return ($num,%texts);
929: }
930:
931: sub remove_lock {
932: my ($id)=@_;
933: my $newlocks='';
934: foreach my $lock (split(/\,/,$env{'session.locks'})) {
935: if (($lock=~/\w/) && ($lock ne $id)) {
936: $newlocks.=','.$lock;
937: }
938: }
939: &appenv({'session.locks' => $newlocks});
940: &delenv('session.lock.'.$id);
941: }
942:
943: sub remove_all_locks {
944: my $activelocks=$env{'session.locks'};
945: foreach my $lock (split(/\,/,$env{'session.locks'})) {
946: if ($lock=~/\w/) {
947: &remove_lock($lock);
948: }
949: }
950: }
951:
952:
1.369 albertel 953: # ------------------------------------------ Find out current server userload
954: sub userload {
955: my $numusers=0;
956: {
957: opendir(LONIDS,$perlvar{'lonIDsDir'});
958: my $filename;
959: my $curtime=time;
960: while ($filename=readdir(LONIDS)) {
1.925 albertel 961: next if ($filename eq '.' || $filename eq '..');
962: next if ($filename =~ /publicuser_\d+\.id/);
1.1390 raeburn 963: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 964: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 965: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 966: }
967: closedir(LONIDS);
968: }
969: my $userloadpercent=0;
970: my $maxuserload=$perlvar{'lonUserLoadLim'};
971: if ($maxuserload) {
1.371 albertel 972: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 973: }
1.372 albertel 974: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 975: return $userloadpercent;
1.283 www 976: }
977:
1.1 albertel 978: # ------------------------------ Find server with least workload from spare.tab
1.11 www 979:
1.1 albertel 980: sub spareserver {
1.1451 raeburn 981: my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 982: my $spare_server;
1.370 albertel 983: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 984: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
985: : $userloadpercent;
1.1083 raeburn 986: my ($uint_dom,$remotesessions);
987: if (($udom ne '') && (&domain($udom) ne '')) {
1.1494 raeburn 988: my $uprimary_id = &domain($udom,'primary');
989: $uint_dom = &internet_dom($uprimary_id);
990: my %udomdefaults = &get_domain_defaults($udom);
1.1083 raeburn 991: $remotesessions = $udomdefaults{'remotesessions'};
992: }
1.1123 raeburn 993: my $spareshash = &this_host_spares($udom);
994: if (ref($spareshash) eq 'HASH') {
995: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
996: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 997: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
998: $try_server));
1.1123 raeburn 999: ($spare_server, $lowest_load) =
1000: &compare_server_load($try_server, $spare_server, $lowest_load);
1001: }
1.1083 raeburn 1002: }
1.784 albertel 1003:
1.1123 raeburn 1004: my $found_server = ($spare_server ne '' && $lowest_load < 100);
1005:
1006: if (!$found_server) {
1007: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1008: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 1009: next unless (&spare_can_host($udom,$uint_dom,
1010: $remotesessions,$try_server));
1.1123 raeburn 1011: ($spare_server, $lowest_load) =
1012: &compare_server_load($try_server, $spare_server, $lowest_load);
1013: }
1014: }
1015: }
1.784 albertel 1016: }
1017:
1018: if (!$want_server_name) {
1.1001 raeburn 1019: if (defined($spare_server)) {
1020: my $hostname = &hostname($spare_server);
1.1083 raeburn 1021: if (defined($hostname)) {
1.1397 raeburn 1022: my $protocol = 'http';
1023: if ($protocol{$spare_server} eq 'https') {
1024: $protocol = $protocol{$spare_server};
1025: }
1.1494 raeburn 1026: my $alias = &use_proxy_alias($r,$spare_server);
1.1451 raeburn 1027: $hostname = $alias if ($alias ne '');
1.1001 raeburn 1028: $spare_server = $protocol.'://'.$hostname;
1029: }
1030: }
1.784 albertel 1031: }
1032: return $spare_server;
1033: }
1034:
1035: sub compare_server_load {
1.1253 raeburn 1036: my ($try_server, $spare_server, $lowest_load, $required) = @_;
1037:
1038: if ($required) {
1039: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
1040: my $remoterev = &get_server_loncaparev(undef,$try_server);
1041: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
1042: if (($major eq '' && $minor eq '') ||
1043: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
1044: return ($spare_server,$lowest_load);
1045: }
1046: }
1.784 albertel 1047:
1048: my $loadans = &reply('load', $try_server);
1049: my $userloadans = &reply('userload',$try_server);
1050:
1051: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 1052: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 1053: }
1054:
1055: my $load;
1056: if ($loadans =~ /\d/) {
1057: if ($userloadans =~ /\d/) {
1058: #both are numbers, pick the bigger one
1059: $load = ($loadans > $userloadans) ? $loadans
1060: : $userloadans;
1.411 albertel 1061: } else {
1.784 albertel 1062: $load = $loadans;
1.411 albertel 1063: }
1.784 albertel 1064: } else {
1065: $load = $userloadans;
1066: }
1067:
1068: if (($load =~ /\d/) && ($load < $lowest_load)) {
1069: $spare_server = $try_server;
1070: $lowest_load = $load;
1.370 albertel 1071: }
1.784 albertel 1072: return ($spare_server,$lowest_load);
1.202 matthew 1073: }
1.914 albertel 1074:
1075: # --------------------------- ask offload servers if user already has a session
1076: sub find_existing_session {
1077: my ($udom,$uname) = @_;
1.1123 raeburn 1078: my $spareshash = &this_host_spares($udom);
1079: if (ref($spareshash) eq 'HASH') {
1080: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1081: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1082: return $try_server if (&has_user_session($try_server, $udom, $uname));
1083: }
1084: }
1085: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1086: foreach my $try_server (@{ $spareshash->{'default'} }) {
1087: return $try_server if (&has_user_session($try_server, $udom, $uname));
1088: }
1089: }
1.914 albertel 1090: }
1091: return;
1092: }
1093:
1.1411 raeburn 1094: sub delusersession {
1095: my ($lonid,$udom,$uname) = @_;
1096: my $uprimary_id = &domain($udom,'primary');
1097: my $uintdom = &internet_dom($uprimary_id);
1098: my $intdom = &internet_dom($lonid);
1099: my $serverhomedom = &host_domain($lonid);
1100: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1101: return &reply(join(':','delusersession',
1102: map {&escape($_)} ($udom,$uname)),$lonid);
1103: }
1104: return;
1105: }
1106:
1.1389 raeburn 1107: # check if user's browser sent load balancer cookie and server still has session
1108: # and is not overloaded.
1109: sub check_for_balancer_cookie {
1110: my ($r,$update_mtime) = @_;
1111: my ($otherserver,$cookie);
1112: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1113: if (exists($cookies{'balanceID'})) {
1114: my $balid = $cookies{'balanceID'};
1115: $cookie=&LONCAPA::clean_handle($balid->value);
1116: my $balancedir=$r->dir_config('lonBalanceDir');
1117: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1118: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1119: my ($possudom,$possuname) = ($1,$2);
1120: my $has_session = 0;
1121: if ((&domain($possudom) ne '') &&
1122: (&homeserver($possuname,$possudom) ne 'no_host')) {
1123: my $try_server;
1124: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1125: if ($opened) {
1126: flock($idf,LOCK_SH);
1127: while (my $line = <$idf>) {
1128: chomp($line);
1129: if (&hostname($line) ne '') {
1130: $try_server = $line;
1131: last;
1132: }
1133: }
1134: close($idf);
1135: if (($try_server) &&
1136: (&has_user_session($try_server,$possudom,$possuname))) {
1137: my $lowest_load = 30000;
1138: ($otherserver,$lowest_load) =
1139: &compare_server_load($try_server,undef,$lowest_load);
1140: if ($otherserver ne '' && $lowest_load < 100) {
1141: $has_session = 1;
1142: } else {
1143: undef($otherserver);
1144: }
1145: }
1146: }
1147: }
1148: if ($has_session) {
1149: if ($update_mtime) {
1150: my $atime = my $mtime = time;
1151: utime($atime,$mtime,"$balancedir/$cookie.id");
1152: }
1153: } else {
1154: unlink("$balancedir/$cookie.id");
1155: }
1156: }
1157: }
1158: }
1159: return ($otherserver,$cookie);
1160: }
1161:
1.1431 raeburn 1162: sub updatebalcookie {
1163: my ($cookie,$balancer,$lastentry)=@_;
1164: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1165: my ($udom,$uname) = ($1,$2);
1166: my $uprimary_id = &domain($udom,'primary');
1167: my $uintdom = &internet_dom($uprimary_id);
1168: my $intdom = &internet_dom($balancer);
1169: my $serverhomedom = &host_domain($balancer);
1170: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1171: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1172: }
1173: }
1174: return;
1175: }
1176:
1.1389 raeburn 1177: sub delbalcookie {
1178: my ($cookie,$balancer) =@_;
1179: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1180: my ($udom,$uname) = ($1,$2);
1181: my $uprimary_id = &domain($udom,'primary');
1182: my $uintdom = &internet_dom($uprimary_id);
1183: my $intdom = &internet_dom($balancer);
1184: my $serverhomedom = &host_domain($balancer);
1185: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1431 raeburn 1186: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1389 raeburn 1187: }
1188: }
1189: }
1190:
1.914 albertel 1191: # -------------------------------- ask if server already has a session for user
1192: sub has_user_session {
1193: my ($lonid,$udom,$uname) = @_;
1194: my $result = &reply(join(':','userhassession',
1195: map {&escape($_)} ($udom,$uname)),$lonid);
1196: return 1 if ($result eq 'ok');
1197:
1198: return 0;
1199: }
1200:
1.1076 raeburn 1201: # --------- determine least loaded server in a user's domain which allows login
1202:
1203: sub choose_server {
1.1259 raeburn 1204: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1205: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1206: my %servers = &get_servers($udom);
1.1076 raeburn 1207: my $lowest_load = 30000;
1.1259 raeburn 1208: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1209: if ($skiploadbal) {
1210: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1211: unless (defined($cached)) {
1212: my $cachetime = 60*60*24;
1213: my %domconfig =
1.1494 raeburn 1214: &get_dom('configuration',['loadbalancing'],$udom);
1.1259 raeburn 1215: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1216: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1217: $cachetime);
1218: }
1219: }
1220: }
1.1076 raeburn 1221: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1222: if ($skiploadbal) {
1223: if (ref($balancers) eq 'HASH') {
1224: next if (exists($balancers->{$lonhost}));
1225: }
1.1389 raeburn 1226: }
1.1115 raeburn 1227: my $loginvia;
1228: if ($checkloginvia) {
1229: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1230: if ($loginvia) {
1231: my ($server,$path) = split(/:/,$loginvia);
1232: ($login_host, $lowest_load) =
1.1253 raeburn 1233: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1234: if ($login_host eq $server) {
1235: $portal_path = $path;
1.1151 raeburn 1236: $isredirect = 1;
1.1116 raeburn 1237: }
1238: } else {
1239: ($login_host, $lowest_load) =
1.1253 raeburn 1240: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1241: if ($login_host eq $lonhost) {
1242: $portal_path = '';
1.1151 raeburn 1243: $isredirect = '';
1.1116 raeburn 1244: }
1245: }
1246: } else {
1.1076 raeburn 1247: ($login_host, $lowest_load) =
1.1253 raeburn 1248: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1249: }
1250: }
1251: if ($login_host ne '') {
1.1116 raeburn 1252: $hostname = &hostname($login_host);
1.1076 raeburn 1253: }
1.1331 raeburn 1254: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1255: }
1256:
1.1420 raeburn 1257: sub get_course_sessions {
1258: my ($cnum,$cdom,$lastactivity) = @_;
1259: my %servers = &internet_dom_servers($cdom);
1260: my %returnhash;
1261: foreach my $server (sort(keys(%servers))) {
1262: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1263: my @pairs=split(/\&/,$rep);
1264: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1265: foreach my $item (@pairs) {
1266: my ($key,$value)=split(/=/,$item,2);
1267: $key = &unescape($key);
1268: next if ($key =~ /^error: 2 /);
1269: if (exists($returnhash{$key})) {
1270: next if ($value < $returnhash{$key});
1271: }
1272: $returnhash{$key}=$value;
1273: }
1274: }
1275: }
1276: return %returnhash;
1277: }
1278:
1.202 matthew 1279: # --------------------------------------------- Try to change a user's password
1280:
1281: sub changepass {
1.799 raeburn 1282: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1283: $currentpass = &escape($currentpass);
1284: $newpass = &escape($newpass);
1.1030 raeburn 1285: my $lonhost = $perlvar{'lonHostID'};
1286: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1287: $server);
1288: if (! $answer) {
1289: &logthis("No reply on password change request to $server ".
1290: "by $uname in domain $udom.");
1291: } elsif ($answer =~ "^ok") {
1292: &logthis("$uname in $udom successfully changed their password ".
1293: "on $server.");
1294: } elsif ($answer =~ "^pwchange_failure") {
1295: &logthis("$uname in $udom was unable to change their password ".
1296: "on $server. The action was blocked by either lcpasswd ".
1297: "or pwchange");
1298: } elsif ($answer =~ "^non_authorized") {
1299: &logthis("$uname in $udom did not get their password correct when ".
1300: "attempting to change it on $server.");
1301: } elsif ($answer =~ "^auth_mode_error") {
1302: &logthis("$uname in $udom attempted to change their password despite ".
1303: "not being locally or internally authenticated on $server.");
1304: } elsif ($answer =~ "^unknown_user") {
1305: &logthis("$uname in $udom attempted to change their password ".
1306: "on $server but were unable to because $server is not ".
1307: "their home server.");
1308: } elsif ($answer =~ "^refused") {
1309: &logthis("$server refused to change $uname in $udom password because ".
1310: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1311: } elsif ($answer =~ "invalid_client") {
1312: &logthis("$server refused to change $uname in $udom password because ".
1313: "it was a reset by e-mail originating from an invalid server.");
1.1408 raeburn 1314: } elsif ($answer =~ "^prioruse") {
1315: &logthis("$server refused to change $uname in $udom password because ".
1316: "the password had been used before");
1.202 matthew 1317: }
1318: return $answer;
1.1 albertel 1319: }
1320:
1.169 harris41 1321: # ----------------------- Try to determine user's current authentication scheme
1322:
1323: sub queryauthenticate {
1324: my ($uname,$udom)=@_;
1.456 albertel 1325: my $uhome=&homeserver($uname,$udom);
1.1484 raeburn 1326: if ((!$uhome) || ($uhome eq 'no_host')) {
1.456 albertel 1327: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1328: return 'no_host';
1329: }
1330: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1331: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1332: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1333: }
1.456 albertel 1334: return $answer;
1.169 harris41 1335: }
1336:
1.1 albertel 1337: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1338:
1.1 albertel 1339: sub authenticate {
1.1073 raeburn 1340: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1341: $upass=&escape($upass);
1342: $uname= &LONCAPA::clean_username($uname);
1.836 www 1343: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1344: my $newhome;
1.836 www 1345: if ((!$uhome) || ($uhome eq 'no_host')) {
1346: # Maybe the machine was offline and only re-appeared again recently?
1347: &reconlonc();
1348: # One more
1.952 raeburn 1349: $uhome=&homeserver($uname,$udom,1);
1350: if (($uhome eq 'no_host') && $checkdefauth) {
1351: if (defined(&domain($udom,'primary'))) {
1352: $newhome=&domain($udom,'primary');
1353: }
1354: if ($newhome ne '') {
1355: $uhome = $newhome;
1356: }
1357: }
1.836 www 1358: if ((!$uhome) || ($uhome eq 'no_host')) {
1359: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1360: return 'no_host';
1361: }
1.1 albertel 1362: }
1.1073 raeburn 1363: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1364: if ($answer eq 'authorized') {
1.952 raeburn 1365: if ($newhome) {
1366: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1367: return 'no_account_on_host';
1368: } else {
1369: &logthis("User $uname at $udom authorized by $uhome");
1370: return $uhome;
1371: }
1.471 albertel 1372: }
1373: if ($answer eq 'non_authorized') {
1374: &logthis("User $uname at $udom rejected by $uhome");
1.1484 raeburn 1375: return 'no_host';
1.9 www 1376: }
1.471 albertel 1377: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1378: return 'no_host';
1379: }
1380:
1.1491 raeburn 1381: sub can_switchserver {
1382: my ($udom,$home) = @_;
1383: my ($canswitch,@intdoms);
1384: my $internet_names = &get_internet_names($home);
1385: if (ref($internet_names) eq 'ARRAY') {
1386: @intdoms = @{$internet_names};
1387: }
1388: my $uint_dom = &internet_dom(&domain($udom,'primary'));
1389: if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1390: $canswitch = 1;
1391: } else {
1392: my $serverhomeID = &get_server_homeID(&hostname($home));
1393: my $serverhomedom = &host_domain($serverhomeID);
1394: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1395: my %udomdefaults = &get_domain_defaults($udom);
1396: my $remoterev = &get_server_loncaparev('',$home);
1397: $canswitch = &can_host_session($udom,$home,$remoterev,
1398: $udomdefaults{'remotesessions'},
1399: $defdomdefaults{'hostedsessions'});
1400: }
1401: return $canswitch;
1402: }
1403:
1.1073 raeburn 1404: sub can_host_session {
1.1074 raeburn 1405: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1406: my $canhost = 1;
1.1494 raeburn 1407: my $host_idn = &internet_dom($lonhost);
1.1073 raeburn 1408: if (ref($remotesessions) eq 'HASH') {
1409: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1410: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1411: $canhost = 0;
1412: } else {
1413: $canhost = 1;
1414: }
1415: }
1416: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1417: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1418: $canhost = 1;
1419: } else {
1420: $canhost = 0;
1421: }
1422: }
1423: if ($canhost) {
1424: if ($remotesessions->{'version'} ne '') {
1425: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1426: if ($reqmajor ne '' && $reqminor ne '') {
1427: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1428: my $major = $1;
1429: my $minor = $2;
1430: if (($major < $reqmajor ) ||
1431: (($major == $reqmajor) && ($minor < $reqminor))) {
1432: $canhost = 0;
1433: }
1434: } else {
1435: $canhost = 0;
1436: }
1437: }
1438: }
1439: }
1440: }
1441: if ($canhost) {
1442: if (ref($hostedsessions) eq 'HASH') {
1.1494 raeburn 1443: my $uprimary_id = &domain($udom,'primary');
1444: my $uint_dom = &internet_dom($uprimary_id);
1.1073 raeburn 1445: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1446: if (($uint_dom ne '') &&
1447: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1448: $canhost = 0;
1449: } else {
1450: $canhost = 1;
1451: }
1452: }
1453: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1454: if (($uint_dom ne '') &&
1455: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1456: $canhost = 1;
1457: } else {
1458: $canhost = 0;
1459: }
1460: }
1461: }
1462: }
1463: return $canhost;
1464: }
1465:
1.1083 raeburn 1466: sub spare_can_host {
1467: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1468: my $canhost=1;
1.1279 raeburn 1469: my $try_server_hostname = &hostname($try_server);
1470: my $serverhomeID = &get_server_homeID($try_server_hostname);
1471: my $serverhomedom = &host_domain($serverhomeID);
1472: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1473: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1474: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1475: $canhost = 0;
1476: }
1477: }
1.1439 raeburn 1478: if ($canhost) {
1479: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1480: if ($defdomdefaults{'offloadoth'}{$try_server}) {
1481: unless (&shared_institution($udom,$try_server)) {
1482: $canhost = 0;
1483: }
1484: }
1485: }
1486: }
1.1279 raeburn 1487: if (($canhost) && ($uint_dom)) {
1488: my @intdoms;
1489: my $internet_names = &get_internet_names($try_server);
1490: if (ref($internet_names) eq 'ARRAY') {
1491: @intdoms = @{$internet_names};
1492: }
1493: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1494: my $remoterev = &get_server_loncaparev(undef,$try_server);
1495: $canhost = &can_host_session($udom,$try_server,$remoterev,
1496: $remotesessions,
1497: $defdomdefaults{'hostedsessions'});
1498: }
1.1083 raeburn 1499: }
1500: return $canhost;
1501: }
1502:
1.1123 raeburn 1503: sub this_host_spares {
1504: my ($dom) = @_;
1.1126 raeburn 1505: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1506: my @hosts = ¤t_machine_ids();
1507: foreach my $lonhost (@hosts) {
1508: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1509: $dom_in_use = $dom;
1510: $lonhost_in_use = $lonhost;
1.1123 raeburn 1511: last;
1512: }
1513: }
1.1126 raeburn 1514: if ($dom_in_use ne '') {
1515: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1516: }
1517: if (ref($result) ne 'HASH') {
1518: $lonhost_in_use = $perlvar{'lonHostID'};
1519: $dom_in_use = &host_domain($lonhost_in_use);
1520: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1521: if (ref($result) ne 'HASH') {
1522: $result = \%spareid;
1523: }
1524: }
1525: return $result;
1526: }
1527:
1528: sub spares_for_offload {
1529: my ($dom_in_use,$lonhost_in_use) = @_;
1530: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1531: if (defined($cached)) {
1532: return $result;
1533: } else {
1.1126 raeburn 1534: my $cachetime = 60*60*24;
1535: my %domconfig =
1.1494 raeburn 1536: &get_dom('configuration',['usersessions'],$dom_in_use);
1.1126 raeburn 1537: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1538: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1539: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1540: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1541: }
1542: }
1543: }
1544: }
1.1126 raeburn 1545: return;
1.1123 raeburn 1546: }
1547:
1.1129 raeburn 1548: sub get_lonbalancer_config {
1549: my ($servers) = @_;
1550: my ($currbalancer,$currtargets);
1551: if (ref($servers) eq 'HASH') {
1552: foreach my $server (keys(%{$servers})) {
1553: my %what = (
1554: spareid => 1,
1555: perlvar => 1,
1556: );
1557: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1558: if ($result eq 'ok') {
1559: if (ref($returnhash) eq 'HASH') {
1560: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1561: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1562: $currbalancer = $server;
1563: $currtargets = {};
1564: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1565: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1566: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1567: }
1568: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1569: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1570: }
1571: }
1572: last;
1573: }
1574: }
1575: }
1576: }
1577: }
1578: }
1579: return ($currbalancer,$currtargets);
1580: }
1581:
1582: sub check_loadbalancing {
1.1331 raeburn 1583: my ($uname,$udom,$caller) = @_;
1.1191 raeburn 1584: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391 raeburn 1585: $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129 raeburn 1586: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1587: my @hosts = ¤t_machine_ids();
1.1494 raeburn 1588: my $uprimary_id = &domain($udom,'primary');
1589: my $uintdom = &internet_dom($uprimary_id);
1590: my $intdom = &internet_dom($lonhost);
1.1129 raeburn 1591: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1592: my $domneedscache;
1.1129 raeburn 1593: my $cachetime = 60*60*24;
1594:
1595: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1596: $dom_in_use = $udom;
1597: $homeintdom = 1;
1598: } else {
1599: $dom_in_use = $serverhomedom;
1600: }
1601: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1602: unless (defined($cached)) {
1603: my %domconfig =
1.1494 raeburn 1604: &get_dom('configuration',['loadbalancing'],$dom_in_use);
1.1129 raeburn 1605: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1606: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1607: } else {
1608: $domneedscache = $dom_in_use;
1.1129 raeburn 1609: }
1610: }
1611: if (ref($result) eq 'HASH') {
1.1391 raeburn 1612: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1613: &check_balancer_result($result,@hosts);
1.1129 raeburn 1614: if ($is_balancer) {
1615: if (ref($currrules) eq 'HASH') {
1616: if ($homeintdom) {
1617: if ($uname ne '') {
1618: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1619: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1620: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1621: $rule_in_effect = $currrules->{'_LC_author'};
1622: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1623: $rule_in_effect = $currrules->{'_LC_adv'}
1624: }
1625: }
1626: if ($rule_in_effect eq '') {
1627: my %userenv = &userenvironment($udom,$uname,'inststatus');
1628: if ($userenv{'inststatus'} ne '') {
1629: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1630: my ($othertitle,$usertypes,$types) =
1631: &Apache::loncommon::sorted_inst_types($udom);
1632: if (ref($types) eq 'ARRAY') {
1633: foreach my $type (@{$types}) {
1634: if (grep(/^\Q$type\E$/,@statuses)) {
1635: if (exists($currrules->{$type})) {
1636: $rule_in_effect = $currrules->{$type};
1637: }
1638: }
1639: }
1640: }
1641: } else {
1642: if (exists($currrules->{'default'})) {
1643: $rule_in_effect = $currrules->{'default'};
1644: }
1645: }
1646: }
1647: } else {
1648: if (exists($currrules->{'default'})) {
1649: $rule_in_effect = $currrules->{'default'};
1650: }
1651: }
1652: } else {
1653: if ($currrules->{'_LC_external'} ne '') {
1654: $rule_in_effect = $currrules->{'_LC_external'};
1655: }
1656: }
1657: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1658: $uname,$udom);
1659: }
1660: }
1661: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1662: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1663: unless (defined($cached)) {
1664: my %domconfig =
1.1494 raeburn 1665: &get_dom('configuration',['loadbalancing'],$serverhomedom);
1.1129 raeburn 1666: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1667: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1668: } else {
1669: $domneedscache = $serverhomedom;
1.1129 raeburn 1670: }
1671: }
1672: if (ref($result) eq 'HASH') {
1.1391 raeburn 1673: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1674: &check_balancer_result($result,@hosts);
1675: if ($is_balancer) {
1.1129 raeburn 1676: if (ref($currrules) eq 'HASH') {
1677: if ($currrules->{'_LC_internetdom'} ne '') {
1678: $rule_in_effect = $currrules->{'_LC_internetdom'};
1679: }
1680: }
1681: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1682: $uname,$udom);
1683: }
1684: } else {
1685: if ($perlvar{'lonBalancer'} eq 'yes') {
1686: $is_balancer = 1;
1687: $offloadto = &this_host_spares($dom_in_use);
1688: }
1.1307 raeburn 1689: unless (defined($cached)) {
1690: $domneedscache = $serverhomedom;
1691: }
1.1129 raeburn 1692: }
1693: } else {
1694: if ($perlvar{'lonBalancer'} eq 'yes') {
1695: $is_balancer = 1;
1696: $offloadto = &this_host_spares($dom_in_use);
1697: }
1.1307 raeburn 1698: unless (defined($cached)) {
1699: $domneedscache = $serverhomedom;
1700: }
1701: }
1702: if ($domneedscache) {
1703: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1704: }
1.1430 raeburn 1705: if (($is_balancer) && ($caller ne 'switchserver')) {
1.1176 raeburn 1706: my $lowest_load = 30000;
1707: if (ref($offloadto) eq 'HASH') {
1708: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1709: foreach my $try_server (@{$offloadto->{'primary'}}) {
1710: ($otherserver,$lowest_load) =
1711: &compare_server_load($try_server,$otherserver,$lowest_load);
1712: }
1.1129 raeburn 1713: }
1.1176 raeburn 1714: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1715:
1.1176 raeburn 1716: if (!$found_server) {
1717: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1718: foreach my $try_server (@{$offloadto->{'default'}}) {
1719: ($otherserver,$lowest_load) =
1720: &compare_server_load($try_server,$otherserver,$lowest_load);
1721: }
1722: }
1723: }
1724: } elsif (ref($offloadto) eq 'ARRAY') {
1725: if (@{$offloadto} == 1) {
1726: $otherserver = $offloadto->[0];
1727: } elsif (@{$offloadto} > 1) {
1728: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1729: ($otherserver,$lowest_load) =
1730: &compare_server_load($try_server,$otherserver,$lowest_load);
1731: }
1732: }
1733: }
1.1331 raeburn 1734: unless ($caller eq 'login') {
1735: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1736: $is_balancer = 0;
1737: if ($uname ne '' && $udom ne '') {
1738: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389 raeburn 1739: &appenv({'user.loadbalexempt' => $lonhost,
1.1331 raeburn 1740: 'user.loadbalcheck.time' => time});
1741: }
1.1176 raeburn 1742: }
1.1129 raeburn 1743: }
1744: }
1.1430 raeburn 1745: }
1746: if (($is_balancer) && (!$homeintdom)) {
1747: undef($setcookie);
1.1129 raeburn 1748: }
1.1391 raeburn 1749: return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129 raeburn 1750: }
1751:
1.1191 raeburn 1752: sub check_balancer_result {
1753: my ($result,@hosts) = @_;
1.1391 raeburn 1754: my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1755: if (ref($result) eq 'HASH') {
1756: if ($result->{'lonhost'} ne '') {
1757: my $currbalancer = $result->{'lonhost'};
1758: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1759: $is_balancer = 1;
1760: $currtargets = $result->{'targets'};
1761: $currrules = $result->{'rules'};
1762: }
1.1391 raeburn 1763: $dom_balancers = $currbalancer;
1.1191 raeburn 1764: } else {
1.1391 raeburn 1765: if (keys(%{$result})) {
1766: foreach my $key (keys(%{$result})) {
1767: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1768: (ref($result->{$key}) eq 'HASH')) {
1769: $is_balancer = 1;
1770: $currrules = $result->{$key}{'rules'};
1771: $currtargets = $result->{$key}{'targets'};
1772: $setcookie = $result->{$key}{'cookie'};
1773: last;
1774: }
1.1191 raeburn 1775: }
1.1391 raeburn 1776: $dom_balancers = join(',',sort(keys(%{$result})));
1.1191 raeburn 1777: }
1778: }
1779: }
1.1391 raeburn 1780: return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1781: }
1782:
1.1129 raeburn 1783: sub get_loadbalancer_targets {
1784: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1785: my $offloadto;
1.1175 raeburn 1786: if ($rule_in_effect eq 'none') {
1787: return [$perlvar{'lonHostID'}];
1788: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1789: $offloadto = $currtargets;
1790: } else {
1791: if ($rule_in_effect eq 'homeserver') {
1792: my $homeserver = &homeserver($uname,$udom);
1793: if ($homeserver ne 'no_host') {
1794: $offloadto = [$homeserver];
1795: }
1796: } elsif ($rule_in_effect eq 'externalbalancer') {
1797: my %domconfig =
1.1494 raeburn 1798: &get_dom('configuration',['loadbalancing'],$udom);
1.1129 raeburn 1799: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1800: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1801: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1802: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1803: }
1804: }
1805: } else {
1.1178 raeburn 1806: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1807: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1808: if (&hostname($remotebalancer) ne '') {
1809: $offloadto = [$remotebalancer];
1810: }
1811: }
1812: } elsif (&hostname($rule_in_effect) ne '') {
1813: $offloadto = [$rule_in_effect];
1814: }
1815: }
1816: return $offloadto;
1817: }
1818:
1.1127 raeburn 1819: sub internet_dom_servers {
1820: my ($dom) = @_;
1821: my (%uniqservers,%servers);
1822: my $primaryserver = &hostname(&domain($dom,'primary'));
1823: my @machinedoms = &machine_domains($primaryserver);
1824: foreach my $mdom (@machinedoms) {
1825: my %currservers = %servers;
1826: my %server = &get_servers($mdom);
1827: %servers = (%currservers,%server);
1828: }
1829: my %by_hostname;
1830: foreach my $id (keys(%servers)) {
1831: push(@{$by_hostname{$servers{$id}}},$id);
1832: }
1833: foreach my $hostname (sort(keys(%by_hostname))) {
1834: if (@{$by_hostname{$hostname}} > 1) {
1835: my $match = 0;
1836: foreach my $id (@{$by_hostname{$hostname}}) {
1837: if (&host_domain($id) eq $dom) {
1838: $uniqservers{$id} = $hostname;
1839: $match = 1;
1840: }
1841: }
1842: unless ($match) {
1843: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1844: }
1845: } else {
1846: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1847: }
1848: }
1849: return %uniqservers;
1850: }
1851:
1.1347 raeburn 1852: sub trusted_domains {
1853: my ($cmdtype,$calldom) = @_;
1.1349 raeburn 1854: my ($trusted,$untrusted);
1.1347 raeburn 1855: if (&domain($calldom) eq '') {
1.1349 raeburn 1856: return ($trusted,$untrusted);
1.1347 raeburn 1857: }
1.1395 raeburn 1858: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349 raeburn 1859: return ($trusted,$untrusted);
1.1347 raeburn 1860: }
1861: my $callprimary = &domain($calldom,'primary');
1.1494 raeburn 1862: my $intcalldom = &internet_dom($callprimary);
1.1347 raeburn 1863: if ($intcalldom eq '') {
1.1349 raeburn 1864: return ($trusted,$untrusted);
1.1347 raeburn 1865: }
1866:
1.1494 raeburn 1867: my ($trustconfig,$cached)=&is_cached_new('trust',$calldom);
1.1347 raeburn 1868: unless (defined($cached)) {
1.1494 raeburn 1869: my %domconfig = &get_dom('configuration',['trust'],$calldom);
1870: &do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1.1347 raeburn 1871: $trustconfig = $domconfig{'trust'};
1872: }
1873: if (ref($trustconfig)) {
1874: my (%possexc,%possinc,@allexc,@allinc);
1875: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1876: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1877: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1878: }
1879: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395 raeburn 1880: $possinc{$intcalldom} = 1;
1.1347 raeburn 1881: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1882: }
1883: }
1884: if (keys(%possexc)) {
1885: if (keys(%possinc)) {
1886: foreach my $key (sort(keys(%possexc))) {
1887: next if ($key eq $intcalldom);
1888: unless ($possinc{$key}) {
1889: push(@allexc,$key);
1890: }
1891: }
1892: } else {
1893: @allexc = sort(keys(%possexc));
1894: }
1895: }
1896: if (keys(%possinc)) {
1897: $possinc{$intcalldom} = 1;
1898: @allinc = sort(keys(%possinc));
1899: }
1900: if ((@allexc > 0) || (@allinc > 0)) {
1901: my %doms_by_intdom;
1902: my %allintdoms = &all_host_intdom();
1903: my %alldoms = &all_host_domain();
1904: foreach my $key (%allintdoms) {
1905: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1906: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1907: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1908: }
1909: } else {
1910: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1911: }
1912: }
1913: foreach my $exc (@allexc) {
1914: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395 raeburn 1915: push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347 raeburn 1916: }
1917: }
1918: foreach my $inc (@allinc) {
1919: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395 raeburn 1920: push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347 raeburn 1921: }
1922: }
1923: }
1924: }
1.1349 raeburn 1925: return ($trusted,$untrusted);
1.1347 raeburn 1926: }
1927:
1928: sub will_trust {
1929: my ($cmdtype,$domain,$possdom) = @_;
1930: return 1 if ($domain eq $possdom);
1931: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1932: my $willtrust;
1933: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1934: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1935: $willtrust = 1;
1936: }
1937: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1938: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1939: $willtrust = 1;
1940: }
1941: } else {
1942: $willtrust = 1;
1943: }
1944: return $willtrust;
1945: }
1946:
1.1 albertel 1947: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1948:
1.599 albertel 1949: my %homecache;
1.1 albertel 1950: sub homeserver {
1.230 stredwic 1951: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1952: my $index="$uname:$udom";
1.426 albertel 1953:
1.599 albertel 1954: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1955:
1956: my %servers = &get_servers($udom,'library');
1957: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1958: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1959: exists($badServerCache{$tryserver}));
1.841 albertel 1960:
1961: my $answer=reply("home:$udom:$uname",$tryserver);
1962: if ($answer eq 'found') {
1963: delete($badServerCache{$tryserver});
1964: return $homecache{$index}=$tryserver;
1965: } elsif ($answer eq 'no_host') {
1966: $badServerCache{$tryserver}=1;
1967: }
1.1 albertel 1968: }
1969: return 'no_host';
1.70 www 1970: }
1971:
1.1300 raeburn 1972: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1973:
1974: sub idget {
1.1300 raeburn 1975: my ($udom,$idsref,$namespace)=@_;
1.70 www 1976: my %returnhash=();
1.1300 raeburn 1977: my @ids=();
1978: if (ref($idsref) eq 'ARRAY') {
1979: @ids = @{$idsref};
1980: } else {
1981: return %returnhash;
1982: }
1983: if ($namespace eq '') {
1984: $namespace = 'ids';
1985: }
1.70 www 1986:
1.841 albertel 1987: my %servers = &get_servers($udom,'library');
1988: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1989: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1990: if ($namespace eq 'ids') {
1991: $idlist=~tr/A-Z/a-z/;
1992: }
1993: my $reply;
1994: if ($namespace eq 'ids') {
1995: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1996: } else {
1997: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1998: }
1.841 albertel 1999: my @answer=();
2000: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
2001: @answer=split(/\&/,$reply);
2002: } ;
2003: my $i;
2004: for ($i=0;$i<=$#ids;$i++) {
2005: if ($answer[$i]) {
1.1299 raeburn 2006: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 2007: }
1.841 albertel 2008: }
1.1300 raeburn 2009: }
1.70 www 2010: return %returnhash;
2011: }
2012:
2013: # ------------------------------------- Find the IDs behind a list of usernames
2014:
2015: sub idrget {
2016: my ($udom,@unames)=@_;
2017: my %returnhash=();
1.800 albertel 2018: foreach my $uname (@unames) {
2019: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 2020: }
1.70 www 2021: return %returnhash;
2022: }
2023:
1.1300 raeburn 2024: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 2025:
2026: sub idput {
1.1300 raeburn 2027: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 2028: my %servers=();
1.1300 raeburn 2029: my %ids=();
2030: my %byid = ();
2031: if (ref($idsref) eq 'HASH') {
2032: %ids=%{$idsref};
2033: }
2034: if ($namespace eq '') {
2035: $namespace = 'ids';
2036: }
1.800 albertel 2037: foreach my $uname (keys(%ids)) {
2038: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 2039: if ($uhom eq '') {
2040: $uhom=&homeserver($uname,$udom);
2041: }
1.70 www 2042: if ($uhom ne 'no_host') {
1.800 albertel 2043: my $esc_unam=&escape($uname);
1.1300 raeburn 2044: if ($namespace eq 'ids') {
2045: my $id=&escape($ids{$uname});
2046: $id=~tr/A-Z/a-z/;
2047: my $esc_unam=&escape($uname);
2048: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 2049: } else {
1.1300 raeburn 2050: my @currids = split(/,/,$ids{$uname});
2051: foreach my $id (@currids) {
2052: $byid{$uhom}{$id} .= $uname.',';
2053: }
2054: }
2055: }
2056: }
2057: if ($namespace eq 'clickers') {
2058: foreach my $server (keys(%byid)) {
2059: if (ref($byid{$server}) eq 'HASH') {
2060: foreach my $id (keys(%{$byid{$server}})) {
2061: $byid{$server} =~ s/,$//;
2062: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
2063: }
1.70 www 2064: }
2065: }
1.191 harris41 2066: }
1.800 albertel 2067: foreach my $server (keys(%servers)) {
1.1300 raeburn 2068: $servers{$server} =~ s/\&$//;
2069: if ($namespace eq 'ids') {
2070: &critical('idput:'.$udom.':'.$servers{$server},$server);
2071: } else {
2072: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
2073: }
1.191 harris41 2074: }
1.344 www 2075: }
2076:
1.1300 raeburn 2077: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 2078:
2079: sub iddel {
1.1300 raeburn 2080: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 2081: my %result=();
1.1300 raeburn 2082: my %ids=();
2083: my %byid = ();
2084: if (ref($idshashref) eq 'HASH') {
2085: %ids=%{$idshashref};
2086: } else {
1.1231 raeburn 2087: return %result;
2088: }
1.1300 raeburn 2089: if ($namespace eq '') {
2090: $namespace = 'ids';
2091: }
1.1231 raeburn 2092: my %servers=();
1.1300 raeburn 2093: while (my ($id,$unamestr) = each(%ids)) {
2094: if ($namespace eq 'ids') {
2095: my $uhom = $uhome;
2096: if ($uhom eq '') {
2097: $uhom=&homeserver($unamestr,$udom);
2098: }
2099: if ($uhom ne 'no_host') {
2100: $servers{$uhom}.='&'.&escape($id);
2101: }
2102: } else {
2103: my @curritems = split(/,/,$ids{$id});
2104: foreach my $uname (@curritems) {
2105: my $uhom = $uhome;
2106: if ($uhom eq '') {
2107: $uhom=&homeserver($uname,$udom);
2108: }
2109: if ($uhom ne 'no_host') {
2110: $byid{$uhom}{$id} .= $uname.',';
2111: }
2112: }
1.1231 raeburn 2113: }
1.1300 raeburn 2114: }
2115: if ($namespace eq 'clickers') {
2116: foreach my $server (keys(%byid)) {
2117: if (ref($byid{$server}) eq 'HASH') {
2118: foreach my $id (keys(%{$byid{$server}})) {
2119: $byid{$server}{$id} =~ s/,$//;
2120: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
2121: }
1.1231 raeburn 2122: }
2123: }
2124: }
2125: foreach my $server (keys(%servers)) {
1.1300 raeburn 2126: $servers{$server} =~ s/\&$//;
2127: if ($namespace eq 'ids') {
2128: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
2129: } elsif ($namespace eq 'clickers') {
2130: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
2131: }
1.1231 raeburn 2132: }
2133: return %result;
2134: }
2135:
1.1300 raeburn 2136: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
2137:
2138: sub updateclickers {
2139: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
2140: my %clickers;
2141: if (ref($idshashref) eq 'HASH') {
2142: %clickers=%{$idshashref};
2143: } else {
2144: return;
2145: }
2146: my $items='';
2147: foreach my $item (keys(%clickers)) {
2148: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
2149: }
2150: $items=~s/\&$//;
2151: my $request = "updateclickers:$udom:$action:$items";
2152: if ($critical) {
2153: return &critical($request,$uhome);
2154: } else {
2155: return &reply($request,$uhome);
2156: }
2157: }
2158:
1.1023 raeburn 2159: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 2160: sub dump_dom {
1.1165 droeschl 2161: my ($namespace, $udom, $regexp) = @_;
2162:
2163: $udom ||= $env{'user.domain'};
2164:
2165: return () unless $udom;
2166:
2167: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 2168: }
2169:
1.1023 raeburn 2170: # ------------------------------------------ get items from domain db files
1.806 raeburn 2171:
2172: sub get_dom {
1.1462 raeburn 2173: my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1267 raeburn 2174: return if ($udom eq 'public');
1.806 raeburn 2175: my $items='';
2176: foreach my $item (@$storearr) {
2177: $items.=&escape($item).'&';
2178: }
2179: $items=~s/\&$//;
1.860 raeburn 2180: if (!$udom) {
2181: $udom=$env{'user.domain'};
1.1267 raeburn 2182: return if ($udom eq 'public');
1.860 raeburn 2183: if (defined(&domain($udom,'primary'))) {
2184: $uhome=&domain($udom,'primary');
2185: } else {
1.874 albertel 2186: undef($uhome);
1.860 raeburn 2187: }
2188: } else {
2189: if (!$uhome) {
2190: if (defined(&domain($udom,'primary'))) {
2191: $uhome=&domain($udom,'primary');
2192: }
2193: }
2194: }
2195: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344 raeburn 2196: my $rep;
1.1442 raeburn 2197: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
2198: # domain information is hosted on this machine
1.1462 raeburn 2199: $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1344 raeburn 2200: } else {
1.1462 raeburn 2201: if ($encrypt) {
1.1442 raeburn 2202: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
2203: } else {
2204: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
2205: }
1.1344 raeburn 2206: }
1.866 raeburn 2207: my %returnhash;
1.875 albertel 2208: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 2209: return %returnhash;
2210: }
1.806 raeburn 2211: my @pairs=split(/\&/,$rep);
2212: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2213: return @pairs;
2214: }
2215: my $i=0;
2216: foreach my $item (@$storearr) {
2217: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2218: $i++;
2219: }
2220: return %returnhash;
2221: } else {
1.880 banghart 2222: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 2223: }
2224: }
2225:
2226: # -------------------------------------------- put items in domain db files
2227:
2228: sub put_dom {
1.1462 raeburn 2229: my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860 raeburn 2230: if (!$udom) {
2231: $udom=$env{'user.domain'};
2232: if (defined(&domain($udom,'primary'))) {
2233: $uhome=&domain($udom,'primary');
2234: } else {
1.874 albertel 2235: undef($uhome);
1.860 raeburn 2236: }
2237: } else {
2238: if (!$uhome) {
2239: if (defined(&domain($udom,'primary'))) {
2240: $uhome=&domain($udom,'primary');
2241: }
2242: }
2243: }
2244: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 2245: my $items='';
2246: foreach my $item (keys(%$storehash)) {
2247: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2248: }
2249: $items=~s/\&$//;
1.1462 raeburn 2250: if ($encrypt) {
1.1344 raeburn 2251: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2252: } else {
2253: return &reply("putdom:$udom:$namespace:$items",$uhome);
2254: }
1.806 raeburn 2255: } else {
1.860 raeburn 2256: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 2257: }
2258: }
2259:
1.1023 raeburn 2260: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 2261: sub newput_dom {
1.1023 raeburn 2262: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 2263: my $result;
2264: if (!$udom) {
2265: $udom=$env{'user.domain'};
2266: }
1.1023 raeburn 2267: if ($udom) {
2268: my $uname = &get_domainconfiguser($udom);
2269: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 2270: }
2271: return $result;
2272: }
2273:
1.1023 raeburn 2274: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 2275: sub del_dom {
1.1023 raeburn 2276: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 2277: if (ref($storearr) eq 'ARRAY') {
2278: if (!$udom) {
2279: $udom=$env{'user.domain'};
2280: }
1.1023 raeburn 2281: if ($udom) {
2282: my $uname = &get_domainconfiguser($udom);
2283: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 2284: }
2285: }
2286: }
2287:
1.1481 raeburn 2288: sub store_dom {
1.1482 raeburn 2289: my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
1.1481 raeburn 2290: $$storehash{'ip'}=&get_requestor_ip();
2291: $$storehash{'host'}=$perlvar{'lonHostID'};
2292: my $namevalue='';
2293: foreach my $key (keys(%{$storehash})) {
2294: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2295: }
2296: $namevalue=~s/\&$//;
2297: if (grep { $_ eq $home } current_machine_ids()) {
2298: return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
2299: } else {
2300: if ($namespace eq 'private') {
2301: return 'refused';
1.1482 raeburn 2302: } elsif ($encrypt) {
2303: return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481 raeburn 2304: } else {
1.1482 raeburn 2305: return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481 raeburn 2306: }
2307: }
2308: }
2309:
1.1482 raeburn 2310: sub restore_dom {
2311: my ($id,$namespace,$dom,$home,$encrypt) = @_;
2312: my $answer;
2313: if (grep { $_ eq $home } current_machine_ids()) {
2314: $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
2315: } elsif ($namespace ne 'private') {
2316: if ($encrypt) {
2317: $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
2318: } else {
2319: $answer=&reply("restoredom:$dom:$namespace:$id",$home);
2320: }
2321: }
2322: my %returnhash=();
2323: unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') ||
2324: ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
2325: foreach my $line (split(/\&/,$answer)) {
2326: my ($name,$value)=split(/\=/,$line);
2327: $returnhash{&unescape($name)}=&thaw_unescape($value);
2328: }
2329: my $version;
2330: for ($version=1;$version<=$returnhash{'version'};$version++) {
2331: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2332: $returnhash{$item}=$returnhash{$version.':'.$item};
2333: }
2334: }
2335: }
2336: return %returnhash;
2337: }
2338:
1.1023 raeburn 2339: # ----------------------------------construct domainconfig user for a domain
2340: sub get_domainconfiguser {
2341: my ($udom) = @_;
2342: return $udom.'-domainconfig';
2343: }
2344:
1.837 raeburn 2345: sub retrieve_inst_usertypes {
2346: my ($udom) = @_;
2347: my (%returnhash,@order);
1.1494 raeburn 2348: my %domdefs = &get_domain_defaults($udom);
1.989 raeburn 2349: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2350: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 2351: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2352: } else {
2353: if (defined(&domain($udom,'primary'))) {
2354: my $uhome=&domain($udom,'primary');
2355: my $rep=&reply("inst_usertypes:$udom",$uhome);
2356: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 2357: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2358: return (\%returnhash,\@order);
2359: }
2360: my ($hashitems,$orderitems) = split(/:/,$rep);
2361: my @pairs=split(/\&/,$hashitems);
2362: foreach my $item (@pairs) {
2363: my ($key,$value)=split(/=/,$item,2);
2364: $key = &unescape($key);
2365: next if ($key =~ /^error: 2 /);
2366: $returnhash{$key}=&thaw_unescape($value);
2367: }
2368: my @esc_order = split(/\&/,$orderitems);
2369: foreach my $item (@esc_order) {
2370: push(@order,&unescape($item));
2371: }
2372: } else {
1.1256 raeburn 2373: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2374: }
1.1256 raeburn 2375: return (\%returnhash,\@order);
1.837 raeburn 2376: }
2377: }
2378:
1.868 raeburn 2379: sub is_domainimage {
2380: my ($url) = @_;
1.1468 raeburn 2381: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868 raeburn 2382: if (&domain($1) ne '') {
2383: return '1';
2384: }
2385: }
2386: return;
2387: }
2388:
1.899 raeburn 2389: sub inst_directory_query {
2390: my ($srch) = @_;
2391: my $udom = $srch->{'srchdomain'};
2392: my %results;
2393: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2394: my $outcome;
1.899 raeburn 2395: if ($homeserver ne '') {
1.1357 raeburn 2396: unless ($homeserver eq $perlvar{'lonHostID'}) {
2397: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2398: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357 raeburn 2399: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2400: if (($major eq '' && $minor eq '') || ($major < 2) ||
2401: (($major == 2) && ($minor < 12))) {
2402: return;
2403: }
2404: }
2405: }
1.904 albertel 2406: my $queryid=&reply("querysend:instdirsearch:".
2407: &escape($srch->{'srchby'}).':'.
2408: &escape($srch->{'srchterm'}).':'.
2409: &escape($srch->{'srchtype'}),$homeserver);
2410: my $host=&hostname($homeserver);
2411: if ($queryid !~/^\Q$host\E\_/) {
1.1343 raeburn 2412: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2413: return;
2414: }
2415: my $response = &get_query_reply($queryid);
2416: my $maxtries = 5;
2417: my $tries = 1;
2418: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2419: $response = &get_query_reply($queryid);
2420: $tries ++;
2421: }
2422:
2423: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2424: if ($response eq 'unavailable') {
2425: $outcome = $response;
2426: } else {
2427: $outcome = 'ok';
2428: my @matches = split(/\n/,$response);
2429: foreach my $match (@matches) {
2430: my ($key,$value) = split(/=/,$match);
2431: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2432: }
1.899 raeburn 2433: }
2434: }
2435: }
1.909 raeburn 2436: return ($outcome,%results);
1.899 raeburn 2437: }
2438:
2439: sub usersearch {
2440: my ($srch) = @_;
2441: my $dom = $srch->{'srchdomain'};
2442: my %results;
2443: my %libserv = &all_library();
2444: my $query = 'usersearch';
2445: foreach my $tryserver (keys(%libserv)) {
2446: if (&host_domain($tryserver) eq $dom) {
1.1357 raeburn 2447: unless ($tryserver eq $perlvar{'lonHostID'}) {
2448: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2449: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357 raeburn 2450: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2451: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2452: (($major == 2) && ($minor < 12)));
2453: }
2454: }
1.899 raeburn 2455: my $host=&hostname($tryserver);
2456: my $queryid=
1.911 raeburn 2457: &reply("querysend:".&escape($query).':'.
2458: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2459: &escape($srch->{'srchtype'}).':'.
2460: &escape($srch->{'srchterm'}),$tryserver);
2461: if ($queryid !~/^\Q$host\E\_/) {
2462: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2463: next;
1.899 raeburn 2464: }
2465: my $reply = &get_query_reply($queryid);
2466: my $maxtries = 1;
2467: my $tries = 1;
2468: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2469: $reply = &get_query_reply($queryid);
2470: $tries ++;
2471: }
2472: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2473: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2474: } else {
1.911 raeburn 2475: my @matches;
2476: if ($reply =~ /\n/) {
2477: @matches = split(/\n/,$reply);
2478: } else {
2479: @matches = split(/\&/,$reply);
2480: }
1.899 raeburn 2481: foreach my $match (@matches) {
2482: my ($uname,$udom,%userhash);
1.911 raeburn 2483: foreach my $entry (split(/:/,$match)) {
2484: my ($key,$value) =
2485: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2486: $userhash{$key} = $value;
2487: if ($key eq 'username') {
2488: $uname = $value;
2489: } elsif ($key eq 'domain') {
2490: $udom = $value;
1.911 raeburn 2491: }
1.899 raeburn 2492: }
2493: $results{$uname.':'.$udom} = \%userhash;
2494: }
2495: }
2496: }
2497: }
2498: return %results;
2499: }
2500:
1.912 raeburn 2501: sub get_instuser {
2502: my ($udom,$uname,$id) = @_;
2503: my $homeserver = &domain($udom,'primary');
2504: my ($outcome,%results);
2505: if ($homeserver ne '') {
2506: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2507: &escape($id).':'.&escape($udom),$homeserver);
2508: my $host=&hostname($homeserver);
2509: if ($queryid !~/^\Q$host\E\_/) {
2510: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2511: return;
2512: }
2513: my $response = &get_query_reply($queryid);
2514: my $maxtries = 5;
2515: my $tries = 1;
2516: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2517: $response = &get_query_reply($queryid);
2518: $tries ++;
2519: }
2520: if (!&error($response) && $response ne 'refused') {
2521: if ($response eq 'unavailable') {
2522: $outcome = $response;
2523: } else {
2524: $outcome = 'ok';
2525: my @matches = split(/\n/,$response);
2526: foreach my $match (@matches) {
2527: my ($key,$value) = split(/=/,$match);
2528: $results{&unescape($key)} = &thaw_unescape($value);
2529: }
2530: }
2531: }
2532: }
2533: my %userinfo;
2534: if (ref($results{$uname}) eq 'HASH') {
2535: %userinfo = %{$results{$uname}};
2536: }
2537: return ($outcome,%userinfo);
2538: }
2539:
1.1290 raeburn 2540: sub get_multiple_instusers {
2541: my ($udom,$users,$caller) = @_;
2542: my ($outcome,$results);
2543: if (ref($users) eq 'HASH') {
2544: my $count = keys(%{$users});
2545: my $requested = &freeze_escape($users);
2546: my $homeserver = &domain($udom,'primary');
2547: if ($homeserver ne '') {
2548: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2549: my $host=&hostname($homeserver);
2550: if ($queryid !~/^\Q$host\E\_/) {
2551: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2552: ' for host: '.$homeserver.'in domain '.$udom);
2553: return ($outcome,$results);
2554: }
2555: my $response = &get_query_reply($queryid);
2556: my $maxtries = 5;
2557: if ($count > 100) {
2558: $maxtries = 1+int($count/20);
2559: }
2560: my $tries = 1;
2561: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2562: $response = &get_query_reply($queryid);
2563: $tries ++;
2564: }
2565: if ($response eq '') {
2566: $results = {};
2567: foreach my $key (keys(%{$users})) {
2568: my ($uname,$id);
2569: if ($caller eq 'id') {
2570: $id = $key;
2571: } else {
2572: $uname = $key;
2573: }
2574: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2575: $outcome = $resp;
1.1290 raeburn 2576: if ($resp eq 'ok') {
2577: %{$results} = (%{$results}, %info);
2578: } else {
2579: last;
2580: }
2581: }
2582: } elsif(!&error($response) && ($response ne 'refused')) {
2583: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2584: $outcome = $response;
2585: } else {
1.1291 raeburn 2586: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2587: if ($outcome eq 'ok') {
2588: $results = &thaw_unescape($userdata);
2589: }
2590: }
2591: }
2592: }
2593: }
2594: return ($outcome,$results);
2595: }
2596:
1.912 raeburn 2597: sub inst_rulecheck {
1.923 raeburn 2598: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2599: my %returnhash;
2600: if ($udom ne '') {
2601: if (ref($rules) eq 'ARRAY') {
2602: @{$rules} = map {&escape($_);} (@{$rules});
2603: my $rulestr = join(':',@{$rules});
2604: my $homeserver=&domain($udom,'primary');
2605: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2606: my $response;
2607: if ($item eq 'username') {
2608: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2609: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2610: $homeserver));
1.923 raeburn 2611: } elsif ($item eq 'id') {
2612: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2613: ':'.&escape($id).':'.$rulestr,
2614: $homeserver));
1.945 raeburn 2615: } elsif ($item eq 'selfcreate') {
2616: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2617: &escape($udom).':'.&escape($uname).
2618: ':'.$rulestr,$homeserver));
1.1484 raeburn 2619: } elsif ($item eq 'unamemap') {
2620: $response=&unescape(&reply('instunamemapcheck:'.
2621: &escape($udom).':'.&escape($uname).
2622: ':'.$rulestr,$homeserver));
1.923 raeburn 2623: }
1.912 raeburn 2624: if ($response ne 'refused') {
2625: my @pairs=split(/\&/,$response);
2626: foreach my $item (@pairs) {
2627: my ($key,$value)=split(/=/,$item,2);
2628: $key = &unescape($key);
2629: next if ($key =~ /^error: 2 /);
2630: $returnhash{$key}=&thaw_unescape($value);
2631: }
2632: }
2633: }
2634: }
2635: }
2636: return %returnhash;
2637: }
2638:
2639: sub inst_userrules {
1.923 raeburn 2640: my ($udom,$check) = @_;
1.912 raeburn 2641: my (%ruleshash,@ruleorder);
2642: if ($udom ne '') {
2643: my $homeserver=&domain($udom,'primary');
2644: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2645: my $response;
2646: if ($check eq 'id') {
2647: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2648: $homeserver);
1.943 raeburn 2649: } elsif ($check eq 'email') {
2650: $response=&reply('instemailrules:'.&escape($udom),
2651: $homeserver);
1.1484 raeburn 2652: } elsif ($check eq 'unamemap') {
2653: $response=&reply('unamemaprules:'.&escape($udom),
2654: $homeserver);
1.923 raeburn 2655: } else {
2656: $response=&reply('instuserrules:'.&escape($udom),
2657: $homeserver);
2658: }
1.912 raeburn 2659: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2660: ($response ne 'unknown_cmd') &&
1.912 raeburn 2661: ($response ne 'no_such_host')) {
2662: my ($hashitems,$orderitems) = split(/:/,$response);
2663: my @pairs=split(/\&/,$hashitems);
2664: foreach my $item (@pairs) {
2665: my ($key,$value)=split(/=/,$item,2);
2666: $key = &unescape($key);
2667: next if ($key =~ /^error: 2 /);
2668: $ruleshash{$key}=&thaw_unescape($value);
2669: }
2670: my @esc_order = split(/\&/,$orderitems);
2671: foreach my $item (@esc_order) {
2672: push(@ruleorder,&unescape($item));
2673: }
2674: }
2675: }
2676: }
2677: return (\%ruleshash,\@ruleorder);
2678: }
2679:
1.976 raeburn 2680: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2681:
2682: sub get_domain_defaults {
1.1240 raeburn 2683: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2684: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2685: my $cachetime = 60*60*24;
1.1240 raeburn 2686: unless ($ignore_cache) {
2687: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2688: if (defined($cached)) {
2689: if (ref($result) eq 'HASH') {
2690: return %{$result};
2691: }
1.943 raeburn 2692: }
2693: }
2694: my %domdefaults;
2695: my %domconfig =
1.1494 raeburn 2696: &get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2697: 'requestcourses','inststatus',
1.1183 raeburn 2698: 'coursedefaults','usersessions',
1.1258 raeburn 2699: 'requestauthor','selfenrollment',
1.1320 raeburn 2700: 'coursecategories','ssl','autoenroll',
1.1482 raeburn 2701: 'trust','helpsettings','wafproxy','ltisec'],$domain);
1.1305 raeburn 2702: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2703: if (ref($domconfig{'defaults'}) eq 'HASH') {
2704: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2705: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2706: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2707: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2708: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2709: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1492 raeburn 2710: $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
2711: $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
1.1340 raeburn 2712: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2713: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2714: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1484 raeburn 2715: $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943 raeburn 2716: } else {
2717: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2718: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2719: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2720: }
1.976 raeburn 2721: if (ref($domconfig{'quotas'}) eq 'HASH') {
2722: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2723: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2724: } else {
2725: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2726: }
1.1177 raeburn 2727: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2728: foreach my $item (@usertools) {
2729: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2730: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2731: }
2732: }
1.1229 raeburn 2733: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2734: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2735: }
1.976 raeburn 2736: }
1.985 raeburn 2737: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2738: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2739: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2740: }
2741: }
1.1183 raeburn 2742: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2743: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2744: }
1.989 raeburn 2745: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2746: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2747: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2748: }
2749: }
1.1047 raeburn 2750: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2751: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2752: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1476 raeburn 2753: $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1277 raeburn 2754: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2755: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2756: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2757: }
1.1254 raeburn 2758: foreach my $type (@coursetypes) {
2759: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2760: unless ($type eq 'community') {
2761: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2762: }
2763: }
2764: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2765: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2766: }
1.1277 raeburn 2767: if ($domdefaults{'postsubmit'} eq 'on') {
2768: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2769: $domdefaults{$type.'postsubtimeout'} =
2770: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2771: }
2772: }
1.1230 raeburn 2773: }
1.1286 raeburn 2774: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2775: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2776: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2777: if (@clonecodes) {
2778: $domdefaults{'canclone'} = join('+',@clonecodes);
2779: }
2780: }
2781: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2782: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2783: }
1.1356 raeburn 2784: if ($domconfig{'coursedefaults'}{'texengine'}) {
2785: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
1.1480 raeburn 2786: }
2787: if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
2788: $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
2789: }
1.1047 raeburn 2790: }
1.1073 raeburn 2791: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2792: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2793: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2794: }
2795: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2796: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2797: }
1.1279 raeburn 2798: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2799: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2800: }
1.1440 raeburn 2801: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439 raeburn 2802: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2803: }
1.1073 raeburn 2804: }
1.1254 raeburn 2805: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2806: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2807: my @settings = ('types','registered','enroll_dates','access_dates','section',
2808: 'approval','limit');
2809: foreach my $type (@coursetypes) {
2810: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2811: my @mgrdc = ();
2812: foreach my $item (@settings) {
2813: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2814: push(@mgrdc,$item);
2815: }
2816: }
2817: if (@mgrdc) {
2818: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2819: }
2820: }
2821: }
2822: }
2823: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2824: foreach my $type (@coursetypes) {
2825: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2826: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2827: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2828: }
2829: }
2830: }
2831: }
2832: }
1.1258 raeburn 2833: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2834: $domdefaults{'catauth'} = 'std';
2835: $domdefaults{'catunauth'} = 'std';
1.1413 raeburn 2836: if ($domconfig{'coursecategories'}{'auth'}) {
1.1258 raeburn 2837: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2838: }
2839: if ($domconfig{'coursecategories'}{'unauth'}) {
2840: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2841: }
2842: }
1.1315 raeburn 2843: if (ref($domconfig{'ssl'}) eq 'HASH') {
2844: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2845: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2846: }
1.1338 raeburn 2847: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2848: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2849: }
2850: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2851: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315 raeburn 2852: }
2853: }
1.1320 raeburn 2854: if (ref($domconfig{'trust'}) eq 'HASH') {
2855: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2856: foreach my $prefix (@prefixes) {
2857: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2858: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2859: }
2860: }
2861: }
1.1314 raeburn 2862: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2863: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1477 raeburn 2864: $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1314 raeburn 2865: }
1.1332 raeburn 2866: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2867: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2868: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2869: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2870: }
2871: }
1.1434 raeburn 2872: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1449 raeburn 2873: foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
1.1434 raeburn 2874: if ($domconfig{'wafproxy'}{$item}) {
2875: $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
2876: }
2877: }
1.1482 raeburn 2878: }
2879: if (ref($domconfig{'ltisec'}) eq 'HASH') {
2880: if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
2881: $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
2882: $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
2883: $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
2884: }
2885: if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
2886: if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
2887: $domdefaults{'privhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
2888: }
2889: }
2890: }
1.1219 raeburn 2891: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2892: return %domdefaults;
2893: }
2894:
1.1412 raeburn 2895: sub get_dom_cats {
2896: my ($dom) = @_;
2897: return unless (&domain($dom));
2898: my ($cats,$cached)=&is_cached_new('cats',$dom);
2899: unless (defined($cached)) {
2900: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2901: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2902: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2903: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2904: } else {
2905: $cats = {};
2906: }
2907: } else {
2908: $cats = {};
2909: }
1.1494 raeburn 2910: &do_cache_new('cats',$dom,$cats,3600);
1.1412 raeburn 2911: }
1.1413 raeburn 2912: return $cats;
2913: }
2914:
2915: sub get_dom_instcats {
2916: my ($dom) = @_;
2917: return unless (&domain($dom));
2918: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2919: unless (defined($cached)) {
2920: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2921: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2922: if ($totcodes > 0) {
2923: my $caller = 'global';
2924: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2925: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2926: $instcats = {
1.1503 ! raeburn 2927: totcodes => $totcodes,
1.1413 raeburn 2928: codes => \%codes,
2929: codetitles => \@codetitles,
2930: cat_titles => \%cat_titles,
2931: cat_order => \%cat_order,
2932: };
2933: &do_cache_new('instcats',$dom,$instcats,3600);
2934: }
2935: }
2936: }
2937: return $instcats;
2938: }
2939:
2940: sub retrieve_instcodes {
2941: my ($coursecodes,$dom) = @_;
2942: my $totcodes;
2943: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2944: foreach my $course (keys(%courses)) {
2945: if (ref($courses{$course}) eq 'HASH') {
2946: if ($courses{$course}{'inst_code'} ne '') {
2947: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2948: $totcodes ++;
2949: }
2950: }
2951: }
2952: return $totcodes;
1.1412 raeburn 2953: }
2954:
1.1311 raeburn 2955: sub course_portal_url {
1.1451 raeburn 2956: my ($cnum,$cdom,$r) = @_;
1.1311 raeburn 2957: my $chome = &homeserver($cnum,$cdom);
2958: my $hostname = &hostname($chome);
2959: my $protocol = $protocol{$chome};
2960: $protocol = 'http' if ($protocol ne 'https');
2961: my %domdefaults = &get_domain_defaults($cdom);
2962: my $firsturl;
2963: if ($domdefaults{'portal_def'}) {
2964: $firsturl = $domdefaults{'portal_def'};
2965: } else {
1.1494 raeburn 2966: my $alias = &use_proxy_alias($r,$chome);
1.1451 raeburn 2967: $hostname = $alias if ($alias ne '');
1.1311 raeburn 2968: $firsturl = $protocol.'://'.$hostname;
2969: }
2970: return $firsturl;
2971: }
2972:
1.1492 raeburn 2973: sub url_prefix {
2974: my ($r,$dom,$home,$context) = @_;
2975: my $prefix;
2976: my %domdefs = &get_domain_defaults($dom);
2977: if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
2978: if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
2979: $prefix = $1;
2980: }
2981: }
2982: if ($prefix eq '') {
2983: my $hostname = &hostname($home);
2984: my $protocol = $protocol{$home};
2985: $protocol = 'http' if ($protocol{$home} ne 'https');
2986: my $alias = &use_proxy_alias($r,$home);
2987: $hostname = $alias if ($alias ne '');
2988: $prefix = $protocol.'://'.$hostname;
2989: }
2990: return $prefix;
2991: }
2992:
1.1407 raeburn 2993: # --------------------------------------------- Get domain config for passwords
2994:
2995: sub get_passwdconf {
2996: my ($dom) = @_;
2997: my (%passwdconf,$gotconf,$lookup);
2998: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2999: if (defined($cached)) {
3000: if (ref($result) eq 'HASH') {
3001: %passwdconf = %{$result};
3002: $gotconf = 1;
3003: }
3004: }
3005: unless ($gotconf) {
3006: my %domconfig = &get_dom('configuration',['passwords'],$dom);
3007: if (ref($domconfig{'passwords'}) eq 'HASH') {
3008: %passwdconf = %{$domconfig{'passwords'}};
3009: }
3010: my $cachetime = 24*60*60;
3011: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
3012: }
3013: return %passwdconf;
3014: }
3015:
1.344 www 3016: # --------------------------------------------------- Assign a key to a student
3017:
3018: sub assign_access_key {
1.364 www 3019: #
3020: # a valid key looks like uname:udom#comments
3021: # comments are being appended
3022: #
1.498 www 3023: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
3024: $kdom=
1.620 albertel 3025: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 3026: $knum=
1.620 albertel 3027: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 3028: $cdom=
1.620 albertel 3029: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3030: $cnum=
1.620 albertel 3031: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3032: $udom=$env{'user.name'} unless (defined($udom));
3033: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 3034: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 3035: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 3036: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 3037: # assigned to this person
3038: # - this should not happen,
1.345 www 3039: # unless something went wrong
3040: # the first time around
3041: # ready to assign
1.364 www 3042: $logentry=$1.'; '.$logentry;
1.496 www 3043: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 3044: $kdom,$knum) eq 'ok') {
1.345 www 3045: # key now belongs to user
1.346 www 3046: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 3047: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 3048: &appenv({'environment.'.$envkey => $ckey});
1.345 www 3049: return 'ok';
3050: } else {
3051: return
3052: 'error: Count not permanently assign key, will need to be re-entered later.';
3053: }
3054: } else {
3055: return 'error: Could not assign key, try again later.';
3056: }
1.364 www 3057: } elsif (!$existing{$ckey}) {
1.345 www 3058: # the key does not exist
3059: return 'error: The key does not exist';
3060: } else {
3061: # the key is somebody else's
3062: return 'error: The key is already in use';
3063: }
1.344 www 3064: }
3065:
1.364 www 3066: # ------------------------------------------ put an additional comment on a key
3067:
3068: sub comment_access_key {
3069: #
3070: # a valid key looks like uname:udom#comments
3071: # comments are being appended
3072: #
3073: my ($ckey,$cdom,$cnum,$logentry)=@_;
3074: $cdom=
1.620 albertel 3075: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 3076: $cnum=
1.620 albertel 3077: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 3078: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
3079: if ($existing{$ckey}) {
3080: $existing{$ckey}.='; '.$logentry;
3081: # ready to assign
1.367 www 3082: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 3083: $cdom,$cnum) eq 'ok') {
3084: return 'ok';
3085: } else {
3086: return 'error: Count not store comment.';
3087: }
3088: } else {
3089: # the key does not exist
3090: return 'error: The key does not exist';
3091: }
3092: }
3093:
1.344 www 3094: # ------------------------------------------------------ Generate a set of keys
3095:
3096: sub generate_access_keys {
1.364 www 3097: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 3098: $cdom=
1.620 albertel 3099: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3100: $cnum=
1.620 albertel 3101: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 3102: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 3103: unless (($cdom) && ($cnum)) { return 0; }
3104: if ($number>10000) { return 0; }
3105: sleep(2); # make sure don't get same seed twice
3106: srand(time()^($$+($$<<15))); # from "Programming Perl"
3107: my $total=0;
3108: for (my $i=1;$i<=$number;$i++) {
3109: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
3110: sprintf("%lx",int(100000*rand)).'-'.
3111: sprintf("%lx",int(100000*rand));
3112: $newkey=~s/1/g/g; # folks mix up 1 and l
3113: $newkey=~s/0/h/g; # and also 0 and O
3114: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
3115: if ($existing{$newkey}) {
3116: $i--;
3117: } else {
1.364 www 3118: if (&put('accesskeys',
3119: { $newkey => '# generated '.localtime().
1.620 albertel 3120: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 3121: '; '.$logentry },
3122: $cdom,$cnum) eq 'ok') {
1.344 www 3123: $total++;
3124: }
3125: }
3126: }
1.620 albertel 3127: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 3128: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
3129: return $total;
3130: }
3131:
3132: # ------------------------------------------------------- Validate an accesskey
3133:
3134: sub validate_access_key {
3135: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
3136: $cdom=
1.620 albertel 3137: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3138: $cnum=
1.620 albertel 3139: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3140: $udom=$env{'user.domain'} unless (defined($udom));
3141: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 3142: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 3143: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 3144: }
3145:
3146: # ------------------------------------- Find the section of student in a course
1.652 albertel 3147: sub devalidate_getsection_cache {
3148: my ($udom,$unam,$courseid)=@_;
3149: my $hashid="$udom:$unam:$courseid";
3150: &devalidate_cache_new('getsection',$hashid);
3151: }
1.298 matthew 3152:
1.815 albertel 3153: sub courseid_to_courseurl {
3154: my ($courseid) = @_;
3155: #already url style courseid
3156: return $courseid if ($courseid =~ m{^/});
3157:
3158: if (exists($env{'course.'.$courseid.'.num'})) {
3159: my $cnum = $env{'course.'.$courseid.'.num'};
3160: my $cdom = $env{'course.'.$courseid.'.domain'};
3161: return "/$cdom/$cnum";
3162: }
3163:
1.1494 raeburn 3164: my %courseinfo=&coursedescription($courseid);
1.815 albertel 3165: if (exists($courseinfo{'num'})) {
3166: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
3167: }
3168:
3169: return undef;
3170: }
3171:
1.298 matthew 3172: sub getsection {
3173: my ($udom,$unam,$courseid)=@_;
1.599 albertel 3174: my $cachetime=1800;
1.551 albertel 3175:
3176: my $hashid="$udom:$unam:$courseid";
1.599 albertel 3177: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 3178: if (defined($cached)) { return $result; }
3179:
1.298 matthew 3180: my %Pending;
3181: my %Expired;
3182: #
3183: # Each role can either have not started yet (pending), be active,
3184: # or have expired.
3185: #
3186: # If there is an active role, we are done.
3187: #
3188: # If there is more than one role which has not started yet,
3189: # choose the one which will start sooner
3190: # If there is one role which has not started yet, return it.
3191: #
3192: # If there is more than one expired role, choose the one which ended last.
3193: # If there is a role which has expired, return it.
3194: #
1.815 albertel 3195: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 3196: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 3197: foreach my $key (keys(%roleshash)) {
1.479 albertel 3198: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 3199: my $section=$1;
3200: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 3201: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 3202: my $now=time;
1.548 albertel 3203: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 3204: $Expired{$end}=$section;
3205: next;
3206: }
1.548 albertel 3207: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 3208: $Pending{$start}=$section;
3209: next;
3210: }
1.599 albertel 3211: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 3212: }
3213: #
3214: # Presumedly there will be few matching roles from the above
3215: # loop and the sorting time will be negligible.
3216: if (scalar(keys(%Pending))) {
3217: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 3218: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 3219: }
3220: if (scalar(keys(%Expired))) {
3221: my @sorted = sort {$a <=> $b} keys(%Expired);
3222: my $time = pop(@sorted);
1.599 albertel 3223: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 3224: }
1.599 albertel 3225: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 3226: }
1.70 www 3227:
1.599 albertel 3228: sub save_cache {
3229: &purge_remembered();
1.722 albertel 3230: #&Apache::loncommon::validate_page();
1.620 albertel 3231: undef(%env);
1.780 albertel 3232: undef($env_loaded);
1.599 albertel 3233: }
1.452 albertel 3234:
1.599 albertel 3235: my $to_remember=-1;
3236: my %remembered;
3237: my %accessed;
3238: my $kicks=0;
3239: my $hits=0;
1.849 albertel 3240: sub make_key {
3241: my ($name,$id) = @_;
1.872 albertel 3242: if (length($id) > 65
3243: && length(&escape($id)) > 200) {
3244: $id=length($id).':'.&Digest::MD5::md5_hex($id);
3245: }
1.849 albertel 3246: return &escape($name.':'.$id);
3247: }
3248:
1.599 albertel 3249: sub devalidate_cache_new {
3250: my ($name,$id,$debug) = @_;
3251: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 3252: my $remembered_id=$name.':'.$id;
1.849 albertel 3253: $id=&make_key($name,$id);
1.599 albertel 3254: $memcache->delete($id);
1.1319 damieng 3255: delete($remembered{$remembered_id});
3256: delete($accessed{$remembered_id});
1.599 albertel 3257: }
3258:
3259: sub is_cached_new {
3260: my ($name,$id,$debug) = @_;
1.1319 damieng 3261: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
3262: if (exists($remembered{$remembered_id})) {
3263: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
3264: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3265: $hits++;
1.1319 damieng 3266: return ($remembered{$remembered_id},1);
1.599 albertel 3267: }
1.1319 damieng 3268: $id=&make_key($name,$id);
1.599 albertel 3269: my $value = $memcache->get($id);
3270: if (!(defined($value))) {
3271: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 3272: return (undef,undef);
1.416 albertel 3273: }
1.599 albertel 3274: if ($value eq '__undef__') {
3275: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3276: $value=undef;
3277: }
1.1319 damieng 3278: &make_room($remembered_id,$value,$debug);
1.599 albertel 3279: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3280: return ($value,1);
3281: }
3282:
3283: sub do_cache_new {
3284: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 3285: my $remembered_id=$name.':'.$id;
1.849 albertel 3286: $id=&make_key($name,$id);
1.599 albertel 3287: my $setvalue=$value;
3288: if (!defined($setvalue)) {
3289: $setvalue='__undef__';
3290: }
1.623 albertel 3291: if (!defined($time) ) {
3292: $time=600;
3293: }
1.599 albertel 3294: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 3295: my $result = $memcache->set($id,$setvalue,$time);
3296: if (! $result) {
1.872 albertel 3297: &logthis("caching of id -> $id failed");
1.910 albertel 3298: $memcache->disconnect_all();
1.872 albertel 3299: }
1.600 albertel 3300: # need to make a copy of $value
1.1319 damieng 3301: &make_room($remembered_id,$value,$debug);
1.599 albertel 3302: return $value;
3303: }
3304:
3305: sub make_room {
1.1319 damieng 3306: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 3307:
1.1319 damieng 3308: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 3309: : $value;
1.599 albertel 3310: if ($to_remember<0) { return; }
1.1319 damieng 3311: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3312: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3313: my $to_kick;
3314: my $max_time=0;
3315: foreach my $other (keys(%accessed)) {
3316: if (&tv_interval($accessed{$other}) > $max_time) {
3317: $to_kick=$other;
3318: $max_time=&tv_interval($accessed{$other});
3319: }
3320: }
3321: delete($remembered{$to_kick});
3322: delete($accessed{$to_kick});
3323: $kicks++;
3324: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 3325: return;
3326: }
3327:
1.599 albertel 3328: sub purge_remembered {
1.604 albertel 3329: #&logthis("Tossing ".scalar(keys(%remembered)));
3330: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 3331: undef(%remembered);
3332: undef(%accessed);
1.428 albertel 3333: }
1.70 www 3334: # ------------------------------------- Read an entry from a user's environment
3335:
3336: sub userenvironment {
3337: my ($udom,$unam,@what)=@_;
1.976 raeburn 3338: my $items;
3339: foreach my $item (@what) {
3340: $items.=&escape($item).'&';
3341: }
3342: $items=~s/\&$//;
1.70 www 3343: my %returnhash=();
1.1009 raeburn 3344: my $uhome = &homeserver($unam,$udom);
3345: unless ($uhome eq 'no_host') {
3346: my @answer=split(/\&/,
3347: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 3348: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3349: return %returnhash;
3350: }
1.1009 raeburn 3351: my $i;
3352: for ($i=0;$i<=$#what;$i++) {
3353: $returnhash{$what[$i]}=&unescape($answer[$i]);
3354: }
1.70 www 3355: }
3356: return %returnhash;
1.1 albertel 3357: }
3358:
1.617 albertel 3359: # ---------------------------------------------------------- Get a studentphoto
3360: sub studentphoto {
3361: my ($udom,$unam,$ext) = @_;
1.1494 raeburn 3362: my $home=&homeserver($unam,$udom);
1.706 raeburn 3363: if (defined($env{'request.course.id'})) {
1.708 raeburn 3364: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 3365: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3366: return(&retrievestudentphoto($udom,$unam,$ext));
3367: } else {
3368: my ($result,$perm_reqd)=
1.1494 raeburn 3369: &auto_photo_permission($unam,$udom);
1.706 raeburn 3370: if ($result eq 'ok') {
3371: if (!($perm_reqd eq 'yes')) {
3372: return(&retrievestudentphoto($udom,$unam,$ext));
3373: }
3374: }
3375: }
3376: }
3377: } else {
3378: my ($result,$perm_reqd) =
1.1494 raeburn 3379: &auto_photo_permission($unam,$udom);
1.706 raeburn 3380: if ($result eq 'ok') {
3381: if (!($perm_reqd eq 'yes')) {
3382: return(&retrievestudentphoto($udom,$unam,$ext));
3383: }
3384: }
3385: }
3386: return '/adm/lonKaputt/lonlogo_broken.gif';
3387: }
3388:
3389: sub retrievestudentphoto {
3390: my ($udom,$unam,$ext,$type) = @_;
1.1494 raeburn 3391: my $home=&homeserver($unam,$udom);
3392: my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
1.706 raeburn 3393: if ($ret eq 'ok') {
3394: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3395: if ($type eq 'thumbnail') {
3396: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3397: }
1.1494 raeburn 3398: my $tokenurl=&tokenwrapper($url);
1.706 raeburn 3399: return $tokenurl;
3400: } else {
3401: if ($type eq 'thumbnail') {
3402: return '/adm/lonKaputt/genericstudent_tn.gif';
3403: } else {
3404: return '/adm/lonKaputt/lonlogo_broken.gif';
3405: }
1.617 albertel 3406: }
3407: }
3408:
1.263 www 3409: # -------------------------------------------------------------------- New chat
3410:
3411: sub chatsend {
1.724 raeburn 3412: my ($newentry,$anon,$group)=@_;
1.620 albertel 3413: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3414: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3415: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 3416: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 3417: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 3418: &escape($newentry)).':'.$group,$chome);
1.292 www 3419: }
3420:
3421: # ------------------------------------------ Find current version of a resource
3422:
3423: sub getversion {
3424: my $fname=&clutter(shift);
1.1189 raeburn 3425: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3426: return ¤tversion(&filelocation('',$fname));
3427: }
3428:
3429: sub currentversion {
3430: my $fname=shift;
3431: my $author=$fname;
3432: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3433: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3434: my $home=&homeserver($uname,$udom);
1.292 www 3435: if ($home eq 'no_host') {
3436: return -1;
3437: }
1.1112 www 3438: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3439: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3440: return -1;
3441: }
1.1112 www 3442: return $answer;
1.263 www 3443: }
3444:
1.1111 www 3445: #
3446: # Return special version number of resource if set by override, empty otherwise
3447: #
3448: sub usedversion {
3449: my $fname=shift;
3450: unless ($fname) { $fname=$env{'request.uri'}; }
3451: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3452: if ($urlversion) { return $urlversion; }
3453: return '';
3454: }
3455:
1.1 albertel 3456: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3457:
1.1 albertel 3458: sub subscribe {
3459: my $fname=shift;
1.761 raeburn 3460: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3461: $fname=~s/[\n\r]//g;
1.1 albertel 3462: my $author=$fname;
3463: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3464: my ($udom,$uname)=split(/\//,$author);
3465: my $home=homeserver($uname,$udom);
1.335 albertel 3466: if ($home eq 'no_host') {
3467: return 'not_found';
1.1 albertel 3468: }
3469: my $answer=reply("sub:$fname",$home);
1.64 www 3470: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3471: $answer.=' by '.$home;
3472: }
1.1 albertel 3473: return $answer;
3474: }
3475:
1.8 www 3476: # -------------------------------------------------------------- Replicate file
3477:
3478: sub repcopy {
3479: my $filename=shift;
1.23 www 3480: $filename=~s/\/+/\//g;
1.1142 raeburn 3481: my $londocroot = $perlvar{'lonDocRoot'};
3482: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3483: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3484: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3485: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3486: return &repcopy_userfile($filename);
3487: }
1.532 albertel 3488: $filename=~s/[\n\r]//g;
1.8 www 3489: my $transname="$filename.in.transfer";
1.828 www 3490: # FIXME: this should flock
1.607 raeburn 3491: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3492: my $remoteurl=subscribe($filename);
1.64 www 3493: if ($remoteurl =~ /^con_lost by/) {
3494: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3495: return 'unavailable';
1.8 www 3496: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3497: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3498: return 'not_found';
1.64 www 3499: } elsif ($remoteurl =~ /^rejected by/) {
3500: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3501: return 'forbidden';
1.20 www 3502: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3503: return 'ok';
1.8 www 3504: } else {
1.290 www 3505: my $author=$filename;
3506: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3507: my ($udom,$uname)=split(/\//,$author);
3508: my $home=homeserver($uname,$udom);
3509: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3510: my @parts=split(/\//,$filename);
3511: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3512: if ($path ne "$londocroot/res") {
1.8 www 3513: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3514: return 'bad_request';
1.8 www 3515: }
3516: my $count;
3517: for ($count=5;$count<$#parts;$count++) {
3518: $path.="/$parts[$count]";
3519: if ((-e $path)!=1) {
3520: mkdir($path,0777);
3521: }
3522: }
3523: my $request=new HTTP::Request('GET',"$remoteurl");
1.1345 raeburn 3524: my $response;
3525: if ($remoteurl =~ m{/raw/}) {
3526: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3527: } else {
3528: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3529: }
1.8 www 3530: if ($response->is_error()) {
3531: unlink($transname);
3532: my $message=$response->status_line;
1.672 albertel 3533: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3534: ." LWP get: $message: $filename</font>");
1.607 raeburn 3535: return 'unavailable';
1.8 www 3536: } else {
1.16 www 3537: if ($remoteurl!~/\.meta$/) {
3538: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345 raeburn 3539: my $mresponse;
3540: if ($remoteurl =~ m{/raw/}) {
3541: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3542: } else {
3543: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3544: }
1.16 www 3545: if ($mresponse->is_error()) {
3546: unlink($filename.'.meta');
3547: &logthis(
1.672 albertel 3548: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3549: }
3550: }
1.8 www 3551: rename($transname,$filename);
1.607 raeburn 3552: return 'ok';
1.8 www 3553: }
1.290 www 3554: }
1.8 www 3555: }
1.330 www 3556: }
3557:
1.1422 raeburn 3558: # ------------------------------------------------- Unsubscribe from a resource
3559:
3560: sub unsubscribe {
3561: my ($fname) = @_;
3562: my $answer;
3563: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3564: $fname=~s/[\n\r]//g;
3565: my $author=$fname;
3566: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3567: my ($udom,$uname)=split(/\//,$author);
3568: my $home=homeserver($uname,$udom);
3569: if ($home eq 'no_host') {
3570: $answer = 'no_host';
3571: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3572: $answer = 'home';
3573: } else {
3574: my $defdom = $perlvar{'lonDefDomain'};
3575: if (&will_trust('content',$defdom,$udom)) {
3576: $answer = reply("unsub:$fname",$home);
3577: } else {
3578: $answer = 'untrusted';
3579: }
3580: }
3581: return $answer;
3582: }
3583:
1.330 www 3584: # ------------------------------------------------ Get server side include body
3585: sub ssi_body {
1.381 albertel 3586: my ($filelink,%form)=@_;
1.606 matthew 3587: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3588: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3589: }
1.953 www 3590: my $output='';
3591: my $response;
1.980 raeburn 3592: if ($filelink=~/^https?\:/) {
1.954 raeburn 3593: ($output,$response)=&externalssi($filelink);
1.953 www 3594: } else {
1.1004 droeschl 3595: $filelink .= $filelink=~/\?/ ? '&' : '?';
3596: $filelink .= 'inhibitmenu=yes';
1.953 www 3597: ($output,$response)=&ssi($filelink,%form);
3598: }
1.778 albertel 3599: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3600: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3601: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3602: if (wantarray) {
3603: return ($output, $response);
3604: } else {
3605: return $output;
3606: }
1.8 www 3607: }
3608:
1.15 www 3609: # --------------------------------------------------------- Server Side Include
3610:
1.782 albertel 3611: sub absolute_url {
1.1447 raeburn 3612: my ($host_name,$unalias,$keep_proto) = @_;
1.782 albertel 3613: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3614: if ($host_name eq '') {
3615: $host_name = $ENV{'SERVER_NAME'};
3616: }
1.1447 raeburn 3617: if ($unalias) {
3618: my $alias = &get_proxy_alias();
3619: if ($alias eq $host_name) {
3620: my $lonhost = $perlvar{'lonHostID'};
3621: my $hostname = &hostname($lonhost);
3622: my $lcproto;
3623: if (($keep_proto) || ($hostname eq '')) {
3624: $lcproto = $protocol;
3625: } else {
3626: $lcproto = $protocol{$lonhost};
3627: $lcproto = 'http' if ($lcproto ne 'https');
3628: $lcproto .= '://';
3629: }
3630: unless ($hostname eq '') {
3631: return $lcproto.$hostname;
3632: }
3633: }
3634: }
1.782 albertel 3635: return $protocol.$host_name;
3636: }
3637:
1.942 foxr 3638: #
3639: # Server side include.
3640: # Parameters:
3641: # fn Possibly encrypted resource name/id.
3642: # form Hash that describes how the rendering should be done
3643: # and other things.
1.944 foxr 3644: # Returns:
1.950 raeburn 3645: # Scalar context: The content of the response.
3646: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3647: #
1.15 www 3648: sub ssi {
3649:
1.944 foxr 3650: my ($fn,%form)=@_;
1.1447 raeburn 3651: my ($host,$request,$response);
3652: $host = &absolute_url('',1);
1.711 albertel 3653:
3654: $form{'no_update_last_known'}=1;
1.895 albertel 3655: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3656: if (%form) {
1.1447 raeburn 3657: $request=new HTTP::Request('POST',$host.$fn);
1.1272 droeschl 3658: $request->content(join('&',map {
3659: my $name = escape($_);
3660: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3661: ? join("&$name=", map {escape($_) } @{$form{$_}})
3662: : &escape($form{$_}) );
3663: } keys(%form)));
1.23 www 3664: } else {
1.1447 raeburn 3665: $request=new HTTP::Request('GET',$host.$fn);
1.23 www 3666: }
3667:
1.15 www 3668: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345 raeburn 3669: my $lonhost = $perlvar{'lonHostID'};
1.1385 raeburn 3670: my $islocal;
3671: if (($env{'request.course.id'}) &&
3672: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3673: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3674: ($form{'grade_symb'} ne '') &&
1.1494 raeburn 3675: (&allowed('mgr',$env{'request.course.id'}.
3676: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1385 raeburn 3677: $islocal = 1;
3678: }
1.1447 raeburn 3679: $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
3680: '','','',$islocal);
1.1182 foxr 3681:
1.944 foxr 3682: if (wantarray) {
1.1345 raeburn 3683: return ($response->content, $response);
1.944 foxr 3684: } else {
1.1345 raeburn 3685: return $response->content;
1.942 foxr 3686: }
1.324 www 3687: }
3688:
3689: sub externalssi {
3690: my ($url)=@_;
3691: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 3692: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954 raeburn 3693: if (wantarray) {
3694: return ($response->content, $response);
3695: } else {
3696: return $response->content;
3697: }
1.15 www 3698: }
1.254 www 3699:
1.1354 raeburn 3700:
3701: # If the local copy of a replicated resource is outdated, trigger a
3702: # connection from the homeserver to flush the delayed queue. If no update
3703: # happens, remove local copies of outdated resource (and corresponding
3704: # metadata file).
3705:
1.1352 raeburn 3706: sub remove_stale_resfile {
3707: my ($url) = @_;
1.1354 raeburn 3708: my $removed;
1.1352 raeburn 3709: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3710: my $audom = $1;
3711: my $auname = $2;
1.1353 raeburn 3712: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352 raeburn 3713: my $homeserver = &homeserver($auname,$audom);
3714: unless (($homeserver eq 'no_host') ||
3715: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3716: my $fname = &filelocation('',$url);
3717: if (-e $fname) {
3718: my $hostname = &hostname($homeserver);
3719: if ($hostname) {
1.1397 raeburn 3720: my $protocol = $protocol{$homeserver};
3721: $protocol = 'http' if ($protocol ne 'https');
1.1352 raeburn 3722: my $uri = &declutter($url);
3723: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3724: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3725: if ($response->is_success()) {
3726: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3727: my $locmodtime = (stat($fname))[9];
3728: if ($locmodtime < $remmodtime) {
1.1354 raeburn 3729: my $stale;
3730: my $answer = &reply('pong',$homeserver);
3731: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3732: sleep(0.2);
3733: $locmodtime = (stat($fname))[9];
3734: if ($locmodtime < $remmodtime) {
3735: my $posstransfer = $fname.'.in.transfer';
3736: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3737: $removed = 1;
3738: } else {
3739: $stale = 1;
3740: }
3741: } else {
3742: $removed = 1;
3743: }
3744: } else {
3745: $stale = 1;
3746: }
3747: if ($stale) {
1.1421 raeburn 3748: if (unlink($fname)) {
3749: if ($uri!~/\.meta$/) {
3750: if (-e $fname.'.meta') {
3751: unlink($fname.'.meta');
3752: }
3753: }
1.1422 raeburn 3754: my $unsubresult = &unsubscribe($fname);
3755: unless ($unsubresult eq 'ok') {
3756: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3757: }
1.1421 raeburn 3758: $removed = 1;
1.1354 raeburn 3759: }
1.1352 raeburn 3760: }
3761: }
3762: }
3763: }
3764: }
3765: }
3766: }
3767: }
1.1354 raeburn 3768: return $removed;
1.1352 raeburn 3769: }
3770:
1.492 albertel 3771: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3772:
3773: sub allowuploaded {
3774: my ($srcurl,$url)=@_;
3775: $url=&clutter(&declutter($url));
3776: my $dir=$url;
3777: $dir=~s/\/[^\/]+$//;
3778: my %httpref=();
3779: my $httpurl=&hreflocation('',$url);
3780: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3781: &Apache::lonnet::appenv(\%httpref);
1.254 www 3782: }
1.477 raeburn 3783:
1.1193 raeburn 3784: #
3785: # Determine if the current user should be able to edit a particular resource,
3786: # when viewing in course context.
3787: # (a) When viewing resource used to determine if "Edit" item is included in
3788: # Functions.
3789: # (b) When displaying folder contents in course editor, used to determine if
3790: # "Edit" link will be displayed alongside resource.
3791: #
1.1196 raeburn 3792: # input: six args -- filename (decluttered), course number, course domain,
3793: # url, symb (if registered) and group (if this is a group
3794: # item -- e.g., bulletin board, group page etc.).
3795: # output: array of five scalars --
1.1193 raeburn 3796: # $cfile -- url for file editing if editable on current server
3797: # $home -- homeserver of resource (i.e., for author if published,
3798: # or course if uploaded.).
3799: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3800: # $forceedit -- 1 if icon/link should be to go to edit mode
3801: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3802: #
3803:
3804: sub can_edit_resource {
1.1194 raeburn 3805: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3806: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3807: #
3808: # For aboutme pages user can only edit his/her own.
3809: #
1.1199 raeburn 3810: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3811: my ($sdom,$sname) = ($1,$2);
3812: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3813: $home = $env{'user.home'};
3814: $cfile = $resurl;
3815: if ($env{'form.forceedit'}) {
3816: $forceview = 1;
3817: } else {
3818: $forceedit = 1;
3819: }
3820: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3821: } else {
3822: return;
3823: }
3824: }
3825:
3826: if ($env{'request.course.id'}) {
1.1494 raeburn 3827: my $crsedit = &allowed('mdc',$env{'request.course.id'});
1.1194 raeburn 3828: if ($group ne '') {
3829: # if this is a group homepage or group bulletin board, check group privs
3830: my $allowed = 0;
1.1197 raeburn 3831: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3832: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3833: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3834: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3835: $allowed = 1;
3836: }
1.1197 raeburn 3837: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3838: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3839: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3840: $allowed = 1;
3841: }
3842: }
3843: if ($allowed) {
3844: $home=&homeserver($cnum,$cdom);
3845: if ($env{'form.forceedit'}) {
3846: $forceview = 1;
3847: } else {
3848: $forceedit = 1;
3849: }
3850: $cfile = $resurl;
3851: } else {
3852: return;
3853: }
3854: } else {
1.1208 raeburn 3855: if ($resurl =~ m{^/?adm/viewclasslist$}) {
1.1494 raeburn 3856: unless (&allowed('opa',$env{'request.course.id'})) {
1.1208 raeburn 3857: return;
3858: }
3859: } elsif (!$crsedit) {
1.1194 raeburn 3860: #
3861: # No edit allowed where CC has switched to student role.
3862: #
3863: return;
3864: }
3865: }
3866: }
3867:
1.1193 raeburn 3868: if ($file ne '') {
3869: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3870: if (&is_course_upload($file,$cnum,$cdom)) {
3871: $uploaded = 1;
3872: $incourse = 1;
1.1193 raeburn 3873: if ($file =~/\.(htm|html|css|js|txt)$/) {
3874: $cfile = &hreflocation('',$file);
1.1201 raeburn 3875: if ($env{'form.forceedit'}) {
3876: $forceview = 1;
3877: } else {
3878: $forceedit = 1;
3879: }
1.1194 raeburn 3880: }
3881: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3882: $incourse = 1;
3883: if ($env{'form.forceedit'}) {
3884: $forceview = 1;
3885: } else {
3886: $forceedit = 1;
3887: }
3888: $cfile = $resurl;
3889: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3890: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3891: $incourse = 1;
3892: if ($env{'form.forceedit'}) {
3893: $forceview = 1;
3894: } else {
3895: $forceedit = 1;
3896: }
3897: $cfile = $resurl;
1.1199 raeburn 3898: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3899: $incourse = 1;
3900: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3901: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3902: $incourse = 1;
1.1199 raeburn 3903: if ($env{'form.forceedit'}) {
3904: $forceview = 1;
3905: } else {
3906: $forceedit = 1;
3907: }
3908: $cfile = $resurl;
1.1419 raeburn 3909: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3910: my ($map,$id,$res) = &decode_symb($symb);
3911: if ($map =~ /\.page$/) {
3912: $incourse = 1;
3913: if ($env{'form.forceedit'}) {
3914: $forceview = 1;
3915: $cfile = $map;
3916: } else {
3917: $forceedit = 1;
3918: $cfile = '/adm/wrapper'.$resurl;
3919: }
3920: }
1.1343 raeburn 3921: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3922: $incourse = 1;
3923: if ($env{'form.forceedit'}) {
3924: $forceview = 1;
3925: } else {
3926: $forceedit = 1;
3927: }
3928: $cfile = $resurl;
1.1208 raeburn 3929: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3930: $incourse = 1;
3931: if ($env{'form.forceedit'}) {
3932: $forceview = 1;
3933: } else {
3934: $forceedit = 1;
3935: }
3936: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3937: }
3938: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3939: my $template = '/res/lib/templates/simpleproblem.problem';
3940: if (&is_on_map($template)) {
3941: $incourse = 1;
3942: $forceview = 1;
3943: $cfile = $template;
1.1193 raeburn 3944: }
1.1199 raeburn 3945: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418 raeburn 3946: $incourse = 1;
3947: if ($env{'form.forceedit'}) {
3948: $forceview = 1;
3949: } else {
3950: $forceedit = 1;
3951: }
3952: $cfile = $resurl;
1.1343 raeburn 3953: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298 raeburn 3954: $incourse = 1;
3955: if ($env{'form.forceedit'}) {
3956: $forceview = 1;
3957: } else {
3958: $forceedit = 1;
3959: }
3960: $cfile = $resurl;
1.1199 raeburn 3961: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3962: $incourse = 1;
3963: $forceview = 1;
3964: if ($symb) {
3965: my ($map,$id,$res)=&decode_symb($symb);
3966: $env{'request.symb'} = $symb;
3967: $cfile = &clutter($res);
3968: } else {
3969: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3970: my $escfile = &unescape($cfile);
1.1343 raeburn 3971: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3972: $cfile = '/adm/wrapper'.$escfile;
3973: } else {
3974: $escfile =~ s{^http://}{};
3975: $cfile = &escape("/adm/wrapper/ext/$escfile");
3976: }
1.1199 raeburn 3977: }
1.1234 raeburn 3978: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3979: if ($env{'form.forceedit'}) {
3980: $forceview = 1;
3981: } else {
3982: $forceedit = 1;
3983: }
3984: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3985: }
3986: }
1.1194 raeburn 3987: if ($uploaded || $incourse) {
3988: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3989: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3990: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3991: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3992: # Check that the user has permission to edit this resource
3993: my $setpriv = 1;
3994: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3995: if (defined($cfudom)) {
3996: $home=&homeserver($cfuname,$cfudom);
3997: $cfile=$file;
3998: }
3999: }
1.1194 raeburn 4000: if (($cfile ne '') && (!$incourse || $uploaded) &&
4001: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 4002: my @ids=¤t_machine_ids();
4003: unless (grep(/^\Q$home\E$/,@ids)) {
4004: $switchserver=1;
4005: }
4006: }
4007: }
1.1194 raeburn 4008: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 4009: }
4010:
4011: sub is_course_upload {
4012: my ($file,$cnum,$cdom) = @_;
4013: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
4014: $uploadpath =~ s{^\/}{};
1.1201 raeburn 4015: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
4016: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 4017: return 1;
4018: }
4019: return;
4020: }
4021:
1.1194 raeburn 4022: sub in_course {
1.1195 raeburn 4023: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
4024: if ($hideprivileged) {
4025: my $skipuser;
1.1219 raeburn 4026: my %coursehash = &coursedescription($cdom.'_'.$cnum);
4027: my @possdoms = ($cdom);
4028: if ($coursehash{'checkforpriv'}) {
4029: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4030: }
4031: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 4032: $skipuser = 1;
4033: if ($coursehash{'nothideprivileged'}) {
4034: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4035: my $user;
4036: if ($item =~ /:/) {
4037: $user = $item;
4038: } else {
4039: $user = join(':',split(/[\@]/,$item));
4040: }
4041: if ($user eq $uname.':'.$udom) {
4042: undef($skipuser);
4043: last;
4044: }
4045: }
4046: }
4047: if ($skipuser) {
4048: return 0;
4049: }
4050: }
4051: }
1.1194 raeburn 4052: $type ||= 'any';
4053: if (!defined($cdom) || !defined($cnum)) {
4054: my $cid = $env{'request.course.id'};
4055: $cdom = $env{'course.'.$cid.'.domain'};
4056: $cnum = $env{'course.'.$cid.'.num'};
4057: }
4058: my $typesref;
1.1195 raeburn 4059: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 4060: $typesref = ['active','previous','future'];
4061: } elsif ($type eq 'previous' || $type eq 'future') {
4062: $typesref = [$type];
4063: }
4064: my %roles = &get_my_roles($uname,$udom,'userroles',
4065: $typesref,undef,[$cdom]);
4066: my ($tmp) = keys(%roles);
4067: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
4068: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
4069: if (@course_roles > 0) {
4070: return 1;
4071: }
4072: return 0;
4073: }
4074:
1.478 albertel 4075: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 4076: # input: action, courseID, current domain, intended
1.637 raeburn 4077: # path to file, source of file, instruction to parse file for objects,
4078: # ref to hash for embedded objects,
4079: # ref to hash for codebase of java objects.
1.1095 raeburn 4080: # reference to scalar to accommodate mime type determined
4081: # from File::MMagic if $parser = parse.
1.637 raeburn 4082: #
1.485 raeburn 4083: # output: url to file (if action was uploaddoc),
4084: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 4085: #
1.478 albertel 4086: # Allows directory structure to be used within lonUsers/../userfiles/ for a
4087: # course.
1.477 raeburn 4088: #
1.478 albertel 4089: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4090: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
4091: # course's home server.
1.477 raeburn 4092: #
1.478 albertel 4093: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
4094: # be copied from $source (current location) to
4095: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4096: # and will then be copied to
4097: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
4098: # course's home server.
1.485 raeburn 4099: #
1.481 raeburn 4100: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 4101: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 4102: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4103: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
4104: # in course's home server.
1.637 raeburn 4105: #
1.477 raeburn 4106:
4107: sub process_coursefile {
1.1095 raeburn 4108: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
4109: $mimetype)=@_;
1.477 raeburn 4110: my $fetchresult;
1.638 albertel 4111: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 4112: if ($action eq 'propagate') {
1.638 albertel 4113: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4114: $home);
1.481 raeburn 4115: } else {
1.477 raeburn 4116: my $fpath = '';
4117: my $fname = $file;
1.478 albertel 4118: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 4119: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 4120: my $filepath = &build_filepath($fpath);
1.481 raeburn 4121: if ($action eq 'copy') {
4122: if ($source eq '') {
4123: $fetchresult = 'no source file';
4124: return $fetchresult;
4125: } else {
4126: my $destination = $filepath.'/'.$fname;
4127: rename($source,$destination);
4128: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4129: $home);
1.481 raeburn 4130: }
4131: } elsif ($action eq 'uploaddoc') {
1.1359 raeburn 4132: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 4133: print $fh $env{'form.'.$source};
1.481 raeburn 4134: close($fh);
1.637 raeburn 4135: if ($parser eq 'parse') {
1.1024 raeburn 4136: my $mm = new File::MMagic;
1.1095 raeburn 4137: my $type = $mm->checktype_filename($filepath.'/'.$fname);
4138: if ($type eq 'text/html') {
1.1024 raeburn 4139: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
4140: unless ($parse_result eq 'ok') {
4141: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
4142: }
1.637 raeburn 4143: }
1.1095 raeburn 4144: if (ref($mimetype)) {
4145: $$mimetype = $type;
4146: }
1.637 raeburn 4147: }
1.477 raeburn 4148: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4149: $home);
1.481 raeburn 4150: if ($fetchresult eq 'ok') {
4151: return '/uploaded/'.$fpath.'/'.$fname;
4152: } else {
4153: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4154: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 4155: return '/adm/notfound.html';
4156: }
1.477 raeburn 4157: }
4158: }
1.485 raeburn 4159: unless ( $fetchresult eq 'ok') {
1.477 raeburn 4160: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4161: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 4162: }
4163: return $fetchresult;
4164: }
4165:
1.637 raeburn 4166: sub build_filepath {
4167: my ($fpath) = @_;
4168: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
4169: unless ($fpath eq '') {
4170: my @parts=split('/',$fpath);
4171: foreach my $part (@parts) {
4172: $filepath.= '/'.$part;
4173: if ((-e $filepath)!=1) {
4174: mkdir($filepath,0777);
4175: }
4176: }
4177: }
4178: return $filepath;
4179: }
4180:
4181: sub store_edited_file {
1.638 albertel 4182: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 4183: my $file = $primary_url;
4184: $file =~ s#^/uploaded/$docudom/$docuname/##;
4185: my $fpath = '';
4186: my $fname = $file;
4187: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
4188: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
4189: my $filepath = &build_filepath($fpath);
1.1359 raeburn 4190: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 4191: print $fh $content;
4192: close($fh);
1.638 albertel 4193: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 4194: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4195: $home);
1.637 raeburn 4196: if ($$fetchresult eq 'ok') {
4197: return '/uploaded/'.$fpath.'/'.$fname;
4198: } else {
1.638 albertel 4199: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4200: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 4201: return '/adm/notfound.html';
4202: }
4203: }
4204:
1.531 albertel 4205: sub clean_filename {
1.831 albertel 4206: my ($fname,$args)=@_;
1.315 www 4207: # Replace Windows backslashes by forward slashes
1.257 www 4208: $fname=~s/\\/\//g;
1.831 albertel 4209: if (!$args->{'keep_path'}) {
4210: # Get rid of everything but the actual filename
4211: $fname=~s/^.*\/([^\/]+)$/$1/;
4212: }
1.315 www 4213: # Replace spaces by underscores
4214: $fname=~s/\s+/\_/g;
1.1406 raeburn 4215: # Transliterate non-ascii text to ascii
4216: my $lang = &Apache::lonlocal::current_language();
4217: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 4218: # Replace all other weird characters by nothing
1.831 albertel 4219: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 4220: # Replace all .\d. sequences with _\d. so they no longer look like version
4221: # numbers
4222: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443 raeburn 4223: # Replace three or more adjacent underscores with one for consistency
4224: # with loncfile::filename_check() so complete url can be extracted by
4225: # lonnet::decode_symb()
4226: $fname=~s/_{3,}/_/g;
1.531 albertel 4227: return $fname;
4228: }
1.1406 raeburn 4229:
1.1051 raeburn 4230: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4231: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4232: # image with the same aspect ratio as the original, but with dimensions which do
4233: # not exceed $resizewidth and $resizeheight.
4234:
1.984 neumanie 4235: sub resizeImage {
1.1051 raeburn 4236: my ($img_path,$resizewidth,$resizeheight) = @_;
4237: my $ima = Image::Magick->new;
4238: my $resized;
4239: if (-e $img_path) {
4240: $ima->Read($img_path);
4241: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4242: my $width = $ima->Get('width');
4243: my $height = $ima->Get('height');
4244: if ($width > $resizewidth) {
4245: my $factor = $width/$resizewidth;
4246: my $newheight = $height/$factor;
4247: $ima->Scale(width=>$resizewidth,height=>$newheight);
4248: $resized = 1;
4249: }
4250: }
4251: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4252: my $width = $ima->Get('width');
4253: my $height = $ima->Get('height');
4254: if ($height > $resizeheight) {
4255: my $factor = $height/$resizeheight;
4256: my $newwidth = $width/$factor;
4257: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4258: $resized = 1;
4259: }
4260: }
4261: if ($resized) {
4262: $ima->Write($img_path);
4263: }
4264: }
4265: return;
1.977 amueller 4266: }
4267:
1.608 albertel 4268: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 4269: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 4270: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 4271: # $context - possible values: coursedoc, existingfile, overwrite,
1.1401 raeburn 4272: # canceloverwrite, scantron or ''.
1.1090 raeburn 4273: # if 'coursedoc': upload to the current course
4274: # if 'existingfile': write file to tmp/overwrites directory
4275: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4276: # $context is passed as argument to &finishuserfileupload
1.686 albertel 4277: # $subdir - directory in userfile to store the file into
1.1401 raeburn 4278: # $parser - instruction to parse file for objects ($parser = parse) or
4279: # if context is 'scantron', $parser is hashref of csv column mapping
4280: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4281: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 4282: # $allfiles - reference to hash for embedded objects
4283: # $codebase - reference to hash for codebase of java objects
4284: # $desuname - username for permanent storage of uploaded file
4285: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 4286: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4287: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 4288: # $resizewidth - width (pixels) to which to resize uploaded image
4289: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 4290: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 4291: # from File::MMagic.
1.858 raeburn 4292: #
1.686 albertel 4293: # output: url of file in userspace, or error: <message>
4294: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 4295:
1.531 albertel 4296: sub userfileupload {
1.1090 raeburn 4297: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 4298: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 4299: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 4300: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 4301: $fname=&clean_filename($fname);
1.1090 raeburn 4302: # See if there is anything left
1.257 www 4303: unless ($fname) { return 'error: no uploaded file'; }
1.1406 raeburn 4304: # If filename now begins with a . prepend unix timestamp _ milliseconds
4305: if ($fname =~ /^\./) {
4306: my ($s,$usec) = &gettimeofday();
4307: while (length($usec) < 6) {
4308: $usec = '0'.$usec;
4309: }
4310: $fname = $s.'_'.substr($usec,0,3).$fname;
4311: }
1.1090 raeburn 4312: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4313: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4314: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4315: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 4316: my $now = time;
1.1090 raeburn 4317: my $filepath;
1.1095 raeburn 4318: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 4319: $filepath = 'tmp/helprequests/'.$now;
4320: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4321: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4322: '_'.$env{'user.domain'}.'/pending';
4323: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4324: my ($docuname,$docudom);
1.1350 raeburn 4325: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 4326: $docudom = $destudom;
4327: } else {
4328: $docudom = $env{'user.domain'};
4329: }
1.1350 raeburn 4330: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 4331: $docuname = $destuname;
4332: } else {
4333: $docuname = $env{'user.name'};
4334: }
4335: if (exists($env{'form.group'})) {
4336: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4337: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4338: }
4339: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4340: if ($context eq 'canceloverwrite') {
4341: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4342: if (-e $tempfile) {
4343: my @info = stat($tempfile);
4344: if ($info[9] eq $env{'form.timestamp'}) {
4345: unlink($tempfile);
4346: }
4347: }
4348: return;
1.523 raeburn 4349: }
4350: }
1.1090 raeburn 4351: # Create the directory if not present
1.741 raeburn 4352: my @parts=split(/\//,$filepath);
4353: my $fullpath = $perlvar{'lonDaemons'};
4354: for (my $i=0;$i<@parts;$i++) {
4355: $fullpath .= '/'.$parts[$i];
4356: if ((-e $fullpath)!=1) {
4357: mkdir($fullpath,0777);
4358: }
4359: }
1.1359 raeburn 4360: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 4361: print $fh $env{'form.'.$formname};
4362: close($fh);
1.1090 raeburn 4363: if ($context eq 'existingfile') {
4364: my @info = stat($fullpath.'/'.$fname);
4365: return ($fullpath.'/'.$fname,$info[9]);
4366: } else {
4367: return $fullpath.'/'.$fname;
4368: }
1.523 raeburn 4369: }
1.995 raeburn 4370: if ($subdir eq 'scantron') {
4371: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 4372: } else {
1.995 raeburn 4373: $fname="$subdir/$fname";
4374: }
1.1090 raeburn 4375: if ($context eq 'coursedoc') {
1.638 albertel 4376: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4377: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 4378: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 4379: return &finishuserfileupload($docuname,$docudom,
4380: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 4381: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 4382: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 4383: } else {
1.1218 raeburn 4384: if ($env{'form.folder'}) {
4385: $fname=$env{'form.folder'}.'/'.$fname;
4386: }
1.638 albertel 4387: return &process_coursefile('uploaddoc',$docuname,$docudom,
4388: $fname,$formname,$parser,
1.1095 raeburn 4389: $allfiles,$codebase,$mimetype);
1.481 raeburn 4390: }
1.719 banghart 4391: } elsif (defined($destuname)) {
4392: my $docuname=$destuname;
4393: my $docudom=$destudom;
1.860 raeburn 4394: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4395: $parser,$allfiles,$codebase,
1.1051 raeburn 4396: $thumbwidth,$thumbheight,
1.1095 raeburn 4397: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4398: } else {
1.638 albertel 4399: my $docuname=$env{'user.name'};
4400: my $docudom=$env{'user.domain'};
1.1220 raeburn 4401: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 4402: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4403: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4404: }
1.860 raeburn 4405: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4406: $parser,$allfiles,$codebase,
1.1051 raeburn 4407: $thumbwidth,$thumbheight,
1.1095 raeburn 4408: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4409: }
1.271 www 4410: }
4411:
4412: sub finishuserfileupload {
1.860 raeburn 4413: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4414: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4415: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4416: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4417:
1.860 raeburn 4418: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4419: $file=$fname;
4420: if ($fname=~m|/|) {
4421: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4422: $path.=$fnamepath.'/';
4423: }
1.259 www 4424: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4425: my $count;
4426: for ($count=4;$count<=$#parts;$count++) {
4427: $filepath.="/$parts[$count]";
4428: if ((-e $filepath)!=1) {
4429: mkdir($filepath,0777);
4430: }
4431: }
1.984 neumanie 4432:
1.258 www 4433: # Save the file
4434: {
1.1359 raeburn 4435: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4436: &logthis('Failed to create '.$filepath.'/'.$file);
4437: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4438: return '/adm/notfound.html';
4439: }
1.1090 raeburn 4440: if ($context eq 'overwrite') {
1.1117 foxr 4441: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4442: my $target = $filepath.'/'.$file;
4443: if (-e $source) {
4444: my @info = stat($source);
4445: if ($info[9] eq $env{'form.timestamp'}) {
4446: unless (&File::Copy::move($source,$target)) {
4447: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4448: return "Moving from $source failed";
4449: }
4450: } else {
4451: return "Temporary file: $source had unexpected date/time for last modification";
4452: }
4453: } else {
4454: return "Temporary file: $source missing";
4455: }
4456: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4457: &logthis('Failed to write to '.$filepath.'/'.$file);
4458: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4459: return '/adm/notfound.html';
4460: }
1.570 albertel 4461: close(FH);
1.1051 raeburn 4462: if ($resizewidth && $resizeheight) {
4463: my $mm = new File::MMagic;
4464: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4465: if ($mime_type =~ m{^image/}) {
4466: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4467: }
1.977 amueller 4468: }
1.258 www 4469: }
1.1152 raeburn 4470: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4471: if (ref($mimetype)) {
4472: if ($$mimetype eq '') {
4473: my $mm = new File::MMagic;
4474: my $type = $mm->checktype_filename($filepath.'/'.$file);
4475: $$mimetype = $type;
4476: }
4477: }
4478: }
1.1401 raeburn 4479: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4480: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4481: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4482: $allfiles,$codebase);
4483: unless ($parse_result eq 'ok') {
4484: &logthis('Failed to parse '.$filepath.$file.
4485: ' for embedded media: '.$parse_result);
4486: }
1.637 raeburn 4487: }
1.1401 raeburn 4488: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4489: my $format = $env{'form.scantron_format'};
4490: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4491: }
1.860 raeburn 4492: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4493: my $input = $filepath.'/'.$file;
4494: my $output = $filepath.'/'.'tn-'.$file;
4495: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359 raeburn 4496: my @args = ('convert','-sample',$thumbsize,$input,$output);
4497: system({$args[0]} @args);
1.860 raeburn 4498: if (-e $filepath.'/'.'tn-'.$file) {
4499: $fetchthumb = 1;
4500: }
4501: }
1.858 raeburn 4502:
1.259 www 4503: # Notify homeserver to grep it
4504: #
1.984 neumanie 4505: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4506: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4507: if ($fetchresult eq 'ok') {
1.860 raeburn 4508: if ($fetchthumb) {
4509: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4510: if ($thumbresult ne 'ok') {
4511: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4512: $docuhome.': '.$thumbresult);
4513: }
4514: }
1.259 www 4515: #
1.258 www 4516: # Return the URL to it
1.494 albertel 4517: return '/uploaded/'.$path.$file;
1.263 www 4518: } else {
1.494 albertel 4519: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4520: ': '.$fetchresult);
1.263 www 4521: return '/adm/notfound.html';
1.858 raeburn 4522: }
1.493 albertel 4523: }
4524:
1.637 raeburn 4525: sub extract_embedded_items {
1.961 raeburn 4526: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4527: my @state = ();
1.1164 raeburn 4528: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4529: my %javafiles = (
4530: codebase => '',
4531: code => '',
4532: archive => ''
4533: );
4534: my %mediafiles = (
4535: src => '',
4536: movie => '',
4537: );
1.648 raeburn 4538: my $p;
4539: if ($content) {
4540: $p = HTML::LCParser->new($content);
4541: } else {
1.961 raeburn 4542: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4543: }
1.641 albertel 4544: while (my $t=$p->get_token()) {
1.640 albertel 4545: if ($t->[0] eq 'S') {
4546: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4547: push(@state, $tagname);
1.648 raeburn 4548: if (lc($tagname) eq 'allow') {
4549: &add_filetype($allfiles,$attr->{'src'},'src');
4550: }
1.640 albertel 4551: if (lc($tagname) eq 'img') {
4552: &add_filetype($allfiles,$attr->{'src'},'src');
4553: }
1.886 albertel 4554: if (lc($tagname) eq 'a') {
1.1222 raeburn 4555: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 4556: &add_filetype($allfiles,$attr->{'href'},'href');
4557: }
1.886 albertel 4558: }
1.645 raeburn 4559: if (lc($tagname) eq 'script') {
1.1164 raeburn 4560: my $src;
1.645 raeburn 4561: if ($attr->{'archive'} =~ /\.jar$/i) {
4562: &add_filetype($allfiles,$attr->{'archive'},'archive');
4563: } else {
1.1164 raeburn 4564: if ($attr->{'src'} ne '') {
4565: $src = $attr->{'src'};
4566: &add_filetype($allfiles,$src,'src');
4567: }
4568: }
4569: my $text = $p->get_trimmed_text();
4570: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4571: my @swfargs = split(/,/,$1);
4572: foreach my $item (@swfargs) {
4573: $item =~ s/["']//g;
4574: $item =~ s/^\s+//;
4575: $item =~ s/\s+$//;
4576: }
4577: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4578: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4579: push(@{$related{$swfargs[0]}},$swfargs[2]);
4580: } else {
4581: $related{$swfargs[0]} = [$swfargs[2]];
4582: }
4583: }
1.645 raeburn 4584: }
4585: }
4586: if (lc($tagname) eq 'link') {
4587: if (lc($attr->{'rel'}) eq 'stylesheet') {
4588: &add_filetype($allfiles,$attr->{'href'},'href');
4589: }
4590: }
1.640 albertel 4591: if (lc($tagname) eq 'object' ||
4592: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4593: foreach my $item (keys(%javafiles)) {
4594: $javafiles{$item} = '';
4595: }
1.1164 raeburn 4596: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4597: $lastids{lc($tagname)} = $attr->{'id'};
4598: }
1.640 albertel 4599: }
4600: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4601: my $name = lc($attr->{'name'});
4602: foreach my $item (keys(%javafiles)) {
4603: if ($name eq $item) {
4604: $javafiles{$item} = $attr->{'value'};
4605: last;
4606: }
4607: }
1.1164 raeburn 4608: my $pathfrom;
1.640 albertel 4609: foreach my $item (keys(%mediafiles)) {
4610: if ($name eq $item) {
1.1164 raeburn 4611: $pathfrom = $attr->{'value'};
4612: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4613: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4614: last;
4615: }
4616: }
1.1164 raeburn 4617: if ($name eq 'flashvars') {
4618: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4619: }
4620: if ($pathfrom ne '') {
4621: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4622: $pathfrom);
4623: }
1.640 albertel 4624: }
4625: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4626: foreach my $item (keys(%javafiles)) {
4627: if ($attr->{$item}) {
4628: $javafiles{$item} = $attr->{$item};
4629: last;
4630: }
4631: }
4632: foreach my $item (keys(%mediafiles)) {
4633: if ($attr->{$item}) {
4634: &add_filetype($allfiles,$attr->{$item},$item);
4635: last;
4636: }
4637: }
1.1164 raeburn 4638: if (lc($tagname) eq 'embed') {
4639: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4640: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4641: $attr->{'src'});
4642: }
4643: }
1.640 albertel 4644: }
1.1243 raeburn 4645: if (lc($tagname) eq 'iframe') {
4646: my $src = $attr->{'src'} ;
4647: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4648: &add_filetype($allfiles,$src,'src');
4649: } elsif ($src =~ m{^/}) {
4650: if ($env{'request.course.id'}) {
4651: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4652: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4653: my $url = &hreflocation('',$fullpath);
4654: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4655: my $relpath = $1;
4656: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4657: &add_filetype($allfiles,$1,'src');
4658: }
4659: }
4660: }
4661: }
4662: }
1.1164 raeburn 4663: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 4664: pop(@state);
1.1164 raeburn 4665: }
1.640 albertel 4666: } elsif ($t->[0] eq 'E') {
4667: my ($tagname) = ($t->[1]);
4668: if ($javafiles{'codebase'} ne '') {
4669: $javafiles{'codebase'} .= '/';
4670: }
4671: if (lc($tagname) eq 'applet' ||
4672: lc($tagname) eq 'object' ||
4673: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4674: ) {
4675: foreach my $item (keys(%javafiles)) {
4676: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4677: my $file=$javafiles{'codebase'}.$javafiles{$item};
4678: &add_filetype($allfiles,$file,$item);
4679: }
4680: }
4681: }
4682: pop @state;
4683: }
4684: }
1.1164 raeburn 4685: foreach my $id (sort(keys(%flashvars))) {
4686: if ($shockwave{$id} ne '') {
4687: my @pairs = split(/\&/,$flashvars{$id});
4688: foreach my $pair (@pairs) {
4689: my ($key,$value) = split(/\=/,$pair);
4690: if ($key eq 'thumb') {
4691: &add_filetype($allfiles,$value,$key);
4692: } elsif ($key eq 'content') {
4693: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4694: my ($ext) = ($value =~ /\.([^.]+)$/);
4695: if ($ext ne '') {
4696: &add_filetype($allfiles,$path.$value,$ext);
4697: }
4698: }
4699: }
4700: }
4701: }
1.637 raeburn 4702: return 'ok';
4703: }
4704:
1.639 albertel 4705: sub add_filetype {
4706: my ($allfiles,$file,$type)=@_;
4707: if (exists($allfiles->{$file})) {
4708: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4709: push(@{$allfiles->{$file}}, &escape($type));
4710: }
4711: } else {
4712: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4713: }
4714: }
4715:
1.1164 raeburn 4716: sub embedded_dependency {
4717: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4718: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4719: if (($identifier ne '') &&
4720: (ref($related->{$identifier}) eq 'ARRAY') &&
4721: ($pathfrom ne '')) {
4722: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4723: foreach my $dep (@{$related->{$identifier}}) {
4724: &add_filetype($allfiles,$path.$dep,'object');
4725: }
4726: }
4727: }
4728: return;
4729: }
4730:
1.1401 raeburn 4731: sub bubblesheet_converter {
4732: my ($cdom,$fullpath,$config,$format) = @_;
4733: if ((&domain($cdom) ne '') &&
1.1403 raeburn 4734: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401 raeburn 4735: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404 raeburn 4736: my (%csvcols,%csvoptions);
4737: if (ref($config->{'fields'}) eq 'HASH') {
4738: %csvcols = %{$config->{'fields'}};
4739: }
4740: if (ref($config->{'options'}) eq 'HASH') {
4741: %csvoptions = %{$config->{'options'}};
4742: }
1.1401 raeburn 4743: my %csvbynum = reverse(%csvcols);
4744: my %scantronconf = &get_scantron_config($format,$cdom);
4745: if (keys(%scantronconf)) {
4746: my %bynum = (
4747: $scantronconf{CODEstart} => 'CODEstart',
4748: $scantronconf{IDstart} => 'IDstart',
4749: $scantronconf{PaperID} => 'PaperID',
4750: $scantronconf{FirstName} => 'FirstName',
4751: $scantronconf{LastName} => 'LastName',
4752: $scantronconf{Qstart} => 'Qstart',
4753: );
4754: my @ordered;
4755: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403 raeburn 4756: push(@ordered,$bynum{$item});
1.1401 raeburn 4757: }
4758: my %mapstart = (
4759: CODEstart => 'CODE',
4760: IDstart => 'ID',
4761: PaperID => 'PaperID',
4762: FirstName => 'FirstName',
4763: LastName => 'LastName',
4764: Qstart => 'FirstQuestion',
4765: );
4766: my %maplength = (
4767: CODEstart => 'CODElength',
4768: IDstart => 'IDlength',
4769: PaperID => 'PaperIDlength',
4770: FirstName => 'FirstNamelength',
4771: LastName => 'LastNamelength',
4772: );
4773: if (open(my $fh,'<',$fullpath)) {
4774: my $output;
1.1403 raeburn 4775: my %lettdig = &letter_to_digits();
4776: my %diglett = reverse(%lettdig);
4777: my $numletts = scalar(keys(%lettdig));
1.1404 raeburn 4778: my $num = 0;
1.1401 raeburn 4779: while (my $line=<$fh>) {
1.1404 raeburn 4780: $num ++;
4781: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401 raeburn 4782: $line =~ s{[\r\n]+$}{};
4783: my %found;
1.1475 raeburn 4784: my @values = split(/,/,$line,-1);
1.1401 raeburn 4785: my ($qstart,$record);
4786: for (my $i=0; $i<@values; $i++) {
1.1403 raeburn 4787: if ((($qstart ne '') && ($i > $qstart)) ||
4788: ($csvbynum{$i} eq 'FirstQuestion')) {
4789: if ($values[$i] eq '') {
4790: $values[$i] = $scantronconf{'Qoff'};
4791: } elsif ($scantronconf{'Qon'} eq 'number') {
4792: if ($values[$i] =~ /^[A-Ja-j]$/) {
4793: $values[$i] = $lettdig{uc($values[$i])};
4794: }
4795: } elsif ($scantronconf{'Qon'} eq 'letter') {
4796: if ($values[$i] =~ /^[0-9]$/) {
4797: $values[$i] = $diglett{$values[$i]};
4798: }
4799: } else {
4800: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4801: my $digit;
4802: if ($values[$i] =~ /^[A-Ja-j]$/) {
4803: $digit = $lettdig{uc($values[$i])}-1;
4804: if ($values[$i] eq 'J') {
4805: $digit += $numletts;
4806: }
4807: } elsif ($values[$i] =~ /^[0-9]$/) {
4808: $digit = $values[$i]-1;
4809: if ($values[$i] eq '0') {
4810: $digit += $numletts;
4811: }
4812: }
4813: my $qval='';
4814: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4815: if ($j == $digit) {
4816: $qval .= $scantronconf{'Qon'};
4817: } else {
4818: $qval .= $scantronconf{'Qoff'};
4819: }
4820: }
4821: $values[$i] = $qval;
4822: }
4823: }
4824: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4825: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4826: }
4827: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4828: if ($numblank > 0) {
4829: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4830: }
1.1401 raeburn 4831: if ($csvbynum{$i} eq 'FirstQuestion') {
4832: $qstart = $i;
1.1403 raeburn 4833: $found{$csvbynum{$i}} = $values[$i];
1.1401 raeburn 4834: } else {
1.1403 raeburn 4835: $found{'FirstQuestion'} .= $values[$i];
4836: }
4837: } elsif (exists($csvbynum{$i})) {
1.1404 raeburn 4838: if ($csvoptions{'rem'}) {
4839: $values[$i] =~ s/^\s+//;
4840: }
4841: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403 raeburn 4842: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4843: $values[$i] = '0'.$values[$i];
1.1401 raeburn 4844: }
4845: }
4846: $found{$csvbynum{$i}} = $values[$i];
4847: }
4848: }
4849: foreach my $item (@ordered) {
4850: my $currlength = 1+length($record);
4851: my $numspaces = $scantronconf{$item} - $currlength;
4852: if ($numspaces > 0) {
4853: $record .= (' ' x $numspaces);
4854: }
4855: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4856: unless ($item eq 'Qstart') {
4857: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4858: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4859: }
4860: }
4861: $record .= $found{$mapstart{$item}};
4862: }
4863: }
4864: $output .= "$record\n";
4865: }
4866: close($fh);
4867: if ($output) {
4868: if (open(my $fh,'>',$fullpath)) {
4869: print $fh $output;
4870: close($fh);
4871: }
4872: }
4873: }
4874: }
4875: return;
4876: }
4877: }
4878:
1.1403 raeburn 4879: sub letter_to_digits {
4880: my %lettdig = (
4881: A => 1,
4882: B => 2,
4883: C => 3,
4884: D => 4,
4885: E => 5,
4886: F => 6,
4887: G => 7,
4888: H => 8,
4889: I => 9,
4890: J => 0,
4891: );
4892: return %lettdig;
4893: }
4894:
1.1401 raeburn 4895: sub get_scantron_config {
4896: my ($which,$cdom) = @_;
4897: my @lines = &get_scantronformat_file($cdom);
4898: my %config;
4899: #FIXME probably should move to XML it has already gotten a bit much now
4900: foreach my $line (@lines) {
4901: my ($name,$descrip)=split(/:/,$line);
4902: if ($name ne $which ) { next; }
4903: chomp($line);
4904: my @config=split(/:/,$line);
4905: $config{'name'}=$config[0];
4906: $config{'description'}=$config[1];
4907: $config{'CODElocation'}=$config[2];
4908: $config{'CODEstart'}=$config[3];
4909: $config{'CODElength'}=$config[4];
4910: $config{'IDstart'}=$config[5];
4911: $config{'IDlength'}=$config[6];
4912: $config{'Qstart'}=$config[7];
4913: $config{'Qlength'}=$config[8];
4914: $config{'Qoff'}=$config[9];
4915: $config{'Qon'}=$config[10];
4916: $config{'PaperID'}=$config[11];
4917: $config{'PaperIDlength'}=$config[12];
4918: $config{'FirstName'}=$config[13];
4919: $config{'FirstNamelength'}=$config[14];
4920: $config{'LastName'}=$config[15];
4921: $config{'LastNamelength'}=$config[16];
4922: $config{'BubblesPerRow'}=$config[17];
4923: last;
4924: }
4925: return %config;
4926: }
4927:
4928: sub get_scantronformat_file {
4929: my ($cdom) = @_;
4930: if ($cdom eq '') {
4931: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4932: }
4933: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4934: my $gottab = 0;
4935: my @lines;
4936: if (ref($domconfig{'scantron'}) eq 'HASH') {
4937: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4938: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4939: if ($formatfile ne '-1') {
4940: @lines = split("\n",$formatfile,-1);
4941: $gottab = 1;
4942: }
4943: }
4944: }
4945: if (!$gottab) {
4946: my $confname = $cdom.'-domainconfig';
4947: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4948: my $formatfile = &getfile($default);
4949: if ($formatfile ne '-1') {
4950: @lines = split("\n",$formatfile,-1);
4951: $gottab = 1;
4952: }
4953: }
4954: if (!$gottab) {
4955: my @domains = ¤t_machine_domains();
4956: if (grep(/^\Q$cdom\E$/,@domains)) {
4957: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4958: @lines = <$fh>;
4959: close($fh);
1.1403 raeburn 4960: }
1.1401 raeburn 4961: } else {
4962: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4963: @lines = <$fh>;
4964: close($fh);
4965: }
4966: }
1.1488 raeburn 4967: chomp(@lines);
1.1401 raeburn 4968: }
4969: return @lines;
4970: }
4971:
1.493 albertel 4972: sub removeuploadedurl {
1.984 neumanie 4973: my ($url)=@_;
4974: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4975: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4976: }
4977:
4978: sub removeuserfile {
4979: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4980: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4981: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4982: if ($result eq 'ok') {
1.798 raeburn 4983: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4984: my $metafile = $fname.'.meta';
4985: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4986: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4987: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4988: my $sqlresult =
1.823 albertel 4989: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4990: 'portfolio_metadata',$group,
4991: 'delete');
1.798 raeburn 4992: }
4993: }
4994: return $result;
1.257 www 4995: }
1.15 www 4996:
1.530 albertel 4997: sub mkdiruserfile {
4998: my ($docuname,$docudom,$dir)=@_;
4999: my $home=&homeserver($docuname,$docudom);
5000: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
5001: }
5002:
1.531 albertel 5003: sub renameuserfile {
5004: my ($docuname,$docudom,$old,$new)=@_;
5005: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 5006: my $result = &reply("renameuserfile:$docudom:$docuname:".
5007: &escape("$old").':'.&escape("$new"),$home);
5008: if ($result eq 'ok') {
5009: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
5010: my $oldmeta = $old.'.meta';
5011: my $newmeta = $new.'.meta';
5012: my $metaresult =
5013: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 5014: my $url = "/uploaded/$docudom/$docuname/$old";
5015: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 5016: my $sqlresult =
1.823 albertel 5017: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 5018: 'portfolio_metadata',$group,
5019: 'delete');
1.798 raeburn 5020: }
5021: }
5022: return $result;
1.531 albertel 5023: }
5024:
1.14 www 5025: # ------------------------------------------------------------------------- Log
5026:
5027: sub log {
5028: my ($dom,$nam,$hom,$what)=@_;
1.47 www 5029: return critical("log:$dom:$nam:$what",$hom);
1.157 www 5030: }
5031:
5032: # ------------------------------------------------------------------ Course Log
1.352 www 5033: #
5034: # This routine flushes several buffers of non-mission-critical nature
5035: #
1.157 www 5036:
5037: sub flushcourselogs {
1.352 www 5038: &logthis('Flushing log buffers');
5039: #
5040: # course logs
5041: # This is a log of all transactions in a course, which can be used
5042: # for data mining purposes
5043: #
5044: # It also collects the courseid database, which lists last transaction
5045: # times and course titles for all courseids
5046: #
5047: my %courseidbuffer=();
1.921 raeburn 5048: foreach my $crsid (keys(%courselogs)) {
1.352 www 5049: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 5050: &escape($courselogs{$crsid}),
5051: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 5052: delete $courselogs{$crsid};
5053: } else {
5054: &logthis('Failed to flush log buffer for '.$crsid);
5055: if (length($courselogs{$crsid})>40000) {
1.672 albertel 5056: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 5057: " exceeded maximum size, deleting.</font>");
5058: delete $courselogs{$crsid};
5059: }
1.352 www 5060: }
1.920 raeburn 5061: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 5062: 'description' => $coursedescrbuf{$crsid},
5063: 'inst_code' => $courseinstcodebuf{$crsid},
5064: 'type' => $coursetypebuf{$crsid},
5065: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 5066: };
1.191 harris41 5067: }
1.352 www 5068: #
5069: # Write course id database (reverse lookup) to homeserver of courses
5070: # Is used in pickcourse
5071: #
1.840 albertel 5072: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 5073: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 5074: $courseidbuffer{$crs_home},
5075: $crs_home,'timeonly');
1.352 www 5076: }
5077: #
5078: # File accesses
5079: # Writes to the dynamic metadata of resources to get hit counts, etc.
5080: #
1.449 matthew 5081: foreach my $entry (keys(%accesshash)) {
1.458 matthew 5082: if ($entry =~ /___count$/) {
5083: my ($dom,$name);
1.807 albertel 5084: ($dom,$name,undef)=
1.811 albertel 5085: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 5086: if (! defined($dom) || $dom eq '' ||
5087: ! defined($name) || $name eq '') {
1.620 albertel 5088: my $cid = $env{'request.course.id'};
1.1472 raeburn 5089: #
5090: # FIXME 11/29/2021
5091: # Typo in rev. 1.458 (2003/12/09)??
5092: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
5093: #
5094: # While these ramain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
5095: # $dom and $name will always be null, so the &inc() call will default to storing this data
5096: # in a nohist_accesscount.db file for the user rather than the course.
5097: #
5098: # That said there is a lot of noise in the data being stored.
5099: # So counts for prtspool/ and adm/ etc. are recorded.
5100: #
5101: # A review of which items ending '___count' are written to %accesshash should likely be
5102: # made before deciding whether to set these to 'course.' instead of 'request.'
5103: #
5104: # Under the current scheme each user receives a nohist_accesscount.db file listing
5105: # accesses for things which are not published resources, regardless of course, and
5106: # there is not a nohist_accesscount.db file in a course, which might log accesses from
5107: # anyone in the course for things which are not published resources.
5108: #
5109: # For an author, nohist_accesscount.db ends up having records for other items
5110: # mixed up with the legitimate access counts for the author's published resources.
5111: #
1.620 albertel 5112: $dom = $env{'request.'.$cid.'.domain'};
5113: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 5114: }
1.450 matthew 5115: my $value = $accesshash{$entry};
5116: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
5117: my %temphash=($url => $value);
1.449 matthew 5118: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
5119: if ($result eq 'ok') {
5120: delete $accesshash{$entry};
5121: }
5122: } else {
1.811 albertel 5123: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 5124: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 5125: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 5126: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
5127: delete $accesshash{$entry};
5128: }
1.185 www 5129: }
1.191 harris41 5130: }
1.352 www 5131: #
5132: # Roles
5133: # Reverse lookup of user roles for course faculty/staff and co-authorship
5134: #
1.800 albertel 5135: foreach my $entry (keys(%userrolehash)) {
1.351 www 5136: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 5137: split(/\:/,$entry);
1.1494 raeburn 5138: if (&put('nohist_userroles',
1.351 www 5139: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 5140: $rudom,$runame) eq 'ok') {
5141: delete $userrolehash{$entry};
5142: }
5143: }
1.662 raeburn 5144: #
1.1334 raeburn 5145: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 5146: #
5147: my %domrolebuffer = ();
1.1000 raeburn 5148: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 5149: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 5150: if ($domrolebuffer{$rudom}) {
5151: $domrolebuffer{$rudom}.='&'.&escape($entry).
5152: '='.&escape($domainrolehash{$entry});
5153: } else {
5154: $domrolebuffer{$rudom}.=&escape($entry).
5155: '='.&escape($domainrolehash{$entry});
5156: }
5157: delete $domainrolehash{$entry};
5158: }
5159: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 5160: my %servers;
5161: if (defined(&domain($dom,'primary'))) {
5162: my $primary=&domain($dom,'primary');
5163: my $hostname=&hostname($primary);
5164: $servers{$primary} = $hostname;
5165: } else {
5166: %servers = &get_servers($dom,'library');
5167: }
1.841 albertel 5168: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 5169: if (&reply('domroleput:'.$dom.':'.
5170: $domrolebuffer{$dom},$tryserver) eq 'ok') {
5171: last;
5172: } else {
1.841 albertel 5173: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
5174: }
1.662 raeburn 5175: }
5176: }
1.186 www 5177: $dumpcount++;
1.157 www 5178: }
5179:
5180: sub courselog {
5181: my $what=shift;
1.158 www 5182: $what=time.':'.$what;
1.620 albertel 5183: unless ($env{'request.course.id'}) { return ''; }
5184: $coursedombuf{$env{'request.course.id'}}=
5185: $env{'course.'.$env{'request.course.id'}.'.domain'};
5186: $coursenumbuf{$env{'request.course.id'}}=
5187: $env{'course.'.$env{'request.course.id'}.'.num'};
5188: $coursehombuf{$env{'request.course.id'}}=
5189: $env{'course.'.$env{'request.course.id'}.'.home'};
5190: $coursedescrbuf{$env{'request.course.id'}}=
5191: $env{'course.'.$env{'request.course.id'}.'.description'};
5192: $courseinstcodebuf{$env{'request.course.id'}}=
5193: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
5194: $courseownerbuf{$env{'request.course.id'}}=
5195: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 5196: $coursetypebuf{$env{'request.course.id'}}=
5197: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 5198: if (defined $courselogs{$env{'request.course.id'}}) {
5199: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 5200: } else {
1.620 albertel 5201: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 5202: }
1.620 albertel 5203: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 5204: &flushcourselogs();
5205: }
1.158 www 5206: }
5207:
5208: sub courseacclog {
5209: my $fnsymb=shift;
1.620 albertel 5210: unless ($env{'request.course.id'}) { return ''; }
5211: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 5212: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 5213: $what.=':POST';
1.583 matthew 5214: # FIXME: Probably ought to escape things....
1.800 albertel 5215: foreach my $key (keys(%env)) {
5216: if ($key=~/^form\.(.*)/) {
1.975 raeburn 5217: my $formitem = $1;
5218: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
5219: $what.=':'.$formitem.'='.$env{$key};
5220: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432 raeburn 5221: if ($formitem eq 'proctorpassword') {
1.1433 raeburn 5222: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432 raeburn 5223: } else {
5224: $what.=':'.$formitem.'='.$env{$key};
5225: }
1.975 raeburn 5226: }
1.158 www 5227: }
1.191 harris41 5228: }
1.583 matthew 5229: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
5230: # FIXME: We should not be depending on a form parameter that someone
5231: # editing lonsearchcat.pm might change in the future.
1.620 albertel 5232: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 5233: $what.= ':POST';
5234: # FIXME: Probably ought to escape things....
5235: foreach my $element ('courseexp','crsfulltext','crsrelated',
5236: 'crsdiscuss') {
1.620 albertel 5237: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 5238: }
5239: }
1.158 www 5240: }
5241: &courselog($what);
1.149 www 5242: }
5243:
1.185 www 5244: sub countacc {
5245: my $url=&declutter(shift);
1.458 matthew 5246: return if (! defined($url) || $url eq '');
1.620 albertel 5247: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 5248: #
5249: # Mark that this url was used in this course
5250: #
1.620 albertel 5251: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 5252: #
5253: # Increase the access count for this resource in this child process
5254: #
1.281 www 5255: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 5256: $accesshash{$key}++;
1.185 www 5257: }
1.349 www 5258:
1.361 www 5259: sub linklog {
5260: my ($from,$to)=@_;
5261: $from=&declutter($from);
5262: $to=&declutter($to);
5263: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5264: $accesshash{$to.'___'.$from.'___goto'}=1;
5265: }
1.1160 www 5266:
5267: sub statslog {
5268: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5269: if ($users<2) { return; }
5270: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5271: 'course' => $env{'request.course.id'},
5272: 'sections' => '"all"',
5273: 'num_students' => $users,
5274: 'part' => $part,
5275: 'symb' => $symb,
5276: 'mean_tries' => $av_attempts,
5277: 'deg_of_diff' => $degdiff});
5278: foreach my $key (keys(%dynstore)) {
5279: $accesshash{$key}=$dynstore{$key};
5280: }
5281: }
1.361 www 5282:
1.349 www 5283: sub userrolelog {
5284: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 5285: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 5286: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5287: $userrolehash
5288: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 5289: =$tend.':'.$tstart;
1.662 raeburn 5290: }
1.1169 droeschl 5291: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 5292: $userrolehash
5293: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5294: =$tend.':'.$tstart;
5295: }
1.1334 raeburn 5296: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 5297: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5298: $domainrolehash
5299: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5300: = $tend.':'.$tstart;
5301: }
1.351 www 5302: }
5303:
1.957 raeburn 5304: sub courserolelog {
5305: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 5306: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5307: my $cdom = $1;
5308: my $cnum = $2;
5309: my $sec = $3;
5310: my $namespace = 'rolelog';
5311: my %storehash = (
5312: role => $trole,
5313: start => $tstart,
5314: end => $tend,
5315: selfenroll => $selfenroll,
5316: context => $context,
5317: );
5318: if ($trole eq 'gr') {
5319: $namespace = 'groupslog';
5320: $storehash{'group'} = $sec;
5321: } else {
5322: $storehash{'section'} = $sec;
5323: }
1.1188 raeburn 5324: &write_log('course',$namespace,\%storehash,$delflag,$username,
5325: $domain,$cnum,$cdom);
1.1184 raeburn 5326: if (($trole ne 'st') || ($sec ne '')) {
5327: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 5328: }
5329: }
5330: return;
5331: }
5332:
1.1184 raeburn 5333: sub domainrolelog {
5334: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5335: if ($area =~ m{^/($match_domain)/$}) {
5336: my $cdom = $1;
1.1494 raeburn 5337: my $domconfiguser = &get_domainconfiguser($cdom);
1.1184 raeburn 5338: my $namespace = 'rolelog';
5339: my %storehash = (
5340: role => $trole,
5341: start => $tstart,
5342: end => $tend,
5343: context => $context,
5344: );
1.1188 raeburn 5345: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5346: $domain,$domconfiguser,$cdom);
1.1184 raeburn 5347: }
5348: return;
5349:
5350: }
5351:
5352: sub coauthorrolelog {
5353: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5354: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5355: my $audom = $1;
5356: my $auname = $2;
5357: my $namespace = 'rolelog';
5358: my %storehash = (
5359: role => $trole,
5360: start => $tstart,
5361: end => $tend,
5362: context => $context,
5363: );
1.1188 raeburn 5364: &write_log('author',$namespace,\%storehash,$delflag,$username,
5365: $domain,$auname,$audom);
1.1184 raeburn 5366: }
5367: return;
5368: }
5369:
1.351 www 5370: sub get_course_adv_roles {
1.948 raeburn 5371: my ($cid,$codes) = @_;
1.620 albertel 5372: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 5373: my %coursehash=&coursedescription($cid);
1.988 raeburn 5374: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 5375: my %nothide=();
1.800 albertel 5376: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 5377: if ($user !~ /:/) {
5378: $nothide{join(':',split(/[\@]/,$user))}=1;
5379: } else {
5380: $nothide{$user}=1;
5381: }
1.470 www 5382: }
1.1219 raeburn 5383: my @possdoms = ($coursehash{'domain'});
5384: if ($coursehash{'checkforpriv'}) {
5385: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5386: }
1.351 www 5387: my %returnhash=();
5388: my %dumphash=
5389: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5390: my $now=time;
1.997 raeburn 5391: my %privileged;
1.1000 raeburn 5392: foreach my $entry (keys(%dumphash)) {
1.800 albertel 5393: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 5394: if (($tstart) && ($tstart<0)) { next; }
5395: if (($tend) && ($tend<$now)) { next; }
5396: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 5397: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 5398: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 5399: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 5400: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 5401: if ($role eq 'cr') { next; }
1.948 raeburn 5402: if ($codes) {
5403: if ($section) { $role .= ':'.$section; }
5404: if ($returnhash{$role}) {
5405: $returnhash{$role}.=','.$username.':'.$domain;
5406: } else {
5407: $returnhash{$role}=$username.':'.$domain;
5408: }
1.351 www 5409: } else {
1.988 raeburn 5410: my $key=&plaintext($role,$crstype);
1.973 bisitz 5411: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 5412: if ($returnhash{$key}) {
5413: $returnhash{$key}.=','.$username.':'.$domain;
5414: } else {
5415: $returnhash{$key}=$username.':'.$domain;
5416: }
1.351 www 5417: }
1.948 raeburn 5418: }
1.400 www 5419: return %returnhash;
5420: }
5421:
5422: sub get_my_roles {
1.937 raeburn 5423: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5424: unless (defined($uname)) { $uname=$env{'user.name'}; }
5425: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5426: my (%dumphash,%nothide);
1.1086 raeburn 5427: if ($context eq 'userroles') {
1.1166 raeburn 5428: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5429: } else {
1.1219 raeburn 5430: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5431: if ($hidepriv) {
5432: my %coursehash=&coursedescription($udom.'_'.$uname);
5433: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5434: if ($user !~ /:/) {
5435: $nothide{join(':',split(/[\@]/,$user))} = 1;
5436: } else {
5437: $nothide{$user} = 1;
5438: }
5439: }
5440: }
1.858 raeburn 5441: }
1.400 www 5442: my %returnhash=();
5443: my $now=time;
1.999 raeburn 5444: my %privileged;
1.800 albertel 5445: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5446: my ($role,$tend,$tstart);
5447: if ($context eq 'userroles') {
1.1149 raeburn 5448: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5449: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5450: } else {
5451: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5452: }
1.400 www 5453: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5454: my $status = 'active';
1.939 raeburn 5455: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5456: $status = 'previous';
5457: }
5458: if (($tstart) && ($now<$tstart)) {
5459: $status = 'future';
5460: }
5461: if (ref($types) eq 'ARRAY') {
5462: if (!grep(/^\Q$status\E$/,@{$types})) {
5463: next;
5464: }
5465: } else {
5466: if ($status ne 'active') {
5467: next;
5468: }
5469: }
1.867 raeburn 5470: my ($rolecode,$username,$domain,$section,$area);
5471: if ($context eq 'userroles') {
1.1186 raeburn 5472: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5473: (undef,$domain,$username,$section) = split(/\//,$area);
5474: } else {
5475: ($role,$username,$domain,$section) = split(/\:/,$entry);
5476: }
1.832 raeburn 5477: if (ref($roledoms) eq 'ARRAY') {
5478: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5479: next;
5480: }
5481: }
5482: if (ref($roles) eq 'ARRAY') {
5483: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5484: if ($role =~ /^cr\//) {
5485: if (!grep(/^cr$/,@{$roles})) {
5486: next;
5487: }
1.1104 raeburn 5488: } elsif ($role =~ /^gr\//) {
5489: if (!grep(/^gr$/,@{$roles})) {
5490: next;
5491: }
1.922 raeburn 5492: } else {
5493: next;
5494: }
1.832 raeburn 5495: }
1.867 raeburn 5496: }
1.937 raeburn 5497: if ($hidepriv) {
1.1219 raeburn 5498: my @privroles = ('dc','su');
1.999 raeburn 5499: if ($context eq 'userroles') {
1.1219 raeburn 5500: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5501: } else {
1.1219 raeburn 5502: my $possdoms = [$domain];
5503: if (ref($roledoms) eq 'ARRAY') {
5504: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5505: }
1.1219 raeburn 5506: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5507: if (!$nothide{$username.':'.$domain}) {
5508: next;
5509: }
5510: }
1.937 raeburn 5511: }
5512: }
1.933 raeburn 5513: if ($withsec) {
5514: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5515: $tstart.':'.$tend;
5516: } else {
5517: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5518: }
1.832 raeburn 5519: }
1.373 www 5520: return %returnhash;
1.399 www 5521: }
5522:
1.1333 raeburn 5523: sub get_all_adhocroles {
5524: my ($dom) = @_;
5525: my @roles_by_num = ();
5526: my %domdefaults = &get_domain_defaults($dom);
5527: my (%description,%access_in_dom,%access_info);
5528: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5529: my $count = 0;
5530: my %domcurrent = %{$domdefaults{'adhocroles'}};
5531: my %ordered;
5532: foreach my $role (sort(keys(%domcurrent))) {
5533: my ($order,$desc,$access_in_dom);
5534: if (ref($domcurrent{$role}) eq 'HASH') {
5535: $order = $domcurrent{$role}{'order'};
5536: $desc = $domcurrent{$role}{'desc'};
5537: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5538: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5539: }
5540: if ($order eq '') {
5541: $order = $count;
5542: }
5543: $ordered{$order} = $role;
5544: if ($desc ne '') {
5545: $description{$role} = $desc;
5546: } else {
5547: $description{$role}= $role;
5548: }
5549: $count++;
5550: }
5551: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5552: push(@roles_by_num,$ordered{$item});
5553: }
5554: }
5555: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5556: }
5557:
1.1332 raeburn 5558: sub get_my_adhocroles {
1.1333 raeburn 5559: my ($cid,$checkreg) = @_;
5560: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5561: if ($env{'request.course.id'} eq $cid) {
5562: $cdom = $env{'course.'.$cid.'.domain'};
5563: $cnum = $env{'course.'.$cid.'.num'};
5564: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5565: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5566: $cdom = $1;
5567: $cnum = $2;
1.1494 raeburn 5568: %info = &get('environment',['internal.coursecode'],
5569: $cdom,$cnum);
1.1333 raeburn 5570: }
5571: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5572: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5573: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5574: if ($rosterhash{$user} ne '') {
5575: my $type = (split(/:/,$rosterhash{$user}))[5];
5576: return ([],{}) if ($type eq 'auto');
5577: }
5578: }
5579: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 5580: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 5581: my $then=$env{'user.login.time'};
5582: my $update=$env{'user.update.time'};
1.1335 raeburn 5583: if (!$update) {
5584: $update = $then;
5585: }
5586: my @liveroles;
1.1334 raeburn 5587: foreach my $role ('dh','da') {
5588: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 5589: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 5590: my $limit = $update;
5591: if ($env{'request.role'} eq "$role./$cdom/") {
5592: $limit = $then;
5593: }
1.1335 raeburn 5594: my $activerole = 1;
5595: if ($tstart && $tstart>$limit) { $activerole = 0; }
5596: if ($tend && $tend <$limit) { $activerole = 0; }
5597: if ($activerole) {
5598: push(@liveroles,$role);
5599: }
1.1334 raeburn 5600: }
1.1332 raeburn 5601: }
1.1335 raeburn 5602: if (@liveroles) {
1.1332 raeburn 5603: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 5604: my ($accessref,$accessinfo,%access_in_dom);
5605: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5606: if (ref($roles_by_num) eq 'ARRAY') {
5607: if (@{$roles_by_num}) {
1.1332 raeburn 5608: my %settings;
5609: if ($env{'request.course.id'} eq $cid) {
5610: foreach my $envkey (keys(%env)) {
5611: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5612: $settings{$1} = $env{$envkey};
5613: }
5614: }
5615: } else {
5616: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5617: }
5618: my %setincrs;
5619: if ($settings{'internal.adhocaccess'}) {
5620: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5621: }
5622: my @statuses;
5623: if ($env{'environment.inststatus'}) {
5624: @statuses = split(/,/,$env{'environment.inststatus'});
5625: }
5626: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 5627: if (ref($accessref) eq 'HASH') {
5628: %access_in_dom = %{$accessref};
5629: }
5630: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 5631: my ($curraccess,@okstatus,@personnel);
5632: if ($setincrs{$role}) {
5633: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5634: if ($curraccess eq 'status') {
5635: @okstatus = split(/\&/,$rest);
5636: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5637: @personnel = split(/\&/,$rest);
5638: }
5639: } else {
5640: $curraccess = $access_in_dom{$role};
1.1333 raeburn 5641: if (ref($accessinfo) eq 'HASH') {
5642: if ($curraccess eq 'status') {
5643: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5644: @okstatus = @{$accessinfo->{$role}};
5645: }
5646: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5647: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5648: @personnel = @{$accessinfo->{$role}};
5649: }
1.1332 raeburn 5650: }
5651: }
5652: }
5653: if ($curraccess eq 'none') {
5654: next;
5655: } elsif ($curraccess eq 'all') {
5656: push(@possroles,$role);
1.1336 raeburn 5657: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 5658: if (grep(/^dh$/,@liveroles)) {
5659: push(@possroles,$role);
5660: } else {
5661: next;
5662: }
1.1336 raeburn 5663: } elsif ($curraccess eq 'da') {
1.1335 raeburn 5664: if (grep(/^da$/,@liveroles)) {
5665: push(@possroles,$role);
5666: } else {
5667: next;
5668: }
1.1332 raeburn 5669: } elsif ($curraccess eq 'status') {
5670: if (@okstatus) {
5671: if (!@statuses) {
5672: if (grep(/^default$/,@okstatus)) {
5673: push(@possroles,$role);
5674: }
5675: } else {
5676: foreach my $status (@okstatus) {
5677: if (grep(/^\Q$status\E$/,@statuses)) {
5678: push(@possroles,$role);
5679: last;
5680: }
5681: }
5682: }
5683: }
5684: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5685: if (grep(/^\Q$user\E$/,@personnel)) {
5686: if ($curraccess eq 'exc') {
5687: push(@possroles,$role);
5688: }
5689: } elsif ($curraccess eq 'inc') {
5690: push(@possroles,$role);
5691: }
5692: }
5693: }
5694: }
5695: }
5696: }
5697: }
5698: }
5699: }
1.1333 raeburn 5700: unless (ref($description) eq 'HASH') {
5701: if (ref($roles_by_num) eq 'ARRAY') {
5702: my %desc;
5703: map { $desc{$_} = $_; } (@{$roles_by_num});
5704: $description = \%desc;
5705: } else {
5706: $description = {};
5707: }
5708: }
5709: return (\@possroles,$description);
1.1332 raeburn 5710: }
5711:
1.399 www 5712: # ----------------------------------------------------- Frontpage Announcements
5713: #
5714: #
5715:
5716: sub postannounce {
5717: my ($server,$text)=@_;
1.844 albertel 5718: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5719: unless ($text=~/\w/) { $text=''; }
5720: return &reply('setannounce:'.&escape($text),$server);
5721: }
5722:
5723: sub getannounce {
1.448 albertel 5724:
1.1359 raeburn 5725: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5726: my $announcement='';
1.800 albertel 5727: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5728: close($fh);
1.399 www 5729: if ($announcement=~/\w/) {
5730: return
5731: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5732: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5733: } else {
5734: return '';
5735: }
5736: } else {
5737: return '';
5738: }
1.351 www 5739: }
1.353 www 5740:
5741: # ---------------------------------------------------------- Course ID routines
5742: # Deal with domain's nohist_courseid.db files
5743: #
5744:
5745: sub courseidput {
1.921 raeburn 5746: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5747: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5748: my $outcome;
5749: if ($caller eq 'timeonly') {
5750: my $cids = '';
5751: foreach my $item (keys(%$storehash)) {
5752: $cids.=&escape($item).'&';
5753: }
5754: $cids=~s/\&$//;
5755: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5756: $coursehome);
5757: } else {
5758: my $items = '';
5759: foreach my $item (keys(%$storehash)) {
5760: $items.= &escape($item).'='.
5761: &freeze_escape($$storehash{$item}).'&';
5762: }
5763: $items=~s/\&$//;
5764: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5765: $coursehome);
1.918 raeburn 5766: }
5767: if ($outcome eq 'unknown_cmd') {
5768: my $what;
5769: foreach my $cid (keys(%$storehash)) {
5770: $what .= &escape($cid).'=';
1.921 raeburn 5771: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5772: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5773: }
5774: $what =~ s/\:$/&/;
5775: }
5776: $what =~ s/\&$//;
5777: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5778: } else {
5779: return $outcome;
5780: }
1.353 www 5781: }
5782:
5783: sub courseiddump {
1.921 raeburn 5784: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5785: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5786: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 5787: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 5788: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5789: my $as_hash = 1;
5790: my %returnhash;
5791: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5792: my %libserv = &all_library();
5793: foreach my $tryserver (keys(%libserv)) {
5794: if ( ( $hostidflag == 1
5795: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5796: || (!defined($hostidflag)) ) {
5797:
1.918 raeburn 5798: if (($domfilter eq '') ||
5799: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 5800: my $rep;
5801: if (grep { $_ eq $tryserver } current_machine_ids()) {
5802: $rep = LONCAPA::Lond::dump_course_id_handler(
5803: join(":", (&host_domain($tryserver), $sincefilter,
5804: &escape($descfilter), &escape($instcodefilter),
5805: &escape($ownerfilter), &escape($coursefilter),
5806: &escape($typefilter), &escape($regexp_ok),
5807: $as_hash, &escape($selfenrollonly),
5808: &escape($catfilter), $showhidden, $caller,
5809: &escape($cloner), &escape($cc_clone), $cloneonly,
5810: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 5811: &escape($creationcontext),$domcloner,$hasuniquecode,
5812: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 5813: } else {
5814: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5815: $sincefilter.':'.&escape($descfilter).':'.
5816: &escape($instcodefilter).':'.&escape($ownerfilter).
5817: ':'.&escape($coursefilter).':'.&escape($typefilter).
5818: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5819: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5820: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5821: &escape($cc_clone).':'.$cloneonly.':'.
5822: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 5823: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5824: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 5825: }
5826:
1.918 raeburn 5827: my @pairs=split(/\&/,$rep);
5828: foreach my $item (@pairs) {
5829: my ($key,$value)=split(/\=/,$item,2);
5830: $key = &unescape($key);
5831: next if ($key =~ /^error: 2 /);
5832: my $result = &thaw_unescape($value);
5833: if (ref($result) eq 'HASH') {
5834: $returnhash{$key}=$result;
5835: } else {
1.921 raeburn 5836: my @responses = split(/:/,$value);
5837: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5838: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5839: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5840: }
1.1008 raeburn 5841: }
1.353 www 5842: }
5843: }
5844: }
5845: }
5846: return %returnhash;
5847: }
5848:
1.1055 raeburn 5849: sub courselastaccess {
5850: my ($cdom,$cnum,$hostidref) = @_;
5851: my %returnhash;
5852: if ($cdom && $cnum) {
5853: my $chome = &homeserver($cnum,$cdom);
5854: if ($chome ne 'no_host') {
5855: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5856: &extract_lastaccess(\%returnhash,$rep);
5857: }
5858: } else {
5859: if (!$cdom) { $cdom=''; }
5860: my %libserv = &all_library();
5861: foreach my $tryserver (keys(%libserv)) {
5862: if (ref($hostidref) eq 'ARRAY') {
5863: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5864: }
5865: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5866: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5867: &extract_lastaccess(\%returnhash,$rep);
5868: }
5869: }
5870: }
5871: return %returnhash;
5872: }
5873:
5874: sub extract_lastaccess {
5875: my ($returnhash,$rep) = @_;
5876: if (ref($returnhash) eq 'HASH') {
5877: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5878: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5879: $rep eq '') {
5880: my @pairs=split(/\&/,$rep);
5881: foreach my $item (@pairs) {
5882: my ($key,$value)=split(/\=/,$item,2);
5883: $key = &unescape($key);
5884: next if ($key =~ /^error: 2 /);
5885: $returnhash->{$key} = &thaw_unescape($value);
5886: }
5887: }
5888: }
5889: return;
5890: }
5891:
1.658 raeburn 5892: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5893:
5894: sub dcmailput {
1.685 raeburn 5895: my ($domain,$msgid,$message,$server)=@_;
1.1494 raeburn 5896: my $status = &critical(
1.740 www 5897: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5898: &escape($message),$server);
1.662 raeburn 5899: return $status;
5900: }
5901:
1.658 raeburn 5902: sub dcmaildump {
5903: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5904: my %returnhash=();
1.846 albertel 5905:
5906: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5907: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5908: &escape($enddate).':';
5909: my @esc_senders=map { &escape($_)} @$senders;
5910: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5911: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5912: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5913: if (($key) && ($value)) {
5914: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5915: }
5916: }
5917: }
5918: return %returnhash;
5919: }
1.662 raeburn 5920: # ---------------------------------------------------------- Domain roles
5921:
5922: sub get_domain_roles {
5923: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5924: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5925: $startdate = '.';
5926: }
1.1018 raeburn 5927: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5928: $enddate = '.';
5929: }
1.922 raeburn 5930: my $rolelist;
5931: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 5932: $rolelist = join('&',@{$roles});
1.922 raeburn 5933: }
1.662 raeburn 5934: my %personnel = ();
1.841 albertel 5935:
5936: my %servers = &get_servers($dom,'library');
5937: foreach my $tryserver (keys(%servers)) {
5938: %{$personnel{$tryserver}}=();
5939: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5940: &escape($startdate).':'.
5941: &escape($enddate).':'.
5942: &escape($rolelist), $tryserver))) {
5943: my ($key,$value) = split(/\=/,$line,2);
5944: if (($key) && ($value)) {
5945: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5946: }
5947: }
1.662 raeburn 5948: }
5949: return %personnel;
5950: }
1.658 raeburn 5951:
1.1332 raeburn 5952: sub get_active_domroles {
5953: my ($dom,$roles) = @_;
5954: return () unless (ref($roles) eq 'ARRAY');
5955: my $now = time;
5956: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5957: my %domroles;
5958: foreach my $server (keys(%dompersonnel)) {
5959: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5960: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5961: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5962: }
5963: }
5964: return %domroles;
5965: }
5966:
1.1057 www 5967: # ----------------------------------------------------------- Interval timing
1.149 www 5968:
1.1153 www 5969: {
5970: # Caches needed for speedup of navmaps
5971: # We don't want to cache this for very long at all (5 seconds at most)
5972: #
5973: # The user for whom we cache
5974: my $cachedkey='';
5975: # The cached times for this user
5976: my %cachedtimes=();
5977: # When this was last done
1.1282 raeburn 5978: my $cachedtime='';
1.1153 www 5979:
5980: sub load_all_first_access {
1.1308 raeburn 5981: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5982: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 5983: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5984: (!$ignorecache)) {
1.1154 raeburn 5985: return;
5986: }
5987: $cachedtime=time;
5988: $cachedkey=$uname.':'.$udom;
5989: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5990: }
5991:
1.504 albertel 5992: sub get_first_access {
1.1308 raeburn 5993: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5994: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5995: if ($argsymb) { $symb=$argsymb; }
5996: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5997: if ($argmap) { $map = $argmap; }
1.926 albertel 5998: if ($type eq 'course') {
5999: $res='course';
6000: } elsif ($type eq 'map') {
1.588 albertel 6001: $res=&symbread($map);
6002: } else {
6003: $res=$symb;
6004: }
1.1308 raeburn 6005: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 6006: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 6007: }
6008:
6009: sub set_first_access {
1.1162 raeburn 6010: my ($type,$interval)=@_;
1.790 albertel 6011: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 6012: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 6013: if ($type eq 'course') {
6014: $res='course';
6015: } elsif ($type eq 'map') {
1.588 albertel 6016: $res=&symbread($map);
6017: } else {
6018: $res=$symb;
6019: }
1.1153 www 6020: $cachedkey='';
1.1162 raeburn 6021: my $firstaccess=&get_first_access($type,$symb,$map);
1.1386 raeburn 6022: if ($firstaccess) {
6023: &logthis("First access time already set ($firstaccess) when attempting ".
1.1393 raeburn 6024: "to set new value (type: $type, extent: $res) for $uname:$udom ".
6025: "in $courseid");
1.1386 raeburn 6026: return 'already_set';
6027: } else {
1.1162 raeburn 6028: my $start = time;
6029: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
6030: $udom,$uname);
6031: if ($putres eq 'ok') {
6032: &put('timerinterval',{"$courseid\0$res"=>$interval},
6033: $udom,$uname);
6034: &appenv(
6035: {
6036: 'course.'.$courseid.'.firstaccess.'.$res => $start,
6037: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
6038: }
6039: );
1.1365 raeburn 6040: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
6041: $cachedtimes{"$courseid\0$res"} = $start;
6042: }
1.1386 raeburn 6043: } elsif ($putres ne 'refused') {
6044: &logthis("Result: $putres when attempting to set first access time ".
6045: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 6046: }
6047: return $putres;
1.505 albertel 6048: }
6049: return 'already_set';
1.504 albertel 6050: }
1.1153 www 6051: }
1.1282 raeburn 6052:
1.110 www 6053: # --------------------------------------------- Set Expire Date for Spreadsheet
6054:
6055: sub expirespread {
6056: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 6057: my $cid=$env{'request.course.id'};
1.110 www 6058: if ($cid) {
6059: my $now=time;
6060: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 6061: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
6062: $env{'course.'.$cid.'.num'}.
1.110 www 6063: ':nohist_expirationdates:'.
6064: &escape($key).'='.$now,
1.620 albertel 6065: $env{'course.'.$cid.'.home'})
1.110 www 6066: }
6067: return 'ok';
1.14 www 6068: }
6069:
1.109 www 6070: # ----------------------------------------------------- Devalidate Spreadsheets
6071:
6072: sub devalidate {
1.325 www 6073: my ($symb,$uname,$udom)=@_;
1.620 albertel 6074: my $cid=$env{'request.course.id'};
1.109 www 6075: if ($cid) {
1.391 matthew 6076: # delete the stored spreadsheets for
6077: # - the student level sheet of this user in course's homespace
6078: # - the assessment level sheet for this resource
6079: # for this user in user's homespace
1.553 albertel 6080: # - current conditional state info
1.325 www 6081: my $key=$uname.':'.$udom.':';
1.109 www 6082: my $status=
1.299 matthew 6083: &del('nohist_calculatedsheets',
1.391 matthew 6084: [$key.'studentcalc:'],
1.620 albertel 6085: $env{'course.'.$cid.'.domain'},
6086: $env{'course.'.$cid.'.num'})
1.133 albertel 6087: .' '.
6088: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 6089: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 6090: unless ($status eq 'ok ok') {
6091: &logthis('Could not devalidate spreadsheet '.
1.325 www 6092: $uname.' at '.$udom.' for '.
1.109 www 6093: $symb.': '.$status);
1.133 albertel 6094: }
1.553 albertel 6095: &delenv('user.state.'.$cid);
1.109 www 6096: }
6097: }
6098:
1.265 albertel 6099: sub get_scalar {
6100: my ($string,$end) = @_;
6101: my $value;
6102: if ($$string =~ s/^([^&]*?)($end)/$2/) {
6103: $value = $1;
6104: } elsif ($$string =~ s/^([^&]*?)&//) {
6105: $value = $1;
6106: }
6107: return &unescape($value);
6108: }
6109:
6110: sub array2str {
6111: my (@array) = @_;
6112: my $result=&arrayref2str(\@array);
6113: $result=~s/^__ARRAY_REF__//;
6114: $result=~s/__END_ARRAY_REF__$//;
6115: return $result;
6116: }
6117:
1.204 albertel 6118: sub arrayref2str {
6119: my ($arrayref) = @_;
1.265 albertel 6120: my $result='__ARRAY_REF__';
1.204 albertel 6121: foreach my $elem (@$arrayref) {
1.265 albertel 6122: if(ref($elem) eq 'ARRAY') {
6123: $result.=&arrayref2str($elem).'&';
6124: } elsif(ref($elem) eq 'HASH') {
6125: $result.=&hashref2str($elem).'&';
6126: } elsif(ref($elem)) {
6127: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 6128: } else {
6129: $result.=&escape($elem).'&';
6130: }
6131: }
6132: $result=~s/\&$//;
1.265 albertel 6133: $result .= '__END_ARRAY_REF__';
1.204 albertel 6134: return $result;
6135: }
6136:
1.168 albertel 6137: sub hash2str {
1.204 albertel 6138: my (%hash) = @_;
6139: my $result=&hashref2str(\%hash);
1.265 albertel 6140: $result=~s/^__HASH_REF__//;
6141: $result=~s/__END_HASH_REF__$//;
1.204 albertel 6142: return $result;
6143: }
6144:
6145: sub hashref2str {
6146: my ($hashref)=@_;
1.265 albertel 6147: my $result='__HASH_REF__';
1.800 albertel 6148: foreach my $key (sort(keys(%$hashref))) {
6149: if (ref($key) eq 'ARRAY') {
6150: $result.=&arrayref2str($key).'=';
6151: } elsif (ref($key) eq 'HASH') {
6152: $result.=&hashref2str($key).'=';
6153: } elsif (ref($key)) {
1.265 albertel 6154: $result.='=';
1.800 albertel 6155: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 6156: } else {
1.1132 raeburn 6157: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 6158: }
6159:
1.800 albertel 6160: if(ref($hashref->{$key}) eq 'ARRAY') {
6161: $result.=&arrayref2str($hashref->{$key}).'&';
6162: } elsif(ref($hashref->{$key}) eq 'HASH') {
6163: $result.=&hashref2str($hashref->{$key}).'&';
6164: } elsif(ref($hashref->{$key})) {
1.265 albertel 6165: $result.='&';
1.800 albertel 6166: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 6167: } else {
1.800 albertel 6168: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 6169: }
6170: }
1.168 albertel 6171: $result=~s/\&$//;
1.265 albertel 6172: $result .= '__END_HASH_REF__';
1.168 albertel 6173: return $result;
6174: }
6175:
6176: sub str2hash {
1.265 albertel 6177: my ($string)=@_;
6178: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
6179: return %$hash;
6180: }
6181:
6182: sub str2hashref {
1.168 albertel 6183: my ($string) = @_;
1.265 albertel 6184:
6185: my %hash;
6186:
6187: if($string !~ /^__HASH_REF__/) {
6188: if (! ($string eq '' || !defined($string))) {
6189: $hash{'error'}='Not hash reference';
6190: }
6191: return (\%hash, $string);
6192: }
6193:
6194: $string =~ s/^__HASH_REF__//;
6195:
6196: while($string !~ /^__END_HASH_REF__/) {
6197: #key
6198: my $key='';
6199: if($string =~ /^__HASH_REF__/) {
6200: ($key, $string)=&str2hashref($string);
6201: if(defined($key->{'error'})) {
6202: $hash{'error'}='Bad data';
6203: return (\%hash, $string);
6204: }
6205: } elsif($string =~ /^__ARRAY_REF__/) {
6206: ($key, $string)=&str2arrayref($string);
6207: if($key->[0] eq 'Array reference error') {
6208: $hash{'error'}='Bad data';
6209: return (\%hash, $string);
6210: }
6211: } else {
6212: $string =~ s/^(.*?)=//;
1.267 albertel 6213: $key=&unescape($1);
1.265 albertel 6214: }
6215: $string =~ s/^=//;
6216:
6217: #value
6218: my $value='';
6219: if($string =~ /^__HASH_REF__/) {
6220: ($value, $string)=&str2hashref($string);
6221: if(defined($value->{'error'})) {
6222: $hash{'error'}='Bad data';
6223: return (\%hash, $string);
6224: }
6225: } elsif($string =~ /^__ARRAY_REF__/) {
6226: ($value, $string)=&str2arrayref($string);
6227: if($value->[0] eq 'Array reference error') {
6228: $hash{'error'}='Bad data';
6229: return (\%hash, $string);
6230: }
6231: } else {
6232: $value=&get_scalar(\$string,'__END_HASH_REF__');
6233: }
6234: $string =~ s/^&//;
6235:
6236: $hash{$key}=$value;
1.204 albertel 6237: }
1.265 albertel 6238:
6239: $string =~ s/^__END_HASH_REF__//;
6240:
6241: return (\%hash, $string);
1.204 albertel 6242: }
6243:
6244: sub str2array {
1.265 albertel 6245: my ($string)=@_;
6246: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
6247: return @$array;
6248: }
6249:
6250: sub str2arrayref {
1.204 albertel 6251: my ($string) = @_;
1.265 albertel 6252: my @array;
6253:
6254: if($string !~ /^__ARRAY_REF__/) {
6255: if (! ($string eq '' || !defined($string))) {
6256: $array[0]='Array reference error';
6257: }
6258: return (\@array, $string);
6259: }
6260:
6261: $string =~ s/^__ARRAY_REF__//;
6262:
6263: while($string !~ /^__END_ARRAY_REF__/) {
6264: my $value='';
6265: if($string =~ /^__HASH_REF__/) {
6266: ($value, $string)=&str2hashref($string);
6267: if(defined($value->{'error'})) {
6268: $array[0] ='Array reference error';
6269: return (\@array, $string);
6270: }
6271: } elsif($string =~ /^__ARRAY_REF__/) {
6272: ($value, $string)=&str2arrayref($string);
6273: if($value->[0] eq 'Array reference error') {
6274: $array[0] ='Array reference error';
6275: return (\@array, $string);
6276: }
6277: } else {
6278: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6279: }
6280: $string =~ s/^&//;
6281:
6282: push(@array, $value);
1.191 harris41 6283: }
1.265 albertel 6284:
6285: $string =~ s/^__END_ARRAY_REF__//;
6286:
6287: return (\@array, $string);
1.168 albertel 6288: }
6289:
1.167 albertel 6290: # -------------------------------------------------------------------Temp Store
6291:
1.168 albertel 6292: sub tmpreset {
6293: my ($symb,$namespace,$domain,$stuname) = @_;
6294: if (!$symb) {
6295: $symb=&symbread();
1.620 albertel 6296: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6297: }
6298: $symb=escape($symb);
6299:
1.620 albertel 6300: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 6301: $namespace=~s/\//\_/g;
6302: $namespace=~s/\W//g;
6303:
1.620 albertel 6304: if (!$domain) { $domain=$env{'user.domain'}; }
6305: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6306: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6307: $stuname=&get_requestor_ip();
1.591 albertel 6308: }
1.1117 foxr 6309: my $path=LONCAPA::tempdir();
1.168 albertel 6310: my %hash;
6311: if (tie(%hash,'GDBM_File',
6312: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6313: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 6314: foreach my $key (keys(%hash)) {
1.180 albertel 6315: if ($key=~ /:$symb/) {
1.168 albertel 6316: delete($hash{$key});
6317: }
6318: }
6319: }
6320: }
6321:
1.167 albertel 6322: sub tmpstore {
1.168 albertel 6323: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6324:
6325: if (!$symb) {
6326: $symb=&symbread();
1.620 albertel 6327: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6328: }
6329: $symb=escape($symb);
6330:
6331: if (!$namespace) {
6332: # I don't think we would ever want to store this for a course.
6333: # it seems this will only be used if we don't have a course.
1.620 albertel 6334: #$namespace=$env{'request.course.id'};
1.168 albertel 6335: #if (!$namespace) {
1.620 albertel 6336: $namespace=$env{'request.state'};
1.168 albertel 6337: #}
6338: }
6339: $namespace=~s/\//\_/g;
6340: $namespace=~s/\W//g;
1.620 albertel 6341: if (!$domain) { $domain=$env{'user.domain'}; }
6342: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6343: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6344: $stuname=&get_requestor_ip();
1.591 albertel 6345: }
1.168 albertel 6346: my $now=time;
6347: my %hash;
1.1117 foxr 6348: my $path=LONCAPA::tempdir();
1.168 albertel 6349: if (tie(%hash,'GDBM_File',
6350: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6351: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6352: $hash{"version:$symb"}++;
6353: my $version=$hash{"version:$symb"};
6354: my $allkeys='';
6355: foreach my $key (keys(%$storehash)) {
6356: $allkeys.=$key.':';
1.591 albertel 6357: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6358: }
6359: $hash{"$version:$symb:timestamp"}=$now;
6360: $allkeys.='timestamp';
6361: $hash{"$version:keys:$symb"}=$allkeys;
6362: if (untie(%hash)) {
6363: return 'ok';
6364: } else {
6365: return "error:$!";
6366: }
6367: } else {
6368: return "error:$!";
6369: }
6370: }
1.167 albertel 6371:
1.168 albertel 6372: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6373:
1.168 albertel 6374: sub tmprestore {
6375: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6376:
1.168 albertel 6377: if (!$symb) {
6378: $symb=&symbread();
1.620 albertel 6379: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6380: }
6381: $symb=escape($symb);
6382:
1.620 albertel 6383: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6384:
1.620 albertel 6385: if (!$domain) { $domain=$env{'user.domain'}; }
6386: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6387: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6388: $stuname=&get_requestor_ip();
1.591 albertel 6389: }
1.168 albertel 6390: my %returnhash;
6391: $namespace=~s/\//\_/g;
6392: $namespace=~s/\W//g;
6393: my %hash;
1.1117 foxr 6394: my $path=LONCAPA::tempdir();
1.168 albertel 6395: if (tie(%hash,'GDBM_File',
6396: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6397: &GDBM_READER(),0640)) {
1.168 albertel 6398: my $version=$hash{"version:$symb"};
6399: $returnhash{'version'}=$version;
6400: my $scope;
6401: for ($scope=1;$scope<=$version;$scope++) {
6402: my $vkeys=$hash{"$scope:keys:$symb"};
6403: my @keys=split(/:/,$vkeys);
6404: my $key;
6405: $returnhash{"$scope:keys"}=$vkeys;
6406: foreach $key (@keys) {
1.591 albertel 6407: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6408: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6409: }
6410: }
1.168 albertel 6411: if (!(untie(%hash))) {
6412: return "error:$!";
6413: }
6414: } else {
6415: return "error:$!";
6416: }
6417: return %returnhash;
1.167 albertel 6418: }
6419:
1.9 www 6420: # ----------------------------------------------------------------------- Store
6421:
6422: sub store {
1.1269 raeburn 6423: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6424: my $home='';
6425:
1.168 albertel 6426: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6427:
1.213 www 6428: $symb=&symbclean($symb);
1.122 albertel 6429: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6430:
1.620 albertel 6431: if (!$domain) { $domain=$env{'user.domain'}; }
6432: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6433:
6434: &devalidate($symb,$stuname,$domain);
1.109 www 6435:
6436: $symb=escape($symb);
1.187 www 6437: if (!$namespace) {
1.620 albertel 6438: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6439: return '';
6440: }
6441: }
1.620 albertel 6442: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6443:
1.1434 raeburn 6444: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6445: $$storehash{'host'}=$perlvar{'lonHostID'};
6446:
1.12 www 6447: my $namevalue='';
1.800 albertel 6448: foreach my $key (keys(%$storehash)) {
6449: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6450: }
1.12 www 6451: $namevalue=~s/\&$//;
1.187 www 6452: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 6453: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6454: }
6455:
1.47 www 6456: # -------------------------------------------------------------- Critical Store
6457:
6458: sub cstore {
1.1269 raeburn 6459: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6460: my $home='';
6461:
1.168 albertel 6462: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6463:
1.213 www 6464: $symb=&symbclean($symb);
1.122 albertel 6465: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6466:
1.620 albertel 6467: if (!$domain) { $domain=$env{'user.domain'}; }
6468: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6469:
6470: &devalidate($symb,$stuname,$domain);
1.109 www 6471:
6472: $symb=escape($symb);
1.187 www 6473: if (!$namespace) {
1.620 albertel 6474: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6475: return '';
6476: }
6477: }
1.620 albertel 6478: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6479:
1.1434 raeburn 6480: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6481: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6482:
1.47 www 6483: my $namevalue='';
1.800 albertel 6484: foreach my $key (keys(%$storehash)) {
6485: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6486: }
1.47 www 6487: $namevalue=~s/\&$//;
1.187 www 6488: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6489: return critical
1.1269 raeburn 6490: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6491: }
6492:
1.9 www 6493: # --------------------------------------------------------------------- Restore
6494:
6495: sub restore {
1.124 www 6496: my ($symb,$namespace,$domain,$stuname) = @_;
6497: my $home='';
6498:
1.168 albertel 6499: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6500:
1.122 albertel 6501: if (!$symb) {
1.1224 raeburn 6502: return if ($namespace eq 'courserequests');
6503: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6504: } else {
1.1224 raeburn 6505: unless ($namespace eq 'courserequests') {
6506: $symb=&escape(&symbclean($symb));
6507: }
1.122 albertel 6508: }
1.188 www 6509: if (!$namespace) {
1.620 albertel 6510: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6511: return '';
6512: }
6513: }
1.620 albertel 6514: if (!$domain) { $domain=$env{'user.domain'}; }
6515: if (!$stuname) { $stuname=$env{'user.name'}; }
6516: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6517: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6518:
1.12 www 6519: my %returnhash=();
1.800 albertel 6520: foreach my $line (split(/\&/,$answer)) {
6521: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6522: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6523: }
1.75 www 6524: my $version;
6525: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6526: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6527: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6528: }
1.75 www 6529: }
1.13 www 6530: return %returnhash;
1.34 www 6531: }
6532:
6533: # ---------------------------------------------------------- Course Description
1.1118 foxr 6534: #
6535: #
1.34 www 6536:
6537: sub coursedescription {
1.731 albertel 6538: my ($courseid,$args)=@_;
1.34 www 6539: $courseid=~s/^\///;
1.49 www 6540: $courseid=~s/\_/\//g;
1.34 www 6541: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6542: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6543: my $normalid=$cdomain.'_'.$cnum;
6544: # need to always cache even if we get errors otherwise we keep
6545: # trying and trying and trying to get the course description.
6546: my %envhash=();
6547: my %returnhash=();
1.731 albertel 6548:
6549: my $expiretime=600;
6550: if ($env{'request.course.id'} eq $normalid) {
6551: $expiretime=120;
6552: }
6553:
6554: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6555: if (!$args->{'freshen_cache'}
6556: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6557: foreach my $key (keys(%env)) {
6558: next if ($key !~ /^\Q$prefix\E(.*)/);
6559: my ($setting) = $1;
6560: $returnhash{$setting} = $env{$key};
6561: }
6562: return %returnhash;
6563: }
6564:
1.1118 foxr 6565: # get the data again
6566:
1.731 albertel 6567: if (!$args->{'one_time'}) {
6568: $envhash{'course.'.$normalid.'.last_cache'}=time;
6569: }
1.811 albertel 6570:
1.34 www 6571: if ($chome ne 'no_host') {
1.302 albertel 6572: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6573: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6574: my $username = $env{'user.name'}; # Defult username
6575: if(defined $args->{'user'}) {
6576: $username = $args->{'user'};
6577: }
1.129 albertel 6578: $returnhash{'home'}= $chome;
6579: $returnhash{'domain'} = $cdomain;
6580: $returnhash{'num'} = $cnum;
1.741 raeburn 6581: if (!defined($returnhash{'type'})) {
6582: $returnhash{'type'} = 'Course';
6583: }
1.130 albertel 6584: while (my ($name,$value) = each %returnhash) {
1.53 www 6585: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6586: }
1.270 www 6587: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6588: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6589: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6590: $envhash{'course.'.$normalid.'.home'}=$chome;
6591: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6592: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6593: }
6594: }
1.731 albertel 6595: if (!$args->{'one_time'}) {
1.949 raeburn 6596: &appenv(\%envhash);
1.731 albertel 6597: }
1.302 albertel 6598: return %returnhash;
1.461 www 6599: }
6600:
1.1080 raeburn 6601: sub update_released_required {
6602: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6603: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6604: $cid = $env{'request.course.id'};
6605: $cdom = $env{'course.'.$cid.'.domain'};
6606: $cnum = $env{'course.'.$cid.'.num'};
6607: $chome = $env{'course.'.$cid.'.home'};
6608: }
6609: if ($needsrelease) {
6610: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6611: my $needsupdate;
6612: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6613: $needsupdate = 1;
6614: } else {
6615: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6616: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6617: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6618: $needsupdate = 1;
6619: }
6620: }
6621: if ($needsupdate) {
6622: my %needshash = (
6623: 'internal.releaserequired' => $needsrelease,
6624: );
6625: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6626: if ($putresult eq 'ok') {
6627: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6628: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6629: if (ref($crsinfo{$cid}) eq 'HASH') {
6630: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6631: &courseidput($cdom,\%crsinfo,$chome,'notime');
6632: }
6633: }
6634: }
6635: }
6636: return;
6637: }
6638:
1.461 www 6639: # -------------------------------------------------See if a user is privileged
6640:
6641: sub privileged {
1.1219 raeburn 6642: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6643: my $now = time;
1.1219 raeburn 6644: my $roles;
6645: if (ref($possroles) eq 'ARRAY') {
6646: $roles = $possroles;
6647: } else {
6648: $roles = ['dc','su'];
6649: }
6650: if (ref($possdomains) eq 'ARRAY') {
6651: my %privileged = &privileged_by_domain($possdomains,$roles);
6652: foreach my $dom (@{$possdomains}) {
6653: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6654: (ref($privileged{$dom}) eq 'HASH')) {
6655: foreach my $role (@{$roles}) {
6656: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6657: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6658: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6659: return 1 unless (($end && $end < $now) ||
6660: ($start && $start > $now));
6661: }
6662: }
6663: }
6664: }
6665: }
6666: } else {
6667: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6668: my $now = time;
1.1170 droeschl 6669:
1.1275 musolffc 6670: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6671: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 6672: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 6673: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 6674: or ($tstart && $tstart > $now);
1.1170 droeschl 6675: }
1.1219 raeburn 6676: }
6677: }
6678: return 0;
6679: }
1.1170 droeschl 6680:
1.1219 raeburn 6681: sub privileged_by_domain {
6682: my ($domains,$roles) = @_;
6683: my %privileged = ();
6684: my $cachetime = 60*60*24;
6685: my $now = time;
6686: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6687: return %privileged;
6688: }
6689: foreach my $dom (@{$domains}) {
6690: next if (ref($privileged{$dom}) eq 'HASH');
6691: my $needroles;
6692: foreach my $role (@{$roles}) {
6693: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6694: if (defined($cached)) {
6695: if (ref($result) eq 'HASH') {
6696: $privileged{$dom}{$role} = $result;
6697: }
6698: } else {
6699: $needroles = 1;
6700: }
6701: }
6702: if ($needroles) {
6703: my %dompersonnel = &get_domain_roles($dom,$roles);
6704: $privileged{$dom} = {};
6705: foreach my $server (keys(%dompersonnel)) {
6706: if (ref($dompersonnel{$server}) eq 'HASH') {
6707: foreach my $item (keys(%{$dompersonnel{$server}})) {
6708: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6709: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6710: next if ($end && $end < $now);
6711: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6712: $dompersonnel{$server}{$item};
6713: }
6714: }
6715: }
6716: if (ref($privileged{$dom}) eq 'HASH') {
6717: foreach my $role (@{$roles}) {
6718: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6719: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6720: } else {
6721: my %hash = ();
6722: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6723: }
6724: }
6725: }
6726: }
6727: }
6728: return %privileged;
1.9 www 6729: }
1.1 albertel 6730:
1.103 harris41 6731: # -------------------------------------------------------- Get user privileges
1.11 www 6732:
6733: sub rolesinit {
1.1169 droeschl 6734: my ($domain, $username) = @_;
6735: my %userroles = ('user.login.time' => time);
6736: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6737:
6738: # firstaccess and timerinterval are related to timed maps/resources.
6739: # also, blocking can be triggered by an activating timer
6740: # it's saved in the user's %env.
6741: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6742: my %timerinterval = &dump('timerinterval', $domain, $username);
6743: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6744: %timerintchk, %timerintenv);
6745:
1.1162 raeburn 6746: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6747: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6748: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6749: }
1.1169 droeschl 6750:
1.1162 raeburn 6751: foreach my $key (keys(%timerinterval)) {
6752: my ($cid,$rest) = split(/\0/,$key);
6753: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6754: }
1.1169 droeschl 6755:
1.11 www 6756: my %allroles=();
1.1162 raeburn 6757: my %allgroups=();
1.11 www 6758:
1.1274 raeburn 6759: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6760: my $role = $rolesdump{$area};
6761: $area =~ s/\_\w\w$//;
6762:
6763: my ($trole, $tend, $tstart, $group_privs);
6764:
6765: if ($role =~ /^cr/) {
6766: # Custom role, defined by a user
6767: # e.g., user.role.cr/msu/smith/mynewrole
6768: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6769: $trole = $1;
6770: ($tend, $tstart) = split('_', $2);
6771: } else {
6772: $trole = $role;
6773: }
6774: } elsif ($role =~ m|^gr/|) {
6775: # Role of member in a group, defined within a course/community
6776: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6777: ($trole, $tend, $tstart) = split(/_/, $role);
6778: next if $tstart eq '-1';
6779: ($trole, $group_privs) = split(/\//, $trole);
6780: $group_privs = &unescape($group_privs);
6781: } else {
6782: # Just a normal role, defined in roles.tab
6783: ($trole, $tend, $tstart) = split(/_/,$role);
6784: }
6785:
6786: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6787: $username);
6788: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6789:
6790: # role expired or not available yet?
6791: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6792: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6793:
6794: next if $area eq '' or $trole eq '';
6795:
6796: my $spec = "$trole.$area";
6797: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6798:
6799: if ($trole =~ /^cr\//) {
6800: # Custom role, defined by a user
6801: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6802: } elsif ($trole eq 'gr') {
6803: # Role of a member in a group, defined within a course/community
6804: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6805: next;
6806: } else {
6807: # Normal role, defined in roles.tab
6808: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6809: }
6810:
6811: my $cid = $tdomain.'_'.$trest;
6812: unless ($firstaccchk{$cid}) {
6813: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6814: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6815: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6816: $coursetimerstarts{$cid}{$item};
6817: }
6818: }
6819: $firstaccchk{$cid} = 1;
6820: }
6821: unless ($timerintchk{$cid}) {
6822: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6823: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6824: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6825: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6826: }
1.12 www 6827: }
1.1169 droeschl 6828: $timerintchk{$cid} = 1;
1.191 harris41 6829: }
1.11 www 6830: }
1.1169 droeschl 6831:
1.1341 raeburn 6832: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6833: \%allroles, \%allgroups);
1.1169 droeschl 6834: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 6835: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6836:
1.1162 raeburn 6837: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6838: }
6839:
1.567 raeburn 6840: sub set_arearole {
1.1215 raeburn 6841: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6842: unless ($nolog) {
1.567 raeburn 6843: # log the associated role with the area
1.1215 raeburn 6844: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6845: }
1.743 albertel 6846: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6847: }
6848:
6849: sub custom_roleprivs {
6850: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6851: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 6852: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6853: if (&hostname($homsvr) ne '') {
1.567 raeburn 6854: my ($rdummy,$roledef)=
6855: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6856: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6857: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6858: if (defined($syspriv)) {
1.1043 raeburn 6859: if ($trest =~ /^$match_community$/) {
6860: $syspriv =~ s/bre\&S//;
6861: }
1.567 raeburn 6862: $$allroles{'cm./'}.=':'.$syspriv;
6863: $$allroles{$spec.'./'}.=':'.$syspriv;
6864: }
6865: if ($tdomain ne '') {
6866: if (defined($dompriv)) {
6867: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6868: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6869: }
6870: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 6871: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6872: my $rolename = $1;
6873: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6874: }
1.567 raeburn 6875: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6876: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6877: }
6878: }
6879: }
6880: }
6881: }
6882:
1.1332 raeburn 6883: sub course_adhocrole_privs {
6884: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6885: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6886: if ($overrides{"internal.adhocpriv.$rolename"}) {
6887: my (%currprivs,%storeprivs);
6888: foreach my $item (split(/:/,$coursepriv)) {
6889: my ($priv,$restrict) = split(/\&/,$item);
6890: $currprivs{$priv} = $restrict;
6891: }
6892: my (%possadd,%possremove,%full);
6893: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6894: my ($priv,$restrict)=split(/\&/,$item);
6895: $full{$priv} = $restrict;
6896: }
6897: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1490 raeburn 6898: next if ($item eq '');
6899: my ($rule,$rest) = split(/=/,$item);
6900: next unless (($rule eq 'off') || ($rule eq 'on'));
6901: foreach my $priv (split(/:/,$rest)) {
6902: if ($priv ne '') {
6903: if ($rule eq 'off') {
6904: $possremove{$priv} = 1;
6905: } else {
6906: $possadd{$priv} = 1;
6907: }
6908: }
6909: }
6910: }
6911: foreach my $priv (sort(keys(%full))) {
6912: if (exists($currprivs{$priv})) {
6913: unless (exists($possremove{$priv})) {
6914: $storeprivs{$priv} = $currprivs{$priv};
6915: }
6916: } elsif (exists($possadd{$priv})) {
6917: $storeprivs{$priv} = $full{$priv};
6918: }
6919: }
6920: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6921: }
6922: return $coursepriv;
1.1332 raeburn 6923: }
6924:
1.678 raeburn 6925: sub group_roleprivs {
6926: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6927: my $access = 1;
6928: my $now = time;
6929: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6930: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6931: if ($access) {
1.811 albertel 6932: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6933: $$allgroups{$course}{$group} .=':'.$group_privs;
6934: }
6935: }
1.567 raeburn 6936:
6937: sub standard_roleprivs {
6938: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6939: if (defined($pr{$trole.':s'})) {
6940: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6941: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6942: }
6943: if ($tdomain ne '') {
6944: if (defined($pr{$trole.':d'})) {
6945: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6946: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6947: }
6948: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6949: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6950: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6951: }
6952: }
6953: }
6954:
6955: sub set_userprivs {
1.1064 raeburn 6956: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6957: my $author=0;
6958: my $adv=0;
1.1341 raeburn 6959: my $rar=0;
1.678 raeburn 6960: my %grouproles = ();
6961: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6962: my @groupkeys;
1.1000 raeburn 6963: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6964: push(@groupkeys,$role);
6965: }
6966: if (ref($groups_roles) eq 'HASH') {
6967: foreach my $key (keys(%{$groups_roles})) {
6968: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6969: push(@groupkeys,$key);
6970: }
6971: }
6972: }
6973: if (@groupkeys > 0) {
6974: foreach my $role (@groupkeys) {
6975: my ($trole,$area,$sec,$extendedarea);
6976: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6977: $trole = $1;
6978: $area = $2;
6979: $sec = $3;
6980: $extendedarea = $area.$sec;
6981: if (exists($$allgroups{$area})) {
6982: foreach my $group (keys(%{$$allgroups{$area}})) {
6983: my $spec = $trole.'.'.$extendedarea;
6984: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6985: $$allgroups{$area}{$group};
1.1064 raeburn 6986: }
1.678 raeburn 6987: }
6988: }
6989: }
6990: }
6991: }
1.800 albertel 6992: foreach my $group (keys(%grouproles)) {
6993: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6994: }
1.800 albertel 6995: foreach my $role (keys(%{$allroles})) {
6996: my %thesepriv;
1.941 raeburn 6997: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6998: foreach my $item (split(/:/,$$allroles{$role})) {
6999: if ($item ne '') {
7000: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 7001: if ($restrictions eq '') {
7002: $thesepriv{$privilege}='F';
7003: } elsif ($thesepriv{$privilege} ne 'F') {
7004: $thesepriv{$privilege}.=$restrictions;
7005: }
7006: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 7007: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 7008: }
7009: }
7010: my $thesestr='';
1.1104 raeburn 7011: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 7012: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
7013: }
7014: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 7015: }
1.1341 raeburn 7016: return ($author,$adv,$rar);
1.567 raeburn 7017: }
7018:
1.994 raeburn 7019: sub role_status {
1.1104 raeburn 7020: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 7021: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 7022: my ($one,$two) = split(m{\./},$rolekey,2);
7023: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 7024: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 7025: $$where = '/'.$two;
1.994 raeburn 7026: $$trolecode=$$role.'.'.$$where;
7027: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
7028: $$tstatus='is';
1.1104 raeburn 7029: if ($$tstart && $$tstart>$update) {
1.994 raeburn 7030: $$tstatus='future';
1.1034 raeburn 7031: if ($$tstart<$now) {
7032: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 7033: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 7034: my (%allroles,%allgroups,$group_privs,
7035: %groups_roles,@rolecodes);
1.1002 raeburn 7036: my %userroles = (
7037: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
7038: );
1.1064 raeburn 7039: @rolecodes = ('cm');
1.1002 raeburn 7040: my $spec=$$role.'.'.$$where;
7041: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
7042: if ($$role =~ /^cr\//) {
7043: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 7044: push(@rolecodes,'cr');
1.1002 raeburn 7045: } elsif ($$role eq 'gr') {
1.1064 raeburn 7046: push(@rolecodes,$$role);
1.1002 raeburn 7047: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
7048: $env{'user.name'});
1.1064 raeburn 7049: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 7050: (undef,my $group_privs) = split(/\//,$trole);
7051: $group_privs = &unescape($group_privs);
7052: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 7053: 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 7054: &get_groups_roles($tdomain,$trest,
7055: \%course_roles,\@rolecodes,
7056: \%groups_roles);
1.1002 raeburn 7057: } else {
1.1064 raeburn 7058: push(@rolecodes,$$role);
1.1002 raeburn 7059: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
7060: }
1.1341 raeburn 7061: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
7062: \%groups_roles);
1.1064 raeburn 7063: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 7064: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 7065: }
7066: }
1.1034 raeburn 7067: $$tstatus = 'is';
1.1002 raeburn 7068: }
1.994 raeburn 7069: }
7070: if ($$tend) {
1.1104 raeburn 7071: if ($$tend<$update) {
1.994 raeburn 7072: $$tstatus='expired';
7073: } elsif ($$tend<$now) {
7074: $$tstatus='will_not';
7075: }
7076: }
7077: }
7078: }
7079: }
7080:
1.1104 raeburn 7081: sub get_groups_roles {
7082: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
7083: return unless((ref($cdom_courseroles) eq 'HASH') &&
7084: (ref($rolecodes) eq 'ARRAY') &&
7085: (ref($groups_roles) eq 'HASH'));
7086: if (keys(%{$cdom_courseroles}) > 0) {
7087: my ($cnum) = ($rest =~ /^($match_courseid)/);
7088: if ($cdom ne '' && $cnum ne '') {
7089: foreach my $key (keys(%{$cdom_courseroles})) {
7090: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
7091: my $crsrole = $1;
7092: my $crssec = $2;
7093: if ($crsrole =~ /^cr/) {
7094: unless (grep(/^cr$/,@{$rolecodes})) {
7095: push(@{$rolecodes},'cr');
7096: }
7097: } else {
7098: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
7099: push(@{$rolecodes},$crsrole);
7100: }
7101: }
7102: my $rolekey = "$crsrole./$cdom/$cnum";
7103: if ($crssec ne '') {
7104: $rolekey .= "/$crssec";
7105: }
7106: $rolekey .= './';
7107: $groups_roles->{$rolekey} = $rolecodes;
7108: }
7109: }
7110: }
7111: }
7112: return;
7113: }
7114:
7115: sub delete_env_groupprivs {
7116: my ($where,$courseroles,$possroles) = @_;
7117: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
7118: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
7119: unless (ref($courseroles->{$udom}) eq 'HASH') {
7120: %{$courseroles->{$udom}} =
7121: &get_my_roles('','','userroles',['active'],
7122: $possroles,[$udom],1);
7123: }
7124: if (ref($courseroles->{$udom}) eq 'HASH') {
7125: foreach my $item (keys(%{$courseroles->{$udom}})) {
7126: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
7127: my $area = '/'.$cdom.'/'.$cnum;
7128: my $privkey = "user.priv.$crsrole.$area";
7129: if ($crssec ne '') {
7130: $privkey .= '/'.$crssec;
7131: }
7132: $privkey .= ".$area/$group";
7133: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
7134: }
7135: }
7136: return;
7137: }
7138:
1.994 raeburn 7139: sub check_adhoc_privs {
1.1329 raeburn 7140: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 7141: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 7142: if ($sec) {
7143: $cckey .= '/'.$sec;
7144: }
1.1185 raeburn 7145: my $setprivs;
1.994 raeburn 7146: if ($env{$cckey}) {
7147: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 7148: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 7149: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 7150: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7151: $setprivs = 1;
1.994 raeburn 7152: }
7153: } else {
1.1330 raeburn 7154: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7155: $setprivs = 1;
1.994 raeburn 7156: }
1.1185 raeburn 7157: return $setprivs;
1.994 raeburn 7158: }
7159:
7160: sub set_adhoc_privileges {
1.1326 raeburn 7161: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 7162: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 7163: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 7164: if ($sec ne '') {
7165: $area .= '/'.$sec;
7166: }
1.994 raeburn 7167: my $spec = $role.'.'.$area;
7168: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 7169: $env{'user.name'},1);
1.1326 raeburn 7170: my %rolehash = ();
1.1332 raeburn 7171: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
7172: my $rolename = $1;
1.1326 raeburn 7173: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 7174: my %domdef = &get_domain_defaults($dcdom);
7175: if (ref($domdef{'adhocroles'}) eq 'HASH') {
7176: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
7177: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
7178: }
7179: }
1.1326 raeburn 7180: } else {
7181: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
7182: }
1.1341 raeburn 7183: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 7184: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 7185: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402 raeburn 7186: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
7187: ($caller eq 'tiny')) {
1.1088 raeburn 7188: &appenv( {'request.role' => $spec,
7189: 'request.role.domain' => $dcdom,
1.1332 raeburn 7190: 'request.course.sec' => $sec,
1.1088 raeburn 7191: }
7192: );
7193: my $tadv=0;
7194: if (&allowed('adv') eq 'F') { $tadv=1; }
7195: &appenv({'request.role.adv' => $tadv});
7196: }
1.994 raeburn 7197: }
7198:
1.12 www 7199: # --------------------------------------------------------------- get interface
7200:
7201: sub get {
1.131 albertel 7202: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7203: my $items='';
1.800 albertel 7204: foreach my $item (@$storearr) {
7205: $items.=&escape($item).'&';
1.191 harris41 7206: }
1.12 www 7207: $items=~s/\&$//;
1.620 albertel 7208: if (!$udomain) { $udomain=$env{'user.domain'}; }
7209: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 7210: my $uhome=&homeserver($uname,$udomain);
7211:
1.133 albertel 7212: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7213: my @pairs=split(/\&/,$rep);
1.273 albertel 7214: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
7215: return @pairs;
7216: }
1.15 www 7217: my %returnhash=();
1.42 www 7218: my $i=0;
1.800 albertel 7219: foreach my $item (@$storearr) {
7220: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7221: $i++;
1.191 harris41 7222: }
1.15 www 7223: return %returnhash;
1.27 www 7224: }
7225:
7226: # --------------------------------------------------------------- del interface
7227:
7228: sub del {
1.133 albertel 7229: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 7230: my $items='';
1.800 albertel 7231: foreach my $item (@$storearr) {
7232: $items.=&escape($item).'&';
1.191 harris41 7233: }
1.984 neumanie 7234:
1.27 www 7235: $items=~s/\&$//;
1.620 albertel 7236: if (!$udomain) { $udomain=$env{'user.domain'}; }
7237: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7238: my $uhome=&homeserver($uname,$udomain);
7239: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7240: }
7241:
7242: # -------------------------------------------------------------- dump interface
7243:
1.1180 droeschl 7244: sub unserialize {
7245: my ($rep, $escapedkeys) = @_;
7246:
7247: return {} if $rep =~ /^error/;
7248:
7249: my %returnhash=();
1.1252 raeburn 7250: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 7251: my ($key, $value) = split(/=/, $item, 2);
7252: $key = unescape($key) unless $escapedkeys;
7253: next if $key =~ /^error: 2 /;
1.1252 raeburn 7254: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 7255: }
7256: #return %returnhash;
7257: return \%returnhash;
7258: }
7259:
7260: # see Lond::dump_with_regexp
7261: # if $escapedkeys hash keys won't get unescaped.
1.15 www 7262: sub dump {
1.1462 raeburn 7263: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755 albertel 7264: if (!$udomain) { $udomain=$env{'user.domain'}; }
7265: if (!$uname) { $uname=$env{'user.name'}; }
7266: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 7267:
1.1266 raeburn 7268: if ($regexp) {
7269: $regexp=&escape($regexp);
7270: } else {
7271: $regexp='.';
7272: }
1.1180 droeschl 7273: if (grep { $_ eq $uhome } current_machine_ids()) {
7274: # user is hosted on this machine
1.1266 raeburn 7275: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 7276: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 7277: return %{unserialize($reply, $escapedkeys)};
7278: }
1.1462 raeburn 7279: my $rep;
7280: if ($encrypt) {
7281: $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.1463 raeburn 7282: } else {
1.1462 raeburn 7283: $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7284: }
1.755 albertel 7285: my @pairs=split(/\&/,$rep);
7286: my %returnhash=();
1.1098 foxr 7287: if (!($rep =~ /^error/ )) {
7288: foreach my $item (@pairs) {
7289: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 7290: $key = unescape($key) unless $escapedkeys;
7291: #$key = &unescape($key);
1.1098 foxr 7292: next if ($key =~ /^error: 2 /);
7293: $returnhash{$key}=&thaw_unescape($value);
7294: }
1.755 albertel 7295: }
7296: return %returnhash;
1.407 www 7297: }
7298:
1.1098 foxr 7299:
1.717 albertel 7300: # --------------------------------------------------------- dumpstore interface
7301:
7302: sub dumpstore {
7303: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 7304: # same as dump but keys must be escaped. They may contain colon separated
7305: # lists of values that may themself contain colons (e.g. symbs).
7306: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 7307: }
7308:
1.407 www 7309: # -------------------------------------------------------------- keys interface
7310:
7311: sub getkeys {
7312: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 7313: if (!$udomain) { $udomain=$env{'user.domain'}; }
7314: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 7315: my $uhome=&homeserver($uname,$udomain);
7316: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7317: my @keyarray=();
1.800 albertel 7318: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 7319: next if ($key =~ /^error: 2 /);
1.800 albertel 7320: push(@keyarray,&unescape($key));
1.407 www 7321: }
7322: return @keyarray;
1.318 matthew 7323: }
7324:
1.319 matthew 7325: # --------------------------------------------------------------- currentdump
7326: sub currentdump {
1.328 matthew 7327: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 7328: $courseid = $env{'request.course.id'} if (! defined($courseid));
7329: $sdom = $env{'user.domain'} if (! defined($sdom));
7330: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 7331: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 7332: my $rep;
7333:
7334: if (grep { $_ eq $uhome } current_machine_ids()) {
7335: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7336: $courseid)));
7337: } else {
7338: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7339: }
7340:
1.318 matthew 7341: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7342: #
1.318 matthew 7343: my %returnhash=();
1.319 matthew 7344: #
1.1343 raeburn 7345: if ($rep eq 'unknown_cmd') {
1.319 matthew 7346: # an old lond will not know currentdump
7347: # Do a dump and make it look like a currentdump
1.822 albertel 7348: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7349: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7350: my %hash = @tmp;
7351: @tmp=();
1.424 matthew 7352: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7353: } else {
7354: my @pairs=split(/\&/,$rep);
1.800 albertel 7355: foreach my $pair (@pairs) {
7356: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7357: my ($symb,$param) = split(/:/,$key);
7358: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7359: &thaw_unescape($value);
1.319 matthew 7360: }
1.191 harris41 7361: }
1.12 www 7362: return %returnhash;
1.424 matthew 7363: }
7364:
7365: sub convert_dump_to_currentdump{
7366: my %hash = %{shift()};
7367: my %returnhash;
7368: # Code ripped from lond, essentially. The only difference
7369: # here is the unescaping done by lonnet::dump(). Conceivably
7370: # we might run in to problems with parameter names =~ /^v\./
7371: while (my ($key,$value) = each(%hash)) {
7372: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7373: $symb = &unescape($symb);
7374: $param = &unescape($param);
1.424 matthew 7375: next if ($v eq 'version' || $symb eq 'keys');
7376: next if (exists($returnhash{$symb}) &&
7377: exists($returnhash{$symb}->{$param}) &&
7378: $returnhash{$symb}->{'v.'.$param} > $v);
7379: $returnhash{$symb}->{$param}=$value;
7380: $returnhash{$symb}->{'v.'.$param}=$v;
7381: }
7382: #
7383: # Remove all of the keys in the hashes which keep track of
7384: # the version of the parameter.
7385: while (my ($symb,$param_hash) = each(%returnhash)) {
7386: # use a foreach because we are going to delete from the hash.
7387: foreach my $key (keys(%$param_hash)) {
7388: delete($param_hash->{$key}) if ($key =~ /^v\./);
7389: }
7390: }
7391: return \%returnhash;
1.12 www 7392: }
7393:
1.627 albertel 7394: # ------------------------------------------------------ critical inc interface
7395:
7396: sub cinc {
7397: return &inc(@_,'critical');
7398: }
7399:
1.449 matthew 7400: # --------------------------------------------------------------- inc interface
7401:
7402: sub inc {
1.627 albertel 7403: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7404: if (!$udomain) { $udomain=$env{'user.domain'}; }
7405: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7406: my $uhome=&homeserver($uname,$udomain);
7407: my $items='';
7408: if (! ref($store)) {
7409: # got a single value, so use that instead
7410: $items = &escape($store).'=&';
7411: } elsif (ref($store) eq 'SCALAR') {
7412: $items = &escape($$store).'=&';
7413: } elsif (ref($store) eq 'ARRAY') {
7414: $items = join('=&',map {&escape($_);} @{$store});
7415: } elsif (ref($store) eq 'HASH') {
7416: while (my($key,$value) = each(%{$store})) {
7417: $items.= &escape($key).'='.&escape($value).'&';
7418: }
7419: }
7420: $items=~s/\&$//;
1.627 albertel 7421: if ($critical) {
7422: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7423: } else {
7424: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7425: }
1.449 matthew 7426: }
7427:
1.12 www 7428: # --------------------------------------------------------------- put interface
7429:
7430: sub put {
1.1462 raeburn 7431: my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620 albertel 7432: if (!$udomain) { $udomain=$env{'user.domain'}; }
7433: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7434: my $uhome=&homeserver($uname,$udomain);
1.12 www 7435: my $items='';
1.800 albertel 7436: foreach my $item (keys(%$storehash)) {
7437: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7438: }
1.12 www 7439: $items=~s/\&$//;
1.1462 raeburn 7440: if ($encrypt) {
7441: return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
7442: } else {
7443: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7444: }
1.47 www 7445: }
7446:
1.631 albertel 7447: # ------------------------------------------------------------ newput interface
7448:
7449: sub newput {
7450: my ($namespace,$storehash,$udomain,$uname)=@_;
7451: if (!$udomain) { $udomain=$env{'user.domain'}; }
7452: if (!$uname) { $uname=$env{'user.name'}; }
7453: my $uhome=&homeserver($uname,$udomain);
7454: my $items='';
7455: foreach my $key (keys(%$storehash)) {
7456: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7457: }
7458: $items=~s/\&$//;
7459: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7460: }
7461:
7462: # --------------------------------------------------------- putstore interface
7463:
1.524 raeburn 7464: sub putstore {
1.1269 raeburn 7465: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7466: if (!$udomain) { $udomain=$env{'user.domain'}; }
7467: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7468: my $uhome=&homeserver($uname,$udomain);
7469: my $items='';
1.715 albertel 7470: foreach my $key (keys(%$storehash)) {
7471: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7472: }
1.715 albertel 7473: $items=~s/\&$//;
1.716 albertel 7474: my $esc_symb=&escape($symb);
7475: my $esc_v=&escape($version);
1.715 albertel 7476: my $reply =
1.716 albertel 7477: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7478: $uhome);
1.1269 raeburn 7479: if (($tolog) && ($reply eq 'ok')) {
7480: my $namevalue='';
7481: foreach my $key (keys(%{$storehash})) {
7482: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7483: }
1.1434 raeburn 7484: my $ip = &get_requestor_ip();
7485: $namevalue .= 'ip='.&escape($ip).
1.1269 raeburn 7486: '&host='.&escape($perlvar{'lonHostID'}).
7487: '&version='.$esc_v.
7488: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
1.1494 raeburn 7489: &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
1.1269 raeburn 7490: }
1.715 albertel 7491: if ($reply eq 'unknown_cmd') {
1.716 albertel 7492: # gfall back to way things use to be done
1.715 albertel 7493: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7494: $uname);
1.524 raeburn 7495: }
1.715 albertel 7496: return $reply;
7497: }
7498:
7499: sub old_putstore {
1.716 albertel 7500: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7501: if (!$udomain) { $udomain=$env{'user.domain'}; }
7502: if (!$uname) { $uname=$env{'user.name'}; }
7503: my $uhome=&homeserver($uname,$udomain);
7504: my %newstorehash;
1.800 albertel 7505: foreach my $item (keys(%$storehash)) {
7506: my $key = $version.':'.&escape($symb).':'.$item;
7507: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7508: }
7509: my $items='';
7510: my %allitems = ();
1.800 albertel 7511: foreach my $item (keys(%newstorehash)) {
7512: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7513: my $key = $1.':keys:'.$2;
7514: $allitems{$key} .= $3.':';
7515: }
1.800 albertel 7516: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7517: }
1.800 albertel 7518: foreach my $item (keys(%allitems)) {
7519: $allitems{$item} =~ s/\:$//;
7520: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7521: }
7522: $items=~s/\&$//;
7523: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7524: }
7525:
1.47 www 7526: # ------------------------------------------------------ critical put interface
7527:
7528: sub cput {
1.134 albertel 7529: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7530: if (!$udomain) { $udomain=$env{'user.domain'}; }
7531: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7532: my $uhome=&homeserver($uname,$udomain);
1.47 www 7533: my $items='';
1.800 albertel 7534: foreach my $item (keys(%$storehash)) {
7535: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7536: }
1.47 www 7537: $items=~s/\&$//;
1.134 albertel 7538: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7539: }
7540:
7541: # -------------------------------------------------------------- eget interface
7542:
7543: sub eget {
1.133 albertel 7544: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7545: my $items='';
1.800 albertel 7546: foreach my $item (@$storearr) {
7547: $items.=&escape($item).'&';
1.191 harris41 7548: }
1.12 www 7549: $items=~s/\&$//;
1.620 albertel 7550: if (!$udomain) { $udomain=$env{'user.domain'}; }
7551: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7552: my $uhome=&homeserver($uname,$udomain);
7553: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7554: my @pairs=split(/\&/,$rep);
7555: my %returnhash=();
1.42 www 7556: my $i=0;
1.800 albertel 7557: foreach my $item (@$storearr) {
7558: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7559: $i++;
1.191 harris41 7560: }
1.12 www 7561: return %returnhash;
7562: }
7563:
1.667 albertel 7564: # ------------------------------------------------------------ tmpput interface
7565: sub tmpput {
1.802 raeburn 7566: my ($storehash,$server,$context)=@_;
1.667 albertel 7567: my $items='';
1.800 albertel 7568: foreach my $item (keys(%$storehash)) {
7569: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7570: }
7571: $items=~s/\&$//;
1.802 raeburn 7572: if (defined($context)) {
7573: $items .= ':'.&escape($context);
7574: }
1.667 albertel 7575: return &reply("tmpput:$items",$server);
7576: }
7577:
7578: # ------------------------------------------------------------ tmpget interface
7579: sub tmpget {
1.688 albertel 7580: my ($token,$server)=@_;
7581: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7582: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7583: my %returnhash;
1.1328 raeburn 7584: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7585: return %returnhash;
7586: }
1.667 albertel 7587: foreach my $item (split(/\&/,$rep)) {
7588: my ($key,$value)=split(/=/,$item);
7589: $returnhash{&unescape($key)}=&thaw_unescape($value);
7590: }
7591: return %returnhash;
7592: }
7593:
1.1113 raeburn 7594: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7595: sub tmpdel {
7596: my ($token,$server)=@_;
7597: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7598: return &reply("tmpdel:$token",$server);
7599: }
7600:
1.1198 raeburn 7601: # ------------------------------------------------------------ get_timebased_id
7602:
7603: sub get_timebased_id {
7604: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7605: $maxtries) = @_;
7606: my ($newid,$error,$dellock);
7607: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7608: return ('','ok','invalid call to get suffix');
7609: }
7610:
7611: # set defaults for any optional args for which values were not supplied
7612: if ($who eq '') {
7613: $who = $env{'user.name'}.':'.$env{'user.domain'};
7614: }
7615: if (!$locktries) {
7616: $locktries = 3;
7617: }
7618: if (!$maxtries) {
7619: $maxtries = 10;
7620: }
7621:
7622: if (($cdom eq '') || ($cnum eq '')) {
7623: if ($env{'request.course.id'}) {
7624: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7625: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7626: }
7627: if (($cdom eq '') || ($cnum eq '')) {
7628: return ('','ok','call to get suffix not in course context');
7629: }
7630: }
7631:
7632: # construct locking item
7633: my $lockhash = {
7634: $prefix."\0".'locked_'.$keyid => $who,
7635: };
7636: my $tries = 0;
7637:
7638: # attempt to get lock on nohist_$namespace file
1.1494 raeburn 7639: my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198 raeburn 7640: while (($gotlock ne 'ok') && $tries <$locktries) {
7641: $tries ++;
7642: sleep 1;
1.1494 raeburn 7643: $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198 raeburn 7644: }
7645:
7646: # attempt to get unique identifier, based on current timestamp
7647: if ($gotlock eq 'ok') {
1.1494 raeburn 7648: my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
1.1198 raeburn 7649: my $id = time;
7650: $newid = $id;
1.1268 raeburn 7651: if ($idtype eq 'addcode') {
7652: $newid .= &sixnum_code();
7653: }
1.1198 raeburn 7654: my $idtries = 0;
7655: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7656: if ($idtype eq 'concat') {
7657: $newid = $id.$idtries;
1.1268 raeburn 7658: } elsif ($idtype eq 'addcode') {
7659: $newid = $newid.&sixnum_code();
1.1198 raeburn 7660: } else {
7661: $newid ++;
7662: }
7663: $idtries ++;
7664: }
7665: if (!exists($inuse{$prefix."\0".$newid})) {
7666: my %new_item = (
7667: $prefix."\0".$newid => $who,
7668: );
1.1494 raeburn 7669: my $putresult = &put('nohist_'.$namespace,\%new_item,
1.1198 raeburn 7670: $cdom,$cnum);
7671: if ($putresult ne 'ok') {
7672: undef($newid);
7673: $error = 'error saving new item: '.$putresult;
7674: }
7675: } else {
1.1268 raeburn 7676: undef($newid);
1.1198 raeburn 7677: $error = ('error: no unique suffix available for the new item ');
7678: }
7679: # remove lock
7680: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7681: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7682: } else {
7683: $error = "error: could not obtain lockfile\n";
7684: $dellock = 'ok';
1.1276 raeburn 7685: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7686: $dellock = 'nolock';
7687: }
1.1198 raeburn 7688: }
7689: return ($newid,$dellock,$error);
7690: }
7691:
1.1268 raeburn 7692: sub sixnum_code {
7693: my $code;
7694: for (0..6) {
7695: $code .= int( rand(9) );
7696: }
7697: return $code;
7698: }
7699:
1.765 albertel 7700: # -------------------------------------------------- portfolio access checking
7701:
7702: sub portfolio_access {
1.1270 raeburn 7703: my ($requrl,$clientip) = @_;
1.765 albertel 7704: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 7705: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7706: if ($result) {
7707: my %setters;
7708: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1473 raeburn 7709: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7710: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
7711: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7712: return 'B';
7713: }
7714: } else {
1.1473 raeburn 7715: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7716: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7717: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7718: return 'B';
7719: }
7720: }
7721: }
1.765 albertel 7722: if ($result eq 'ok') {
1.766 albertel 7723: return 'F';
1.765 albertel 7724: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7725: return 'A';
1.765 albertel 7726: }
1.766 albertel 7727: return '';
1.765 albertel 7728: }
7729:
7730: sub get_portfolio_access {
1.1270 raeburn 7731: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7732:
7733: if (!ref($access_hash)) {
7734: my $current_perms = &get_portfile_permissions($udom,$unum);
7735: my %access_controls = &get_access_controls($current_perms,$group,
7736: $file_name);
7737: $access_hash = $access_controls{$file_name};
7738: }
7739:
1.1270 raeburn 7740: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7741: my $now = time;
7742: if (ref($access_hash) eq 'HASH') {
7743: foreach my $key (keys(%{$access_hash})) {
7744: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7745: if ($start > $now) {
7746: next;
7747: }
7748: if ($end && $end<$now) {
7749: next;
7750: }
7751: if ($scope eq 'public') {
7752: $public = $key;
7753: last;
7754: } elsif ($scope eq 'guest') {
7755: $guest = $key;
7756: } elsif ($scope eq 'domains') {
7757: push(@domains,$key);
7758: } elsif ($scope eq 'users') {
7759: push(@users,$key);
7760: } elsif ($scope eq 'course') {
7761: push(@courses,$key);
7762: } elsif ($scope eq 'group') {
7763: push(@groups,$key);
1.1270 raeburn 7764: } elsif ($scope eq 'ip') {
7765: push(@ips,$key);
1.765 albertel 7766: }
7767: }
7768: if ($public) {
7769: return 'ok';
1.1270 raeburn 7770: } elsif (@ips > 0) {
7771: my $allowed;
7772: foreach my $ipkey (@ips) {
7773: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7774: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7775: $allowed = 1;
7776: last;
7777: }
7778: }
7779: }
7780: if ($allowed) {
7781: return 'ok';
7782: }
1.765 albertel 7783: }
7784: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7785: if ($guest) {
7786: return $guest;
7787: }
7788: } else {
7789: if (@domains > 0) {
7790: foreach my $domkey (@domains) {
7791: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7792: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7793: return 'ok';
7794: }
7795: }
7796: }
7797: }
7798: if (@users > 0) {
7799: foreach my $userkey (@users) {
1.865 raeburn 7800: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7801: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7802: if (ref($item) eq 'HASH') {
7803: if (($item->{'uname'} eq $env{'user.name'}) &&
7804: ($item->{'udom'} eq $env{'user.domain'})) {
7805: return 'ok';
7806: }
7807: }
7808: }
7809: }
1.765 albertel 7810: }
7811: }
7812: my %roleshash;
7813: my @courses_and_groups = @courses;
7814: push(@courses_and_groups,@groups);
7815: if (@courses_and_groups > 0) {
7816: my (%allgroups,%allroles);
7817: my ($start,$end,$role,$sec,$group);
7818: foreach my $envkey (%env) {
1.1060 raeburn 7819: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7820: my $cid = $2.'_'.$3;
7821: if ($1 eq 'gr') {
7822: $group = $4;
7823: $allgroups{$cid}{$group} = $env{$envkey};
7824: } else {
7825: if ($4 eq '') {
7826: $sec = 'none';
7827: } else {
7828: $sec = $4;
7829: }
7830: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7831: }
1.811 albertel 7832: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7833: my $cid = $2.'_'.$3;
7834: if ($4 eq '') {
7835: $sec = 'none';
7836: } else {
7837: $sec = $4;
7838: }
7839: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7840: }
7841: }
7842: if (keys(%allroles) == 0) {
7843: return;
7844: }
7845: foreach my $key (@courses_and_groups) {
7846: my %content = %{$$access_hash{$key}};
7847: my $cnum = $content{'number'};
7848: my $cdom = $content{'domain'};
7849: my $cid = $cdom.'_'.$cnum;
7850: if (!exists($allroles{$cid})) {
7851: next;
7852: }
7853: foreach my $role_id (keys(%{$content{'roles'}})) {
7854: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7855: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7856: my @status = @{$content{'roles'}{$role_id}{'access'}};
7857: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7858: foreach my $role (keys(%{$allroles{$cid}})) {
7859: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7860: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7861: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7862: if (grep/^all$/,@sections) {
7863: return 'ok';
7864: } else {
7865: if (grep/^$sec$/,@sections) {
7866: return 'ok';
7867: }
7868: }
7869: }
7870: }
7871: if (keys(%{$allgroups{$cid}}) == 0) {
7872: if (grep/^none$/,@groups) {
7873: return 'ok';
7874: }
7875: } else {
7876: if (grep/^all$/,@groups) {
7877: return 'ok';
7878: }
7879: foreach my $group (keys(%{$allgroups{$cid}})) {
7880: if (grep/^$group$/,@groups) {
7881: return 'ok';
7882: }
7883: }
7884: }
7885: }
7886: }
7887: }
7888: }
7889: }
7890: if ($guest) {
7891: return $guest;
7892: }
7893: }
7894: }
7895: return;
7896: }
7897:
7898: sub course_group_datechecker {
7899: my ($dates,$now,$status) = @_;
7900: my ($start,$end) = split(/\./,$dates);
7901: if (!$start && !$end) {
7902: return 'ok';
7903: }
7904: if (grep/^active$/,@{$status}) {
7905: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7906: return 'ok';
7907: }
7908: }
7909: if (grep/^previous$/,@{$status}) {
7910: if ($end > $now ) {
7911: return 'ok';
7912: }
7913: }
7914: if (grep/^future$/,@{$status}) {
7915: if ($start > $now) {
7916: return 'ok';
7917: }
7918: }
7919: return;
7920: }
7921:
7922: sub parse_portfolio_url {
7923: my ($url) = @_;
7924:
7925: my ($type,$udom,$unum,$group,$file_name);
7926:
1.823 albertel 7927: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7928: $type = 1;
7929: $udom = $1;
7930: $unum = $2;
7931: $file_name = $3;
1.823 albertel 7932: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7933: $type = 2;
7934: $udom = $1;
7935: $unum = $2;
7936: $group = $3;
7937: $file_name = $3.'/'.$4;
7938: }
7939: if (wantarray) {
7940: return ($type,$udom,$unum,$file_name,$group);
7941: }
7942: return $type;
7943: }
7944:
7945: sub is_portfolio_url {
7946: my ($url) = @_;
7947: return scalar(&parse_portfolio_url($url));
7948: }
7949:
1.798 raeburn 7950: sub is_portfolio_file {
7951: my ($file) = @_;
1.820 raeburn 7952: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7953: return 1;
7954: }
7955: return;
7956: }
7957:
1.976 raeburn 7958: sub usertools_access {
1.1084 raeburn 7959: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7960: my ($access,%tools);
7961: if ($context eq '') {
7962: $context = 'tools';
7963: }
7964: if ($context eq 'requestcourses') {
7965: %tools = (
7966: official => 1,
7967: unofficial => 1,
1.1006 raeburn 7968: community => 1,
1.1246 raeburn 7969: textbook => 1,
1.1305 raeburn 7970: placement => 1,
1.1368 raeburn 7971: lti => 1,
1.985 raeburn 7972: );
1.1183 raeburn 7973: } elsif ($context eq 'requestauthor') {
7974: %tools = (
7975: requestauthor => 1,
7976: );
1.985 raeburn 7977: } else {
7978: %tools = (
7979: aboutme => 1,
7980: blog => 1,
1.1177 raeburn 7981: webdav => 1,
1.985 raeburn 7982: portfolio => 1,
1.1489 raeburn 7983: timezone => 1,
1.985 raeburn 7984: );
7985: }
1.976 raeburn 7986: return if (!defined($tools{$tool}));
7987:
1.1242 raeburn 7988: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7989: $udom = $env{'user.domain'};
7990: $uname = $env{'user.name'};
7991: }
7992:
1.978 raeburn 7993: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7994: if ($action ne 'reload') {
1.985 raeburn 7995: if ($context eq 'requestcourses') {
7996: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 7997: } elsif ($context eq 'requestauthor') {
7998: return $env{'environment.canrequest.author'};
1.985 raeburn 7999: } else {
8000: return $env{'environment.availabletools.'.$tool};
8001: }
8002: }
1.976 raeburn 8003: }
8004:
1.1183 raeburn 8005: my ($toolstatus,$inststatus,$envkey);
8006: if ($context eq 'requestauthor') {
8007: $envkey = $context;
8008: } else {
8009: $envkey = $context.'.'.$tool;
8010: }
1.976 raeburn 8011:
1.985 raeburn 8012: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8013: ($action ne 'reload')) {
1.1183 raeburn 8014: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 8015: $inststatus = $env{'environment.inststatus'};
8016: } else {
1.1084 raeburn 8017: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 8018: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 8019: $inststatus = $userenvref->{'inststatus'};
8020: } else {
1.1183 raeburn 8021: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
8022: $toolstatus = $userenv{$envkey};
1.1084 raeburn 8023: $inststatus = $userenv{'inststatus'};
8024: }
1.976 raeburn 8025: }
8026:
8027: if ($toolstatus ne '') {
8028: if ($toolstatus) {
8029: $access = 1;
8030: } else {
8031: $access = 0;
8032: }
8033: return $access;
8034: }
8035:
1.1084 raeburn 8036: my ($is_adv,%domdef);
8037: if (ref($is_advref) eq 'HASH') {
8038: $is_adv = $is_advref->{'is_adv'};
8039: } else {
8040: $is_adv = &is_advanced_user($udom,$uname);
8041: }
8042: if (ref($domdefref) eq 'HASH') {
8043: %domdef = %{$domdefref};
8044: } else {
8045: %domdef = &get_domain_defaults($udom);
8046: }
1.976 raeburn 8047: if (ref($domdef{$tool}) eq 'HASH') {
8048: if ($is_adv) {
8049: if ($domdef{$tool}{'_LC_adv'} ne '') {
8050: if ($domdef{$tool}{'_LC_adv'}) {
8051: $access = 1;
8052: } else {
8053: $access = 0;
8054: }
8055: return $access;
8056: }
8057: }
8058: if ($inststatus ne '') {
8059: my ($hasaccess,$hasnoaccess);
8060: foreach my $affiliation (split(/:/,$inststatus)) {
8061: if ($domdef{$tool}{$affiliation} ne '') {
8062: if ($domdef{$tool}{$affiliation}) {
8063: $hasaccess = 1;
8064: } else {
8065: $hasnoaccess = 1;
8066: }
8067: }
8068: }
8069: if ($hasaccess || $hasnoaccess) {
8070: if ($hasaccess) {
8071: $access = 1;
8072: } elsif ($hasnoaccess) {
8073: $access = 0;
8074: }
8075: return $access;
8076: }
8077: } else {
8078: if ($domdef{$tool}{'default'} ne '') {
8079: if ($domdef{$tool}{'default'}) {
8080: $access = 1;
8081: } elsif ($domdef{$tool}{'default'} == 0) {
8082: $access = 0;
8083: }
8084: return $access;
8085: }
8086: }
8087: } else {
1.1177 raeburn 8088: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 8089: $access = 1;
8090: } else {
8091: $access = 0;
8092: }
1.976 raeburn 8093: return $access;
8094: }
8095: }
8096:
1.1050 raeburn 8097: sub is_course_owner {
8098: my ($cdom,$cnum,$udom,$uname) = @_;
8099: if (($udom eq '') || ($uname eq '')) {
8100: $udom = $env{'user.domain'};
8101: $uname = $env{'user.name'};
8102: }
8103: unless (($udom eq '') || ($uname eq '')) {
8104: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
8105: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
8106: return 1;
8107: } else {
1.1494 raeburn 8108: my %courseinfo = &coursedescription($cdom.'/'.$cnum);
1.1050 raeburn 8109: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
8110: return 1;
8111: }
8112: }
8113: }
8114: }
8115: return;
8116: }
8117:
1.976 raeburn 8118: sub is_advanced_user {
8119: my ($udom,$uname) = @_;
1.1085 raeburn 8120: if ($udom ne '' && $uname ne '') {
8121: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 8122: if (wantarray) {
8123: return ($env{'user.adv'},$env{'user.author'});
8124: } else {
8125: return $env{'user.adv'};
8126: }
1.1085 raeburn 8127: }
8128: }
1.976 raeburn 8129: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
8130: my %allroles;
1.1128 raeburn 8131: my ($is_adv,$is_author);
1.976 raeburn 8132: foreach my $role (keys(%roleshash)) {
8133: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
8134: my $area = '/'.$tdomain.'/'.$trest;
8135: if ($sec ne '') {
8136: $area .= '/'.$sec;
8137: }
8138: if (($area ne '') && ($trole ne '')) {
8139: my $spec=$trole.'.'.$area;
8140: if ($trole =~ /^cr\//) {
8141: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
8142: } elsif ($trole ne 'gr') {
8143: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
8144: }
1.1128 raeburn 8145: if ($trole eq 'au') {
8146: $is_author = 1;
8147: }
1.976 raeburn 8148: }
8149: }
8150: foreach my $role (keys(%allroles)) {
8151: last if ($is_adv);
8152: foreach my $item (split(/:/,$allroles{$role})) {
8153: if ($item ne '') {
8154: my ($privilege,$restrictions)=split(/&/,$item);
8155: if ($privilege eq 'adv') {
8156: $is_adv = 1;
8157: last;
8158: }
8159: }
8160: }
8161: }
1.1128 raeburn 8162: if (wantarray) {
8163: return ($is_adv,$is_author);
8164: }
1.976 raeburn 8165: return $is_adv;
8166: }
1.798 raeburn 8167:
1.1035 raeburn 8168: sub check_can_request {
1.1368 raeburn 8169: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035 raeburn 8170: my $canreq = 0;
1.1368 raeburn 8171: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8172: $uname = $env{'user.name'};
8173: $udom = $env{'user.domain'};
8174: }
1.1035 raeburn 8175: my ($types,$typename) = &Apache::loncommon::course_types();
8176: my @options = ('approval','validate','autolimit');
8177: my $optregex = join('|',@options);
8178: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
1.1486 raeburn 8179: my %willtrust;
1.1035 raeburn 8180: foreach my $type (@{$types}) {
1.1368 raeburn 8181: if (&usertools_access($uname,$udom,$type,undef,
8182: 'requestcourses')) {
1.1035 raeburn 8183: $canreq ++;
1.1036 raeburn 8184: if (ref($request_domains) eq 'HASH') {
1.1368 raeburn 8185: push(@{$request_domains->{$type}},$udom);
1.1036 raeburn 8186: }
1.1368 raeburn 8187: if ($dom eq $udom) {
1.1035 raeburn 8188: $can_request->{$type} = 1;
8189: }
8190: }
1.1368 raeburn 8191: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
8192: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035 raeburn 8193: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
8194: if (@curr > 0) {
1.1036 raeburn 8195: foreach my $item (@curr) {
8196: if (ref($request_domains) eq 'HASH') {
8197: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
8198: if ($otherdom ne '') {
1.1486 raeburn 8199: unless (exists($willtrust{$otherdom})) {
8200: $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
8201: }
8202: if ($willtrust{$otherdom}) {
8203: if (ref($request_domains->{$type}) eq 'ARRAY') {
8204: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
8205: push(@{$request_domains->{$type}},$otherdom);
8206: }
8207: } else {
1.1036 raeburn 8208: push(@{$request_domains->{$type}},$otherdom);
8209: }
8210: }
8211: }
8212: }
8213: }
1.1368 raeburn 8214: unless ($dom eq $env{'user.domain'}) {
1.1036 raeburn 8215: $canreq ++;
1.1035 raeburn 8216: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
8217: $can_request->{$type} = 1;
8218: }
8219: }
8220: }
8221: }
8222: }
8223: }
8224: return $canreq;
8225: }
8226:
1.341 www 8227: # ---------------------------------------------- Custom access rule evaluation
8228:
8229: sub customaccess {
8230: my ($priv,$uri)=@_;
1.807 albertel 8231: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 8232: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 8233: $udom = &LONCAPA::clean_domain($udom);
8234: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 8235: my $access=0;
1.800 albertel 8236: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 8237: my ($effect,$realm,$role,$type)=split(/\:/,$right);
8238: if ($type eq 'user') {
8239: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 8240: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 8241: if ($tdom) {
8242: if ($tdom ne $env{'user.domain'}) { next; }
8243: }
1.896 albertel 8244: if ($tuname) {
8245: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 8246: }
8247: $access=($effect eq 'allow');
8248: last;
8249: }
8250: } else {
8251: if ($role) {
8252: if ($role ne $urole) { next; }
8253: }
8254: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8255: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8256: if ($tdom) {
8257: if ($tdom ne $udom) { next; }
8258: }
8259: if ($tcrs) {
8260: if ($tcrs ne $ucrs) { next; }
8261: }
8262: if ($tsec) {
8263: if ($tsec ne $usec) { next; }
8264: }
8265: $access=($effect eq 'allow');
8266: last;
8267: }
8268: if ($realm eq '' && $role eq '') {
8269: $access=($effect eq 'allow');
8270: }
1.402 bowersj2 8271: }
1.341 www 8272: }
8273: return $access;
8274: }
8275:
1.103 harris41 8276: # ------------------------------------------------- Check for a user privilege
1.12 www 8277:
8278: sub allowed {
1.1461 raeburn 8279: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705 albertel 8280: my $ver_orguri=$uri;
1.439 www 8281: $uri=&deversion($uri);
1.152 www 8282: my $orguri=$uri;
1.52 www 8283: $uri=&declutter($uri);
1.809 raeburn 8284:
1.810 raeburn 8285: if ($priv eq 'evb') {
1.1478 raeburn 8286: # Evade communication block restrictions for specified role in a course or domain
1.810 raeburn 8287: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8288: return $1;
8289: } else {
8290: return;
8291: }
8292: }
8293:
1.620 albertel 8294: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 8295: # Free bre access to adm and meta resources
1.1436 raeburn 8296: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$}))
1.769 albertel 8297: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8298: && ($priv eq 'bre')) {
1.14 www 8299: return 'F';
1.159 www 8300: }
8301:
1.545 banghart 8302: # Free bre access to user's own portfolio contents
1.714 raeburn 8303: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 8304: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 8305: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 8306: my %setters;
1.1473 raeburn 8307: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
8308: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
8309: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 8310: return 'B';
8311: } else {
8312: return 'F';
8313: }
1.545 banghart 8314: }
8315:
1.762 raeburn 8316: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 8317: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8318: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8319: if (exists($env{'request.course.id'})) {
8320: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8321: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8322: if (($domain eq $cdom) && ($name eq $cnum)) {
8323: my $courseprivid=$env{'request.course.id'};
8324: $courseprivid=~s/\_/\//;
8325: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8326: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8327: return $1;
1.762 raeburn 8328: } else {
8329: if ($env{'request.course.sec'}) {
8330: $courseprivid.='/'.$env{'request.course.sec'};
8331: }
8332: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8333: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8334: return $2;
8335: }
1.714 raeburn 8336: }
8337: }
8338: }
8339: }
8340:
1.159 www 8341: # Free bre to public access
8342:
8343: if ($priv eq 'bre') {
1.1362 raeburn 8344: my $copyright;
8345: unless ($uri =~ /ext\.tool/) {
8346: $copyright=&metadata($uri,'copyright');
8347: }
1.620 albertel 8348: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 8349: return 'F';
8350: }
1.238 www 8351: if ($copyright eq 'priv') {
8352: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8353: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 8354: return '';
8355: }
8356: }
8357: if ($copyright eq 'domain') {
8358: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8359: unless (($env{'user.domain'} eq $1) ||
8360: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8361: return '';
8362: }
1.262 matthew 8363: }
1.620 albertel 8364: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8365: # Library role, so allow browsing of resources in this domain.
8366: return 'F';
1.238 www 8367: }
1.341 www 8368: if ($copyright eq 'custom') {
8369: unless (&customaccess($priv,$uri)) { return ''; }
8370: }
1.14 www 8371: }
1.264 matthew 8372: # Domain coordinator is trying to create a course
1.620 albertel 8373: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8374: # uri is the requested domain in this case.
8375: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8376: # a role of dc for the domain in question.
1.620 albertel 8377: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8378: }
1.29 www 8379:
1.52 www 8380: my $thisallowed='';
8381: my $statecond=0;
8382: my $courseprivid='';
8383:
1.1039 raeburn 8384: my $ownaccess;
1.1043 raeburn 8385: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8386: if (($priv eq 'bro') && ($env{'user.author'})) {
8387: if ($uri eq '') {
8388: $ownaccess = 1;
8389: } else {
8390: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8391: my $udom = $env{'user.domain'};
8392: my $uname = $env{'user.name'};
8393: if ($uri =~ m{^\Q$udom\E/?$}) {
8394: $ownaccess = 1;
1.1040 raeburn 8395: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8396: unless ($uri =~ m{\.\./}) {
8397: $ownaccess = 1;
8398: }
8399: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8400: my $now = time;
8401: if ($uri =~ m{^([^/]+)/?$}) {
8402: my $adom = $1;
8403: foreach my $key (keys(%env)) {
1.1042 raeburn 8404: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452 raeburn 8405: my ($start,$end) = split(/\./,$env{$key});
8406: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8407: $ownaccess = 1;
8408: last;
8409: }
8410: }
8411: }
8412: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8413: my $adom = $1;
8414: my $aname = $2;
1.1042 raeburn 8415: foreach my $role ('ca','aa') {
8416: if ($env{"user.role.$role./$adom/$aname"}) {
8417: my ($start,$end) =
1.1452 raeburn 8418: split(/\./,$env{"user.role.$role./$adom/$aname"});
8419: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8420: $ownaccess = 1;
8421: last;
8422: }
1.1039 raeburn 8423: }
8424: }
8425: }
8426: }
8427: }
8428: }
8429: }
8430:
1.52 www 8431: # Course
8432:
1.620 albertel 8433: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8434: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8435: $thisallowed.=$1;
8436: }
1.52 www 8437: }
1.29 www 8438:
1.52 www 8439: # Domain
8440:
1.620 albertel 8441: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8442: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8443: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8444: $thisallowed.=$1;
8445: }
1.12 www 8446: }
1.52 www 8447:
1.1141 raeburn 8448: # User who is not author or co-author might still be able to edit
8449: # resource of an author in the domain (e.g., if Domain Coordinator).
8450: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8451: (&allowed('mdc',$env{'request.course.id'}))) {
8452: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8453: $thisallowed.=$1;
8454: }
8455: }
8456:
1.52 www 8457: # Course: uri itself is a course
1.66 www 8458: my $courseuri=$uri;
8459: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8460: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8461:
1.620 albertel 8462: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8463: =~/\Q$priv\E\&([^\:]*)/) {
1.1409 raeburn 8464: if ($priv eq 'mip') {
8465: my $rem = $1;
8466: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8467: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8468: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8469: if ($cdom ne '') {
1.1410 raeburn 8470: my %passwdconf = &get_passwdconf($cdom);
8471: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8472: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8473: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8474: my @inststatuses = split(':',$env{'environment.inststatus'});
8475: unless (@inststatuses) {
8476: @inststatuses = ('default');
8477: }
8478: foreach my $status (@inststatuses) {
8479: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8480: $thisallowed.=$rem;
8481: }
8482: }
8483: }
8484: }
1.1409 raeburn 8485: }
8486: }
8487: }
8488: } else {
8489: unless (($priv eq 'bro') && (!$ownaccess)) {
8490: $thisallowed.=$1;
8491: }
1.1039 raeburn 8492: }
1.12 www 8493: }
1.29 www 8494:
1.665 albertel 8495: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8496: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8497: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8498: $thisallowed='';
1.671 raeburn 8499: my ($match)=&is_on_map($uri);
8500: if ($match) {
8501: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8502: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 8503: my $value = $1;
1.1461 raeburn 8504: my $deeplinkblock;
8505: unless ($nodeeplinkcheck) {
8506: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8507: }
1.1402 raeburn 8508: if ($deeplinkblock) {
8509: $thisallowed='D';
8510: } elsif ($noblockcheck) {
1.1281 raeburn 8511: $thisallowed.=$value;
1.1162 raeburn 8512: } else {
1.1424 raeburn 8513: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8514: if (@blockers > 0) {
8515: $thisallowed = 'B';
8516: } else {
8517: $thisallowed.=$value;
8518: }
1.1162 raeburn 8519: }
1.671 raeburn 8520: }
8521: } else {
1.705 albertel 8522: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8523: if ($refuri) {
8524: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8525: $thisallowed='F';
1.671 raeburn 8526: } else {
8527: $refuri=&declutter($refuri);
8528: my ($match) = &is_on_map($refuri);
8529: if ($match) {
1.1461 raeburn 8530: my $deeplinkblock;
8531: unless ($nodeeplinkcheck) {
8532: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8533: }
1.1402 raeburn 8534: if ($deeplinkblock) {
8535: $thisallowed='D';
8536: } elsif ($noblockcheck) {
1.1281 raeburn 8537: $thisallowed='F';
1.1162 raeburn 8538: } else {
1.1426 raeburn 8539: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8540: if (@blockers > 0) {
8541: $thisallowed = 'B';
8542: } else {
8543: $thisallowed='F';
8544: }
1.1162 raeburn 8545: }
1.671 raeburn 8546: }
1.669 raeburn 8547: }
1.671 raeburn 8548: }
8549: }
1.314 www 8550: }
1.492 albertel 8551:
1.766 albertel 8552: if ($priv eq 'bre'
8553: && $thisallowed ne 'F'
8554: && $thisallowed ne '2'
8555: && &is_portfolio_url($uri)) {
1.1270 raeburn 8556: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8557: }
1.1250 raeburn 8558:
1.52 www 8559: # Full access at system, domain or course-wide level? Exit.
1.29 www 8560: if ($thisallowed=~/F/) {
8561: return 'F';
8562: }
8563:
1.52 www 8564: # If this is generating or modifying users, exit with special codes
1.29 www 8565:
1.643 www 8566: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8567: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8568: my ($audom,$auname)=split('/',$uri);
1.643 www 8569: # no author name given, so this just checks on the general right to make a co-author in this domain
8570: unless ($auname) { return $thisallowed; }
8571: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8572: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8573: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8574: ($audom ne $env{'request.role.domain'}))) { return ''; }
8575: }
1.52 www 8576: return $thisallowed;
8577: }
8578: #
1.103 harris41 8579: # Gathered so far: system, domain and course wide privileges
1.52 www 8580: #
8581: # Course: See if uri or referer is an individual resource that is part of
8582: # the course
8583:
1.620 albertel 8584: if ($env{'request.course.id'}) {
1.232 www 8585:
1.1409 raeburn 8586: # If this is modifying password (internal auth) domains must match for user and user's role.
8587:
8588: if ($priv eq 'mip') {
8589: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8590: return $thisallowed;
8591: } else {
8592: return '';
8593: }
8594: }
8595:
1.620 albertel 8596: $courseprivid=$env{'request.course.id'};
8597: if ($env{'request.course.sec'}) {
8598: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8599: }
8600: $courseprivid=~s/\_/\//;
8601: my $checkreferer=1;
1.232 www 8602: my ($match,$cond)=&is_on_map($uri);
8603: if ($match) {
8604: $statecond=$cond;
1.620 albertel 8605: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8606: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8607: my $value = $1;
8608: if ($priv eq 'bre') {
1.1461 raeburn 8609: my $deeplinkblock;
8610: unless ($nodeeplinkcheck) {
8611: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8612: }
1.1458 raeburn 8613: if ($deeplinkblock) {
8614: $thisallowed = 'D';
8615: } elsif ($noblockcheck) {
1.1281 raeburn 8616: $thisallowed.=$value;
1.1162 raeburn 8617: } else {
1.1424 raeburn 8618: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8619: if (@blockers > 0) {
8620: $thisallowed = 'B';
8621: } else {
8622: $thisallowed.=$value;
8623: }
1.1162 raeburn 8624: }
8625: } else {
8626: $thisallowed.=$value;
8627: }
1.52 www 8628: $checkreferer=0;
8629: }
1.29 www 8630: }
1.1424 raeburn 8631:
1.148 www 8632: if ($checkreferer) {
1.620 albertel 8633: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8634: unless ($refuri) {
1.800 albertel 8635: foreach my $key (keys(%env)) {
8636: if ($key=~/^httpref\..*\*/) {
8637: my $pattern=$key;
1.156 www 8638: $pattern=~s/^httpref\.\/res\///;
1.148 www 8639: $pattern=~s/\*/\[\^\/\]\+/g;
8640: $pattern=~s/\//\\\//g;
1.152 www 8641: if ($orguri=~/$pattern/) {
1.800 albertel 8642: $refuri=$env{$key};
1.148 www 8643: }
8644: }
1.191 harris41 8645: }
1.148 www 8646: }
1.232 www 8647:
1.148 www 8648: if ($refuri) {
1.152 www 8649: $refuri=&declutter($refuri);
1.232 www 8650: my ($match,$cond)=&is_on_map($refuri);
8651: if ($match) {
8652: my $refstatecond=$cond;
1.620 albertel 8653: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8654: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8655: my $value = $1;
8656: if ($priv eq 'bre') {
1.1461 raeburn 8657: my $deeplinkblock;
8658: unless ($nodeeplinkcheck) {
8659: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8660: }
1.1402 raeburn 8661: if ($deeplinkblock) {
8662: $thisallowed = 'D';
8663: } elsif ($noblockcheck) {
1.1281 raeburn 8664: $thisallowed.=$value;
1.1162 raeburn 8665: } else {
1.1426 raeburn 8666: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8667: if (@blockers > 0) {
8668: $thisallowed = 'B';
8669: } else {
8670: $thisallowed.=$value;
8671: }
1.1162 raeburn 8672: }
8673: } else {
8674: $thisallowed.=$value;
8675: }
1.53 www 8676: $uri=$refuri;
8677: $statecond=$refstatecond;
1.52 www 8678: }
8679: }
1.148 www 8680: }
1.29 www 8681: }
1.52 www 8682: }
1.29 www 8683:
1.52 www 8684: #
1.103 harris41 8685: # Gathered now: all privileges that could apply, and condition number
1.52 www 8686: #
8687: #
8688: # Full or no access?
8689: #
1.29 www 8690:
1.52 www 8691: if ($thisallowed=~/F/) {
8692: return 'F';
8693: }
1.29 www 8694:
1.52 www 8695: unless ($thisallowed) {
8696: return '';
8697: }
1.29 www 8698:
1.52 www 8699: # Restrictions exist, deal with them
8700: #
8701: # C:according to course preferences
8702: # R:according to resource settings
8703: # L:unless locked
8704: # X:according to user session state
8705: #
8706:
8707: # Possibly locked functionality, check all courses
1.1454 raeburn 8708: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 8709: # Locks might take effect only after 10 minutes cache expiration for other
1.1454 raeburn 8710: # courses, and 2 minutes for current course, in which user has st or ta role
8711: # which is neither expired nor a future role (unless current course).
1.52 www 8712:
1.1454 raeburn 8713: my ($needlockcheck,$now,$crsonly);
1.52 www 8714: if ($thisallowed=~/L/) {
1.1454 raeburn 8715: $now = time;
8716: if ($priv eq 'bre') {
8717: if ($uri ne '') {
8718: if ($orguri =~ m{^/+res/}) {
8719: if ($uri =~ m{^lib/templates/}) {
8720: if ($env{'request.course.id'}) {
8721: $crsonly = 1;
8722: $needlockcheck = 1;
8723: }
8724: } else {
8725: $needlockcheck = 1;
8726: }
8727: } elsif ($env{'request.course.id'}) {
8728: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8729: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8730: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8731: $crsonly = 1;
8732: }
8733: $needlockcheck = 1;
8734: }
8735: }
8736: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8737: $needlockcheck = 1;
8738: }
8739: }
8740: if ($needlockcheck) {
1.1453 raeburn 8741: foreach my $envkey (keys(%env)) {
1.54 www 8742: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8743: my $courseid=$2;
8744: my $roleid=$1.'.'.$2;
1.92 www 8745: $courseid=~s/^\///;
1.1453 raeburn 8746: unless ($env{'request.role'} eq $roleid) {
8747: my ($start,$end) = split(/\./,$env{$envkey});
8748: next unless (($now >= $start) && (!$end || $end > $now));
8749: }
1.54 www 8750: my $expiretime=600;
1.620 albertel 8751: if ($env{'request.role'} eq $roleid) {
1.54 www 8752: $expiretime=120;
8753: }
8754: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8755: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8756: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8757: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8758: }
1.620 albertel 8759: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8760: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8761: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8762: &log($env{'user.domain'},$env{'user.name'},
8763: $env{'user.home'},
1.57 www 8764: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8765: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8766: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8767: return '';
8768: }
8769: }
1.620 albertel 8770: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8771: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455 raeburn 8772: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 8773: &log($env{'user.domain'},$env{'user.name'},
8774: $env{'user.home'},
1.57 www 8775: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8776: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8777: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8778: return '';
8779: }
8780: }
8781: }
1.29 www 8782: }
1.52 www 8783: }
1.1424 raeburn 8784:
1.52 www 8785: #
8786: # Rest of the restrictions depend on selected course
8787: #
8788:
1.620 albertel 8789: unless ($env{'request.course.id'}) {
1.766 albertel 8790: if ($thisallowed eq 'A') {
8791: return 'A';
1.814 raeburn 8792: } elsif ($thisallowed eq 'B') {
8793: return 'B';
1.766 albertel 8794: } else {
8795: return '1';
8796: }
1.52 www 8797: }
1.29 www 8798:
1.52 www 8799: #
8800: # Now user is definitely in a course
8801: #
1.53 www 8802:
8803:
8804: # Course preferences
8805:
8806: if ($thisallowed=~/C/) {
1.620 albertel 8807: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8808: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8809: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8810: =~/\Q$rolecode\E/) {
1.1304 raeburn 8811: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8812: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8813: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8814: $env{'request.course.id'});
8815: }
1.237 www 8816: return '';
8817: }
8818:
1.620 albertel 8819: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8820: =~/\Q$unamedom\E/) {
1.1304 raeburn 8821: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8822: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8823: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8824: $env{'request.course.id'});
8825: }
1.54 www 8826: return '';
8827: }
1.53 www 8828: }
8829:
8830: # Resource preferences
8831:
8832: if ($thisallowed=~/R/) {
1.620 albertel 8833: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8834: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8835: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8836: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8837: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8838: }
8839: return '';
1.54 www 8840: }
1.53 www 8841: }
1.30 www 8842:
1.1461 raeburn 8843: # Restricted for deeplinked session?
8844:
8845: if ($env{'request.deeplink.login'}) {
8846: if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
8847: if (!$symb) { $symb=&symbread($uri,1); }
8848: if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
8849: return '';
8850: }
8851: }
8852: }
8853:
1.246 www 8854: # Restricted by state or randomout?
1.30 www 8855:
1.52 www 8856: if ($thisallowed=~/X/) {
1.620 albertel 8857: if ($env{'acc.randomout'}) {
1.579 albertel 8858: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8859: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8860: return '';
8861: }
1.247 www 8862: }
8863: if (&condval($statecond)) {
1.52 www 8864: return '2';
8865: } else {
8866: return '';
8867: }
8868: }
1.30 www 8869:
1.766 albertel 8870: if ($thisallowed eq 'A') {
8871: return 'A';
1.814 raeburn 8872: } elsif ($thisallowed eq 'B') {
8873: return 'B';
1.1402 raeburn 8874: } elsif ($thisallowed eq 'D') {
8875: return 'D';
1.766 albertel 8876: }
1.52 www 8877: return 'F';
1.232 www 8878: }
1.1162 raeburn 8879:
1.1192 raeburn 8880: # ------------------------------------------- Check construction space access
8881:
8882: sub constructaccess {
8883: my ($url,$setpriv)=@_;
8884:
8885: # We do not allow editing of previous versions of files
8886: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8887:
8888: # Get username and domain from URL
8889: my ($ownername,$ownerdomain,$ownerhome);
8890:
8891: ($ownerdomain,$ownername) =
1.1325 raeburn 8892: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 8893:
8894: # The URL does not really point to any authorspace, forget it
8895: unless (($ownername) && ($ownerdomain)) { return ''; }
8896:
8897: # Now we need to see if the user has access to the authorspace of
8898: # $ownername at $ownerdomain
8899:
8900: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8901: # Real author for this?
8902: $ownerhome = $env{'user.home'};
8903: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8904: return ($ownername,$ownerdomain,$ownerhome);
8905: }
8906: } else {
8907: # Co-author for this?
8908: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8909: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8910: $ownerhome = &homeserver($ownername,$ownerdomain);
8911: return ($ownername,$ownerdomain,$ownerhome);
8912: }
1.1312 raeburn 8913: if ($env{'request.course.id'}) {
8914: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
8915: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
8916: if (&allowed('mdc',$env{'request.course.id'})) {
8917: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
8918: return ($ownername,$ownerdomain,$ownerhome);
8919: }
8920: }
8921: }
1.1192 raeburn 8922: }
8923:
8924: # We don't have any access right now. If we are not possibly going to do anything about this,
8925: # we might as well leave
8926: unless ($setpriv) { return ''; }
8927:
8928: # Backdoor access?
8929: my $allowed=&allowed('eco',$ownerdomain);
8930: # Nope
8931: unless ($allowed) { return ''; }
8932: # Looks like we may have access, but could be locked by the owner of the construction space
8933: if ($allowed eq 'U') {
8934: my %blocked=&get('environment',['domcoord.author'],
8935: $ownerdomain,$ownername);
8936: # Is blocked by owner
8937: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8938: }
8939: if (($allowed eq 'F') || ($allowed eq 'U')) {
8940: # Grant temporary access
8941: my $then=$env{'user.login.time'};
1.1209 raeburn 8942: my $update=$env{'user.update.time'};
1.1192 raeburn 8943: if (!$update) { $update = $then; }
8944: my $refresh=$env{'user.refresh.time'};
8945: if (!$refresh) { $refresh = $update; }
8946: my $now = time;
8947: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8948: $now,'ca','constructaccess');
8949: $ownerhome = &homeserver($ownername,$ownerdomain);
8950: return($ownername,$ownerdomain,$ownerhome);
8951: }
8952: # No business here
8953: return '';
8954: }
8955:
1.1282 raeburn 8956: # ----------------------------------------------------------- Content Blocking
8957:
8958: {
8959: # Caches for faster Course Contents display where content blocking
8960: # is in operation (i.e., interval param set) for timed quiz.
8961: #
8962: # User for whom data are being temporarily cached.
8963: my $cacheduser='';
1.1424 raeburn 8964: # Course for which data are being temporarily cached.
8965: my $cachedcid='';
1.1282 raeburn 8966: # Cached blockers for this user (a hash of blocking items).
8967: my %cachedblockers=();
8968: # When the data were last cached.
8969: my $cachedlast='';
8970:
8971: sub load_all_blockers {
1.1427 raeburn 8972: my ($uname,$udom)=@_;
1.1282 raeburn 8973: if (($uname ne '') && ($udom ne '')) {
8974: if (($cacheduser eq $uname.':'.$udom) &&
1.1424 raeburn 8975: ($cachedcid eq $env{'request.course.id'}) &&
1.1427 raeburn 8976: (abs($cachedlast-time)<5)) {
1.1282 raeburn 8977: return;
8978: }
8979: }
8980: $cachedlast=time;
8981: $cacheduser=$uname.':'.$udom;
1.1424 raeburn 8982: $cachedcid=$env{'request.course.id'};
1.1427 raeburn 8983: %cachedblockers = &get_commblock_resources();
1.1424 raeburn 8984: return;
1.1282 raeburn 8985: }
8986:
1.1162 raeburn 8987: sub get_comm_blocks {
8988: my ($cdom,$cnum) = @_;
8989: if ($cdom eq '' || $cnum eq '') {
8990: return unless ($env{'request.course.id'});
8991: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8992: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8993: }
8994: my %commblocks;
8995: my $hashid=$cdom.'_'.$cnum;
8996: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8997: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8998: %commblocks = %{$blocksref};
8999: } else {
1.1494 raeburn 9000: %commblocks = &dump('comm_block',$cdom,$cnum);
1.1162 raeburn 9001: my $cachetime = 600;
9002: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
9003: }
9004: return %commblocks;
9005: }
9006:
1.1282 raeburn 9007: sub get_commblock_resources {
9008: my ($blocks) = @_;
9009: my %blockers = ();
9010: return %blockers unless ($env{'request.course.id'});
1.1470 raeburn 9011: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9012: if ($env{'request.course.sec'}) {
9013: $courseurl .= '/'.$env{'request.course.sec'};
9014: }
9015: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162 raeburn 9016: my %commblocks;
9017: if (ref($blocks) eq 'HASH') {
9018: %commblocks = %{$blocks};
9019: } else {
9020: %commblocks = &get_comm_blocks();
9021: }
1.1282 raeburn 9022: return %blockers unless (keys(%commblocks) > 0);
9023: my $navmap = Apache::lonnavmaps::navmap->new();
9024: return %blockers unless (ref($navmap));
1.1162 raeburn 9025: my $now = time;
9026: foreach my $block (keys(%commblocks)) {
9027: if ($block =~ /^(\d+)____(\d+)$/) {
9028: my ($start,$end) = ($1,$2);
9029: if ($start <= $now && $end >= $now) {
9030: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
9031: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
9032: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 9033: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9034: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 9035: }
9036: }
9037: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 9038: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9039: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 9040: }
9041: }
9042: }
9043: }
9044: }
9045: } elsif ($block =~ /^firstaccess____(.+)$/) {
9046: my $item = $1;
9047: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
9048: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1471 raeburn 9049: my (@interval,$mapname);
1.1282 raeburn 9050: my $type = 'map';
9051: if ($item eq 'course') {
9052: $type = 'course';
9053: @interval=&EXT("resource.0.interval");
9054: } else {
9055: if ($item =~ /___\d+___/) {
9056: $type = 'resource';
9057: @interval=&EXT("resource.0.interval",$item);
1.1162 raeburn 9058: } else {
1.1471 raeburn 9059: $mapname = &deversion($item);
9060: if (ref($navmap)) {
9061: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
9062: @interval = ($timelimit,'map');
1.1162 raeburn 9063: }
9064: }
1.1282 raeburn 9065: }
1.1310 raeburn 9066: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 9067: my $timelimit = $1;
1.1282 raeburn 9068: my $first_access;
9069: if ($type eq 'resource') {
9070: $first_access=&get_first_access($interval[1],$item);
9071: } elsif ($type eq 'map') {
9072: $first_access=&get_first_access($interval[1],undef,$item);
9073: } else {
9074: $first_access=&get_first_access($interval[1]);
9075: }
9076: if ($first_access) {
1.1292 raeburn 9077: my $timesup = $first_access+$timelimit;
1.1282 raeburn 9078: if ($timesup > $now) {
9079: my $activeblock;
1.1471 raeburn 9080: if ($type eq 'resource') {
9081: if (ref($navmap)) {
9082: my $res = $navmap->getBySymb($item);
9083: if ($res->answerable()) {
9084: $activeblock = 1;
9085: }
9086: }
9087: } elsif ($type eq 'map') {
9088: my $mapsymb = &symbread($mapname,1);
9089: if (($mapsymb) && (ref($navmap))) {
9090: my $mapres = $navmap->getBySymb($mapsymb);
9091: if (ref($mapres)) {
9092: my $first = $mapres->map_start();
9093: my $finish = $mapres->map_finish();
9094: my $it = $navmap->getIterator($first,$finish,undef,0,0);
9095: if (ref($it)) {
9096: my $res;
9097: while ($res = $it->next(undef,1)) {
9098: next unless (ref($res));
9099: my $symb = $res->symb();
9100: next if (($symb eq $mapsymb) || ($symb eq ''));
9101: @interval=&EXT("resource.0.interval",$symb);
9102: if ($interval[1] eq 'map') {
9103: if ($res->answerable()) {
9104: $activeblock = 1;
9105: last;
9106: }
9107: }
9108: }
9109: }
9110: }
1.1282 raeburn 9111: }
9112: }
9113: if ($activeblock) {
9114: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
9115: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9116: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
9117: }
9118: }
9119: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
9120: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9121: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 9122: }
1.1162 raeburn 9123: }
9124: }
9125: }
9126: }
9127: }
9128: }
9129: }
9130: }
9131: }
1.1282 raeburn 9132: return %blockers;
1.1162 raeburn 9133: }
9134:
1.1282 raeburn 9135: sub has_comm_blocking {
1.1427 raeburn 9136: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282 raeburn 9137: my @blockers;
9138: return unless ($env{'request.course.id'});
9139: return unless ($priv eq 'bre');
9140: return if ($env{'request.state'} eq 'construct');
1.1470 raeburn 9141: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9142: if ($env{'request.course.sec'}) {
9143: $courseurl .= '/'.$env{'request.course.sec'};
9144: }
9145: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1427 raeburn 9146: my %blockinfo;
9147: if (ref($blocks) eq 'HASH') {
9148: %blockinfo = &get_commblock_resources($blocks);
9149: } else {
9150: &load_all_blockers($env{'user.name'},$env{'user.domain'});
9151: %blockinfo = %cachedblockers;
9152: }
9153: return unless (keys(%blockinfo) > 0);
1.1282 raeburn 9154: my (%possibles,@symbs);
9155: if (!$symb) {
1.1427 raeburn 9156: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 9157: }
1.1282 raeburn 9158: if ($symb) {
9159: @symbs = ($symb);
9160: } elsif (keys(%possibles)) {
9161: @symbs = keys(%possibles);
9162: }
9163: my $noblock;
9164: foreach my $symb (@symbs) {
9165: last if ($noblock);
9166: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427 raeburn 9167: foreach my $block (keys(%blockinfo)) {
1.1282 raeburn 9168: if ($block =~ /^firstaccess____(.+)$/) {
9169: my $item = $1;
1.1424 raeburn 9170: unless ($blocked) {
9171: if (($item eq $map) || ($item eq $symb)) {
9172: $noblock = 1;
9173: last;
9174: }
1.1282 raeburn 9175: }
9176: }
1.1427 raeburn 9177: if (ref($blockinfo{$block}) eq 'HASH') {
9178: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
9179: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282 raeburn 9180: unless (grep(/^\Q$block\E$/,@blockers)) {
9181: push(@blockers,$block);
9182: }
9183: }
9184: }
1.1427 raeburn 9185: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
9186: if ($blockinfo{$block}{'maps'}{$map}) {
1.1424 raeburn 9187: unless (grep(/^\Q$block\E$/,@blockers)) {
9188: push(@blockers,$block);
9189: }
1.1282 raeburn 9190: }
9191: }
1.1162 raeburn 9192: }
9193: }
9194: }
1.1424 raeburn 9195: unless ($noblock) {
9196: return @blockers;
9197: }
9198: return;
1.1282 raeburn 9199: }
1.1162 raeburn 9200: }
9201:
1.1402 raeburn 9202: sub deeplink_check {
9203: my ($priv,$symb,$uri) = @_;
9204: return unless ($env{'request.course.id'});
9205: return unless ($priv eq 'bre');
9206: return if ($env{'request.state'} eq 'construct');
9207: return if ($env{'request.role.adv'});
9208: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9209: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9210: my (%possibles,@symbs);
9211: if (!$symb) {
9212: $symb = &symbread($uri,1,1,1,\%possibles);
9213: }
9214: if ($symb) {
9215: @symbs = ($symb);
9216: } elsif (keys(%possibles)) {
9217: @symbs = keys(%possibles);
9218: }
9219:
1.1461 raeburn 9220: my ($deeplink_symb,$allow);
9221: if ($env{'request.deeplink.login'}) {
9222: $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1.1402 raeburn 9223: }
9224: foreach my $symb (@symbs) {
9225: last if ($allow);
9226: my $deeplink = &EXT("resource.0.deeplink",$symb);
9227: if ($deeplink eq '') {
9228: $allow = 1;
9229: } else {
1.1463 raeburn 9230: my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
9231: if ($state ne 'only') {
1.1402 raeburn 9232: $allow = 1;
1.1463 raeburn 9233: } else {
9234: my $check_deeplink_entry;
9235: if ($protect ne 'none') {
9236: my ($acctype,$item) = split(/:/,$protect);
9237: if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
9238: if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
9239: $check_deeplink_entry = 1
9240: }
9241: } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
9242: if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
9243: $check_deeplink_entry = 1;
9244: }
9245: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
9246: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
9247: $check_deeplink_entry = 1;
9248: }
9249: }
9250: }
9251: if (($protect eq 'none') || ($check_deeplink_entry)) {
1.1402 raeburn 9252: if ($scope eq 'res') {
1.1461 raeburn 9253: if ($symb eq $deeplink_symb) {
1.1402 raeburn 9254: $allow = 1;
9255: }
1.1459 raeburn 9256: } elsif (($scope eq 'map') || ($scope eq 'rec')) {
1.1463 raeburn 9257: my ($map_from_symb,$map_from_login);
1.1461 raeburn 9258: $map_from_symb = &deversion((&decode_symb($symb))[0]);
9259: if ($deeplink_symb =~ /\.(page|sequence)$/) {
9260: $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
9261: } else {
9262: $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
9263: }
1.1459 raeburn 9264: if (($map_from_symb) && ($map_from_login)) {
9265: if ($map_from_symb eq $map_from_login) {
9266: $allow = 1;
9267: } elsif ($scope eq 'rec') {
9268: my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
9269: if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
9270: $allow = 1;
9271: }
9272: }
9273: }
1.1402 raeburn 9274: }
9275: }
9276: }
9277: }
9278: }
9279: return if ($allow);
9280: return 1;
9281: }
9282:
1.1282 raeburn 9283: # -------------------------------- Deversion and split uri into path an filename
9284:
1.1133 foxr 9285: #
1.1282 raeburn 9286: # Removes the version from a URI and
1.1133 foxr 9287: # splits it in to its filename and path to the filename.
9288: # Seems like File::Basename could have done this more clearly.
9289: # Parameters:
9290: # $uri - input URI
9291: # Returns:
9292: # Two element list consisting of
9293: # $pathname - the URI up to and excluding the trailing /
9294: # $filename - The part of the URI following the last /
9295: # NOTE:
9296: # Another realization of this is simply:
9297: # use File::Basename;
9298: # ...
9299: # $uri = shift;
9300: # $filename = basename($uri);
9301: # $path = dirname($uri);
9302: # return ($filename, $path);
9303: #
9304: # The implementation below is probably faster however.
9305: #
1.710 albertel 9306: sub split_uri_for_cond {
9307: my $uri=&deversion(&declutter(shift));
9308: my @uriparts=split(/\//,$uri);
9309: my $filename=pop(@uriparts);
9310: my $pathname=join('/',@uriparts);
9311: return ($pathname,$filename);
9312: }
1.232 www 9313: # --------------------------------------------------- Is a resource on the map?
9314:
9315: sub is_on_map {
1.710 albertel 9316: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 9317: #Trying to find the conditional for the file
1.620 albertel 9318: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 9319: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 9320: if ($match) {
1.289 bowersj2 9321: return (1,$1);
9322: } else {
1.434 www 9323: return (0,0);
1.289 bowersj2 9324: }
1.12 www 9325: }
9326:
1.427 www 9327: # --------------------------------------------------------- Get symb from alias
9328:
9329: sub get_symb_from_alias {
9330: my $symb=shift;
9331: my ($map,$resid,$url)=&decode_symb($symb);
9332: # Already is a symb
9333: if ($url) { return $symb; }
9334: # Must be an alias
9335: my $aliassymb='';
9336: my %bighash;
1.620 albertel 9337: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 9338: &GDBM_READER(),0640)) {
9339: my $rid=$bighash{'mapalias_'.$symb};
9340: if ($rid) {
9341: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 9342: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9343: $resid,$bighash{'src_'.$rid});
1.427 www 9344: }
9345: untie %bighash;
9346: }
9347: return $aliassymb;
9348: }
9349:
1.12 www 9350: # ----------------------------------------------------------------- Define Role
9351:
9352: sub definerole {
9353: if (allowed('mcr','/')) {
1.1326 raeburn 9354: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 9355: foreach my $role (split(':',$sysrole)) {
9356: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9357: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9358: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9359: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9360: return "refused:s:$crole&$cqual";
9361: }
9362: }
1.191 harris41 9363: }
1.800 albertel 9364: foreach my $role (split(':',$domrole)) {
9365: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9366: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9367: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9368: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 9369: return "refused:d:$crole&$cqual";
9370: }
9371: }
1.191 harris41 9372: }
1.800 albertel 9373: foreach my $role (split(':',$courole)) {
9374: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9375: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9376: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9377: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9378: return "refused:c:$crole&$cqual";
9379: }
9380: }
1.191 harris41 9381: }
1.1326 raeburn 9382: my $uhome;
9383: if (($uname ne '') && ($udom ne '')) {
9384: $uhome = &homeserver($uname,$udom);
9385: return $uhome if ($uhome eq 'no_host');
9386: } else {
9387: $uname = $env{'user.name'};
9388: $udom = $env{'user.domain'};
9389: $uhome = $env{'user.home'};
9390: }
1.620 albertel 9391: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 9392: "$udom:$uname:rolesdef_$rolename=".
1.21 www 9393: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 9394: return reply($command,$uhome);
1.12 www 9395: } else {
9396: return 'refused';
9397: }
1.105 harris41 9398: }
9399:
9400: # ---------------- Make a metadata query against the network of library servers
9401:
9402: sub metadata_query {
1.1237 raeburn 9403: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 9404: my %rhash;
1.845 albertel 9405: my %libserv = &all_library();
1.244 matthew 9406: my @server_list = (defined($server_array) ? @$server_array
9407: : keys(%libserv) );
9408: for my $server (@server_list) {
1.1237 raeburn 9409: my $domains = '';
9410: if (ref($domains_hash) eq 'HASH') {
9411: $domains = $domains_hash->{$server};
9412: }
1.118 harris41 9413: unless ($custom or $customshow) {
1.1237 raeburn 9414: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 9415: $rhash{$server}=$reply;
9416: }
9417: else {
9418: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 9419: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 9420: $server);
9421: $rhash{$server}=$reply;
9422: }
1.112 harris41 9423: }
1.118 harris41 9424: return \%rhash;
1.240 www 9425: }
9426:
9427: # ----------------------------------------- Send log queries and wait for reply
9428:
9429: sub log_query {
9430: my ($uname,$udom,$query,%filters)=@_;
9431: my $uhome=&homeserver($uname,$udom);
9432: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 9433: my $uhost=&hostname($uhome);
1.800 albertel 9434: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 9435: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9436: $uhome);
1.479 albertel 9437: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 9438: return get_query_reply($queryid);
9439: }
9440:
1.818 raeburn 9441: # -------------------------- Update MySQL table for portfolio file
9442:
9443: sub update_portfolio_table {
1.821 raeburn 9444: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 9445: if ($group ne '') {
9446: $file_name =~s /^\Q$group\E//;
9447: }
1.818 raeburn 9448: my $homeserver = &homeserver($uname,$udom);
9449: my $queryid=
1.821 raeburn 9450: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9451: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 9452: my $reply = &get_query_reply($queryid);
9453: return $reply;
9454: }
9455:
1.899 raeburn 9456: # -------------------------- Update MySQL allusers table
9457:
9458: sub update_allusers_table {
9459: my ($uname,$udom,$names) = @_;
9460: my $homeserver = &homeserver($uname,$udom);
9461: my $queryid=
9462: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9463: 'lastname='.&escape($names->{'lastname'}).'%%'.
9464: 'firstname='.&escape($names->{'firstname'}).'%%'.
9465: 'middlename='.&escape($names->{'middlename'}).'%%'.
9466: 'generation='.&escape($names->{'generation'}).'%%'.
9467: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9468: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 9469: return;
1.899 raeburn 9470: }
9471:
1.508 raeburn 9472: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 9473:
9474: sub fetch_enrollment_query {
1.511 raeburn 9475: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 9476: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 9477: my $maxtries = 1;
1.508 raeburn 9478: if ($context eq 'automated') {
9479: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 9480: $sleep = 2;
9481: $loopmax = 100;
1.547 raeburn 9482: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 9483: } else {
9484: $homeserver = &homeserver($cnum,$dom);
9485: }
1.838 albertel 9486: my $host=&hostname($homeserver);
1.506 raeburn 9487: my $cmd = '';
1.1000 raeburn 9488: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9489: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9490: }
9491: $cmd =~ s/%%$//;
9492: $cmd = &escape($cmd);
9493: my $query = 'fetchenrollment';
1.620 albertel 9494: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9495: unless ($queryid=~/^\Q$host\E\_/) {
9496: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9497: return 'error: '.$queryid;
9498: }
1.1317 raeburn 9499: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9500: my $tries = 1;
9501: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 9502: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9503: $tries ++;
9504: }
1.526 raeburn 9505: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9506: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9507: } else {
1.901 albertel 9508: my @responses = split(/:/,$reply);
1.1322 raeburn 9509: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9510: foreach my $line (@responses) {
9511: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9512: $$replyref{$key} = $value;
9513: }
9514: } else {
1.1117 foxr 9515: my $pathname = LONCAPA::tempdir();
1.800 albertel 9516: foreach my $line (@responses) {
9517: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9518: $$replyref{$key} = $value;
9519: if ($value > 0) {
1.800 albertel 9520: foreach my $item (@{$$affiliatesref{$key}}) {
9521: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9522: my $destname = $pathname.'/'.$filename;
9523: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9524: if ($xml_classlist =~ /^error/) {
9525: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9526: } else {
1.1359 raeburn 9527: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9528: print FILE &unescape($xml_classlist);
9529: close(FILE);
1.526 raeburn 9530: } else {
9531: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9532: }
9533: }
9534: }
9535: }
9536: }
9537: }
9538: return 'ok';
9539: }
9540: return 'error';
9541: }
9542:
1.242 www 9543: sub get_query_reply {
1.1471 raeburn 9544: my ($queryid,$sleep,$loopmax) = @_;
1.1317 raeburn 9545: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9546: $sleep = 0.2;
9547: }
9548: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9549: $loopmax = 100;
9550: }
1.1117 foxr 9551: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9552: my $reply='';
1.1317 raeburn 9553: for (1..$loopmax) {
9554: sleep($sleep);
1.240 www 9555: if (-e $replyfile.'.end') {
1.1359 raeburn 9556: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9557: $reply = join('',<$fh>);
9558: close($fh);
1.240 www 9559: } else { return 'error: reply_file_error'; }
1.242 www 9560: return &unescape($reply);
9561: }
1.240 www 9562: }
1.242 www 9563: return 'timeout:'.$queryid;
1.240 www 9564: }
9565:
9566: sub courselog_query {
1.241 www 9567: #
9568: # possible filters:
9569: # url: url or symb
9570: # username
9571: # domain
9572: # action: view, submit, grade
9573: # start: timestamp
9574: # end: timestamp
9575: #
1.240 www 9576: my (%filters)=@_;
1.620 albertel 9577: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9578: if ($filters{'url'}) {
9579: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9580: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9581: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9582: }
1.620 albertel 9583: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9584: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9585: return &log_query($cname,$cdom,'courselog',%filters);
9586: }
9587:
9588: sub userlog_query {
1.858 raeburn 9589: #
9590: # possible filters:
9591: # action: log check role
9592: # start: timestamp
9593: # end: timestamp
9594: #
1.240 www 9595: my ($uname,$udom,%filters)=@_;
9596: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9597: }
9598:
1.506 raeburn 9599: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9600:
9601: sub auto_run {
1.508 raeburn 9602: my ($cnum,$cdom) = @_;
1.876 raeburn 9603: my $response = 0;
9604: my $settings;
9605: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9606: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9607: $settings = $domconfig{'autoenroll'};
9608: if ($settings->{'run'} eq '1') {
9609: $response = 1;
9610: }
9611: } else {
1.934 raeburn 9612: my $homeserver;
9613: if (&is_course($cdom,$cnum)) {
9614: $homeserver = &homeserver($cnum,$cdom);
9615: } else {
9616: $homeserver = &domain($cdom,'primary');
9617: }
9618: if ($homeserver ne 'no_host') {
9619: $response = &reply('autorun:'.$cdom,$homeserver);
9620: }
1.876 raeburn 9621: }
1.506 raeburn 9622: return $response;
9623: }
1.776 albertel 9624:
1.506 raeburn 9625: sub auto_get_sections {
1.508 raeburn 9626: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9627: my $homeserver;
9628: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9629: $homeserver = &homeserver($cnum,$cdom);
9630: }
9631: if (!defined($homeserver)) {
9632: if ($cdom =~ /^$match_domain$/) {
9633: $homeserver = &domain($cdom,'primary');
9634: }
9635: }
9636: my @secs;
9637: if (defined($homeserver)) {
9638: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9639: unless ($response eq 'refused') {
9640: @secs = split(/:/,$response);
9641: }
1.506 raeburn 9642: }
9643: return @secs;
9644: }
1.776 albertel 9645:
1.506 raeburn 9646: sub auto_new_course {
1.1099 raeburn 9647: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9648: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9649: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9650: return $response;
9651: }
1.776 albertel 9652:
1.506 raeburn 9653: sub auto_validate_courseID {
1.508 raeburn 9654: my ($cnum,$cdom,$inst_course_id) = @_;
9655: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9656: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9657: return $response;
9658: }
1.776 albertel 9659:
1.1007 raeburn 9660: sub auto_validate_instcode {
1.1020 raeburn 9661: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9662: my ($homeserver,$response);
9663: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9664: $homeserver = &homeserver($cnum,$cdom);
9665: }
9666: if (!defined($homeserver)) {
9667: if ($cdom =~ /^$match_domain$/) {
9668: $homeserver = &domain($cdom,'primary');
9669: }
9670: }
1.1065 raeburn 9671: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9672: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 9673: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9674: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9675: }
9676:
1.1444 raeburn 9677: sub auto_validate_inst_crosslist {
9678: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9679: my ($homeserver,$response);
9680: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9681: $homeserver = &homeserver($cnum,$cdom);
9682: }
9683: if (!defined($homeserver)) {
9684: if ($cdom =~ /^$match_domain$/) {
9685: $homeserver = &domain($cdom,'primary');
9686: }
9687: }
9688: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9689: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9690: &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445 raeburn 9691: &escape($coowner),$homeserver);
1.1444 raeburn 9692: }
9693: return $response;
9694: }
9695:
1.506 raeburn 9696: sub auto_create_password {
1.873 raeburn 9697: my ($cnum,$cdom,$authparam,$udom) = @_;
9698: my ($homeserver,$response);
1.506 raeburn 9699: my $create_passwd = 0;
9700: my $authchk = '';
1.873 raeburn 9701: if ($udom =~ /^$match_domain$/) {
9702: $homeserver = &domain($udom,'primary');
9703: }
9704: if ($homeserver eq '') {
9705: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9706: $homeserver = &homeserver($cnum,$cdom);
9707: }
9708: }
9709: if ($homeserver eq '') {
9710: $authchk = 'nodomain';
1.506 raeburn 9711: } else {
1.873 raeburn 9712: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9713: if ($response eq 'refused') {
9714: $authchk = 'refused';
9715: } else {
1.901 albertel 9716: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9717: }
1.506 raeburn 9718: }
9719: return ($authparam,$create_passwd,$authchk);
9720: }
9721:
1.706 raeburn 9722: sub auto_photo_permission {
9723: my ($cnum,$cdom,$students) = @_;
9724: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9725: my ($outcome,$perm_reqd,$conditions) =
9726: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9727: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9728: return (undef,undef);
9729: }
1.706 raeburn 9730: return ($outcome,$perm_reqd,$conditions);
9731: }
9732:
9733: sub auto_checkphotos {
9734: my ($uname,$udom,$pid) = @_;
9735: my $homeserver = &homeserver($uname,$udom);
9736: my ($result,$resulttype);
9737: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9738: &escape($uname).':'.&escape($pid),
9739: $homeserver));
1.709 albertel 9740: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9741: return (undef,undef);
9742: }
1.706 raeburn 9743: if ($outcome) {
9744: ($result,$resulttype) = split(/:/,$outcome);
9745: }
9746: return ($result,$resulttype);
9747: }
9748:
9749: sub auto_photochoice {
9750: my ($cnum,$cdom) = @_;
9751: my $homeserver = &homeserver($cnum,$cdom);
9752: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9753: &escape($cdom),
9754: $homeserver)));
1.709 albertel 9755: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9756: return (undef,undef);
9757: }
1.706 raeburn 9758: return ($update,$comment);
9759: }
9760:
9761: sub auto_photoupdate {
9762: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9763: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9764: my $host=&hostname($homeserver);
1.706 raeburn 9765: my $cmd = '';
9766: my $maxtries = 1;
1.800 albertel 9767: foreach my $affiliate (keys(%{$affiliatesref})) {
9768: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9769: }
9770: $cmd =~ s/%%$//;
9771: $cmd = &escape($cmd);
9772: my $query = 'institutionalphotos';
9773: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9774: unless ($queryid=~/^\Q$host\E\_/) {
9775: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9776: return 'error: '.$queryid;
9777: }
9778: my $reply = &get_query_reply($queryid);
9779: my $tries = 1;
9780: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9781: $reply = &get_query_reply($queryid);
9782: $tries ++;
9783: }
9784: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9785: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9786: } else {
9787: my @responses = split(/:/,$reply);
9788: my $outcome = shift(@responses);
9789: foreach my $item (@responses) {
9790: my ($key,$value) = split(/=/,$item);
9791: $$photo{$key} = $value;
9792: }
9793: return $outcome;
9794: }
9795: return 'error';
9796: }
9797:
1.521 raeburn 9798: sub auto_instcode_format {
1.793 albertel 9799: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9800: $cat_order) = @_;
1.521 raeburn 9801: my $courses = '';
1.772 raeburn 9802: my @homeservers;
1.521 raeburn 9803: if ($caller eq 'global') {
1.841 albertel 9804: my %servers = &get_servers($codedom,'library');
9805: foreach my $tryserver (keys(%servers)) {
9806: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9807: push(@homeservers,$tryserver);
9808: }
1.584 raeburn 9809: }
1.1022 raeburn 9810: } elsif ($caller eq 'requests') {
9811: if ($codedom =~ /^$match_domain$/) {
9812: my $chome = &domain($codedom,'primary');
9813: unless ($chome eq 'no_host') {
9814: push(@homeservers,$chome);
9815: }
9816: }
1.521 raeburn 9817: } else {
1.772 raeburn 9818: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9819: }
1.793 albertel 9820: foreach my $code (keys(%{$instcodes})) {
9821: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9822: }
9823: chop($courses);
1.772 raeburn 9824: my $ok_response = 0;
9825: my $response;
9826: while (@homeservers > 0 && $ok_response == 0) {
9827: my $server = shift(@homeservers);
9828: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9829: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9830: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9831: split(/:/,$response);
1.772 raeburn 9832: %{$codes} = (%{$codes},&str2hash($codes_str));
9833: push(@{$codetitles},&str2array($codetitles_str));
9834: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9835: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9836: $ok_response = 1;
9837: }
9838: }
9839: if ($ok_response) {
1.521 raeburn 9840: return 'ok';
1.772 raeburn 9841: } else {
9842: return $response;
1.521 raeburn 9843: }
9844: }
9845:
1.792 raeburn 9846: sub auto_instcode_defaults {
9847: my ($domain,$returnhash,$code_order) = @_;
9848: my @homeservers;
1.841 albertel 9849:
9850: my %servers = &get_servers($domain,'library');
9851: foreach my $tryserver (keys(%servers)) {
9852: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9853: push(@homeservers,$tryserver);
9854: }
1.792 raeburn 9855: }
1.841 albertel 9856:
1.792 raeburn 9857: my $response;
1.841 albertel 9858: foreach my $server (@homeservers) {
1.792 raeburn 9859: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9860: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9861:
9862: foreach my $pair (split(/\&/,$response)) {
9863: my ($name,$value)=split(/\=/,$pair);
9864: if ($name eq 'code_order') {
9865: @{$code_order} = split(/\&/,&unescape($value));
9866: } else {
9867: $returnhash->{&unescape($name)}=&unescape($value);
9868: }
9869: }
9870: return 'ok';
1.792 raeburn 9871: }
1.841 albertel 9872:
9873: return $response;
1.1003 raeburn 9874: }
9875:
9876: sub auto_possible_instcodes {
1.1007 raeburn 9877: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9878: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9879: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9880: return;
9881: }
1.1003 raeburn 9882: my (@homeservers,$uhome);
9883: if (defined(&domain($domain,'primary'))) {
9884: $uhome=&domain($domain,'primary');
9885: push(@homeservers,&domain($domain,'primary'));
9886: } else {
9887: my %servers = &get_servers($domain,'library');
9888: foreach my $tryserver (keys(%servers)) {
9889: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9890: push(@homeservers,$tryserver);
9891: }
9892: }
9893: }
9894: my $response;
9895: foreach my $server (@homeservers) {
9896: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9897: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9898: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9899: split(':',$response);
9900: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9901: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9902: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9903: my ($name,$value)=split('=',$item);
9904: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9905: }
9906: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9907: my ($name,$value)=split('=',$item);
9908: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9909: }
9910: return 'ok';
9911: }
9912: return $response;
9913: }
1.792 raeburn 9914:
1.1010 raeburn 9915: sub auto_courserequest_checks {
9916: my ($dom) = @_;
1.1020 raeburn 9917: my ($homeserver,%validations);
9918: if ($dom =~ /^$match_domain$/) {
9919: $homeserver = &domain($dom,'primary');
9920: }
9921: unless ($homeserver eq 'no_host') {
9922: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9923: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9924: my @items = split(/&/,$response);
9925: foreach my $item (@items) {
9926: my ($key,$value) = split('=',$item);
9927: $validations{&unescape($key)} = &thaw_unescape($value);
9928: }
9929: }
9930: }
1.1010 raeburn 9931: return %validations;
9932: }
9933:
1.1020 raeburn 9934: sub auto_courserequest_validation {
1.1255 raeburn 9935: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9936: my ($homeserver,$response);
9937: if ($dom =~ /^$match_domain$/) {
9938: $homeserver = &domain($dom,'primary');
9939: }
1.1255 raeburn 9940: unless ($homeserver eq 'no_host') {
9941: my $customdata;
9942: if (ref($custominfo) eq 'HASH') {
9943: $customdata = &freeze_escape($custominfo);
9944: }
1.1020 raeburn 9945: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9946: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 9947: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9948: $customdata,$homeserver));
1.1020 raeburn 9949: }
9950: return $response;
9951: }
9952:
1.777 albertel 9953: sub auto_validate_class_sec {
1.918 raeburn 9954: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9955: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9956: my $ownerlist;
9957: if (ref($owners) eq 'ARRAY') {
9958: $ownerlist = join(',',@{$owners});
9959: } else {
9960: $ownerlist = $owners;
9961: }
1.773 raeburn 9962: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9963: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9964: return $response;
9965: }
9966:
1.1460 raeburn 9967: sub auto_instsec_reformat {
9968: my ($cdom,$action,$instsecref) = @_;
9969: return unless(($action eq 'clutter') || ($action eq 'declutter'));
9970: my @homeservers;
9971: if (defined(&domain($cdom,'primary'))) {
9972: push(@homeservers,&domain($cdom,'primary'));
9973: } else {
9974: my %servers = &get_servers($cdom,'library');
9975: foreach my $tryserver (keys(%servers)) {
9976: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9977: push(@homeservers,$tryserver);
9978: }
9979: }
9980: }
9981: my $response;
9982: my %reformatted = %{$instsecref};
9983: foreach my $server (@homeservers) {
9984: if (ref($instsecref) eq 'HASH') {
9985: my $info = &freeze_escape($instsecref);
9986: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
9987: $action.':'.$info,$server);
9988: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
9989: my @items = split(/&/,$response);
9990: foreach my $item (@items) {
9991: my ($key,$value) = split(/=/,$item);
9992: $reformatted{&unescape($key)} = &thaw_unescape($value);
9993: }
9994: }
9995: }
9996: return %reformatted;
9997: }
9998:
1.1367 raeburn 9999: sub auto_validate_instclasses {
10000: my ($cdom,$cnum,$owners,$classesref) = @_;
10001: my ($homeserver,%validations);
10002: $homeserver = &homeserver($cnum,$cdom);
10003: unless ($homeserver eq 'no_host') {
10004: my $ownerlist;
10005: if (ref($owners) eq 'ARRAY') {
10006: $ownerlist = join(',',@{$owners});
10007: } else {
10008: $ownerlist = $owners;
10009: }
10010: if (ref($classesref) eq 'HASH') {
10011: my $classes = &freeze_escape($classesref);
10012: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10013: ':'.$cdom.':'.$classes,$homeserver);
10014: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10015: my @items = split(/&/,$response);
10016: foreach my $item (@items) {
10017: my ($key,$value) = split('=',$item);
10018: $validations{&unescape($key)} = &thaw_unescape($value);
10019: }
10020: }
10021: }
10022: }
10023: return %validations;
10024: }
10025:
1.1248 raeburn 10026: sub auto_crsreq_update {
10027: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 10028: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 10029: my ($homeserver,%crsreqresponse);
10030: if ($cdom =~ /^$match_domain$/) {
10031: $homeserver = &domain($cdom,'primary');
10032: }
10033: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10034: my $info;
10035: if (ref($inbound) eq 'HASH') {
10036: $info = &freeze_escape($inbound);
10037: }
10038: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10039: ':'.&escape($action).':'.&escape($ownername).':'.
10040: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 10041: &escape($title).':'.&escape($code).':'.
10042: &escape($accessstart).':'.&escape($accessend).':'.$info,
10043: $homeserver);
1.1248 raeburn 10044: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10045: my @items = split(/&/,$response);
10046: foreach my $item (@items) {
10047: my ($key,$value) = split('=',$item);
10048: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10049: }
10050: }
10051: }
10052: return \%crsreqresponse;
10053: }
10054:
1.1305 raeburn 10055: sub auto_export_grades {
1.1309 raeburn 10056: my ($cdom,$cnum,$inforef,$gradesref) = @_;
10057: my ($homeserver,%exportresponse);
10058: if ($cdom =~ /^$match_domain$/) {
10059: $homeserver = &domain($cdom,'primary');
10060: }
10061: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10062: my $info;
10063: if (ref($inforef) eq 'HASH') {
10064: $info = &freeze_escape($inforef);
10065: }
10066: if (ref($gradesref) eq 'HASH') {
10067: my $grades = &freeze_escape($gradesref);
10068: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10069: $info.':'.$grades,$homeserver);
10070: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10071: my @items = split(/&/,$response);
10072: foreach my $item (@items) {
10073: my ($key,$value) = split('=',$item);
10074: $exportresponse{&unescape($key)} = &thaw_unescape($value);
10075: }
10076: }
10077: }
10078: }
10079: return \%exportresponse;
1.1305 raeburn 10080: }
10081:
1.1287 raeburn 10082: sub check_instcode_cloning {
10083: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10084: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10085: return;
10086: }
10087: my $canclone;
10088: if (@{$code_order} > 0) {
10089: my $instcoderegexp ='^';
10090: my @clonecodes = split(/\&/,$cloner);
10091: foreach my $item (@{$code_order}) {
10092: if (grep(/^\Q$item\E=/,@clonecodes)) {
10093: foreach my $pair (@clonecodes) {
10094: my ($key,$val) = split(/\=/,$pair,2);
10095: $val = &unescape($val);
10096: if ($key eq $item) {
10097: $instcoderegexp .= '('.$val.')';
10098: last;
10099: }
10100: }
10101: } else {
10102: $instcoderegexp .= $codedefaults->{$item};
10103: }
10104: }
10105: $instcoderegexp .= '$';
10106: my (@from,@to);
10107: eval {
10108: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10109: (@to) = ($clonetocode =~ /$instcoderegexp/);
10110: };
10111: if ((@from > 0) && (@to > 0)) {
10112: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10113: if (!@diffs) {
10114: $canclone = 1;
10115: }
10116: }
10117: }
10118: return $canclone;
10119: }
10120:
10121: sub default_instcode_cloning {
10122: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10123: my (%codedefaults,@code_order,$canclone);
10124: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10125: %codedefaults = %{$codedefaultsref};
10126: @code_order = @{$codeorderref};
10127: } elsif ($clonedom) {
10128: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10129: }
10130: if (($domdefclone) && (@code_order)) {
10131: my @clonecodes = split(/\+/,$domdefclone);
10132: my $instcoderegexp ='^';
10133: foreach my $item (@code_order) {
10134: if (grep(/^\Q$item\E$/,@clonecodes)) {
10135: $instcoderegexp .= '('.$codedefaults{$item}.')';
10136: } else {
10137: $instcoderegexp .= $codedefaults{$item};
10138: }
10139: }
10140: $instcoderegexp .= '$';
10141: my (@from,@to);
10142: eval {
10143: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10144: (@to) = ($clonetocode =~ /$instcoderegexp/);
10145: };
10146: if ((@from > 0) && (@to > 0)) {
10147: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10148: if (!@diffs) {
10149: $canclone = 1;
10150: }
10151: }
10152: }
10153: return $canclone;
10154: }
10155:
1.679 raeburn 10156: # ------------------------------------------------------- Course Group routines
10157:
10158: sub get_coursegroups {
1.809 raeburn 10159: my ($cdom,$cnum,$group,$namespace) = @_;
10160: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 10161: }
10162:
1.679 raeburn 10163: sub modify_coursegroup {
10164: my ($cdom,$cnum,$groupsettings) = @_;
10165: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10166: }
10167:
1.809 raeburn 10168: sub toggle_coursegroup_status {
10169: my ($cdom,$cnum,$group,$action) = @_;
10170: my ($from_namespace,$to_namespace);
10171: if ($action eq 'delete') {
10172: $from_namespace = 'coursegroups';
10173: $to_namespace = 'deleted_groups';
10174: } else {
10175: $from_namespace = 'deleted_groups';
10176: $to_namespace = 'coursegroups';
10177: }
10178: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 10179: if (my $tmp = &error(%curr_group)) {
10180: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10181: return ('read error',$tmp);
10182: } else {
10183: my %savedsettings = %curr_group;
1.809 raeburn 10184: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 10185: my $deloutcome;
10186: if ($result eq 'ok') {
1.809 raeburn 10187: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 10188: } else {
10189: return ('write error',$result);
10190: }
10191: if ($deloutcome eq 'ok') {
10192: return 'ok';
10193: } else {
10194: return ('delete error',$deloutcome);
10195: }
10196: }
10197: }
10198:
1.679 raeburn 10199: sub modify_group_roles {
1.957 raeburn 10200: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 10201: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10202: my $role = 'gr/'.&escape($userprivs);
10203: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 10204: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 10205: if ($result eq 'ok') {
10206: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10207: }
1.679 raeburn 10208: return $result;
10209: }
10210:
10211: sub modify_coursegroup_membership {
10212: my ($cdom,$cnum,$membership) = @_;
10213: my $result = &put('groupmembership',$membership,$cdom,$cnum);
10214: return $result;
10215: }
10216:
1.682 raeburn 10217: sub get_active_groups {
10218: my ($udom,$uname,$cdom,$cnum) = @_;
10219: my $now = time;
10220: my %groups = ();
10221: foreach my $key (keys(%env)) {
1.811 albertel 10222: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 10223: my ($start,$end) = split(/\./,$env{$key});
10224: if (($end!=0) && ($end<$now)) { next; }
10225: if (($start!=0) && ($start>$now)) { next; }
10226: if ($1 eq $cdom && $2 eq $cnum) {
10227: $groups{$3} = $env{$key} ;
10228: }
10229: }
10230: }
10231: return %groups;
10232: }
10233:
1.683 raeburn 10234: sub get_group_membership {
10235: my ($cdom,$cnum,$group) = @_;
10236: return(&dump('groupmembership',$cdom,$cnum,$group));
10237: }
10238:
10239: sub get_users_groups {
10240: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 10241: my @usersgroups;
1.683 raeburn 10242: my $cachetime=1800;
10243:
10244: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 10245: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10246: if (defined($cached)) {
1.734 albertel 10247: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 10248: } else {
10249: $grouplist = '';
1.816 raeburn 10250: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 10251: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 10252: my $access_end = $env{'course.'.$courseid.
10253: '.default_enrollment_end_date'};
10254: my $now = time;
10255: foreach my $key (keys(%roleshash)) {
10256: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10257: my $group = $1;
10258: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10259: my $start = $2;
10260: my $end = $1;
10261: if ($start == -1) { next; } # deleted from group
10262: if (($start!=0) && ($start>$now)) { next; }
10263: if (($end!=0) && ($end<$now)) {
10264: if ($access_end && $access_end < $now) {
10265: if ($access_end - $end < 86400) {
10266: push(@usersgroups,$group);
1.733 raeburn 10267: }
10268: }
1.817 raeburn 10269: next;
1.733 raeburn 10270: }
1.817 raeburn 10271: push(@usersgroups,$group);
1.683 raeburn 10272: }
10273: }
10274: }
1.817 raeburn 10275: @usersgroups = &sort_course_groups($courseid,@usersgroups);
10276: $grouplist = join(':',@usersgroups);
10277: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 10278: }
1.733 raeburn 10279: return @usersgroups;
1.683 raeburn 10280: }
10281:
10282: sub devalidate_getgroups_cache {
10283: my ($udom,$uname,$cdom,$cnum)=@_;
10284: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 10285:
1.683 raeburn 10286: my $hashid="$udom:$uname:$courseid";
10287: &devalidate_cache_new('getgroups',$hashid);
10288: }
10289:
1.12 www 10290: # ------------------------------------------------------------------ Plain Text
10291:
10292: sub plaintext {
1.988 raeburn 10293: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 10294: if ($short =~ m{^cr/}) {
1.758 albertel 10295: return (split('/',$short))[-1];
10296: }
1.742 raeburn 10297: if (!defined($cid)) {
10298: $cid = $env{'request.course.id'};
10299: }
10300: my %rolenames = (
1.1008 raeburn 10301: Course => 'std',
10302: Community => 'alt1',
1.1305 raeburn 10303: Placement => 'std',
1.742 raeburn 10304: );
1.1037 raeburn 10305: if ($cid ne '') {
10306: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10307: unless ($forcedefault) {
10308: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
10309: &Apache::lonlocal::mt_escape(\$roletext);
10310: return &Apache::lonlocal::mt($roletext);
10311: }
10312: }
10313: }
10314: if ((defined($type)) && (defined($rolenames{$type})) &&
10315: (defined($rolenames{$type})) &&
10316: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 10317: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 10318: } elsif ($cid ne '') {
10319: my $crstype = $env{'course.'.$cid.'.type'};
10320: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10321: (defined($prp{$short}{$rolenames{$crstype}}))) {
10322: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10323: }
1.742 raeburn 10324: }
1.1037 raeburn 10325: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 10326: }
10327:
10328: # ----------------------------------------------------------------- Assign Role
10329:
10330: sub assignrole {
1.957 raeburn 10331: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10332: $context)=@_;
1.21 www 10333: my $mrole;
10334: if ($role =~ /^cr\//) {
1.393 www 10335: my $cwosec=$url;
1.811 albertel 10336: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.1502 raeburn 10337: if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
1.1026 raeburn 10338: my $refused = 1;
10339: if ($context eq 'requestcourses') {
10340: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10341: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10342: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10343: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10344: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10345: if ($crsenv{'internal.courseowner'} eq
10346: $env{'user.name'}.':'.$env{'user.domain'}) {
10347: $refused = '';
10348: }
10349: }
10350: }
10351: }
10352: }
10353: if ($refused) {
10354: &logthis('Refused custom assignrole: '.
10355: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10356: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10357: return 'refused';
10358: }
1.104 www 10359: }
1.21 www 10360: $mrole='cr';
1.678 raeburn 10361: } elsif ($role =~ /^gr\//) {
10362: my $cwogrp=$url;
1.811 albertel 10363: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 10364: unless (&allowed('mdg',$cwogrp)) {
10365: &logthis('Refused group assignrole: '.
10366: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10367: $env{'user.name'}.' at '.$env{'user.domain'});
10368: return 'refused';
10369: }
10370: $mrole='gr';
1.21 www 10371: } else {
1.82 www 10372: my $cwosec=$url;
1.811 albertel 10373: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 10374: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10375: my $refused;
10376: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10377: if (!(&allowed('c'.$role,$url))) {
10378: $refused = 1;
10379: }
10380: } else {
10381: $refused = 1;
10382: }
1.947 raeburn 10383: if ($refused) {
1.1045 raeburn 10384: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377 raeburn 10385: if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045 raeburn 10386: my %crsenv;
10387: if ($role eq 'cc' || $role eq 'co') {
10388: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10389: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10390: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10391: if ($crsenv{'internal.courseowner'} eq
10392: $env{'user.name'}.':'.$env{'user.domain'}) {
10393: $refused = '';
10394: }
10395: }
10396: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10397: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10398: if ($crsenv{'internal.courseowner'} eq
10399: $env{'user.name'}.':'.$env{'user.domain'}) {
10400: $refused = '';
10401: }
10402: }
10403: }
10404: }
1.1368 raeburn 10405: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10406: if ($role eq 'st') {
10407: $refused = '';
1.1377 raeburn 10408: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368 raeburn 10409: $refused = '';
10410: }
1.1017 raeburn 10411: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 10412: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 10413: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 10414: my $wrongcc;
10415: if ($cnum =~ /^$match_community$/) {
10416: $wrongcc = 1 if ($role eq 'cc');
10417: } else {
10418: $wrongcc = 1 if ($role eq 'co');
10419: }
10420: unless ($wrongcc) {
10421: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10422: if ($crsenv{'internal.courseowner'} eq
10423: $env{'user.name'}.':'.$env{'user.domain'}) {
10424: $refused = '';
10425: }
1.1017 raeburn 10426: }
10427: }
1.1183 raeburn 10428: } elsif ($context eq 'requestauthor') {
10429: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10430: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10431: if ($env{'environment.requestauthor'} eq 'automatic') {
10432: $refused = '';
10433: } else {
10434: my %domdefaults = &get_domain_defaults($udom);
10435: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10436: my $checkbystatus;
10437: if ($env{'user.adv'}) {
10438: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10439: if ($disposition eq 'automatic') {
10440: $refused = '';
10441: } elsif ($disposition eq '') {
10442: $checkbystatus = 1;
10443: }
10444: } else {
10445: $checkbystatus = 1;
10446: }
10447: if ($checkbystatus) {
10448: if ($env{'environment.inststatus'}) {
10449: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10450: foreach my $type (@inststatuses) {
10451: if (($type ne '') &&
10452: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10453: $refused = '';
10454: }
10455: }
10456: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10457: $refused = '';
10458: }
10459: }
10460: }
10461: }
10462: }
1.1017 raeburn 10463: }
10464: if ($refused) {
1.947 raeburn 10465: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10466: ' '.$role.' '.$end.' '.$start.' by '.
10467: $env{'user.name'}.' at '.$env{'user.domain'});
10468: return 'refused';
10469: }
1.932 raeburn 10470: }
1.1131 raeburn 10471: } elsif ($role eq 'au') {
10472: if ($url ne '/'.$udom.'/') {
10473: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10474: ' to assign author role for '.$uname.':'.$udom.
10475: ' in domain: '.$url.' refused (wrong domain).');
10476: return 'refused';
10477: }
1.104 www 10478: }
1.21 www 10479: $mrole=$role;
10480: }
1.620 albertel 10481: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 10482: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 10483: if ($end) { $command.='_'.$end; }
1.21 www 10484: if ($start) {
10485: if ($end) {
1.81 www 10486: $command.='_'.$start;
1.21 www 10487: } else {
1.81 www 10488: $command.='_0_'.$start;
1.21 www 10489: }
10490: }
1.739 raeburn 10491: my $origstart = $start;
10492: my $origend = $end;
1.957 raeburn 10493: my $delflag;
1.357 www 10494: # actually delete
10495: if ($deleteflag) {
1.373 www 10496: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 10497: # modify command to delete the role
1.620 albertel 10498: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 10499: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 10500: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 10501: # set start and finish to negative values for userrolelog
10502: $start=-1;
10503: $end=-1;
1.957 raeburn 10504: $delflag = 1;
1.357 www 10505: }
10506: }
10507: # send command
1.349 www 10508: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 10509: # log new user role if status is ok
1.349 www 10510: if ($answer eq 'ok') {
1.663 raeburn 10511: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 10512: if (($role eq 'cc') || ($role eq 'in') ||
10513: ($role eq 'ep') || ($role eq 'ad') ||
10514: ($role eq 'ta') || ($role eq 'st') ||
10515: ($role=~/^cr/) || ($role eq 'gr') ||
10516: ($role eq 'co')) {
1.1200 raeburn 10517: # for course roles, perform group memberships changes triggered by role change.
10518: unless ($role =~ /^gr/) {
10519: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10520: $origstart,$selfenroll,$context);
10521: }
1.1184 raeburn 10522: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10523: $selfenroll,$context);
10524: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 10525: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10526: ($role eq 'da')) {
1.1184 raeburn 10527: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10528: $context);
10529: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10530: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10531: $context);
10532: }
1.1053 raeburn 10533: if ($role eq 'cc') {
10534: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10535: }
1.349 www 10536: }
10537: return $answer;
1.169 harris41 10538: }
10539:
1.1053 raeburn 10540: sub autoupdate_coowners {
10541: my ($url,$end,$start,$uname,$udom) = @_;
10542: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10543: if (($cdom ne '') && ($cnum ne '')) {
10544: my $now = time;
10545: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10546: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10547: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10548: my $instcode = $coursehash{'internal.coursecode'};
1.1444 raeburn 10549: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 10550: if ($instcode ne '') {
1.1056 raeburn 10551: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10552: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10553: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10554: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444 raeburn 10555: unless ($result eq 'valid') {
10556: if ($xlists ne '') {
10557: foreach my $xlist (split(',',$xlists)) {
10558: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10559: $result =
1.1446 raeburn 10560: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10561: $inst_crosslist,$uname.':'.$udom);
10562: last if ($result eq 'valid');
1.1444 raeburn 10563: }
10564: }
10565: }
1.1056 raeburn 10566: if ($result eq 'valid') {
10567: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10568: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10569: push(@newcoowners,$coowner);
10570: }
10571: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10572: push(@newcoowners,$uname.':'.$udom);
10573: }
10574: @newcoowners = sort(@newcoowners);
10575: } else {
10576: push(@newcoowners,$uname.':'.$udom);
10577: }
1.1444 raeburn 10578: } elsif ($coursehash{'internal.co-owners'}) {
10579: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10580: unless ($coowner eq $uname.':'.$udom) {
10581: push(@newcoowners,$coowner);
1.1053 raeburn 10582: }
1.1444 raeburn 10583: }
10584: unless (@newcoowners > 0) {
10585: $delcoowners = 1;
10586: $coowners = '';
1.1053 raeburn 10587: }
10588: }
10589: if (@newcoowners || $delcoowners) {
10590: &store_coowners($cdom,$cnum,$coursehash{'home'},
10591: $delcoowners,@newcoowners);
10592: }
10593: }
10594: }
10595: }
10596: }
10597: }
10598: }
10599:
10600: sub store_coowners {
10601: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10602: my $cid = $cdom.'_'.$cnum;
10603: my ($coowners,$delresult,$putresult);
10604: if (@newcoowners) {
10605: $coowners = join(',',@newcoowners);
10606: my %coownershash = (
10607: 'internal.co-owners' => $coowners,
10608: );
10609: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10610: if ($putresult eq 'ok') {
10611: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10612: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10613: }
10614: }
10615: }
10616: if ($delcoowners) {
10617: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10618: if ($delresult eq 'ok') {
10619: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10620: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10621: }
10622: }
10623: }
10624: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10625: my %crsinfo =
1.1494 raeburn 10626: &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
1.1053 raeburn 10627: if (ref($crsinfo{$cid}) eq 'HASH') {
10628: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
1.1494 raeburn 10629: my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
1.1053 raeburn 10630: }
10631: }
10632: }
10633:
1.169 harris41 10634: # -------------------------------------------------- Modify user authentication
1.197 www 10635: # Overrides without validation
10636:
1.169 harris41 10637: sub modifyuserauth {
10638: my ($udom,$uname,$umode,$upass)=@_;
10639: my $uhome=&homeserver($uname,$udom);
1.1409 raeburn 10640: my $allowed;
10641: if (&allowed('mau',$udom)) {
10642: $allowed = 1;
10643: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10644: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10645: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10646: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10647: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10648: if (($cdom ne '') && ($cnum ne '')) {
10649: my $is_owner = &is_course_owner($cdom,$cnum);
10650: if ($is_owner) {
10651: $allowed = 1;
10652: }
10653: }
10654: }
10655: unless ($allowed) { return 'refused'; }
1.197 www 10656: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10657: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10658: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10659: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10660: &escape($upass),$uhome);
1.1434 raeburn 10661: my $ip = &get_requestor_ip();
1.620 albertel 10662: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10663: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434 raeburn 10664: '(Remote '.$ip.'): '.$reply);
1.197 www 10665: &log($udom,,$uname,$uhome,
1.620 albertel 10666: 'Authentication changed by '.$env{'user.domain'}.', '.
10667: $env{'user.name'}.', '.$umode.
1.1435 raeburn 10668: '(Remote '.$ip.'): '.$reply);
1.169 harris41 10669: unless ($reply eq 'ok') {
1.197 www 10670: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10671: return 'error: '.$reply;
10672: }
1.170 harris41 10673: return 'ok';
1.80 www 10674: }
10675:
1.81 www 10676: # --------------------------------------------------------------- Modify a user
1.80 www 10677:
1.81 www 10678: sub modifyuser {
1.206 matthew 10679: my ($udom, $uname, $uid,
10680: $umode, $upass, $first,
10681: $middle, $last, $gene,
1.1058 raeburn 10682: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10683: $udom= &LONCAPA::clean_domain($udom);
10684: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10685: my $showcandelete = 'none';
10686: if (ref($candelete) eq 'ARRAY') {
10687: if (@{$candelete} > 0) {
10688: $showcandelete = join(', ',@{$candelete});
10689: }
10690: }
1.81 www 10691: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10692: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10693: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10694: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10695: ' desiredhome not specified').
1.620 albertel 10696: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10697: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10698: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10699: my $newuser;
10700: if ($uhome eq 'no_host') {
10701: $newuser = 1;
1.1368 raeburn 10702: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10703: ($umode eq 'lti')) {
10704: return 'error: more information needed to create new user';
10705: }
1.1075 raeburn 10706: }
1.80 www 10707: # ----------------------------------------------------------------- Create User
1.406 albertel 10708: if (($uhome eq 'no_host') &&
1.1368 raeburn 10709: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80 www 10710: my $unhome='';
1.844 albertel 10711: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10712: $unhome = $desiredhome;
1.620 albertel 10713: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10714: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10715: } else { # load balancing routine for determining $unhome
1.81 www 10716: my $loadm=10000000;
1.841 albertel 10717: my %servers = &get_servers($udom,'library');
10718: foreach my $tryserver (keys(%servers)) {
10719: my $answer=reply('load',$tryserver);
10720: if (($answer=~/\d+/) && ($answer<$loadm)) {
10721: $loadm=$answer;
10722: $unhome=$tryserver;
10723: }
1.80 www 10724: }
10725: }
10726: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10727: return 'error: unable to find a home server for '.$uname.
10728: ' in domain '.$udom;
1.80 www 10729: }
10730: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10731: &escape($upass),$unhome);
10732: unless ($reply eq 'ok') {
10733: return 'error: '.$reply;
10734: }
1.230 stredwic 10735: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10736: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10737: return 'error: unable verify users home machine.';
1.80 www 10738: }
1.209 matthew 10739: } # End of creation of new user
1.80 www 10740: # ---------------------------------------------------------------------- Add ID
10741: if ($uid) {
10742: $uid=~tr/A-Z/a-z/;
10743: my %uidhash=&idrget($udom,$uname);
1.196 www 10744: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10745: && (!$forceid)) {
1.80 www 10746: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10747: return 'error: user id "'.$uid.'" does not match '.
10748: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10749: }
10750: } else {
1.1300 raeburn 10751: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 10752: }
10753: }
10754: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10755: my @tmp=&get('environment',
1.899 raeburn 10756: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10757: 'permanentemail','inststatus'],
1.134 albertel 10758: $udom,$uname);
1.1075 raeburn 10759: my (%names,%oldnames);
1.313 matthew 10760: if ($tmp[0] =~ m/^error:.*/) {
10761: %names=();
10762: } else {
10763: %names = @tmp;
1.1075 raeburn 10764: %oldnames = %names;
1.313 matthew 10765: }
1.388 www 10766: #
1.1058 raeburn 10767: # If name, email and/or uid are blank (e.g., because an uploaded file
10768: # of users did not contain them), do not overwrite existing values
10769: # unless field is in $candelete array ref.
10770: #
10771:
10772: my @fields = ('firstname','middlename','lastname','generation',
10773: 'permanentemail','id');
10774: my %newvalues;
10775: if (ref($candelete) eq 'ARRAY') {
10776: foreach my $field (@fields) {
10777: if (grep(/^\Q$field\E$/,@{$candelete})) {
10778: if ($field eq 'firstname') {
10779: $names{$field} = $first;
10780: } elsif ($field eq 'middlename') {
10781: $names{$field} = $middle;
10782: } elsif ($field eq 'lastname') {
10783: $names{$field} = $last;
10784: } elsif ($field eq 'generation') {
10785: $names{$field} = $gene;
10786: } elsif ($field eq 'permanentemail') {
10787: $names{$field} = $email;
10788: } elsif ($field eq 'id') {
10789: $names{$field} = $uid;
10790: }
10791: }
10792: }
10793: }
1.388 www 10794: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10795: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10796: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10797: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10798: if ($email) {
10799: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10800: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10801: }
1.899 raeburn 10802: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10803: if (defined($inststatus)) {
10804: $names{'inststatus'} = '';
10805: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10806: if (ref($usertypes) eq 'HASH') {
10807: my @okstatuses;
10808: foreach my $item (split(/:/,$inststatus)) {
10809: if (defined($usertypes->{$item})) {
10810: push(@okstatuses,$item);
10811: }
10812: }
10813: if (@okstatuses) {
10814: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10815: }
10816: }
10817: }
1.1075 raeburn 10818: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10819: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10820: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10821: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10822: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10823: } else {
10824: $logmsg .= ' during self creation';
10825: }
1.1075 raeburn 10826: my $changed;
10827: if ($newuser) {
10828: $changed = 1;
10829: } else {
10830: foreach my $field (@fields) {
10831: if ($names{$field} ne $oldnames{$field}) {
10832: $changed = 1;
10833: last;
10834: }
10835: }
10836: }
10837: unless ($changed) {
10838: $logmsg = 'No changes in user information needed for: '.$logmsg;
10839: &logthis($logmsg);
10840: return 'ok';
10841: }
10842: my $reply = &put('environment', \%names, $udom,$uname);
10843: if ($reply ne 'ok') {
10844: return 'error: '.$reply;
10845: }
1.1087 raeburn 10846: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
1.1494 raeburn 10847: &devalidate_cache_new('emailscache',$uname.':'.$udom);
1.1087 raeburn 10848: }
1.1075 raeburn 10849: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10850: &devalidate_cache_new('namescache',$uname.':'.$udom);
10851: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10852: &logthis($logmsg);
1.134 albertel 10853: return 'ok';
1.80 www 10854: }
10855:
1.81 www 10856: # -------------------------------------------------------------- Modify student
1.80 www 10857:
1.81 www 10858: sub modifystudent {
10859: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10860: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 10861: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10862: if (!$cid) {
1.620 albertel 10863: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10864: return 'not_in_class';
10865: }
1.80 www 10866: }
10867: # --------------------------------------------------------------- Make the user
1.81 www 10868: my $reply=&modifyuser
1.209 matthew 10869: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10870: $desiredhome,$email,$inststatus);
1.80 www 10871: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10872: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 10873: # student's environment
1.297 matthew 10874: $uid = undef if (!$forceid);
1.455 albertel 10875: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 10876: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 10877: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10878: return $reply;
10879: }
10880:
10881: sub modify_student_enrollment {
1.1216 raeburn 10882: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 10883: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10884: my ($cdom,$cnum,$chome);
10885: if (!$cid) {
1.620 albertel 10886: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10887: return 'not_in_class';
10888: }
1.620 albertel 10889: $cdom=$env{'course.'.$cid.'.domain'};
10890: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10891: } else {
10892: ($cdom,$cnum)=split(/_/,$cid);
10893: }
1.620 albertel 10894: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10895: if (!$chome) {
1.457 raeburn 10896: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10897: }
1.455 albertel 10898: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10899: # Make sure the user exists
1.81 www 10900: my $uhome=&homeserver($uname,$udom);
10901: if (($uhome eq '') || ($uhome eq 'no_host')) {
10902: return 'error: no such user';
10903: }
1.297 matthew 10904: # Get student data if we were not given enough information
10905: if (!defined($first) || $first eq '' ||
10906: !defined($last) || $last eq '' ||
10907: !defined($uid) || $uid eq '' ||
10908: !defined($middle) || $middle eq '' ||
10909: !defined($gene) || $gene eq '') {
1.294 matthew 10910: # They did not supply us with enough data to enroll the student, so
10911: # we need to pick up more information.
1.297 matthew 10912: my %tmp = &get('environment',
1.294 matthew 10913: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10914: ,$udom,$uname);
10915:
1.800 albertel 10916: #foreach my $key (keys(%tmp)) {
10917: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10918: #}
1.294 matthew 10919: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10920: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10921: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10922: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10923: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10924: }
1.556 albertel 10925: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10926: my $user = "$uname:$udom";
1.1494 raeburn 10927: my %old_entry = &get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10928: my $reply=cput('classlist',
1.1148 raeburn 10929: {$user =>
1.1314 raeburn 10930: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10931: $cdom,$cnum);
1.1148 raeburn 10932: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10933: &devalidate_getsection_cache($udom,$uname,$cid);
10934: } else {
1.81 www 10935: return 'error: '.$reply;
10936: }
1.297 matthew 10937: # Add student role to user
1.83 www 10938: my $uurl='/'.$cid;
1.81 www 10939: $uurl=~s/\_/\//g;
10940: if ($usec) {
10941: $uurl.='/'.$usec;
10942: }
1.1148 raeburn 10943: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10944: $selfenroll,$context);
10945: if ($result ne 'ok') {
10946: if ($old_entry{$user} ne '') {
10947: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10948: } else {
10949: $reply = &del('classlist',[$user],$cdom,$cnum);
10950: }
10951: }
10952: return $result;
1.21 www 10953: }
10954:
1.556 albertel 10955: sub format_name {
10956: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10957: my $name;
10958: if ($first ne 'lastname') {
10959: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10960: } else {
10961: if ($lastname=~/\S/) {
10962: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10963: $name=~s/\s+,/,/;
10964: } else {
10965: $name.= $firstname.' '.$middlename.' '.$generation;
10966: }
10967: }
10968: $name=~s/^\s+//;
10969: $name=~s/\s+$//;
10970: $name=~s/\s+/ /g;
10971: return $name;
10972: }
10973:
1.84 www 10974: # ------------------------------------------------- Write to course preferences
10975:
10976: sub writecoursepref {
10977: my ($courseid,%prefs)=@_;
10978: $courseid=~s/^\///;
10979: $courseid=~s/\_/\//g;
10980: my ($cdomain,$cnum)=split(/\//,$courseid);
10981: my $chome=homeserver($cnum,$cdomain);
10982: if (($chome eq '') || ($chome eq 'no_host')) {
10983: return 'error: no such course';
10984: }
10985: my $cstring='';
1.800 albertel 10986: foreach my $pref (keys(%prefs)) {
10987: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10988: }
1.84 www 10989: $cstring=~s/\&$//;
10990: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10991: }
10992:
10993: # ---------------------------------------------------------- Make/modify course
10994:
10995: sub createcourse {
1.741 raeburn 10996: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423 raeburn 10997: $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84 www 10998: $url=&declutter($url);
10999: my $cid='';
1.1028 raeburn 11000: if ($context eq 'requestcourses') {
11001: my $can_create = 0;
11002: my ($ownername,$ownerdom) = split(':',$course_owner);
11003: if ($udom eq $ownerdom) {
1.1423 raeburn 11004: my $reload;
11005: if (($callercontext eq 'auto') &&
11006: ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11007: $reload = 'reload';
11008: }
11009: if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028 raeburn 11010: $context)) {
11011: $can_create = 1;
11012: }
11013: } else {
11014: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11015: $category);
11016: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11017: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11018: if (@curr > 0) {
11019: my @options = qw(approval validate autolimit);
11020: my $optregex = join('|',@options);
11021: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11022: $can_create = 1;
11023: }
11024: }
11025: }
11026: }
11027: if ($can_create) {
11028: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11029: unless (&allowed('ccc',$udom)) {
11030: return 'refused';
11031: }
1.1017 raeburn 11032: }
11033: } else {
11034: return 'refused';
11035: }
1.1028 raeburn 11036: } elsif (!&allowed('ccc',$udom)) {
11037: return 'refused';
1.84 www 11038: }
1.1011 raeburn 11039: # --------------------------------------------------------------- Get Unique ID
11040: my $uname;
11041: if ($cnum =~ /^$match_courseid$/) {
11042: my $chome=&homeserver($cnum,$udom,'true');
11043: if (($chome eq '') || ($chome eq 'no_host')) {
11044: $uname = $cnum;
11045: } else {
1.1038 raeburn 11046: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 11047: }
11048: } else {
1.1038 raeburn 11049: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 11050: }
11051: return $uname if ($uname =~ /^error/);
11052: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 11053: if (!defined($course_server)) {
11054: if (defined(&domain($udom,'primary'))) {
11055: $course_server = &domain($udom,'primary');
11056: } else {
11057: $course_server = $env{'user.home'};
11058: }
11059: }
11060: my %host_servers =
1.1494 raeburn 11061: &get_servers($udom,'library');
1.1052 raeburn 11062: unless ($host_servers{$course_server}) {
11063: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 11064: }
1.84 www 11065: # ------------------------------------------------------------- Make the course
11066: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 11067: $course_server);
1.84 www 11068: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 11069: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 11070: if (($uhome eq '') || ($uhome eq 'no_host')) {
11071: return 'error: no such course';
11072: }
1.271 www 11073: # ----------------------------------------------------------------- Course made
1.516 raeburn 11074: # log existence
1.1029 raeburn 11075: my $now = time;
1.918 raeburn 11076: my $newcourse = {
11077: $udom.'_'.$uname => {
1.921 raeburn 11078: description => $description,
11079: inst_code => $inst_code,
11080: owner => $course_owner,
11081: type => $crstype,
1.1029 raeburn 11082: creator => $env{'user.name'}.':'.
11083: $env{'user.domain'},
11084: created => $now,
11085: context => $context,
1.918 raeburn 11086: },
11087: };
1.921 raeburn 11088: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 11089: # set toplevel url
1.271 www 11090: my $topurl=$url;
11091: unless ($nonstandard) {
11092: # ------------------------------------------ For standard courses, make top url
11093: my $mapurl=&clutter($url);
1.278 www 11094: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 11095: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 11096: <map>
11097: <resource id="1" type="start"></resource>
11098: <resource id="2" src="$mapurl"></resource>
11099: <resource id="3" type="finish"></resource>
11100: <link index="1" from="1" to="2"></link>
11101: <link index="2" from="2" to="3"></link>
11102: </map>
11103: ENDINITMAP
11104: $topurl=&declutter(
1.638 albertel 11105: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 11106: );
11107: }
11108: # ----------------------------------------------------------- Write preferences
1.84 www 11109: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 11110: ('description' => $description,
11111: 'url' => $topurl,
11112: 'internal.creator' => $env{'user.name'}.':'.
11113: $env{'user.domain'},
11114: 'internal.created' => $now,
11115: 'internal.creationcontext' => $context)
11116: );
1.84 www 11117: return '/'.$udom.'/'.$uname;
11118: }
11119:
1.1011 raeburn 11120: # ------------------------------------------------------------------- Create ID
11121: sub generate_coursenum {
1.1038 raeburn 11122: my ($udom,$crstype) = @_;
1.1011 raeburn 11123: my $domdesc = &domain($udom);
11124: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 11125: my $first;
11126: if ($crstype eq 'Community') {
11127: $first = '0';
11128: } else {
11129: $first = int(1+rand(9));
11130: }
11131: my $uname=$first.
1.1011 raeburn 11132: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11133: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11134: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11135: # ----------------------------------------------- Make sure that does not exist
11136: my $uhome=&homeserver($uname,$udom,'true');
11137: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 11138: if ($crstype eq 'Community') {
11139: $first = '0';
11140: } else {
11141: $first = int(1+rand(9));
11142: }
11143: $uname=$first.
1.1011 raeburn 11144: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11145: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11146: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11147: $uhome=&homeserver($uname,$udom,'true');
11148: unless (($uhome eq '') || ($uhome eq 'no_host')) {
11149: return 'error: unable to generate unique course-ID';
11150: }
11151: }
11152: return $uname;
11153: }
11154:
1.813 albertel 11155: sub is_course {
1.1167 droeschl 11156: my ($cdom, $cnum) = scalar(@_) == 1 ?
11157: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
11158:
1.1381 raeburn 11159: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11160: my $uhome=&homeserver($cnum,$cdom);
11161: my $iscourse;
11162: if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382 raeburn 11163: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381 raeburn 11164: } else {
11165: my $hashid = $cdom.':'.$cnum;
11166: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11167: unless (defined($cached)) {
11168: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11169: $cnum,undef,undef,'.');
11170: $iscourse = 0;
11171: if (exists($courses{$cdom.'_'.$cnum})) {
11172: $iscourse = 1;
11173: }
11174: &do_cache_new('iscourse',$hashid,$iscourse,3600);
11175: }
11176: }
11177: return unless ($iscourse);
1.1167 droeschl 11178: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 11179: }
11180:
1.1015 raeburn 11181: sub store_userdata {
11182: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 11183: my $result;
1.1016 raeburn 11184: if ($datakey ne '') {
1.1013 raeburn 11185: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 11186: if ($udom eq '' || $uname eq '') {
11187: $udom = $env{'user.domain'};
11188: $uname = $env{'user.name'};
11189: }
11190: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 11191: if (($uhome eq '') || ($uhome eq 'no_host')) {
11192: $result = 'error: no_host';
11193: } else {
1.1434 raeburn 11194: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 11195: $storehash->{'host'} = $perlvar{'lonHostID'};
11196:
11197: my $namevalue='';
11198: foreach my $key (keys(%{$storehash})) {
11199: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11200: }
11201: $namevalue=~s/\&$//;
1.1224 raeburn 11202: unless ($namespace eq 'courserequests') {
11203: $datakey = &escape($datakey);
11204: }
1.1105 raeburn 11205: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
11206: $namevalue,$uhome);
1.1013 raeburn 11207: }
11208: } else {
11209: $result = 'error: data to store was not a hash reference';
11210: }
11211: } else {
11212: $result= 'error: invalid requestkey';
11213: }
11214: return $result;
11215: }
11216:
1.21 www 11217: # ---------------------------------------------------------- Assign Custom Role
11218:
11219: sub assigncustomrole {
1.957 raeburn 11220: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11221: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 11222: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 11223: }
11224:
11225: # ----------------------------------------------------------------- Revoke Role
11226:
11227: sub revokerole {
1.957 raeburn 11228: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11229: my $now=time;
1.965 raeburn 11230: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 11231: }
11232:
11233: # ---------------------------------------------------------- Revoke Custom Role
11234:
11235: sub revokecustomrole {
1.957 raeburn 11236: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11237: my $now=time;
1.357 www 11238: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 11239: $deleteflag,$selfenroll,$context);
1.17 www 11240: }
11241:
1.533 banghart 11242: # ------------------------------------------------------------ Disk usage
1.535 albertel 11243: sub diskusage {
1.955 raeburn 11244: my ($udom,$uname,$directorypath,$getpropath)=@_;
11245: $directorypath =~ s/\/$//;
11246: my $listing=&reply('du2:'.&escape($directorypath).':'
11247: .&escape($getpropath).':'.&escape($uname).':'
11248: .&escape($udom),homeserver($uname,$udom));
11249: if ($listing eq 'unknown_cmd') {
11250: if ($getpropath) {
11251: $directorypath = &propath($udom,$uname).'/'.$directorypath;
11252: }
11253: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11254: }
1.514 albertel 11255: return $listing;
1.512 banghart 11256: }
11257:
1.566 banghart 11258: sub is_locked {
1.1096 raeburn 11259: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 11260: my @check;
11261: my $is_locked;
1.1093 raeburn 11262: push (@check,$file_name);
1.613 albertel 11263: my %locked = &get('file_permissions',\@check,
1.620 albertel 11264: $env{'user.domain'},$env{'user.name'});
1.615 albertel 11265: my ($tmp)=keys(%locked);
11266: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 11267:
1.566 banghart 11268: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 11269: $is_locked = 'false';
11270: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 11271: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 11272: $is_locked = 'true';
1.1096 raeburn 11273: if (ref($which) eq 'ARRAY') {
11274: push(@{$which},$entry);
11275: } else {
11276: last;
11277: }
1.745 raeburn 11278: }
11279: }
1.566 banghart 11280: } else {
11281: $is_locked = 'false';
11282: }
1.1093 raeburn 11283: return $is_locked;
1.566 banghart 11284: }
11285:
1.759 albertel 11286: sub declutter_portfile {
11287: my ($file) = @_;
1.833 albertel 11288: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 11289: return $file;
11290: }
11291:
1.559 banghart 11292: # ------------------------------------------------------------- Mark as Read Only
11293:
11294: sub mark_as_readonly {
11295: my ($domain,$user,$files,$what) = @_;
1.613 albertel 11296: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11297: my ($tmp)=keys(%current_permissions);
11298: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 11299: foreach my $file (@{$files}) {
1.759 albertel 11300: $file = &declutter_portfile($file);
1.561 banghart 11301: push(@{$current_permissions{$file}},$what);
1.559 banghart 11302: }
1.613 albertel 11303: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11304: return;
11305: }
11306:
1.572 banghart 11307: # ------------------------------------------------------------Save Selected Files
11308:
11309: sub save_selected_files {
11310: my ($user, $path, @files) = @_;
11311: my $filename = $user."savedfiles";
1.573 banghart 11312: my @other_files = &files_not_in_path($user, $path);
1.1359 raeburn 11313: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 11314: foreach my $file (@files) {
1.620 albertel 11315: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 11316: }
11317: foreach my $file (@other_files) {
1.574 banghart 11318: print (OUT $file."\n");
1.572 banghart 11319: }
1.574 banghart 11320: close (OUT);
1.572 banghart 11321: return 'ok';
11322: }
11323:
1.574 banghart 11324: sub clear_selected_files {
11325: my ($user) = @_;
11326: my $filename = $user."savedfiles";
1.1359 raeburn 11327: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 11328: print (OUT undef);
11329: close (OUT);
11330: return ("ok");
11331: }
11332:
1.572 banghart 11333: sub files_in_path {
11334: my ($user, $path) = @_;
11335: my $filename = $user."savedfiles";
11336: my %return_files;
1.1359 raeburn 11337: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 11338: while (my $line_in = <IN>) {
1.574 banghart 11339: chomp ($line_in);
11340: my @paths_and_file = split (m!/!, $line_in);
11341: my $file_part = pop (@paths_and_file);
11342: my $path_part = join ('/', @paths_and_file);
1.573 banghart 11343: $path_part.='/';
11344: my $path_and_file = $path_part.$file_part;
11345: if ($path_part eq $path) {
11346: $return_files{$file_part}= 'selected';
11347: }
11348: }
1.574 banghart 11349: close (IN);
11350: return (\%return_files);
1.572 banghart 11351: }
11352:
11353: # called in portfolio select mode, to show files selected NOT in current directory
11354: sub files_not_in_path {
11355: my ($user, $path) = @_;
11356: my $filename = $user."savedfiles";
11357: my @return_files;
11358: my $path_part;
1.1359 raeburn 11359: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 11360: while (my $line = <IN>) {
1.572 banghart 11361: #ok, I know it's clunky, but I want it to work
1.800 albertel 11362: my @paths_and_file = split(m|/|, $line);
11363: my $file_part = pop(@paths_and_file);
11364: chomp($file_part);
11365: my $path_part = join('/', @paths_and_file);
1.572 banghart 11366: $path_part .= '/';
11367: my $path_and_file = $path_part.$file_part;
11368: if ($path_part ne $path) {
1.800 albertel 11369: push(@return_files, ($path_and_file));
1.572 banghart 11370: }
11371: }
1.800 albertel 11372: close(OUT);
1.574 banghart 11373: return (@return_files);
1.572 banghart 11374: }
11375:
1.1273 raeburn 11376: #------------------------------Submitted/Handedback Portfolio Files Versioning
11377:
11378: sub portfiles_versioning {
11379: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11380: my $portfolio_root = '/userfiles/portfolio';
11381: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11382: foreach my $file (@{$portfiles}) {
11383: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11384: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11385: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11386: my $getpropath = 1;
11387: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11388: $stu_name,$getpropath);
11389: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11390: my $new_answer =
11391: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11392: if ($new_answer ne 'problem getting file') {
11393: push(@{$versioned_portfiles}, $directory.$new_answer);
11394: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11395: [$symb,$env{'request.course.id'},'graded']);
11396: }
11397: }
11398: }
11399:
11400: sub get_next_version {
11401: my ($answer_name, $answer_ext, $dir_list) = @_;
11402: my $version;
11403: if (ref($dir_list) eq 'ARRAY') {
11404: foreach my $row (@{$dir_list}) {
11405: my ($file) = split(/\&/,$row,2);
11406: my ($file_name,$file_version,$file_ext) =
11407: &file_name_version_ext($file);
11408: if (($file_name eq $answer_name) &&
11409: ($file_ext eq $answer_ext)) {
11410: # gets here if filename and extension match,
11411: # regardless of version
11412: if ($file_version ne '') {
11413: # a versioned file is found so save it for later
11414: if ($file_version > $version) {
11415: $version = $file_version;
11416: }
11417: }
11418: }
11419: }
11420: }
11421: $version ++;
11422: return($version);
11423: }
11424:
11425: sub version_selected_portfile {
11426: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11427: my ($answer_name,$answer_ver,$answer_ext) =
11428: &file_name_version_ext($file_name);
11429: my $new_answer;
11430: $env{'form.copy'} =
11431: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11432: if($env{'form.copy'} eq '-1') {
11433: $new_answer = 'problem getting file';
11434: } else {
11435: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11436: my $copy_result =
11437: &finishuserfileupload($stu_name,$domain,'copy',
11438: '/portfolio'.$directory.$new_answer);
11439: }
11440: undef($env{'form.copy'});
11441: return ($new_answer);
11442: }
11443:
11444: sub file_name_version_ext {
11445: my ($file)=@_;
11446: my @file_parts = split(/\./, $file);
11447: my ($name,$version,$ext);
11448: if (@file_parts > 1) {
11449: $ext=pop(@file_parts);
11450: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11451: $version=pop(@file_parts);
11452: }
11453: $name=join('.',@file_parts);
11454: } else {
11455: $name=join('.',@file_parts);
11456: }
11457: return($name,$version,$ext);
11458: }
11459:
1.745 raeburn 11460: #----------------------------------------------Get portfolio file permissions
1.629 banghart 11461:
1.745 raeburn 11462: sub get_portfile_permissions {
11463: my ($domain,$user) = @_;
1.613 albertel 11464: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11465: my ($tmp)=keys(%current_permissions);
11466: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11467: return \%current_permissions;
11468: }
11469:
11470: #---------------------------------------------Get portfolio file access controls
11471:
1.749 raeburn 11472: sub get_access_controls {
1.745 raeburn 11473: my ($current_permissions,$group,$file) = @_;
1.769 albertel 11474: my %access;
11475: my $real_file = $file;
11476: $file =~ s/\.meta$//;
1.745 raeburn 11477: if (defined($file)) {
1.749 raeburn 11478: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11479: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 11480: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 11481: }
11482: }
1.745 raeburn 11483: } else {
1.749 raeburn 11484: foreach my $key (keys(%{$current_permissions})) {
11485: if ($key =~ /\0accesscontrol$/) {
11486: if (defined($group)) {
11487: if ($key !~ m-^\Q$group\E/-) {
11488: next;
11489: }
11490: }
11491: my ($fullpath) = split(/\0/,$key);
11492: if (ref($$current_permissions{$key}) eq 'HASH') {
11493: foreach my $control (keys(%{$$current_permissions{$key}})) {
11494: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11495: }
11496: }
11497: }
11498: }
11499: }
11500: return %access;
11501: }
11502:
11503: sub modify_access_controls {
11504: my ($file_name,$changes,$domain,$user)=@_;
11505: my ($outcome,$deloutcome);
11506: my %store_permissions;
11507: my %new_values;
11508: my %new_control;
11509: my %translation;
11510: my @deletions = ();
11511: my $now = time;
11512: if (exists($$changes{'activate'})) {
11513: if (ref($$changes{'activate'}) eq 'HASH') {
11514: my @newitems = sort(keys(%{$$changes{'activate'}}));
11515: my $numnew = scalar(@newitems);
11516: for (my $i=0; $i<$numnew; $i++) {
11517: my $newkey = $newitems[$i];
11518: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 11519: if ($newkey =~ /^\d+:/) {
11520: $newkey =~ s/^(\d+)/$newid/;
11521: $translation{$1} = $newid;
11522: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11523: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11524: $translation{$1} = $newid;
11525: }
1.749 raeburn 11526: $new_values{$file_name."\0".$newkey} =
11527: $$changes{'activate'}{$newitems[$i]};
11528: $new_control{$newkey} = $now;
11529: }
11530: }
11531: }
11532: my %todelete;
11533: my %changed_items;
11534: foreach my $action ('delete','update') {
11535: if (exists($$changes{$action})) {
11536: if (ref($$changes{$action}) eq 'HASH') {
11537: foreach my $key (keys(%{$$changes{$action}})) {
11538: my ($itemnum) = ($key =~ /^([^:]+):/);
11539: if ($action eq 'delete') {
11540: $todelete{$itemnum} = 1;
11541: } else {
11542: $changed_items{$itemnum} = $key;
11543: }
11544: }
1.745 raeburn 11545: }
11546: }
1.749 raeburn 11547: }
11548: # get lock on access controls for file.
11549: my $lockhash = {
11550: $file_name."\0".'locked_access_records' => $env{'user.name'}.
11551: ':'.$env{'user.domain'},
11552: };
11553: my $tries = 0;
11554: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11555:
1.1288 damieng 11556: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 11557: $tries ++;
1.1289 damieng 11558: sleep(0.1);
1.749 raeburn 11559: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11560: }
11561: if ($gotlock eq 'ok') {
11562: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11563: my ($tmp)=keys(%curr_permissions);
11564: if ($tmp=~/^error:/) { undef(%curr_permissions); }
11565: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11566: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11567: if (ref($curr_controls) eq 'HASH') {
11568: foreach my $control_item (keys(%{$curr_controls})) {
11569: my ($itemnum) = ($control_item =~ /^([^:]+):/);
11570: if (defined($todelete{$itemnum})) {
11571: push(@deletions,$file_name."\0".$control_item);
11572: } else {
11573: if (defined($changed_items{$itemnum})) {
11574: $new_control{$changed_items{$itemnum}} = $now;
11575: push(@deletions,$file_name."\0".$control_item);
11576: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11577: } else {
11578: $new_control{$control_item} = $$curr_controls{$control_item};
11579: }
11580: }
1.745 raeburn 11581: }
11582: }
11583: }
1.970 raeburn 11584: my ($group);
11585: if (&is_course($domain,$user)) {
11586: ($group,my $file) = split(/\//,$file_name,2);
11587: }
1.749 raeburn 11588: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11589: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11590: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11591: # remove lock
11592: my @del_lock = ($file_name."\0".'locked_access_records');
11593: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11594: my $sqlresult =
1.970 raeburn 11595: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11596: $group);
1.749 raeburn 11597: } else {
11598: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11599: }
1.749 raeburn 11600: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11601: }
11602:
1.827 raeburn 11603: sub make_public_indefinitely {
1.1271 raeburn 11604: my (@requrl) = @_;
11605: return &automated_portfile_access('public',\@requrl);
11606: }
11607:
11608: sub automated_portfile_access {
11609: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 11610: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11611: return 'invalid';
11612: }
1.1271 raeburn 11613: my %urls;
11614: if (ref($addsref) eq 'ARRAY') {
11615: foreach my $requrl (@{$addsref}) {
11616: if (&is_portfolio_url($requrl)) {
11617: unless (exists($urls{$requrl})) {
11618: $urls{$requrl} = 'add';
11619: }
11620: }
11621: }
11622: }
11623: if (ref($delsref) eq 'ARRAY') {
11624: foreach my $requrl (@{$delsref}) {
11625: if (&is_portfolio_url($requrl)) {
11626: unless (exists($urls{$requrl})) {
11627: $urls{$requrl} = 'delete';
11628: }
11629: }
11630: }
11631: }
11632: unless (keys(%urls)) {
11633: return 'invalid';
11634: }
11635: my $ip;
11636: if ($accesstype eq 'ip') {
11637: if (ref($info) eq 'HASH') {
11638: if ($info->{'ip'} ne '') {
11639: $ip = $info->{'ip'};
11640: }
11641: }
11642: if ($ip eq '') {
11643: return 'invalid';
11644: }
11645: }
11646: my $errors;
1.827 raeburn 11647: my $now = time;
1.1271 raeburn 11648: my %current_perms;
11649: foreach my $requrl (sort(keys(%urls))) {
11650: my $action;
11651: if ($urls{$requrl} eq 'add') {
11652: $action = 'activate';
11653: } else {
11654: $action = 'none';
11655: }
11656: my $aclnum = 0;
1.827 raeburn 11657: my (undef,$udom,$unum,$file_name,$group) =
11658: &parse_portfolio_url($requrl);
1.1271 raeburn 11659: unless (exists($current_perms{$unum.':'.$udom})) {
11660: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11661: }
11662: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 11663: $group,$file_name);
11664: foreach my $key (keys(%{$access_controls{$file_name}})) {
11665: my ($num,$scope,$end,$start) =
11666: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 11667: if ($scope eq $accesstype) {
11668: if (($start <= $now) && ($end == 0)) {
11669: if ($accesstype eq 'ip') {
11670: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11671: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11672: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11673: if ($urls{$requrl} eq 'add') {
11674: $action = 'none';
11675: last;
11676: } else {
11677: $action = 'delete';
11678: $aclnum = $num;
11679: last;
11680: }
11681: }
11682: }
11683: }
11684: } elsif ($accesstype eq 'public') {
11685: if ($urls{$requrl} eq 'add') {
11686: $action = 'none';
11687: last;
11688: } else {
11689: $action = 'delete';
11690: $aclnum = $num;
11691: last;
11692: }
11693: }
11694: } elsif ($accesstype eq 'public') {
1.827 raeburn 11695: $action = 'update';
11696: $aclnum = $num;
1.1271 raeburn 11697: last;
1.827 raeburn 11698: }
11699: }
11700: }
11701: if ($action eq 'none') {
1.1271 raeburn 11702: next;
1.827 raeburn 11703: } else {
11704: my %changes;
11705: my $newend = 0;
11706: my $newstart = $now;
1.1271 raeburn 11707: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 11708: $changes{$action}{$newkey} = {
1.1271 raeburn 11709: type => $accesstype,
1.827 raeburn 11710: time => {
11711: start => $newstart,
11712: end => $newend,
11713: },
11714: };
1.1271 raeburn 11715: if ($accesstype eq 'ip') {
11716: $changes{$action}{$newkey}{'ip'} = [$ip];
11717: }
1.827 raeburn 11718: my ($outcome,$deloutcome,$new_values,$translation) =
11719: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 11720: unless ($outcome eq 'ok') {
11721: $errors .= $outcome.' ';
11722: }
1.827 raeburn 11723: }
1.1271 raeburn 11724: }
11725: if ($errors) {
11726: $errors =~ s/\s$//;
11727: return $errors;
1.827 raeburn 11728: } else {
1.1271 raeburn 11729: return 'ok';
1.827 raeburn 11730: }
11731: }
11732:
1.745 raeburn 11733: #------------------------------------------------------Get Marked as Read Only
11734:
11735: sub get_marked_as_readonly {
11736: my ($domain,$user,$what,$group) = @_;
11737: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11738: my @readonly_files;
1.629 banghart 11739: my $cmp1=$what;
11740: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11741: while (my ($file_name,$value) = each(%{$current_permissions})) {
11742: if (defined($group)) {
11743: if ($file_name !~ m-^\Q$group\E/-) {
11744: next;
11745: }
11746: }
1.561 banghart 11747: if (ref($value) eq "ARRAY"){
11748: foreach my $stored_what (@{$value}) {
1.629 banghart 11749: my $cmp2=$stored_what;
1.759 albertel 11750: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11751: $cmp2=join('',@{$stored_what});
1.745 raeburn 11752: }
1.629 banghart 11753: if ($cmp1 eq $cmp2) {
1.561 banghart 11754: push(@readonly_files, $file_name);
1.745 raeburn 11755: last;
1.563 banghart 11756: } elsif (!defined($what)) {
11757: push(@readonly_files, $file_name);
1.745 raeburn 11758: last;
1.561 banghart 11759: }
11760: }
1.745 raeburn 11761: }
1.561 banghart 11762: }
11763: return @readonly_files;
11764: }
1.577 banghart 11765: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11766:
1.577 banghart 11767: sub get_marked_as_readonly_hash {
1.745 raeburn 11768: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11769: my %readonly_files;
1.745 raeburn 11770: while (my ($file_name,$value) = each(%{$current_permissions})) {
11771: if (defined($group)) {
11772: if ($file_name !~ m-^\Q$group\E/-) {
11773: next;
11774: }
11775: }
1.577 banghart 11776: if (ref($value) eq "ARRAY"){
11777: foreach my $stored_what (@{$value}) {
1.745 raeburn 11778: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11779: foreach my $lock_descriptor(@{$stored_what}) {
11780: if ($lock_descriptor eq 'graded') {
11781: $readonly_files{$file_name} = 'graded';
11782: } elsif ($lock_descriptor eq 'handback') {
11783: $readonly_files{$file_name} = 'handback';
11784: } else {
11785: if (!exists($readonly_files{$file_name})) {
11786: $readonly_files{$file_name} = 'locked';
11787: }
11788: }
1.745 raeburn 11789: }
1.750 banghart 11790: }
1.577 banghart 11791: }
11792: }
11793: }
11794: return %readonly_files;
11795: }
1.559 banghart 11796: # ------------------------------------------------------------ Unmark as Read Only
11797:
11798: sub unmark_as_readonly {
1.629 banghart 11799: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11800: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11801: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11802: $file_name = &declutter_portfile($file_name);
1.634 albertel 11803: my $symb_crs = $what;
11804: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11805: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11806: my ($tmp)=keys(%current_permissions);
11807: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11808: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11809: foreach my $file (@readonly_files) {
1.759 albertel 11810: my $clean_file = &declutter_portfile($file);
11811: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11812: my $current_locks = $current_permissions{$file};
1.563 banghart 11813: my @new_locks;
11814: my @del_keys;
11815: if (ref($current_locks) eq "ARRAY"){
11816: foreach my $locker (@{$current_locks}) {
1.632 albertel 11817: my $compare=$locker;
1.749 raeburn 11818: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11819: $compare=join('',@{$locker});
1.746 raeburn 11820: if ($compare ne $symb_crs) {
11821: push(@new_locks, $locker);
11822: }
1.563 banghart 11823: }
11824: }
1.650 albertel 11825: if (scalar(@new_locks) > 0) {
1.563 banghart 11826: $current_permissions{$file} = \@new_locks;
11827: } else {
11828: push(@del_keys, $file);
1.613 albertel 11829: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11830: delete($current_permissions{$file});
1.563 banghart 11831: }
11832: }
1.561 banghart 11833: }
1.613 albertel 11834: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11835: return;
11836: }
1.512 banghart 11837:
1.17 www 11838: # ------------------------------------------------------------ Directory lister
11839:
11840: sub dirlist {
1.955 raeburn 11841: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11842: $uri=~s/^\///;
11843: $uri=~s/\/$//;
1.253 stredwic 11844: my ($udom, $uname);
1.955 raeburn 11845: if ($getuserdir) {
1.253 stredwic 11846: $udom = $userdomain;
11847: $uname = $username;
1.955 raeburn 11848: } else {
11849: (undef,$udom,$uname)=split(/\//,$uri);
11850: if(defined($userdomain)) {
11851: $udom = $userdomain;
11852: }
11853: if(defined($username)) {
11854: $uname = $username;
11855: }
1.253 stredwic 11856: }
1.955 raeburn 11857: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11858:
1.955 raeburn 11859: $dirRoot = $perlvar{'lonDocRoot'};
11860: if (defined($getpropath)) {
11861: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11862: $dirRoot =~ s/\/$//;
1.955 raeburn 11863: } elsif (defined($getuserdir)) {
11864: my $subdir=$uname.'__';
11865: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11866: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11867: ."/$udom/$subdir/$uname";
11868: } elsif (defined($alternateRoot)) {
11869: $dirRoot = $alternateRoot;
1.751 banghart 11870: }
1.253 stredwic 11871:
11872: if($udom) {
11873: if($uname) {
1.1135 raeburn 11874: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11875: if ($uhome eq 'no_host') {
11876: return ([],'no_host');
11877: }
1.955 raeburn 11878: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11879: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11880: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11881: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11882: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11883: } else {
11884: @listing_results = map { &unescape($_); } split(/:/,$listing);
11885: }
1.605 matthew 11886: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11887: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11888: @listing_results = split(/:/,$listing);
11889: } else {
11890: @listing_results = map { &unescape($_); } split(/:/,$listing);
11891: }
1.1135 raeburn 11892: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11893: ($listing eq 'rejected') || ($listing eq 'refused') ||
11894: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11895: return ([],$listing);
11896: } else {
11897: return (\@listing_results);
1.1135 raeburn 11898: }
1.955 raeburn 11899: } elsif(!$alternateRoot) {
1.1136 raeburn 11900: my (%allusers,%listerror);
1.841 albertel 11901: my %servers = &get_servers($udom,'library');
1.955 raeburn 11902: foreach my $tryserver (keys(%servers)) {
11903: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11904: &escape($udom),$tryserver);
11905: if ($listing eq 'unknown_cmd') {
11906: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11907: $udom, $tryserver);
11908: } else {
11909: @listing_results = map { &unescape($_); } split(/:/,$listing);
11910: }
1.841 albertel 11911: if ($listing eq 'unknown_cmd') {
11912: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11913: $udom, $tryserver);
11914: @listing_results = split(/:/,$listing);
11915: } else {
11916: @listing_results =
11917: map { &unescape($_); } split(/:/,$listing);
11918: }
1.1136 raeburn 11919: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11920: ($listing eq 'rejected') || ($listing eq 'refused') ||
11921: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11922: $listerror{$tryserver} = $listing;
11923: } else {
1.841 albertel 11924: foreach my $line (@listing_results) {
11925: my ($entry) = split(/&/,$line,2);
11926: $allusers{$entry} = 1;
11927: }
11928: }
1.253 stredwic 11929: }
1.1136 raeburn 11930: my @alluserslist=();
1.800 albertel 11931: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11932: push(@alluserslist,$user.'&user');
1.253 stredwic 11933: }
1.1318 droeschl 11934:
11935: if (!%listerror) {
11936: # no errors
11937: return (\@alluserslist);
11938: } elsif (scalar(keys(%servers)) == 1) {
11939: # one library server, one error
11940: my ($key) = keys(%listerror);
11941: return (\@alluserslist, $listerror{$key});
11942: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11943: # con_lost indicates that we might miss data from at least one
11944: # library server
11945: return (\@alluserslist, 'con_lost');
11946: } else {
11947: # multiple library servers and no con_lost -> data should be
11948: # complete.
11949: return (\@alluserslist);
11950: }
11951:
1.253 stredwic 11952: } else {
1.1136 raeburn 11953: return ([],'missing username');
1.253 stredwic 11954: }
1.955 raeburn 11955: } elsif(!defined($getpropath)) {
1.1136 raeburn 11956: my $path = $perlvar{'lonDocRoot'}.'/res/';
11957: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11958: return (\@all_domains);
1.955 raeburn 11959: } else {
1.1136 raeburn 11960: return ([],'missing domain');
1.275 stredwic 11961: }
11962: }
11963:
11964: # --------------------------------------------- GetFileTimestamp
11965: # This function utilizes dirlist and returns the date stamp for
11966: # when it was last modified. It will also return an error of -1
11967: # if an error occurs
11968:
11969: sub GetFileTimestamp {
1.955 raeburn 11970: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11971: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11972: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11973: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11974: undef,$getuserdir);
11975: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11976: return -1;
11977: }
11978: if (ref($fileref) eq 'ARRAY') {
11979: my @stats = split('&',$fileref->[0]);
1.375 matthew 11980: # @stats contains first the filename, then the stat output
11981: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11982: } else {
11983: return -1;
1.253 stredwic 11984: }
1.26 www 11985: }
11986:
1.712 albertel 11987: sub stat_file {
11988: my ($uri) = @_;
1.787 albertel 11989: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11990:
1.955 raeburn 11991: my ($udom,$uname,$file);
1.712 albertel 11992: if ($uri =~ m-^/(uploaded|editupload)/-) {
11993: ($udom,$uname,$file) =
1.811 albertel 11994: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11995: $file = 'userfiles/'.$file;
11996: }
11997: if ($uri =~ m-^/res/-) {
11998: ($udom,$uname) =
1.807 albertel 11999: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 12000: $file = $uri;
12001: }
12002:
12003: if (!$udom || !$uname || !$file) {
12004: # unable to handle the uri
12005: return ();
12006: }
1.956 raeburn 12007: my $getpropath;
12008: if ($file =~ /^userfiles\//) {
12009: $getpropath = 1;
12010: }
1.1136 raeburn 12011: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12012: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12013: return ();
12014: } else {
12015: if (ref($listref) eq 'ARRAY') {
12016: my @stats = split('&',$listref->[0]);
12017: shift(@stats); #filename is first
12018: return @stats;
12019: }
1.712 albertel 12020: }
12021: return ();
12022: }
12023:
1.1313 raeburn 12024: # --------------------------------------------------------- recursedirs
12025: # Recursive function to traverse either a specific user's Authoring Space
12026: # or corresponding Published Resource Space, and populate the hash ref:
12027: # $dirhashref with URLs of all directories, and if $filehashref hash
12028: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
1.1503 ! raeburn 12029: # or .rights files in resource space, and .meta, .save, .log, .bak and
! 12030: # .rights files in Authoring Space.
1.1313 raeburn 12031: #
12032: # Inputs:
12033: #
12034: # $is_home - true if current server is home server for user's space
1.1503 ! raeburn 12035: # $recurse - if true will also traverse subdirectories recursively
! 12036: # $include - reference to hash containing allowed file extensions. If provided,
! 12037: # files which do not have a matching extension will be ignored.
! 12038: # $exclude - reference to hash containing excluded file extensions. If provided,
! 12039: # files which have a matching extension will be ignored.
! 12040: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
! 12041: # directory with first file found (with acceptable extension).
1.1313 raeburn 12042: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12043: # $relpath - Current path (relative to top level).
12044: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12045: # $filehashref - reference to hash to populate with URLs of files (Optional)
12046: #
12047: # Returns: nothing
12048: #
12049: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12050: #
12051: # Currently used by interface/londocs.pm to create linked select boxes for
12052: # directory and filename to import a Course "Author" resource into a course, and
12053: # also to create linked select boxes for Authoring Space and Directory to choose
12054: # save location for creation of a new "standard" problem from the Course Editor.
12055: #
12056:
12057: sub recursedirs {
1.1503 ! raeburn 12058: my ($is_home,$recurse,$include,$exclude,$nonemptydir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
1.1313 raeburn 12059: return unless (ref($dirhashref) eq 'HASH');
1.1503 ! raeburn 12060: my $docroot = $perlvar{'lonDocRoot'};
1.1313 raeburn 12061: my $currpath = $docroot.$toppath;
1.1503 ! raeburn 12062: if ($relpath ne '') {
1.1313 raeburn 12063: $currpath .= "/$relpath";
12064: }
1.1503 ! raeburn 12065: my ($savefile,$checkinc,$checkexc);
1.1313 raeburn 12066: if (ref($filehashref)) {
12067: $savefile = 1;
12068: }
1.1503 ! raeburn 12069: if (ref($include) eq 'HASH') {
! 12070: $checkinc = 1;
! 12071: }
! 12072: if (ref($exclude) eq 'HASH') {
! 12073: $checkexc = 1;
! 12074: }
1.1313 raeburn 12075: if ($is_home) {
12076: if (opendir(my $dirh,$currpath)) {
1.1503 ! raeburn 12077: my $filecount = 0;
1.1313 raeburn 12078: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12079: next if ($item eq '');
12080: if (-d "$currpath/$item") {
12081: my $newpath;
1.1503 ! raeburn 12082: if ($relpath ne '') {
1.1313 raeburn 12083: $newpath = "$relpath/$item";
12084: } else {
12085: $newpath = $item;
12086: }
12087: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
1.1503 ! raeburn 12088: if ($recurse) {
! 12089: &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$toppath,$newpath,$dirhashref,$filehashref);
! 12090: }
! 12091: } elsif (($savefile) || ($relpath eq '')) {
! 12092: next if ($nonemptydir && $filecount);
! 12093: if ($checkinc || $checkexc) {
! 12094: my ($extension) = ($item =~ /\.(\w+)$/);
! 12095: if ($checkinc) {
! 12096: next unless ($extension && $include->{$extension});
! 12097: }
! 12098: if ($checkexc) {
! 12099: next if ($extension && $exclude->{$extension});
! 12100: }
! 12101: }
! 12102: if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
! 12103: $dirhashref->{'/'} = 1;
! 12104: }
! 12105: if ($savefile) {
! 12106: if ($relpath eq '') {
! 12107: $filehashref->{'/'}{$item} = 1;
! 12108: } else {
1.1313 raeburn 12109: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12110: }
12111: }
1.1503 ! raeburn 12112: $filecount ++;
1.1313 raeburn 12113: }
12114: }
12115: closedir($dirh);
12116: }
12117: } else {
12118: my ($dirlistref,$listerror) =
12119: &dirlist($toppath.$relpath);
12120: my @dir_lines;
12121: my $dirptr=16384;
12122: if (ref($dirlistref) eq 'ARRAY') {
1.1503 ! raeburn 12123: my $filecount = 0;
1.1313 raeburn 12124: foreach my $dir_line (sort
12125: {
12126: my ($afile)=split('&',$a,2);
12127: my ($bfile)=split('&',$b,2);
12128: return (lc($afile) cmp lc($bfile));
12129: } (@{$dirlistref})) {
12130: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12131: split(/\&/,$dir_line,16);
12132: $item =~ s/\s+$//;
12133: next if (($item =~ /^\.\.?$/) || ($obs));
12134: if ($dirptr&$testdir) {
12135: my $newpath;
12136: if ($relpath) {
12137: $newpath = "$relpath/$item";
12138: } else {
12139: $newpath = $item;
12140: }
12141: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
1.1503 ! raeburn 12142: if ($recurse) {
! 12143: &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$toppath,$newpath,$dirhashref,$filehashref);
! 12144: }
! 12145: } elsif (($savefile) || ($relpath eq '')) {
! 12146: next if ($nonemptydir && $filecount);
! 12147: if ($checkinc || $checkexc) {
! 12148: my $extension;
! 12149: if ($checkinc) {
! 12150: next unless ($extension && $include->{$extension});
! 12151: }
! 12152: if ($checkexc) {
! 12153: next if ($extension && $exclude->{$extension});
! 12154: }
! 12155: }
! 12156: if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
! 12157: $dirhashref->{'/'} = 1;
! 12158: }
! 12159: if ($savefile) {
! 12160: if ($relpath eq '') {
! 12161: $filehashref->{'/'}{$item} = 1;
! 12162: } else {
! 12163: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
1.1313 raeburn 12164: }
12165: }
1.1503 ! raeburn 12166: $filecount ++;
1.1313 raeburn 12167: }
12168: }
12169: }
12170: }
12171: return;
12172: }
12173:
1.1503 ! raeburn 12174: sub priv_exclude {
! 12175: return {
! 12176: meta => 1,
! 12177: save => 1,
! 12178: log => 1,
! 12179: bak => 1,
! 12180: rights => 1,
! 12181: DS_Store => 1,
! 12182: };
! 12183: }
! 12184:
1.26 www 12185: # -------------------------------------------------------- Value of a Condition
12186:
1.713 albertel 12187: # gets the value of a specific preevaluated condition
12188: # stored in the string $env{user.state.<cid>}
12189: # or looks up a condition reference in the bighash and if if hasn't
12190: # already been evaluated recurses into docondval to get the value of
12191: # the condition, then memoizing it to
12192: # $env{user.state.<cid>.<condition>}
1.40 www 12193: sub directcondval {
12194: my $number=shift;
1.620 albertel 12195: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 12196: &Apache::lonuserstate::evalstate();
12197: }
1.713 albertel 12198: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12199: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12200: } elsif ($number =~ /^_/) {
12201: my $sub_condition;
12202: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12203: &GDBM_READER(),0640)) {
12204: $sub_condition=$bighash{'conditions'.$number};
12205: untie(%bighash);
12206: }
12207: my $value = &docondval($sub_condition);
1.949 raeburn 12208: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 12209: return $value;
12210: }
1.620 albertel 12211: if ($env{'user.state.'.$env{'request.course.id'}}) {
12212: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 12213: } else {
12214: return 2;
12215: }
12216: }
12217:
1.713 albertel 12218: # get the collection of conditions for this resource
1.26 www 12219: sub condval {
12220: my $condidx=shift;
1.54 www 12221: my $allpathcond='';
1.713 albertel 12222: foreach my $cond (split(/\|/,$condidx)) {
12223: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12224: $allpathcond.=
12225: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12226: }
1.191 harris41 12227: }
1.54 www 12228: $allpathcond=~s/\|$//;
1.713 albertel 12229: return &docondval($allpathcond);
12230: }
12231:
12232: #evaluates an expression of conditions
12233: sub docondval {
12234: my ($allpathcond) = @_;
12235: my $result=0;
12236: if ($env{'request.course.id'}
12237: && defined($allpathcond)) {
12238: my $operand='|';
12239: my @stack;
12240: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12241: if ($chunk eq '(') {
12242: push @stack,($operand,$result);
12243: } elsif ($chunk eq ')') {
12244: my $before=pop @stack;
12245: if (pop @stack eq '&') {
12246: $result=$result>$before?$before:$result;
12247: } else {
12248: $result=$result>$before?$result:$before;
12249: }
12250: } elsif (($chunk eq '&') || ($chunk eq '|')) {
12251: $operand=$chunk;
12252: } else {
12253: my $new=directcondval($chunk);
12254: if ($operand eq '&') {
12255: $result=$result>$new?$new:$result;
12256: } else {
12257: $result=$result>$new?$result:$new;
12258: }
12259: }
12260: }
1.26 www 12261: }
12262: return $result;
1.421 albertel 12263: }
12264:
12265: # ---------------------------------------------------- Devalidate courseresdata
12266:
12267: sub devalidatecourseresdata {
12268: my ($coursenum,$coursedomain)=@_;
12269: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12270: &devalidate_cache_new('courseres',$hashid);
1.28 www 12271: }
12272:
1.763 www 12273:
1.200 www 12274: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 12275: #
12276: # Parameters:
12277: # $coursenum - Number of the course.
12278: # $coursedomain - Domain at which the course was created.
12279: # Returns:
12280: # A hash of the course parameters along (I think) with timestamps
12281: # and version info.
1.877 foxr 12282:
1.624 albertel 12283: sub get_courseresdata {
12284: my ($coursenum,$coursedomain)=@_;
1.200 www 12285: my $coursehom=&homeserver($coursenum,$coursedomain);
12286: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12287: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 12288: my %dumpreply;
1.417 albertel 12289: unless (defined($cached)) {
1.624 albertel 12290: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 12291: $result=\%dumpreply;
1.251 albertel 12292: my ($tmp) = keys(%dumpreply);
12293: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 12294: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 12295: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12296: return $tmp;
1.416 albertel 12297: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 12298: $result=undef;
1.599 albertel 12299: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 12300: }
12301: }
1.624 albertel 12302: return $result;
12303: }
12304:
1.633 albertel 12305: sub devalidateuserresdata {
12306: my ($uname,$udom)=@_;
12307: my $hashid="$udom:$uname";
12308: &devalidate_cache_new('userres',$hashid);
12309: }
12310:
1.624 albertel 12311: sub get_userresdata {
12312: my ($uname,$udom)=@_;
12313: #most student don\'t have any data set, check if there is some data
12314: if (&EXT_cache_status($udom,$uname)) { return undef; }
12315:
12316: my $hashid="$udom:$uname";
12317: my ($result,$cached)=&is_cached_new('userres',$hashid);
12318: if (!defined($cached)) {
12319: my %resourcedata=&dump('resourcedata',$udom,$uname);
12320: $result=\%resourcedata;
12321: &do_cache_new('userres',$hashid,$result,600);
12322: }
12323: my ($tmp)=keys(%$result);
12324: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12325: return $result;
12326: }
12327: #error 2 occurs when the .db doesn't exist
12328: if ($tmp!~/error: 2 /) {
1.1294 raeburn 12329: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12330: &logthis("<font color=\"blue\">WARNING:".
12331: " Trying to get resource data for ".
12332: $uname." at ".$udom.": ".
12333: $tmp."</font>");
12334: }
1.624 albertel 12335: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 12336: #&EXT_cache_set($udom,$uname);
12337: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 12338: undef($tmp); # not really an error so don't send it back
1.624 albertel 12339: }
12340: return $tmp;
12341: }
1.879 foxr 12342: #----------------------------------------------- resdata - return resource data
12343: # Purpose:
12344: # Return resource data for either users or for a course.
12345: # Parameters:
12346: # $name - Course/user name.
12347: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 12348: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 12349: # $mapp - decluttered URL of enclosing map
12350: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
12351: # $recurseup - Ref to array of map URLs, starting with map containing
12352: # $mapp up through hierarchy of nested maps to top level map.
12353: # $courseid - CourseID (first part of param identifier).
12354: # $modifier - Middle part of param identifier.
12355: # $what - Last part of param identifier.
1.879 foxr 12356: # @which - Array of names of resources desired.
12357: # Returns:
12358: # The value of the first reasource in @which that is found in the
12359: # resource hash.
12360: # Exceptional Conditions:
12361: # If the $type passed in is not valid (not the string 'course' or
12362: # 'user', an undefined reference is returned.
12363: # If none of the resources are found, an undef is returned
1.624 albertel 12364: sub resdata {
1.1301 raeburn 12365: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12366: $modifier,$what,@which)=@_;
1.624 albertel 12367: my $result;
12368: if ($type eq 'course') {
12369: $result=&get_courseresdata($name,$domain);
12370: } elsif ($type eq 'user') {
12371: $result=&get_userresdata($name,$domain);
12372: }
12373: if (!ref($result)) { return $result; }
1.251 albertel 12374: foreach my $item (@which) {
1.1301 raeburn 12375: if ($item->[1] eq 'course') {
12376: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12377: unless ($$recursed) {
1.1302 raeburn 12378: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 12379: $$recursed = 1;
12380: }
12381: foreach my $item (@${recurseup}) {
12382: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12383: last if (defined($result->{$norecursechk}));
12384: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12385: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12386: }
12387: }
12388: }
12389: if (defined($result->{$item->[0]})) {
1.927 albertel 12390: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 12391: }
1.250 albertel 12392: }
1.291 albertel 12393: return undef;
1.200 www 12394: }
12395:
1.1360 raeburn 12396: sub get_domain_lti {
12397: my ($cdom,$context) = @_;
1.1483 raeburn 12398: my ($name,$cachename,%lti);
1.1360 raeburn 12399: if ($context eq 'consumer') {
12400: $name = 'ltitools';
12401: } elsif ($context eq 'provider') {
12402: $name = 'lti';
1.1483 raeburn 12403: } elsif ($context eq 'linkprot') {
12404: $name = 'ltisec';
1.1360 raeburn 12405: } else {
12406: return %lti;
12407: }
1.1483 raeburn 12408:
12409: if ($context eq 'linkprot') {
12410: $cachename = $context;
12411: } else {
12412: $cachename = $name;
12413: }
12414:
12415: my ($result,$cached)=&is_cached_new($cachename,$cdom);
1.1298 raeburn 12416: if (defined($cached)) {
12417: if (ref($result) eq 'HASH') {
1.1360 raeburn 12418: %lti = %{$result};
1.1298 raeburn 12419: }
12420: } else {
1.1360 raeburn 12421: my %domconfig = &get_dom('configuration',[$name],$cdom);
12422: if (ref($domconfig{$name}) eq 'HASH') {
1.1483 raeburn 12423: if ($context eq 'linkprot') {
12424: if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12425: %lti = %{$domconfig{$name}{'linkprot'}};
12426: }
12427: } else {
12428: %lti = %{$domconfig{$name}};
12429: }
12430: if (($context eq 'consumer') && (keys(%lti))) {
12431: my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
12432: if (ref($encdomconfig{$name}) eq 'HASH') {
12433: foreach my $id (keys(%lti)) {
12434: if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12435: foreach my $item ('key','secret') {
12436: $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12437: }
1.1344 raeburn 12438: }
12439: }
12440: }
12441: }
1.1298 raeburn 12442: }
12443: my $cachetime = 24*60*60;
1.1483 raeburn 12444: &do_cache_new($cachename,$cdom,\%lti,$cachetime);
1.1298 raeburn 12445: }
1.1360 raeburn 12446: return %lti;
1.1298 raeburn 12447: }
12448:
1.1463 raeburn 12449: sub get_course_lti {
12450: my ($cnum,$cdom) = @_;
12451: my $hashid=$cdom.'_'.$cnum;
12452: my %courselti;
12453: my ($result,$cached)=&is_cached_new('courselti',$hashid);
12454: if (defined($cached)) {
12455: if (ref($result) eq 'HASH') {
12456: %courselti = %{$result};
12457: }
12458: } else {
12459: %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
12460: my $cachetime = 24*60*60;
12461: &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
12462: }
12463: return %courselti;
12464: }
12465:
1.1479 raeburn 12466: sub courselti_itemid {
12467: my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12468: my ($chome,$itemid);
12469: $chome = &homeserver($cnum,$cdom);
12470: return if ($chome eq 'no_host');
12471: if (ref($params) eq 'HASH') {
12472: my $rep;
12473: if (grep { $_ eq $chome } current_machine_ids()) {
12474: $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12475: } else {
12476: my $escurl = &escape($url);
12477: my $escmethod = &escape($method);
12478: my $items = &freeze_escape($params);
12479: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12480: }
12481: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12482: ($rep eq 'unknown_cmd')) {
12483: $itemid = $rep;
12484: }
12485: }
12486: return $itemid;
12487: }
12488:
12489: sub domainlti_itemid {
12490: my ($cdom,$url,$method,$params,$context) = @_;
12491: my ($primary_id,$itemid);
12492: $primary_id = &domain($cdom,'primary');
12493: return if ($primary_id eq '');
12494: if (ref($params) eq 'HASH') {
12495: my $rep;
12496: if (grep { $_ eq $primary_id } current_machine_ids()) {
12497: $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12498: } else {
12499: my $cnum = '';
12500: my $escurl = &escape($url);
12501: my $escmethod = &escape($method);
12502: my $items = &freeze_escape($params);
12503: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12504: }
12505: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12506: ($rep eq 'unknown_cmd')) {
12507: $itemid = $rep;
12508: }
12509: }
12510: return $itemid;
12511: }
12512:
1.1496 raeburn 12513: sub count_supptools {
12514: my ($cnum,$cdom,$ignorecache,$reload)=@_;
12515: my $hashid=$cnum.':'.$cdom;
12516: my ($numexttools,$cached);
12517: unless ($ignorecache) {
12518: ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
12519: }
12520: unless (defined($cached)) {
12521: my $chome=&homeserver($cnum,$cdom);
12522: $numexttools = 0;
12523: unless ($chome eq 'no_host') {
1.1500 raeburn 12524: my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
1.1496 raeburn 12525: if (ref($supplemental) eq 'HASH') {
12526: if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12527: foreach my $key (keys(%{$supplemental->{'ids'}})) {
12528: if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
12529: $numexttools ++;
12530: }
12531: }
12532: }
12533: }
12534: }
12535: &do_cache_new('supptools',$hashid,$numexttools,600);
12536: }
12537: return $numexttools;
12538: }
12539:
12540: sub has_unhidden_suppfiles {
1.1498 raeburn 12541: my ($cnum,$cdom,$ignorecache,$possdel)=@_;
1.1236 raeburn 12542: my $hashid=$cnum.':'.$cdom;
1.1496 raeburn 12543: my ($showsupp,$cached);
1.1236 raeburn 12544: unless ($ignorecache) {
1.1496 raeburn 12545: ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
1.1236 raeburn 12546: }
12547: unless (defined($cached)) {
12548: my $chome=&homeserver($cnum,$cdom);
12549: unless ($chome eq 'no_host') {
1.1500 raeburn 12550: my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
1.1496 raeburn 12551: if (ref($supplemental) eq 'HASH') {
12552: if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12553: foreach my $key (keys(%{$supplemental->{'ids'}})) {
12554: next if ($key =~ /\.sequence$/);
12555: if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
12556: foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
12557: unless ($supplemental->{'hidden'}->{$id}) {
12558: $showsupp = 1;
12559: last;
12560: }
12561: }
12562: }
12563: last if ($showsupp);
12564: }
12565: }
12566: }
1.1236 raeburn 12567: }
1.1496 raeburn 12568: &do_cache_new('showsupp',$hashid,$showsupp,600);
1.1236 raeburn 12569: }
1.1496 raeburn 12570: return $showsupp;
12571: }
12572:
1.379 matthew 12573: #
12574: # EXT resource caching routines
12575: #
12576:
1.1302 raeburn 12577: {
12578: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12579: #
12580: # The course for which we cache
12581: my $cachedmapkey='';
12582: # The cached recursive maps for this course
12583: my %cachedmaps=();
12584: # When this was last done
12585: my $cachedmaptime='';
12586:
1.379 matthew 12587: sub clear_EXT_cache_status {
1.383 albertel 12588: &delenv('cache.EXT.');
1.379 matthew 12589: }
12590:
12591: sub EXT_cache_status {
12592: my ($target_domain,$target_user) = @_;
1.383 albertel 12593: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 12594: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 12595: # We know already the user has no data
12596: return 1;
12597: } else {
12598: return 0;
12599: }
12600: }
12601:
12602: sub EXT_cache_set {
12603: my ($target_domain,$target_user) = @_;
1.383 albertel 12604: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 12605: #&appenv({$cachename => time});
1.379 matthew 12606: }
12607:
1.28 www 12608: # --------------------------------------------------------- Value of a Variable
1.58 www 12609: sub EXT {
1.715 albertel 12610:
1.1461 raeburn 12611: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
1.68 www 12612: unless ($varname) { return ''; }
1.218 albertel 12613: #get real user name/domain, courseid and symb
12614: my $courseid;
1.359 albertel 12615: my $publicuser;
1.427 www 12616: if ($symbparm) {
12617: $symbparm=&get_symb_from_alias($symbparm);
12618: }
1.218 albertel 12619: if (!($uname && $udom)) {
1.790 albertel 12620: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 12621: if (!$symbparm) { $symbparm=$cursymb; }
12622: } else {
1.620 albertel 12623: $courseid=$env{'request.course.id'};
1.218 albertel 12624: }
1.48 www 12625: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12626: my $rest;
1.320 albertel 12627: if (defined($therest[0])) {
1.48 www 12628: $rest=join('.',@therest);
12629: } else {
12630: $rest='';
12631: }
1.320 albertel 12632:
1.57 www 12633: my $qualifierrest=$qualifier;
12634: if ($rest) { $qualifierrest.='.'.$rest; }
12635: my $spacequalifierrest=$space;
12636: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 12637: if ($realm eq 'user') {
1.48 www 12638: # --------------------------------------------------------------- user.resource
12639: if ($space eq 'resource') {
1.651 albertel 12640: if ( (defined($Apache::lonhomework::parsing_a_problem)
12641: || defined($Apache::lonhomework::parsing_a_task))
12642: &&
1.1469 raeburn 12643: ($symbparm eq &symbread()) ) {
1.744 albertel 12644: # if we are in the middle of processing the resource the
12645: # get the value we are planning on committing
12646: if (defined($Apache::lonhomework::results{$qualifierrest})) {
12647: return $Apache::lonhomework::results{$qualifierrest};
12648: } else {
12649: return $Apache::lonhomework::history{$qualifierrest};
12650: }
1.335 albertel 12651: } else {
1.359 albertel 12652: my %restored;
1.620 albertel 12653: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 12654: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12655: } else {
12656: %restored=&restore($symbparm,$courseid,$udom,$uname);
12657: }
1.335 albertel 12658: return $restored{$qualifierrest};
12659: }
1.48 www 12660: # ----------------------------------------------------------------- user.access
12661: } elsif ($space eq 'access') {
1.218 albertel 12662: # FIXME - not supporting calls for a specific user
1.48 www 12663: return &allowed($qualifier,$rest);
12664: # ------------------------------------------ user.preferences, user.environment
12665: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 12666: if (($uname eq $env{'user.name'}) &&
12667: ($udom eq $env{'user.domain'})) {
12668: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 12669: } else {
1.359 albertel 12670: my %returnhash;
12671: if (!$publicuser) {
12672: %returnhash=&userenvironment($udom,$uname,
12673: $qualifierrest);
12674: }
1.218 albertel 12675: return $returnhash{$qualifierrest};
12676: }
1.48 www 12677: # ----------------------------------------------------------------- user.course
12678: } elsif ($space eq 'course') {
1.218 albertel 12679: # FIXME - not supporting calls for a specific user
1.620 albertel 12680: return $env{join('.',('request.course',$qualifier))};
1.48 www 12681: # ------------------------------------------------------------------- user.role
12682: } elsif ($space eq 'role') {
1.218 albertel 12683: # FIXME - not supporting calls for a specific user
1.620 albertel 12684: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 12685: if ($qualifier eq 'value') {
12686: return $role;
12687: } elsif ($qualifier eq 'extent') {
12688: return $where;
12689: }
12690: # ----------------------------------------------------------------- user.domain
12691: } elsif ($space eq 'domain') {
1.218 albertel 12692: return $udom;
1.48 www 12693: # ------------------------------------------------------------------- user.name
12694: } elsif ($space eq 'name') {
1.218 albertel 12695: return $uname;
1.48 www 12696: # ---------------------------------------------------- Any other user namespace
1.29 www 12697: } else {
1.359 albertel 12698: my %reply;
12699: if (!$publicuser) {
12700: %reply=&get($space,[$qualifierrest],$udom,$uname);
12701: }
12702: return $reply{$qualifierrest};
1.48 www 12703: }
1.236 www 12704: } elsif ($realm eq 'query') {
12705: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 12706: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12707: [$spacequalifierrest]);
1.620 albertel 12708: return $env{'form.'.$spacequalifierrest};
1.236 www 12709: } elsif ($realm eq 'request') {
1.48 www 12710: # ------------------------------------------------------------- request.browser
12711: if ($space eq 'browser') {
1.1145 bisitz 12712: return $env{'browser.'.$qualifier};
1.57 www 12713: # ------------------------------------------------------------ request.filename
12714: } else {
1.620 albertel 12715: return $env{'request.'.$spacequalifierrest};
1.29 www 12716: }
1.28 www 12717: } elsif ($realm eq 'course') {
1.48 www 12718: # ---------------------------------------------------------- course.description
1.620 albertel 12719: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 12720: } elsif ($realm eq 'resource') {
1.165 www 12721:
1.620 albertel 12722: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 12723: if (!$symbparm) { $symbparm=&symbread(); }
12724: }
1.693 albertel 12725:
1.1232 raeburn 12726: if ($qualifier eq '') {
12727: if ($space eq 'title') {
12728: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12729: return &gettitle($symbparm);
12730: }
1.693 albertel 12731:
1.1232 raeburn 12732: if ($space eq 'map') {
12733: my ($map) = &decode_symb($symbparm);
12734: return &symbread($map);
12735: }
12736: if ($space eq 'maptitle') {
12737: my ($map) = &decode_symb($symbparm);
12738: return &gettitle($map);
12739: }
12740: if ($space eq 'filename') {
12741: if ($symbparm) {
12742: return &clutter((&decode_symb($symbparm))[2]);
12743: }
12744: return &hreflocation('',$env{'request.filename'});
1.905 albertel 12745: }
1.1232 raeburn 12746:
1.1233 raeburn 12747: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12748: if ($space eq 'visibleparts') {
12749: my $navmap = Apache::lonnavmaps::navmap->new();
12750: my $item;
12751: if (ref($navmap)) {
12752: my $res = $navmap->getBySymb($symbparm);
12753: my $parts = $res->parts();
12754: if (ref($parts) eq 'ARRAY') {
12755: $item = join(',',@{$parts});
12756: }
12757: undef($navmap);
1.1232 raeburn 12758: }
1.1233 raeburn 12759: return $item;
1.1232 raeburn 12760: }
12761: }
12762: }
1.693 albertel 12763:
1.1301 raeburn 12764: my ($section, $group, @groups, @recurseup, $recursed);
1.1461 raeburn 12765: if (ref($recurseupref) eq 'ARRAY') {
12766: @recurseup = @{$recurseupref};
12767: $recursed = 1;
12768: }
1.1301 raeburn 12769: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 12770: if (($courseid eq '') && ($cid)) {
12771: $courseid = $cid;
12772: }
12773: if (($symbparm && $courseid) &&
12774: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 12775:
1.218 albertel 12776: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 12777:
1.60 www 12778: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 12779: my $symbp=$symbparm;
1.1301 raeburn 12780: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 12781: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 12782: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 12783: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 12784: if (($env{'user.name'} eq $uname) &&
12785: ($env{'user.domain'} eq $udom)) {
12786: $section=$env{'request.course.sec'};
1.733 raeburn 12787: @groups = split(/:/,$env{'request.course.groups'});
12788: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 12789: } else {
1.539 albertel 12790: if (! defined($usection)) {
1.551 albertel 12791: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 12792: } else {
12793: $section = $usection;
12794: }
1.733 raeburn 12795: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 12796: }
12797:
12798: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12799: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 12800: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 12801: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12802:
1.593 albertel 12803: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 12804: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 12805: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 12806: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 12807:
1.60 www 12808: # ----------------------------------------------------------- first, check user
1.624 albertel 12809:
1.1301 raeburn 12810: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12811: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 12812: ([$courselevelr,'resource'],
12813: [$courselevelm,'map' ],
1.1301 raeburn 12814: [$courseleveli,'map' ],
1.927 albertel 12815: [$courselevel, 'course' ]));
1.931 albertel 12816: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 12817:
1.594 albertel 12818: # ------------------------------------------------ second, check some of course
1.684 raeburn 12819: my $coursereply;
1.691 raeburn 12820: if (@groups > 0) {
12821: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 12822: $recurseparm,$mapparm,$spacequalifierrest,
12823: $mapp,\$recursed,\@recurseup);
12824: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 12825: }
1.96 www 12826:
1.684 raeburn 12827: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 12828: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12829: 'course',$mapp,\$recursed,\@recurseup,
12830: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 12831: ([$seclevelr, 'resource'],
12832: [$seclevelm, 'map' ],
1.1301 raeburn 12833: [$secleveli, 'map' ],
1.927 albertel 12834: [$seclevel, 'course' ],
12835: [$courselevelr,'resource']));
12836: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 12837:
1.60 www 12838: # ------------------------------------------------------ third, check map parms
1.218 albertel 12839: my %parmhash=();
12840: my $thisparm='';
12841: if (tie(%parmhash,'GDBM_File',
1.620 albertel 12842: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 12843: &GDBM_READER(),0640)) {
1.218 albertel 12844: $thisparm=$parmhash{$symbparm};
12845: untie(%parmhash);
12846: }
1.927 albertel 12847: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 12848: }
1.594 albertel 12849: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 12850:
12851: my $what = $spacequalifierrest;
12852: $what=~s/\./\_/;
1.282 albertel 12853: my $filename;
12854: if (!$symbparm) { $symbparm=&symbread(); }
12855: if ($symbparm) {
1.409 www 12856: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 12857: } else {
1.620 albertel 12858: $filename=$env{'request.filename'};
1.282 albertel 12859: }
1.1362 raeburn 12860: my $toolsymb;
12861: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12862: $toolsymb = $symbparm;
12863: }
12864: my $metadata=&metadata($filename,$what,$toolsymb);
1.927 albertel 12865: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362 raeburn 12866: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927 albertel 12867: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 12868:
1.1301 raeburn 12869: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 12870: if ($symbparm && defined($courseid) &&
1.620 albertel 12871: $courseid eq $env{'request.course.id'}) {
1.624 albertel 12872: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12873: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12874: 'course',$mapp,\$recursed,\@recurseup,
12875: $courseid,'.',$spacequalifierrest,
1.927 albertel 12876: ([$courselevelm,'map' ],
1.1301 raeburn 12877: [$courseleveli,'map' ],
1.927 albertel 12878: [$courselevel, 'course']));
12879: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 12880: }
1.145 www 12881: # ------------------------------------------------------------------ Cascade up
1.218 albertel 12882: unless ($space eq '0') {
1.336 albertel 12883: my @parts=split(/_/,$space);
12884: my $id=pop(@parts);
12885: my $part=join('_',@parts);
12886: if ($part eq '') { $part='0'; }
1.927 albertel 12887: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 12888: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 12889: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 12890: }
1.395 albertel 12891: if ($recurse) { return undef; }
1.1362 raeburn 12892: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927 albertel 12893: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 12894: # ---------------------------------------------------- Any other user namespace
12895: } elsif ($realm eq 'environment') {
12896: # ----------------------------------------------------------------- environment
1.620 albertel 12897: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12898: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 12899: } else {
1.770 albertel 12900: if ($uname eq 'anonymous' && $udom eq '') {
12901: return '';
12902: }
1.219 albertel 12903: my %returnhash=&userenvironment($udom,$uname,
12904: $spacequalifierrest);
12905: return $returnhash{$spacequalifierrest};
12906: }
1.28 www 12907: } elsif ($realm eq 'system') {
1.48 www 12908: # ----------------------------------------------------------------- system.time
12909: if ($space eq 'time') {
12910: return time;
12911: }
1.696 albertel 12912: } elsif ($realm eq 'server') {
12913: # ----------------------------------------------------------------- system.time
12914: if ($space eq 'name') {
12915: return $ENV{'SERVER_NAME'};
12916: }
1.1415 raeburn 12917: } elsif ($realm eq 'client') {
12918: if ($space eq 'remote_addr') {
1.1441 raeburn 12919: return &get_requestor_ip();
1.1415 raeburn 12920: }
1.28 www 12921: }
1.48 www 12922: return '';
1.61 www 12923: }
12924:
1.927 albertel 12925: sub get_reply {
12926: my ($reply_value) = @_;
1.940 raeburn 12927: if (ref($reply_value) eq 'ARRAY') {
12928: if (wantarray) {
12929: return @$reply_value;
12930: }
12931: return $reply_value->[0];
12932: } else {
12933: return $reply_value;
1.927 albertel 12934: }
12935: }
12936:
1.691 raeburn 12937: sub check_group_parms {
1.1301 raeburn 12938: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12939: $recursed,$recurseupref) = @_;
12940: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12941: [$what,'course']);
12942: my $coursereply;
1.691 raeburn 12943: foreach my $group (@{$groups}) {
1.1301 raeburn 12944: my @groupitems = ();
1.691 raeburn 12945: foreach my $level (@levels) {
1.927 albertel 12946: my $item = $courseid.'.['.$group.'].'.$level->[0];
12947: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 12948: }
1.1301 raeburn 12949: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12950: $env{'course.'.$courseid.'.domain'},
12951: 'course',$mapp,$recursed,$recurseupref,
12952: $courseid,'.['.$group.'].',$what,
12953: @groupitems);
12954: last if (defined($coursereply));
1.691 raeburn 12955: }
12956: return $coursereply;
12957: }
12958:
1.1301 raeburn 12959: sub get_map_hierarchy {
1.1302 raeburn 12960: my ($mapname,$courseid) = @_;
12961: my @recurseup = ();
1.1301 raeburn 12962: if ($mapname) {
1.1302 raeburn 12963: if (($cachedmapkey eq $courseid) &&
12964: (abs($cachedmaptime-time)<5)) {
12965: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12966: return @{$cachedmaps{$mapname}};
12967: }
12968: }
1.1301 raeburn 12969: my $navmap = Apache::lonnavmaps::navmap->new();
12970: if (ref($navmap)) {
12971: @recurseup = $navmap->recurseup_maps($mapname);
12972: undef($navmap);
1.1302 raeburn 12973: $cachedmaps{$mapname} = \@recurseup;
12974: $cachedmaptime=time;
12975: $cachedmapkey=$courseid;
1.1301 raeburn 12976: }
12977: }
12978: return @recurseup;
12979: }
12980:
1.1302 raeburn 12981: }
12982:
1.691 raeburn 12983: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 12984: my ($courseid,@groups) = @_;
12985: @groups = sort(@groups);
1.691 raeburn 12986: return @groups;
12987: }
12988:
1.395 albertel 12989: sub packages_tab_default {
1.1362 raeburn 12990: my ($uri,$varname,$toolsymb)=@_;
1.395 albertel 12991: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 12992:
12993: my (@extension,@specifics,$do_default);
1.1362 raeburn 12994: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395 albertel 12995: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 12996: if ($pack_type eq 'default') {
12997: $do_default=1;
12998: } elsif ($pack_type eq 'extension') {
12999: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 13000: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 13001: # only look at packages defaults for packages that this id is
1.738 albertel 13002: push(@specifics,[$package,$pack_type,$pack_part]);
13003: }
13004: }
13005: # first look for a package that matches the requested part id
13006: foreach my $package (@specifics) {
13007: my (undef,$pack_type,$pack_part)=@{$package};
13008: next if ($pack_part ne $part);
13009: if (defined($packagetab{"$pack_type&$name&default"})) {
13010: return $packagetab{"$pack_type&$name&default"};
13011: }
13012: }
13013: # look for any possible matching non extension_ package
13014: foreach my $package (@specifics) {
13015: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 13016: if (defined($packagetab{"$pack_type&$name&default"})) {
13017: return $packagetab{"$pack_type&$name&default"};
13018: }
1.585 albertel 13019: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 13020: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13021: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 13022: }
13023: }
1.738 albertel 13024: # look for any posible extension_ match
13025: foreach my $package (@extension) {
13026: my ($package,$pack_type)=@{$package};
13027: if (defined($packagetab{"$pack_type&$name&default"})) {
13028: return $packagetab{"$pack_type&$name&default"};
13029: }
13030: if (defined($packagetab{$package."&$name&default"})) {
13031: return $packagetab{$package."&$name&default"};
13032: }
13033: }
13034: # look for a global default setting
13035: if ($do_default && defined($packagetab{"default&$name&default"})) {
13036: return $packagetab{"default&$name&default"};
13037: }
1.395 albertel 13038: return undef;
13039: }
13040:
1.334 albertel 13041: sub add_prefix_and_part {
13042: my ($prefix,$part)=@_;
13043: my $keyroot;
13044: if (defined($prefix) && $prefix !~ /^__/) {
13045: # prefix that has a part already
13046: $keyroot=$prefix;
13047: } elsif (defined($prefix)) {
13048: # prefix that is missing a part
13049: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13050: } else {
13051: # no prefix at all
13052: if (defined($part)) { $keyroot='_'.$part; }
13053: }
13054: return $keyroot;
13055: }
13056:
1.71 www 13057: # ---------------------------------------------------------------- Get metadata
13058:
1.599 albertel 13059: my %metaentry;
1.1070 www 13060: my %importedpartids;
1.1369 raeburn 13061: my %importedrespids;
1.71 www 13062: sub metadata {
1.1362 raeburn 13063: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71 www 13064: $uri=&declutter($uri);
1.288 albertel 13065: # if it is a non metadata possible uri return quickly
1.529 albertel 13066: if (($uri eq '') ||
13067: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 13068: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 13069: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 13070: return undef;
13071: }
1.1261 raeburn 13072: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 13073: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 13074: return undef;
1.288 albertel 13075: }
1.73 www 13076: my $filename=$uri;
13077: $uri=~s/\.meta$//;
1.172 www 13078: #
13079: # Is the metadata already cached?
1.177 www 13080: # Look at timestamp of caching
1.172 www 13081: # Everything is cached by the main uri, libraries are never directly cached
13082: #
1.428 albertel 13083: if (!defined($liburi)) {
1.599 albertel 13084: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 13085: if (defined($cached)) { return $result->{':'.$what}; }
13086: }
1.1362 raeburn 13087:
13088: #
13089: # If the uri is for an external tool the file from
13090: # which metadata should be retrieved depends on whether
13091: # the tool had been configured to be gradable (set in the Course
13092: # Editor or Resource Editor).
13093: #
13094: # If a valid symb has been included as the third arg in the call
13095: # to &metadata() that can be used to retrieve the value of
13096: # parameter_0_gradable set for the resource, and included in the
13097: # uploaded map containing the tool. The value is retrieved via
13098: # &EXT(), if a valid symb is available. Otherwise the value of
13099: # gradable in the exttool_$marker.db file for the tool instance
1.1364 raeburn 13100: # is retrieved via &get().
13101: #
13102: # When lonuserstate::traceroute() calls lonnet::EXT() for
13103: # hiddenresource and encrypturl (during course initialization)
13104: # the map-level parameter for resource.0.gradable included in the
13105: # uploaded map containing the tool will not yet have been stored
13106: # in the user_course_parms.db file for the user's session, so in
13107: # this case fall back to retrieving gradable status from the
13108: # exttool_$marker.db file.
1.1362 raeburn 13109: #
13110: # In order to avoid an infinite loop, &metadata() will return
13111: # before a call to &EXT(), if the uri is for an external tool
13112: # and the $what for which metadata is being requested is
13113: # parameter_0_gradable or 0_gradable.
13114: #
13115:
13116: if ($uri =~ /ext\.tool$/) {
13117: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13118: return;
13119: } else {
13120: my ($checked,$use_passback);
13121: if ($toolsymb ne '') {
13122: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364 raeburn 13123: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362 raeburn 13124: $checked = 1;
13125: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13126: $use_passback = 1;
13127: }
13128: }
13129: }
13130: unless ($checked) {
13131: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13132: $marker=~s/\D//g;
1.1363 raeburn 13133: if ($marker) {
1.1362 raeburn 13134: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13135: $use_passback = $toolsettings{'gradable'};
13136: }
13137: }
13138: if ($use_passback) {
13139: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13140: } else {
13141: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13142: }
13143: }
13144: }
13145:
1.428 albertel 13146: {
1.1069 www 13147: # Imported parts would go here
1.1369 raeburn 13148: my @origfiletagids=();
1.1069 www 13149: my $importedparts=0;
1.1369 raeburn 13150:
13151: # Imported responseids would go here
13152: my $importedresponses=0;
1.172 www 13153: #
13154: # Is this a recursive call for a library?
13155: #
1.599 albertel 13156: # if (! exists($metacache{$uri})) {
13157: # $metacache{$uri}={};
13158: # }
1.924 albertel 13159: my $cachetime = 60*60;
1.171 www 13160: if ($liburi) {
13161: $liburi=&declutter($liburi);
13162: $filename=$liburi;
1.401 bowersj2 13163: } else {
1.599 albertel 13164: &devalidate_cache_new('meta',$uri);
13165: undef(%metaentry);
1.401 bowersj2 13166: }
1.140 www 13167: my %metathesekeys=();
1.73 www 13168: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 13169: my $metastring;
1.1140 www 13170: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 13171: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 13172: $metastring =
1.929 albertel 13173: &Apache::lonnet::ssi_body($which,
1.924 albertel 13174: ('grade_target' => 'meta'));
13175: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 13176: } elsif (($uri !~ m -^(editupload)/-) &&
13177: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 13178: my $file=&filelocation('',&clutter($filename));
1.599 albertel 13179: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 13180: $metastring=&getfile($file);
1.489 albertel 13181: }
1.208 albertel 13182: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 13183: my $token;
1.140 www 13184: undef %metathesekeys;
1.71 www 13185: while ($token=$parser->get_token) {
1.339 albertel 13186: if ($token->[0] eq 'S') {
13187: if (defined($token->[2]->{'package'})) {
1.172 www 13188: #
13189: # This is a package - get package info
13190: #
1.339 albertel 13191: my $package=$token->[2]->{'package'};
13192: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13193: if (defined($token->[2]->{'id'})) {
13194: $keyroot.='_'.$token->[2]->{'id'};
13195: }
1.599 albertel 13196: if ($metaentry{':packages'}) {
13197: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 13198: } else {
1.599 albertel 13199: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 13200: }
1.736 albertel 13201: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 13202: my $part=$keyroot;
13203: $part=~s/^\_//;
1.736 albertel 13204: if ($pack_entry=~/^\Q$package\E\&/ ||
13205: $pack_entry=~/^\Q$package\E_0\&/) {
13206: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 13207: # ignore package.tab specified default values
13208: # here &package_tab_default() will fetch those
13209: if ($subp eq 'default') { next; }
1.736 albertel 13210: my $value=$packagetab{$pack_entry};
1.432 albertel 13211: my $unikey;
13212: if ($pack =~ /_0$/) {
13213: $unikey='parameter_0_'.$name;
13214: $part=0;
13215: } else {
13216: $unikey='parameter'.$keyroot.'_'.$name;
13217: }
1.339 albertel 13218: if ($subp eq 'display') {
13219: $value.=' [Part: '.$part.']';
13220: }
1.599 albertel 13221: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 13222: $metathesekeys{$unikey}=1;
1.599 albertel 13223: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13224: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 13225: }
1.599 albertel 13226: if (defined($metaentry{':'.$unikey.'.default'})) {
13227: $metaentry{':'.$unikey}=
13228: $metaentry{':'.$unikey.'.default'};
1.356 albertel 13229: }
1.339 albertel 13230: }
13231: }
13232: } else {
1.172 www 13233: #
13234: # This is not a package - some other kind of start tag
1.339 albertel 13235: #
13236: my $entry=$token->[1];
1.1068 www 13237: my $unikey='';
1.175 www 13238:
1.339 albertel 13239: if ($entry eq 'import') {
1.175 www 13240: #
13241: # Importing a library here
1.339 albertel 13242: #
1.1067 www 13243: my $location=$parser->get_text('/import');
13244: my $dir=$filename;
13245: $dir=~s|[^/]*$||;
13246: $location=&filelocation($dir,$location);
1.1369 raeburn 13247:
13248: my $importid=$token->[2]->{'id'};
1.1068 www 13249: my $importmode=$token->[2]->{'importmode'};
1.1369 raeburn 13250: #
13251: # Check metadata for imported file to
13252: # see if it contained response items
13253: #
1.1372 raeburn 13254: my ($origfile,@libfilekeys);
1.1370 raeburn 13255: my %currmetaentry = %metaentry;
1.1372 raeburn 13256: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13257: $depthcount+1));
13258: if (grep(/^responseorder$/,@libfilekeys)) {
13259: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13260: undef,$depthcount+1);
13261: if ($libresponseorder ne '') {
13262: if ($#origfiletagids<0) {
13263: undef(%importedrespids);
13264: undef(%importedpartids);
13265: }
1.1373 raeburn 13266: my @respids = split(/\s*,\s*/,$libresponseorder);
13267: if (@respids) {
13268: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13269: }
13270: if ($importedrespids{$importid} ne '') {
1.1372 raeburn 13271: $importedresponses = 1;
1.1369 raeburn 13272: # We need to get the original file and the imported file to get the response order correct
13273: # Load and inspect original file
1.1372 raeburn 13274: if ($#origfiletagids<0) {
13275: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13276: $origfile=&getfile($origfilelocation);
13277: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13278: }
1.1369 raeburn 13279: }
13280: }
13281: }
1.1370 raeburn 13282: # Do not overwrite contents of %metaentry hash for resource itself with
13283: # hash populated for imported library file
13284: %metaentry = %currmetaentry;
13285: undef(%currmetaentry);
1.1374 raeburn 13286: if ($importmode eq 'part') {
1.1068 www 13287: # Import as part(s)
1.1069 www 13288: $importedparts=1;
13289: # We need to get the original file and the imported file to get the part order correct
13290: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369 raeburn 13291: # Load and inspect original file if we didn't do that already
13292: if ($#origfiletagids<0) {
13293: undef(%importedrespids);
13294: undef(%importedpartids);
13295: if ($origfile eq '') {
13296: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13297: $origfile=&getfile($origfilelocation);
13298: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13299: }
1.1070 www 13300: }
1.1372 raeburn 13301: my @impfilepartids;
13302: # If <partorder> tag is included in metadata for the imported file
13303: # get the parts in the imported file from that.
13304: if (grep(/^partorder$/,@libfilekeys)) {
13305: %currmetaentry = %metaentry;
13306: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13307: $depthcount+1);
13308: %metaentry = %currmetaentry;
13309: undef(%currmetaentry);
13310: if ($libpartorder ne '') {
13311: @impfilepartids=split(/\s*,\s*/,$libpartorder);
13312: }
13313: } else {
13314: # If no <partorder> tag available, load and inspect imported file
13315: my $impfile=&getfile($location);
13316: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13317: }
1.1069 www 13318: if ($#impfilepartids>=0) {
13319: # This problem had parts
1.1070 www 13320: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 13321: } else {
13322: # Importing by turning a single problem into a problem part
13323: # It gets the import-tags ID as part-ID
13324: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 13325: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 13326: }
1.1068 www 13327: } else {
1.1374 raeburn 13328: # Import as problem or as normal import
13329: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13330: unless ($importmode eq 'problem') {
1.1068 www 13331: # Normal import
1.1374 raeburn 13332: if (defined($token->[2]->{'id'})) {
13333: $unikey.='_'.$token->[2]->{'id'};
13334: }
13335: }
13336: # Check metadata for imported file to
13337: # see if it contained parts
13338: if (grep(/^partorder$/,@libfilekeys)) {
13339: %currmetaentry = %metaentry;
13340: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13341: $depthcount+1);
13342: %metaentry = %currmetaentry;
13343: undef(%currmetaentry);
13344: if ($libpartorder ne '') {
13345: $importedparts = 1;
13346: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13347: }
13348: }
1.1067 www 13349: }
1.339 albertel 13350: if ($depthcount<20) {
1.736 albertel 13351: my $metadata =
1.1362 raeburn 13352: &metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736 albertel 13353: $depthcount+1);
13354: foreach my $meta (split(',',$metadata)) {
13355: $metaentry{':'.$meta}=$metaentry{':'.$meta};
13356: $metathesekeys{$meta}=1;
1.339 albertel 13357: }
1.1068 www 13358: }
1.1067 www 13359: } else {
13360: #
13361: # Not importing, some other kind of non-package, non-library start tag
13362: #
13363: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13364: if (defined($token->[2]->{'id'})) {
13365: $unikey.='_'.$token->[2]->{'id'};
13366: }
1.339 albertel 13367: if (defined($token->[2]->{'name'})) {
13368: $unikey.='_'.$token->[2]->{'name'};
13369: }
13370: $metathesekeys{$unikey}=1;
1.736 albertel 13371: foreach my $param (@{$token->[3]}) {
13372: $metaentry{':'.$unikey.'.'.$param} =
13373: $token->[2]->{$param};
1.339 albertel 13374: }
13375: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 13376: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 13377: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13378: # only ws inside the tag, and not in default, so use default
13379: # as value
1.599 albertel 13380: $metaentry{':'.$unikey}=$default;
1.908 albertel 13381: } elsif ( $internaltext =~ /\S/ ) {
13382: # something interesting inside the tag
13383: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 13384: } else {
1.908 albertel 13385: # no interesting values, don't set a default
1.339 albertel 13386: }
1.172 www 13387: # end of not-a-package not-a-library import
1.339 albertel 13388: }
1.172 www 13389: # end of not-a-package start tag
1.339 albertel 13390: }
1.172 www 13391: # the next is the end of "start tag"
1.339 albertel 13392: }
13393: }
1.483 albertel 13394: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 13395: $extension = lc($extension);
13396: if ($extension eq 'htm') { $extension='html'; }
13397:
1.737 albertel 13398: foreach my $key (keys(%packagetab)) {
1.483 albertel 13399: #no specific packages #how's our extension
13400: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 13401: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 13402: \%metathesekeys);
13403: }
1.883 albertel 13404:
13405: if (!exists($metaentry{':packages'})
13406: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 13407: foreach my $key (keys(%packagetab)) {
1.483 albertel 13408: #no specific packages well let's get default then
13409: if ($key!~/^default&/) { next; }
1.488 albertel 13410: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 13411: \%metathesekeys);
13412: }
13413: }
1.338 www 13414: # are there custom rights to evaluate
1.599 albertel 13415: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 13416:
1.338 www 13417: #
13418: # Importing a rights file here
1.339 albertel 13419: #
13420: unless ($depthcount) {
1.599 albertel 13421: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 13422: my $dir=$filename;
13423: $dir=~s|[^/]*$||;
13424: $location=&filelocation($dir,$location);
1.736 albertel 13425: my $rights_metadata =
1.1362 raeburn 13426: &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736 albertel 13427: $depthcount+1);
13428: foreach my $rights (split(',',$rights_metadata)) {
13429: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13430: $metathesekeys{$rights}=1;
1.339 albertel 13431: }
13432: }
13433: }
1.737 albertel 13434: # uniqifiy package listing
13435: my %seen;
13436: my @uniq_packages =
13437: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13438: $metaentry{':packages'} = join(',',@uniq_packages);
13439:
1.1369 raeburn 13440: if (($importedresponses) || ($importedparts)) {
13441: if ($importedparts) {
1.1070 www 13442: # We had imported parts and need to rebuild partorder
1.1369 raeburn 13443: $metaentry{':partorder'}='';
13444: $metathesekeys{'partorder'}=1;
13445: }
13446: if ($importedresponses) {
13447: # We had imported responses and need to rebuil responseorder
13448: $metaentry{':responseorder'}='';
13449: $metathesekeys{'responseorder'}=1;
13450: }
13451: for (my $index=0;$index<$#origfiletagids;$index+=2) {
13452: my $origid = $origfiletagids[$index+1];
13453: if ($origfiletagids[$index] eq 'part') {
13454: # Original part, part of the problem
13455: if ($importedparts) {
13456: $metaentry{':partorder'}.=','.$origid;
13457: }
13458: } elsif ($origfiletagids[$index] eq 'import') {
13459: if ($importedparts) {
13460: # We have imported parts at this position
1.1373 raeburn 13461: if ($importedpartids{$origid} ne '') {
13462: $metaentry{':partorder'}.=','.$importedpartids{$origid};
13463: }
1.1369 raeburn 13464: }
13465: if ($importedresponses) {
13466: # We have imported responses at this position
1.1373 raeburn 13467: if ($importedrespids{$origid} ne '') {
13468: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369 raeburn 13469: }
13470: }
13471: } else {
13472: # Original response item, part of the problem
13473: if ($importedresponses) {
13474: $metaentry{':responseorder'}.=','.$origid;
13475: }
13476: }
13477: }
13478: if ($importedparts) {
13479: $metaentry{':partorder'}=~s/^\,//;
13480: }
13481: if ($importedresponses) {
13482: $metaentry{':responseorder'}=~s/^\,//;
13483: }
1.1070 www 13484: }
1.737 albertel 13485: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 13486: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 13487: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371 raeburn 13488: unless ($liburi) {
13489: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13490: }
1.177 www 13491: # this is the end of "was not already recently cached
1.71 www 13492: }
1.599 albertel 13493: return $metaentry{':'.$what};
1.261 albertel 13494: }
13495:
1.488 albertel 13496: sub metadata_create_package_def {
1.483 albertel 13497: my ($uri,$key,$package,$metathesekeys)=@_;
13498: my ($pack,$name,$subp)=split(/\&/,$key);
13499: if ($subp eq 'default') { next; }
13500:
1.599 albertel 13501: if (defined($metaentry{':packages'})) {
13502: $metaentry{':packages'}.=','.$package;
1.483 albertel 13503: } else {
1.599 albertel 13504: $metaentry{':packages'}=$package;
1.483 albertel 13505: }
13506: my $value=$packagetab{$key};
13507: my $unikey;
13508: $unikey='parameter_0_'.$name;
1.599 albertel 13509: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 13510: $$metathesekeys{$unikey}=1;
1.599 albertel 13511: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13512: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 13513: }
1.599 albertel 13514: if (defined($metaentry{':'.$unikey.'.default'})) {
13515: $metaentry{':'.$unikey}=
13516: $metaentry{':'.$unikey.'.default'};
1.483 albertel 13517: }
13518: }
13519:
1.261 albertel 13520: sub metadata_generate_part0 {
13521: my ($metadata,$metacache,$uri) = @_;
13522: my %allnames;
1.737 albertel 13523: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 13524: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 13525: my $part=$$metacache{':'.$metakey.'.part'};
13526: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 13527: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 13528: $allnames{$name}=$part;
13529: }
13530: }
13531: }
13532: foreach my $name (keys(%allnames)) {
13533: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 13534: my $key=":parameter_0_$name";
1.261 albertel 13535: $$metacache{"$key.part"}='0';
13536: $$metacache{"$key.name"}=$name;
1.428 albertel 13537: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 13538: $allnames{$name}.'_'.$name.
13539: '.type'};
1.428 albertel 13540: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 13541: '.display'};
1.644 www 13542: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 13543: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 13544: $$metacache{"$key.display"}=$olddis;
13545: }
1.71 www 13546: }
13547:
1.764 albertel 13548: # ------------------------------------------------------ Devalidate title cache
13549:
13550: sub devalidate_title_cache {
13551: my ($url)=@_;
13552: if (!$env{'request.course.id'}) { return; }
13553: my $symb=&symbread($url);
13554: if (!$symb) { return; }
13555: my $key=$env{'request.course.id'}."\0".$symb;
13556: &devalidate_cache_new('title',$key);
13557: }
13558:
1.1014 droeschl 13559: # ------------------------------------------------- Get the title of a course
13560:
13561: sub current_course_title {
13562: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13563: }
1.301 www 13564: # ------------------------------------------------- Get the title of a resource
13565:
13566: sub gettitle {
13567: my $urlsymb=shift;
13568: my $symb=&symbread($urlsymb);
1.534 albertel 13569: if ($symb) {
1.620 albertel 13570: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 13571: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 13572: if (defined($cached)) {
13573: return $result;
13574: }
1.534 albertel 13575: my ($map,$resid,$url)=&decode_symb($symb);
13576: my $title='';
1.907 albertel 13577: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13578: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13579: } else {
13580: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13581: &GDBM_READER(),0640)) {
13582: my $mapid=$bighash{'map_pc_'.&clutter($map)};
13583: $title=$bighash{'title_'.$mapid.'.'.$resid};
13584: untie(%bighash);
13585: }
1.534 albertel 13586: }
13587: $title=~s/\&colon\;/\:/gs;
13588: if ($title) {
1.1159 www 13589: # Remember both $symb and $title for dynamic metadata
13590: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 13591: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 13592: # Cache this title and then return it
1.599 albertel 13593: return &do_cache_new('title',$key,$title,600);
1.534 albertel 13594: }
13595: $urlsymb=$url;
13596: }
13597: my $title=&metadata($urlsymb,'title');
13598: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
13599: return $title;
1.301 www 13600: }
1.613 albertel 13601:
1.614 albertel 13602: sub get_slot {
13603: my ($which,$cnum,$cdom)=@_;
13604: if (!$cnum || !$cdom) {
1.790 albertel 13605: (undef,my $courseid)=&whichuser();
1.620 albertel 13606: $cdom=$env{'course.'.$courseid.'.domain'};
13607: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 13608: }
1.703 albertel 13609: my $key=join("\0",'slots',$cdom,$cnum,$which);
13610: my %slotinfo;
13611: if (exists($remembered{$key})) {
13612: $slotinfo{$which} = $remembered{$key};
13613: } else {
13614: %slotinfo=&get('slots',[$which],$cdom,$cnum);
13615: &Apache::lonhomework::showhash(%slotinfo);
13616: my ($tmp)=keys(%slotinfo);
13617: if ($tmp=~/^error:/) { return (); }
13618: $remembered{$key} = $slotinfo{$which};
13619: }
1.616 albertel 13620: if (ref($slotinfo{$which}) eq 'HASH') {
13621: return %{$slotinfo{$which}};
13622: }
13623: return $slotinfo{$which};
1.614 albertel 13624: }
1.1150 raeburn 13625:
13626: sub get_reservable_slots {
13627: my ($cnum,$cdom,$uname,$udom) = @_;
13628: my $now = time;
13629: my $reservable_info;
13630: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13631: if (exists($remembered{$key})) {
13632: $reservable_info = $remembered{$key};
13633: } else {
13634: my %resv;
13635: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13636: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13637: $reservable_info = \%resv;
13638: $remembered{$key} = $reservable_info;
13639: }
13640: return $reservable_info;
13641: }
13642:
13643: sub get_course_slots {
13644: my ($cnum,$cdom) = @_;
13645: my $hashid=$cnum.':'.$cdom;
1.1494 raeburn 13646: my ($result,$cached) = &is_cached_new('allslots',$hashid);
1.1150 raeburn 13647: if (defined($cached)) {
13648: if (ref($result) eq 'HASH') {
13649: return %{$result};
13650: }
13651: } else {
1.1494 raeburn 13652: my %slots=&dump('slots',$cdom,$cnum);
1.1150 raeburn 13653: my ($tmp) = keys(%slots);
13654: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 13655: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 13656: return %slots;
13657: }
13658: }
13659: return;
13660: }
13661:
13662: sub devalidate_slots_cache {
13663: my ($cnum,$cdom)=@_;
13664: my $hashid=$cnum.':'.$cdom;
13665: &devalidate_cache_new('allslots',$hashid);
13666: }
13667:
1.1181 raeburn 13668: sub get_coursechange {
13669: my ($cdom,$cnum) = @_;
13670: if ($cdom eq '' || $cnum eq '') {
13671: return unless ($env{'request.course.id'});
13672: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13673: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13674: }
13675: my $hashid=$cdom.'_'.$cnum;
13676: my ($change,$cached)=&is_cached_new('crschange',$hashid);
13677: if ((defined($cached)) && ($change ne '')) {
13678: return $change;
13679: } else {
13680: my %crshash;
13681: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13682: if ($crshash{'internal.contentchange'} eq '') {
13683: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13684: if ($change eq '') {
13685: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13686: $change = $crshash{'internal.created'};
13687: }
13688: } else {
13689: $change = $crshash{'internal.contentchange'};
13690: }
13691: my $cachetime = 600;
13692: &do_cache_new('crschange',$hashid,$change,$cachetime);
13693: }
13694: return $change;
13695: }
13696:
13697: sub devalidate_coursechange_cache {
1.1496 raeburn 13698: my ($cdom,$cnum)=@_;
13699: my $hashid=$cdom.'_'.$cnum;
1.1181 raeburn 13700: &devalidate_cache_new('crschange',$hashid);
13701: }
13702:
1.1496 raeburn 13703: sub get_suppchange {
13704: my ($cdom,$cnum) = @_;
13705: if ($cdom eq '' || $cnum eq '') {
13706: return unless ($env{'request.course.id'});
13707: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13708: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13709: }
13710: my $hashid=$cdom.'_'.$cnum;
13711: my ($change,$cached)=&is_cached_new('suppchange',$hashid);
13712: if ((defined($cached)) && ($change ne '')) {
13713: return $change;
13714: } else {
13715: my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
13716: if ($crshash{'internal.supplementalchange'} eq '') {
13717: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13718: if ($change eq '') {
13719: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13720: $change = $crshash{'internal.created'};
13721: }
13722: } else {
13723: $change = $crshash{'internal.supplementalchange'};
13724: }
13725: my $cachetime = 600;
13726: &do_cache_new('suppchange',$hashid,$change,$cachetime);
13727: }
13728: return $change;
13729: }
13730:
13731: sub devalidate_suppchange_cache {
13732: my ($cdom,$cnum)=@_;
13733: my $hashid=$cdom.'_'.$cnum;
13734: &devalidate_cache_new('suppchange',$hashid);
13735: }
13736:
1.1497 raeburn 13737: sub update_supp_caches {
13738: my ($cdom,$cnum) = @_;
13739: my %servers = &internet_dom_servers($cdom);
13740: my @ids=¤t_machine_ids();
13741: foreach my $server (keys(%servers)) {
13742: next if (grep(/^\Q$server\E$/,@ids));
13743: my $hashid=$cnum.':'.$cdom;
13744: my $cachekey = &escape('showsupp').':'.&escape($hashid);
13745: &remote_devalidate_cache($server,[$cachekey]);
13746: }
13747: &has_unhidden_suppfiles($cnum,$cdom,1,1);
13748: &count_supptools($cnum,$cdom,1);
13749: my $now = time;
13750: if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
13751: &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
13752: }
13753: &put('environment',{'internal.supplementalchange' => $now},
13754: $cdom,$cnum);
13755: &Apache::lonnet::appenv(
13756: {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
13757: &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
13758: }
13759:
1.31 www 13760: # ------------------------------------------------- Update symbolic store links
13761:
13762: sub symblist {
13763: my ($mapname,%newhash)=@_;
1.438 www 13764: $mapname=&deversion(&declutter($mapname));
1.31 www 13765: my %hash;
1.620 albertel 13766: if (($env{'request.course.fn'}) && (%newhash)) {
13767: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 13768: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 13769: foreach my $url (keys(%newhash)) {
1.711 albertel 13770: next if ($url eq 'last_known'
13771: && $env{'form.no_update_last_known'});
13772: $hash{declutter($url)}=&encode_symb($mapname,
13773: $newhash{$url}->[1],
13774: $newhash{$url}->[0]);
1.191 harris41 13775: }
1.31 www 13776: if (untie(%hash)) {
13777: return 'ok';
13778: }
13779: }
13780: }
13781: return 'error';
1.212 www 13782: }
13783:
13784: # --------------------------------------------------------------- Verify a symb
13785:
13786: sub symbverify {
1.1190 raeburn 13787: my ($symb,$thisurl,$encstate)=@_;
1.510 www 13788: my $thisfn=$thisurl;
1.439 www 13789: $thisfn=&declutter($thisfn);
1.215 www 13790: # direct jump to resource in page or to a sequence - will construct own symbs
13791: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13792: # check URL part
1.409 www 13793: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 13794:
1.431 www 13795: unless ($url eq $thisfn) { return 0; }
1.213 www 13796:
1.216 www 13797: $symb=&symbclean($symb);
1.510 www 13798: $thisurl=&deversion($thisurl);
1.439 www 13799: $thisfn=&deversion($thisfn);
1.213 www 13800:
13801: my %bighash;
13802: my $okay=0;
1.431 www 13803:
1.620 albertel 13804: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13805: &GDBM_READER(),0640)) {
1.1032 raeburn 13806: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13807: $thisurl =~ s/\?.+$//;
1.1204 raeburn 13808: if ($map =~ m{^uploaded/.+\.page$}) {
13809: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13810: $thisurl =~ s{^\Qhttp://https://\E}{https://};
13811: }
13812: }
13813: my $ids;
1.1419 raeburn 13814: if ($map =~ m{^uploaded/.+\.page$}) {
13815: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204 raeburn 13816: } else {
13817: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 13818: }
1.1102 raeburn 13819: unless ($ids) {
13820: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
13821: $ids=$bighash{$idkey};
1.216 www 13822: }
13823: if ($ids) {
13824: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 13825: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 13826: $symb =~ s/\?.+$//;
1.1202 raeburn 13827: }
1.800 albertel 13828: foreach my $id (split(/\,/,$ids)) {
13829: my ($mapid,$resid)=split(/\./,$id);
1.216 www 13830: if (
13831: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 13832: eq $symb) {
13833: if (ref($encstate)) {
13834: $$encstate = $bighash{'encrypted_'.$id};
13835: }
1.620 albertel 13836: if (($env{'request.role.adv'}) ||
1.1101 raeburn 13837: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13838: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 13839: $okay=1;
1.1202 raeburn 13840: last;
1.582 albertel 13841: }
13842: }
1.216 www 13843: }
13844: }
1.213 www 13845: untie(%bighash);
13846: }
13847: return $okay;
1.31 www 13848: }
13849:
1.210 www 13850: # --------------------------------------------------------------- Clean-up symb
13851:
13852: sub symbclean {
13853: my $symb=shift;
1.568 albertel 13854: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 13855: # remove version from map
13856: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 13857:
1.210 www 13858: # remove version from URL
13859: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 13860:
1.507 www 13861: # remove wrapper
13862:
1.510 www 13863: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 13864: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 13865: return $symb;
1.409 www 13866: }
13867:
13868: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 13869:
13870: sub encode_symb {
13871: my ($map,$resid,$url)=@_;
13872: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13873: }
1.409 www 13874:
13875: sub decode_symb {
1.568 albertel 13876: my $symb=shift;
13877: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13878: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 13879: return (&fixversion($map),$resid,&fixversion($url));
13880: }
13881:
13882: sub fixversion {
13883: my $fn=shift;
1.609 banghart 13884: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 13885: my %bighash;
13886: my $uri=&clutter($fn);
1.620 albertel 13887: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 13888: # is this cached?
1.599 albertel 13889: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 13890: if (defined($cached)) { return $result; }
13891: # unfortunately not cached, or expired
1.620 albertel 13892: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 13893: &GDBM_READER(),0640)) {
13894: if ($bighash{'version_'.$uri}) {
13895: my $version=$bighash{'version_'.$uri};
1.444 www 13896: unless (($version eq 'mostrecent') ||
13897: ($version==&getversion($uri))) {
1.440 www 13898: $uri=~s/\.(\w+)$/\.$version\.$1/;
13899: }
13900: }
13901: untie %bighash;
1.413 www 13902: }
1.599 albertel 13903: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 13904: }
13905:
13906: sub deversion {
13907: my $url=shift;
13908: $url=~s/\.\d+\.(\w+)$/\.$1/;
13909: return $url;
1.210 www 13910: }
13911:
1.31 www 13912: # ------------------------------------------------------ Return symb list entry
13913:
13914: sub symbread {
1.1424 raeburn 13915: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427 raeburn 13916: $ignoresymbdb,$noenccheck)=@_;
1.1265 raeburn 13917: my $cache_str='request.symbread.cached.'.$thisfn;
1.1427 raeburn 13918: if (defined($env{$cache_str})) {
1.1424 raeburn 13919: unless (ref($possibles) eq 'HASH') {
13920: if ($ignorecachednull) {
13921: return $env{$cache_str} unless ($env{$cache_str} eq '');
13922: } else {
13923: return $env{$cache_str};
13924: }
1.1282 raeburn 13925: }
13926: }
1.242 www 13927: # no filename provided? try from environment
1.1265 raeburn 13928: unless ($thisfn) {
1.620 albertel 13929: if ($env{'request.symb'}) {
1.1427 raeburn 13930: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 13931: }
1.620 albertel 13932: $thisfn=$env{'request.filename'};
1.44 www 13933: }
1.569 albertel 13934: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 13935: # is that filename actually a symb? Verify, clean, and return
13936: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 13937: if (&symbverify($thisfn,$1)) {
1.1427 raeburn 13938: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 13939: }
1.242 www 13940: }
1.44 www 13941: $thisfn=declutter($thisfn);
1.31 www 13942: my %hash;
1.37 www 13943: my %bighash;
13944: my $syval='';
1.620 albertel 13945: if (($env{'request.course.fn'}) && ($thisfn)) {
1.1427 raeburn 13946: unless ($ignoresymbdb) {
1.1424 raeburn 13947: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13948: &GDBM_READER(),0640)) {
1.1487 raeburn 13949: $syval=$hash{$thisfn};
1.1424 raeburn 13950: untie(%hash);
13951: }
1.1427 raeburn 13952: if ($syval && $checkforblock) {
13953: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424 raeburn 13954: if (@blockers) {
13955: $syval='';
13956: }
13957: }
1.37 www 13958: }
13959: # ---------------------------------------------------------- There was an entry
13960: if ($syval) {
1.601 albertel 13961: #unless ($syval=~/\_\d+$/) {
1.620 albertel 13962: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 13963: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13964: #return $env{$cache_str}='';
1.601 albertel 13965: #}
13966: #$syval.=$1;
13967: #}
1.37 www 13968: } else {
13969: # ------------------------------------------------------- Was not in symb table
1.620 albertel 13970: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13971: &GDBM_READER(),0640)) {
1.37 www 13972: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 13973: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 13974: unless ($ids) {
13975: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 13976: }
13977: unless ($ids) {
13978: # alias?
13979: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 13980: }
1.37 www 13981: if ($ids) {
13982: # ------------------------------------------------------------------- Has ID(s)
13983: my @possibilities=split(/\,/,$ids);
1.39 www 13984: if ($#possibilities==0) {
13985: # ----------------------------------------------- There is only one possibility
1.37 www 13986: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 13987: $syval=&encode_symb($bighash{'map_id_'.$mapid},
13988: $resid,$thisfn);
1.1282 raeburn 13989: if (ref($possibles) eq 'HASH') {
1.1424 raeburn 13990: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13991: $possibles->{$syval} = 1;
13992: }
1.1282 raeburn 13993: }
13994: if ($checkforblock) {
1.1424 raeburn 13995: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426 raeburn 13996: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424 raeburn 13997: if (@blockers) {
13998: $syval = '';
1.1425 raeburn 13999: untie(%bighash);
14000: return $env{$cache_str}='';
1.1424 raeburn 14001: }
1.1282 raeburn 14002: }
14003: }
14004: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 14005: # ------------------------------------------ There is more than one possibility
14006: my $realpossible=0;
1.800 albertel 14007: foreach my $id (@possibilities) {
14008: my $file=$bighash{'src_'.$id};
1.1282 raeburn 14009: my $canaccess;
14010: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14011: $canaccess = 1;
14012: } else {
14013: $canaccess = &allowed('bre',$file);
14014: }
14015: if ($canaccess) {
14016: my ($mapid,$resid)=split(/\./,$id);
14017: if ($bighash{'map_type_'.$mapid} ne 'page') {
14018: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14019: $resid,$thisfn);
1.1424 raeburn 14020: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426 raeburn 14021: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282 raeburn 14022: if ($checkforblock) {
1.1426 raeburn 14023: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424 raeburn 14024: if (@blockers > 0) {
14025: $syval = '';
14026: } else {
1.1282 raeburn 14027: $syval = $poss_syval;
14028: $realpossible++;
14029: }
14030: } else {
14031: $syval = $poss_syval;
14032: $realpossible++;
14033: }
1.1424 raeburn 14034: if ($syval) {
14035: if (ref($possibles) eq 'HASH') {
14036: $possibles->{$syval} = 1;
14037: }
14038: }
1.1282 raeburn 14039: }
1.39 www 14040: }
1.191 harris41 14041: }
1.39 www 14042: if ($realpossible!=1) { $syval=''; }
1.249 www 14043: } else {
14044: $syval='';
1.37 www 14045: }
14046: }
1.1282 raeburn 14047: untie(%bighash);
1.481 raeburn 14048: }
1.31 www 14049: }
1.62 www 14050: if ($syval) {
1.1427 raeburn 14051: return $env{$cache_str}=$syval;
1.62 www 14052: }
1.31 www 14053: }
1.949 raeburn 14054: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 14055: return $env{$cache_str}='';
1.31 www 14056: }
14057:
14058: # ---------------------------------------------------------- Return random seed
14059:
1.32 www 14060: sub numval {
14061: my $txt=shift;
14062: $txt=~tr/A-J/0-9/;
14063: $txt=~tr/a-j/0-9/;
14064: $txt=~tr/K-T/0-9/;
14065: $txt=~tr/k-t/0-9/;
14066: $txt=~tr/U-Z/0-5/;
14067: $txt=~tr/u-z/0-5/;
14068: $txt=~s/\D//g;
1.564 albertel 14069: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 14070: return int($txt);
1.368 albertel 14071: }
14072:
1.484 albertel 14073: sub numval2 {
14074: my $txt=shift;
14075: $txt=~tr/A-J/0-9/;
14076: $txt=~tr/a-j/0-9/;
14077: $txt=~tr/K-T/0-9/;
14078: $txt=~tr/k-t/0-9/;
14079: $txt=~tr/U-Z/0-5/;
14080: $txt=~tr/u-z/0-5/;
14081: $txt=~s/\D//g;
14082: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14083: my $total;
14084: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 14085: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 14086: return int($total);
14087: }
14088:
1.575 albertel 14089: sub numval3 {
14090: use integer;
14091: my $txt=shift;
14092: $txt=~tr/A-J/0-9/;
14093: $txt=~tr/a-j/0-9/;
14094: $txt=~tr/K-T/0-9/;
14095: $txt=~tr/k-t/0-9/;
14096: $txt=~tr/U-Z/0-5/;
14097: $txt=~tr/u-z/0-5/;
14098: $txt=~s/\D//g;
14099: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14100: my $total;
14101: foreach my $val (@txts) { $total+=$val; }
14102: if ($_64bit) { $total=(($total<<32)>>32); }
14103: return $total;
14104: }
14105:
1.675 albertel 14106: sub digest {
14107: my ($data)=@_;
14108: my $digest=&Digest::MD5::md5($data);
14109: my ($a,$b,$c,$d)=unpack("iiii",$digest);
14110: my ($e,$f);
14111: {
14112: use integer;
14113: $e=($a+$b);
14114: $f=($c+$d);
14115: if ($_64bit) {
14116: $e=(($e<<32)>>32);
14117: $f=(($f<<32)>>32);
14118: }
14119: }
14120: if (wantarray) {
14121: return ($e,$f);
14122: } else {
14123: my $g;
14124: {
14125: use integer;
14126: $g=($e+$f);
14127: if ($_64bit) {
14128: $g=(($g<<32)>>32);
14129: }
14130: }
14131: return $g;
14132: }
14133: }
14134:
1.368 albertel 14135: sub latest_rnd_algorithm_id {
1.675 albertel 14136: return '64bit5';
1.366 albertel 14137: }
1.32 www 14138:
1.503 albertel 14139: sub get_rand_alg {
14140: my ($courseid)=@_;
1.790 albertel 14141: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 14142: if ($courseid) {
1.620 albertel 14143: return $env{"course.$courseid.rndseed"};
1.503 albertel 14144: }
14145: return &latest_rnd_algorithm_id();
14146: }
14147:
1.562 albertel 14148: sub validCODE {
14149: my ($CODE)=@_;
14150: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14151: return 0;
14152: }
14153:
1.491 albertel 14154: sub getCODE {
1.620 albertel 14155: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 14156: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14157: defined($Apache::lonhomework::parsing_a_task) ) &&
14158: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 14159: return $Apache::lonhomework::history{'resource.CODE'};
14160: }
14161: return undef;
14162: }
1.1133 foxr 14163: #
14164: # Determines the random seed for a specific context:
14165: #
14166: # parameters:
14167: # symb - in course context the symb for the seed.
14168: # course_id - The course id of the form domain_coursenum.
14169: # domain - Domain for the user.
14170: # course - Course for the user.
14171: # cenv - environment of the course.
14172: #
14173: # NOTE:
14174: # All parameters are picked out of the environment if missing
14175: # or not defined.
14176: # If a symb cannot be determined the current time is used instead.
14177: #
14178: # For a given well defined symb, courside, domain, username,
14179: # and course environment, the seed is reproducible.
14180: #
1.31 www 14181: sub rndseed {
1.1133 foxr 14182: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 14183: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 14184: if (!defined($symb)) {
1.366 albertel 14185: unless ($symb=$wsymb) { return time; }
14186: }
1.1146 foxr 14187: if (!defined $courseid) {
14188: $courseid=$wcourseid;
14189: }
14190: if (!defined $domain) { $domain=$wdomain; }
14191: if (!defined $username) { $username=$wusername }
1.1133 foxr 14192:
14193: my $which;
14194: if (defined($cenv->{'rndseed'})) {
14195: $which = $cenv->{'rndseed'};
14196: } else {
14197: $which =&get_rand_alg($courseid);
14198: }
1.491 albertel 14199: if (defined(&getCODE())) {
1.1133 foxr 14200:
1.675 albertel 14201: if ($which eq '64bit5') {
14202: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14203: } elsif ($which eq '64bit4') {
1.575 albertel 14204: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14205: } else {
14206: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14207: }
1.675 albertel 14208: } elsif ($which eq '64bit5') {
14209: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 14210: } elsif ($which eq '64bit4') {
14211: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 14212: } elsif ($which eq '64bit3') {
14213: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 14214: } elsif ($which eq '64bit2') {
14215: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 14216: } elsif ($which eq '64bit') {
14217: return &rndseed_64bit($symb,$courseid,$domain,$username);
14218: }
14219: return &rndseed_32bit($symb,$courseid,$domain,$username);
14220: }
14221:
14222: sub rndseed_32bit {
14223: my ($symb,$courseid,$domain,$username)=@_;
14224: {
14225: use integer;
14226: my $symbchck=unpack("%32C*",$symb) << 27;
14227: my $symbseed=numval($symb) << 22;
14228: my $namechck=unpack("%32C*",$username) << 17;
14229: my $nameseed=numval($username) << 12;
14230: my $domainseed=unpack("%32C*",$domain) << 7;
14231: my $courseseed=unpack("%32C*",$courseid);
14232: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 14233: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14234: #&logthis("rndseed :$num:$symb");
1.564 albertel 14235: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 14236: return $num;
14237: }
14238: }
14239:
14240: sub rndseed_64bit {
14241: my ($symb,$courseid,$domain,$username)=@_;
14242: {
14243: use integer;
14244: my $symbchck=unpack("%32S*",$symb) << 21;
14245: my $symbseed=numval($symb) << 10;
14246: my $namechck=unpack("%32S*",$username);
14247:
14248: my $nameseed=numval($username) << 21;
14249: my $domainseed=unpack("%32S*",$domain) << 10;
14250: my $courseseed=unpack("%32S*",$courseid);
14251:
14252: my $num1=$symbchck+$symbseed+$namechck;
14253: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14254: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14255: #&logthis("rndseed :$num:$symb");
1.564 albertel 14256: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 14257: return "$num1,$num2";
1.155 albertel 14258: }
1.366 albertel 14259: }
14260:
1.443 albertel 14261: sub rndseed_64bit2 {
14262: my ($symb,$courseid,$domain,$username)=@_;
14263: {
14264: use integer;
14265: # strings need to be an even # of cahracters long, it it is odd the
14266: # last characters gets thrown away
14267: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14268: my $symbseed=numval($symb) << 10;
14269: my $namechck=unpack("%32S*",$username.' ');
14270:
14271: my $nameseed=numval($username) << 21;
1.501 albertel 14272: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14273: my $courseseed=unpack("%32S*",$courseid.' ');
14274:
14275: my $num1=$symbchck+$symbseed+$namechck;
14276: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14277: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14278: #&logthis("rndseed :$num:$symb");
1.803 albertel 14279: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 14280: return "$num1,$num2";
14281: }
14282: }
14283:
14284: sub rndseed_64bit3 {
14285: my ($symb,$courseid,$domain,$username)=@_;
14286: {
14287: use integer;
14288: # strings need to be an even # of cahracters long, it it is odd the
14289: # last characters gets thrown away
14290: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14291: my $symbseed=numval2($symb) << 10;
14292: my $namechck=unpack("%32S*",$username.' ');
14293:
14294: my $nameseed=numval2($username) << 21;
1.443 albertel 14295: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14296: my $courseseed=unpack("%32S*",$courseid.' ');
14297:
14298: my $num1=$symbchck+$symbseed+$namechck;
14299: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14300: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14301: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 14302: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14303:
1.503 albertel 14304: return "$num1:$num2";
1.443 albertel 14305: }
14306: }
14307:
1.575 albertel 14308: sub rndseed_64bit4 {
14309: my ($symb,$courseid,$domain,$username)=@_;
14310: {
14311: use integer;
14312: # strings need to be an even # of cahracters long, it it is odd the
14313: # last characters gets thrown away
14314: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14315: my $symbseed=numval3($symb) << 10;
14316: my $namechck=unpack("%32S*",$username.' ');
14317:
14318: my $nameseed=numval3($username) << 21;
14319: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14320: my $courseseed=unpack("%32S*",$courseid.' ');
14321:
14322: my $num1=$symbchck+$symbseed+$namechck;
14323: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14324: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14325: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 14326: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14327:
1.575 albertel 14328: return "$num1:$num2";
14329: }
14330: }
14331:
1.675 albertel 14332: sub rndseed_64bit5 {
14333: my ($symb,$courseid,$domain,$username)=@_;
14334: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14335: return "$num1:$num2";
14336: }
14337:
1.366 albertel 14338: sub rndseed_CODE_64bit {
14339: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 14340: {
1.366 albertel 14341: use integer;
1.443 albertel 14342: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 14343: my $symbseed=numval2($symb);
1.491 albertel 14344: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14345: my $CODEseed=numval(&getCODE());
1.443 albertel 14346: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 14347: my $num1=$symbseed+$CODEchck;
14348: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14349: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14350: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 14351: if ($_64bit) { $num1=(($num1<<32)>>32); }
14352: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 14353: return "$num1:$num2";
1.366 albertel 14354: }
14355: }
14356:
1.575 albertel 14357: sub rndseed_CODE_64bit4 {
14358: my ($symb,$courseid,$domain,$username)=@_;
14359: {
14360: use integer;
14361: my $symbchck=unpack("%32S*",$symb.' ') << 16;
14362: my $symbseed=numval3($symb);
14363: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14364: my $CODEseed=numval3(&getCODE());
14365: my $courseseed=unpack("%32S*",$courseid.' ');
14366: my $num1=$symbseed+$CODEchck;
14367: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14368: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14369: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 14370: if ($_64bit) { $num1=(($num1<<32)>>32); }
14371: if ($_64bit) { $num2=(($num2<<32)>>32); }
14372: return "$num1:$num2";
14373: }
14374: }
14375:
1.675 albertel 14376: sub rndseed_CODE_64bit5 {
14377: my ($symb,$courseid,$domain,$username)=@_;
14378: my $code = &getCODE();
14379: my ($num1,$num2)=&digest("$symb,$courseid,$code");
14380: return "$num1:$num2";
14381: }
14382:
1.366 albertel 14383: sub setup_random_from_rndseed {
14384: my ($rndseed)=@_;
1.503 albertel 14385: if ($rndseed =~/([,:])/) {
1.1262 raeburn 14386: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14387: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14388: &Math::Random::random_set_seed_from_phrase($rndseed);
14389: } else {
14390: &Math::Random::random_set_seed($num1,$num2);
14391: }
1.366 albertel 14392: } else {
14393: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 14394: }
1.36 albertel 14395: }
14396:
1.474 albertel 14397: sub latest_receipt_algorithm_id {
1.835 albertel 14398: return 'receipt3';
1.474 albertel 14399: }
14400:
1.480 www 14401: sub recunique {
14402: my $fucourseid=shift;
14403: my $unique;
1.835 albertel 14404: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14405: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14406: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 14407: } else {
14408: $unique=$perlvar{'lonReceipt'};
14409: }
14410: return unpack("%32C*",$unique);
14411: }
14412:
14413: sub recprefix {
14414: my $fucourseid=shift;
14415: my $prefix;
1.835 albertel 14416: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14417: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14418: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 14419: } else {
14420: $prefix=$perlvar{'lonHostID'};
14421: }
14422: return unpack("%32C*",$prefix);
14423: }
14424:
1.76 www 14425: sub ireceipt {
1.474 albertel 14426: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 14427:
14428: my $return =&recprefix($fucourseid).'-';
14429:
14430: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14431: $env{'request.state'} eq 'construct') {
14432: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14433: return $return;
14434: }
14435:
1.76 www 14436: my $cuname=unpack("%32C*",$funame);
14437: my $cudom=unpack("%32C*",$fudom);
14438: my $cucourseid=unpack("%32C*",$fucourseid);
14439: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 14440: my $cunique=&recunique($fucourseid);
1.474 albertel 14441: my $cpart=unpack("%32S*",$part);
1.835 albertel 14442: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14443:
1.790 albertel 14444: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 14445:
14446: $return.= ($cunique%$cuname+
14447: $cunique%$cudom+
14448: $cusymb%$cuname+
14449: $cusymb%$cudom+
14450: $cucourseid%$cuname+
14451: $cucourseid%$cudom+
14452: $cpart%$cuname+
14453: $cpart%$cudom);
14454: } else {
14455: $return.= ($cunique%$cuname+
14456: $cunique%$cudom+
14457: $cusymb%$cuname+
14458: $cusymb%$cudom+
14459: $cucourseid%$cuname+
14460: $cucourseid%$cudom);
14461: }
14462: return $return;
1.76 www 14463: }
14464:
14465: sub receipt {
1.474 albertel 14466: my ($part)=@_;
1.790 albertel 14467: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 14468: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 14469: }
1.260 ng 14470:
1.790 albertel 14471: sub whichuser {
14472: my ($passedsymb)=@_;
14473: my ($symb,$courseid,$domain,$name,$publicuser);
14474: if (defined($env{'form.grade_symb'})) {
14475: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14476: my $allowed=&allowed('vgr',$tmp_courseid);
14477: if (!$allowed &&
14478: exists($env{'request.course.sec'}) &&
14479: $env{'request.course.sec'} !~ /^\s*$/) {
14480: $allowed=&allowed('vgr',$tmp_courseid.
14481: '/'.$env{'request.course.sec'});
14482: }
14483: if ($allowed) {
14484: ($symb)=&get_env_multiple('form.grade_symb');
14485: $courseid=$tmp_courseid;
14486: ($domain)=&get_env_multiple('form.grade_domain');
14487: ($name)=&get_env_multiple('form.grade_username');
14488: return ($symb,$courseid,$domain,$name,$publicuser);
14489: }
14490: }
14491: if (!$passedsymb) {
14492: $symb=&symbread();
14493: } else {
14494: $symb=$passedsymb;
14495: }
14496: $courseid=$env{'request.course.id'};
14497: $domain=$env{'user.domain'};
14498: $name=$env{'user.name'};
14499: if ($name eq 'public' && $domain eq 'public') {
14500: if (!defined($env{'form.username'})) {
14501: $env{'form.username'}.=time.rand(10000000);
14502: }
14503: $name.=$env{'form.username'};
14504: }
14505: return ($symb,$courseid,$domain,$name,$publicuser);
14506:
14507: }
14508:
1.36 albertel 14509: # ------------------------------------------------------------ Serves up a file
1.472 albertel 14510: # returns either the contents of the file or
14511: # -1 if the file doesn't exist
1.481 raeburn 14512: #
14513: # if the target is a file that was uploaded via DOCS,
14514: # a check will be made to see if a current copy exists on the local server,
14515: # if it does this will be served, otherwise a copy will be retrieved from
14516: # the home server for the course and stored in /home/httpd/html/userfiles on
14517: # the local server.
1.472 albertel 14518:
1.36 albertel 14519: sub getfile {
1.538 albertel 14520: my ($file) = @_;
1.609 banghart 14521: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 14522: &repcopy($file);
14523: return &readfile($file);
14524: }
14525:
14526: sub repcopy_userfile {
14527: my ($file)=@_;
1.1142 raeburn 14528: my $londocroot = $perlvar{'lonDocRoot'};
14529: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 14530: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 14531: my ($cdom,$cnum,$filename) =
1.811 albertel 14532: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 14533: my $uri="/uploaded/$cdom/$cnum/$filename";
14534: if (-e "$file") {
1.828 www 14535: # we already have a local copy, check it out
1.538 albertel 14536: my @fileinfo = stat($file);
1.828 www 14537: my $rtncode;
14538: my $info;
1.538 albertel 14539: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 14540: if ($lwpresp ne 'ok') {
1.828 www 14541: # there is no such file anymore, even though we had a local copy
1.482 albertel 14542: if ($rtncode eq '404') {
1.538 albertel 14543: unlink($file);
1.482 albertel 14544: }
14545: return -1;
14546: }
14547: if ($info < $fileinfo[9]) {
1.828 www 14548: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 14549: return 'ok';
1.828 www 14550: } else {
14551: # the file is outdated, get rid of it
14552: unlink($file);
1.482 albertel 14553: }
1.828 www 14554: }
14555: # one way or the other, at this point, we don't have the file
14556: # construct the correct path for the file
14557: my @parts = ($cdom,$cnum);
14558: if ($filename =~ m|^(.+)/[^/]+$|) {
14559: push @parts, split(/\//,$1);
14560: }
14561: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14562: foreach my $part (@parts) {
14563: $path .= '/'.$part;
14564: if (!-e $path) {
14565: mkdir($path,0770);
1.482 albertel 14566: }
14567: }
1.828 www 14568: # now the path exists for sure
14569: # get a user agent
14570: my $transferfile=$file.'.in.transfer';
14571: # FIXME: this should flock
14572: if (-e $transferfile) { return 'ok'; }
14573: my $request;
14574: $uri=~s/^\///;
1.980 raeburn 14575: my $homeserver = &homeserver($cnum,$cdom);
1.1398 raeburn 14576: my $hostname = &hostname($homeserver);
1.980 raeburn 14577: my $protocol = $protocol{$homeserver};
14578: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14579: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345 raeburn 14580: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828 www 14581: # did it work?
14582: if ($response->is_error()) {
14583: unlink($transferfile);
14584: &logthis("Userfile repcopy failed for $uri");
14585: return -1;
14586: }
14587: # worked, rename the transfer file
14588: rename($transferfile,$file);
1.607 raeburn 14589: return 'ok';
1.481 raeburn 14590: }
14591:
1.517 albertel 14592: sub tokenwrapper {
14593: my $uri=shift;
1.980 raeburn 14594: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 14595: $uri=~s|^/||;
1.620 albertel 14596: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 14597: my $token=$1;
1.552 albertel 14598: my (undef,$udom,$uname,$file)=split('/',$uri,4);
14599: if ($udom && $uname && $file) {
14600: $file=~s|(\?\.*)*$||;
1.949 raeburn 14601: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 14602: my $homeserver = &homeserver($uname,$udom);
1.1397 raeburn 14603: my $hostname = &hostname($homeserver);
1.980 raeburn 14604: my $protocol = $protocol{$homeserver};
14605: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14606: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 14607: (($uri=~/\?/)?'&':'?').'token='.$token.
14608: '&tokenissued='.$perlvar{'lonHostID'};
14609: } else {
14610: return '/adm/notfound.html';
14611: }
14612: }
14613:
1.828 www 14614: # call with reqtype HEAD: get last modification time
14615: # call with reqtype GET: get the file contents
14616: # Do not call this with reqtype GET for large files! It loads everything into memory
14617: #
1.481 raeburn 14618: sub getuploaded {
14619: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14620: $uri=~s/^\///;
1.980 raeburn 14621: my $homeserver = &homeserver($cnum,$cdom);
1.1397 raeburn 14622: my $hostname = &hostname($homeserver);
1.980 raeburn 14623: my $protocol = $protocol{$homeserver};
14624: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14625: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 14626: my $request=new HTTP::Request($reqtype,$uri);
1.1345 raeburn 14627: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481 raeburn 14628: $$rtncode = $response->code;
1.482 albertel 14629: if (! $response->is_success()) {
14630: return 'failed';
14631: }
14632: if ($reqtype eq 'HEAD') {
1.486 www 14633: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 14634: } elsif ($reqtype eq 'GET') {
14635: $$info = $response->content;
1.472 albertel 14636: }
1.482 albertel 14637: return 'ok';
1.36 albertel 14638: }
14639:
1.481 raeburn 14640: sub readfile {
14641: my $file = shift;
14642: if ( (! -e $file ) || ($file eq '') ) { return -1; };
14643: my $fh;
1.1359 raeburn 14644: open($fh,"<",$file);
1.481 raeburn 14645: my $a='';
1.800 albertel 14646: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 14647: return $a;
14648: }
14649:
1.36 albertel 14650: sub filelocation {
1.590 banghart 14651: my ($dir,$file) = @_;
14652: my $location;
14653: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 14654:
14655: if ($file =~ m-^/adm/-) {
14656: $file=~s-^/adm/wrapper/-/-;
14657: $file=~s-^/adm/coursedocs/showdoc/-/-;
14658: }
1.882 albertel 14659:
1.1139 www 14660: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 14661: $location = $file;
1.609 banghart 14662: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 14663: my ($udom,$uname,$filename)=
1.811 albertel 14664: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 14665: my $home=&homeserver($uname,$udom);
14666: my $is_me=0;
14667: my @ids=¤t_machine_ids();
14668: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14669: if ($is_me) {
1.1117 foxr 14670: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 14671: } else {
14672: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14673: $udom.'/'.$uname.'/'.$filename;
14674: }
1.882 albertel 14675: } elsif ($file =~ m-^/adm/-) {
14676: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 14677: } else {
14678: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 14679: $file=~s:^/(res|priv)/:/:;
14680: my $space=$1;
1.590 banghart 14681: if ( !( $file =~ m:^/:) ) {
14682: $location = $dir. '/'.$file;
14683: } else {
1.1142 raeburn 14684: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 14685: }
1.59 albertel 14686: }
1.590 banghart 14687: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 14688: while ($location=~m{/\.\./}) {
14689: if ($location =~ m{/[^/]+/\.\./}) {
14690: $location=~ s{/[^/]+/\.\./}{/}g;
14691: } else {
14692: $location=~ s{/\.\./}{/}g;
14693: }
14694: } #remove dir/..
1.590 banghart 14695: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14696: return $location;
1.46 www 14697: }
1.36 albertel 14698:
1.46 www 14699: sub hreflocation {
14700: my ($dir,$file)=@_;
1.980 raeburn 14701: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 14702: $file=filelocation($dir,$file);
1.700 albertel 14703: } elsif ($file=~m-^/adm/-) {
14704: $file=~s-^/adm/wrapper/-/-;
14705: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 14706: }
14707: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14708: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14709: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 14710: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14711: {/uploaded/$1/$2/}x;
1.46 www 14712: }
1.913 albertel 14713: if ($file=~ m{^/userfiles/}) {
14714: $file =~ s{^/userfiles/}{/uploaded/};
14715: }
1.462 albertel 14716: return $file;
1.465 albertel 14717: }
14718:
1.1139 www 14719:
14720:
14721:
14722:
1.465 albertel 14723: sub current_machine_domains {
1.853 albertel 14724: return &machine_domains(&hostname($perlvar{'lonHostID'}));
14725: }
14726:
14727: sub machine_domains {
14728: my ($hostname) = @_;
1.465 albertel 14729: my @domains;
1.838 albertel 14730: my %hostname = &all_hostnames();
1.465 albertel 14731: while( my($id, $name) = each(%hostname)) {
1.467 matthew 14732: # &logthis("-$id-$name-$hostname-");
1.465 albertel 14733: if ($hostname eq $name) {
1.844 albertel 14734: push(@domains,&host_domain($id));
1.465 albertel 14735: }
14736: }
14737: return @domains;
14738: }
14739:
14740: sub current_machine_ids {
1.853 albertel 14741: return &machine_ids(&hostname($perlvar{'lonHostID'}));
14742: }
14743:
14744: sub machine_ids {
14745: my ($hostname) = @_;
14746: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 14747: my @ids;
1.888 albertel 14748: my %name_to_host = &all_names();
1.889 albertel 14749: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14750: return @{ $name_to_host{$hostname} };
14751: }
14752: return;
1.31 www 14753: }
14754:
1.824 raeburn 14755: sub additional_machine_domains {
14756: my @domains;
1.1466 raeburn 14757: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14758: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14759: while (my $line = <$fh>) {
14760: chomp($line);
14761: $line =~ s/\s//g;
14762: push(@domains,$line);
14763: }
14764: close($fh);
14765: }
1.824 raeburn 14766: }
14767: return @domains;
14768: }
14769:
14770: sub default_login_domain {
14771: my $domain = $perlvar{'lonDefDomain'};
14772: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14773: foreach my $posdom (¤t_machine_domains(),
14774: &additional_machine_domains()) {
14775: if (lc($posdom) eq lc($testdomain)) {
14776: $domain=$posdom;
14777: last;
14778: }
14779: }
14780: return $domain;
14781: }
14782:
1.1414 raeburn 14783: sub shared_institution {
1.1439 raeburn 14784: my ($dom,$lonhost) = @_;
14785: if ($lonhost eq '') {
14786: $lonhost = $perlvar{'lonHostID'};
14787: }
1.1414 raeburn 14788: my $same_intdom;
1.1439 raeburn 14789: my $hostintdom = &internet_dom($lonhost);
1.1414 raeburn 14790: if ($hostintdom ne '') {
14791: my %iphost = &get_iphost();
14792: my $primary_id = &domain($dom,'primary');
14793: my $primary_ip = &get_host_ip($primary_id);
14794: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14795: foreach my $id (@{$iphost{$primary_ip}}) {
14796: my $intdom = &internet_dom($id);
14797: if ($intdom eq $hostintdom) {
14798: $same_intdom = 1;
14799: last;
14800: }
14801: }
14802: }
14803: }
14804: return $same_intdom;
14805: }
14806:
1.1398 raeburn 14807: sub uses_sts {
14808: my ($ignore_cache) = @_;
14809: my $lonhost = $perlvar{'lonHostID'};
14810: my $hostname = &hostname($lonhost);
14811: my $sts_on;
14812: if ($protocol{$lonhost} eq 'https') {
14813: my $cachetime = 12*3600;
14814: if (!$ignore_cache) {
14815: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14816: if (defined($cached)) {
14817: return $sts_on;
14818: }
14819: }
14820: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14821: my $request=new HTTP::Request('HEAD',$url);
14822: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14823: if ($response->is_success) {
14824: my $has_sts = $response->header('Strict-Transport-Security');
14825: if ($has_sts eq '') {
14826: $sts_on = 0;
14827: } else {
14828: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14829: my $maxage = $1;
14830: if ($maxage) {
14831: $sts_on = 1;
14832: } else {
14833: $sts_on = 0;
14834: }
14835: } else {
14836: $sts_on = 0;
14837: }
14838: }
14839: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14840: }
14841: }
14842: return;
14843: }
14844:
1.1449 raeburn 14845: sub waf_allssl {
14846: my ($host_name) = @_;
14847: my $alias = &get_proxy_alias();
14848: if ($host_name eq '') {
14849: $host_name = $ENV{'SERVER_NAME'};
14850: }
14851: if (($host_name ne '') && ($alias eq $host_name)) {
14852: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14853: my %defdomdefaults = &get_domain_defaults($serverhomedom);
14854: if ($defdomdefaults{'waf_sslopt'}) {
14855: return $defdomdefaults{'waf_sslopt'};
14856: }
14857: }
14858: return;
14859: }
14860:
1.1434 raeburn 14861: sub get_requestor_ip {
14862: my ($r,$nolookup,$noproxy) = @_;
14863: my $from_ip;
14864: if (ref($r)) {
1.1447 raeburn 14865: if ($r->can('useragent_ip')) {
14866: if ($noproxy && $r->can('client_ip')) {
14867: $from_ip = $r->client_ip();
14868: } else {
14869: $from_ip = $r->useragent_ip();
14870: }
14871: } elsif ($r->connection->can('remote_ip')) {
14872: $from_ip = $r->connection->remote_ip();
14873: } else {
14874: $from_ip = $r->get_remote_host($nolookup);
14875: }
1.1434 raeburn 14876: } else {
14877: $from_ip = $ENV{'REMOTE_ADDR'};
14878: }
14879: return $from_ip if ($noproxy);
14880: # Who controls proxy settings for server
14881: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14882: my $proxyinfo = &get_proxy_settings($dom_in_use);
14883: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437 raeburn 14884: if ($proxyinfo->{'vpnint'}) {
14885: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434 raeburn 14886: return $from_ip;
14887: }
14888: }
14889: if ($proxyinfo->{'trusted'}) {
14890: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14891: my $ipheader = $proxyinfo->{'ipheader'};
14892: my ($ip,$xfor);
14893: if (ref($r)) {
14894: if ($ipheader) {
14895: $ip = $r->headers_in->{$ipheader};
14896: }
14897: $xfor = $r->headers_in->{'X-Forwarded-For'};
14898: } else {
14899: if ($ipheader) {
14900: $ip = $ENV{'HTTP_'.uc($ipheader)};
14901: }
14902: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14903: }
14904: if (($ip eq '') && ($xfor ne '')) {
14905: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14906: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14907: $ip = $poss_ip;
1.1435 raeburn 14908: last;
1.1434 raeburn 14909: }
14910: }
14911: }
14912: if ($ip ne '') {
14913: return $ip;
14914: }
14915: }
14916: }
14917: }
14918: return $from_ip;
14919: }
14920:
14921: sub get_proxy_settings {
14922: my ($dom_in_use) = @_;
1.1494 raeburn 14923: my %domdefaults = &get_domain_defaults($dom_in_use);
1.1434 raeburn 14924: my $proxyinfo = {
14925: ipheader => $domdefaults{'waf_ipheader'},
14926: trusted => $domdefaults{'waf_trusted'},
1.1437 raeburn 14927: vpnint => $domdefaults{'waf_vpnint'},
1.1438 raeburn 14928: vpnext => $domdefaults{'waf_vpnext'},
1.1449 raeburn 14929: sslopt => $domdefaults{'waf_sslopt'},
1.1434 raeburn 14930: };
14931: return $proxyinfo;
14932: }
14933:
14934: sub ip_match {
14935: my ($ip,$pattern_str) = @_;
14936: $ip=Net::CIDR::cidrvalidate($ip);
14937: if ($ip) {
14938: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14939: }
14940: return;
14941: }
14942:
14943: sub get_proxy_alias {
1.1450 raeburn 14944: my ($lonid) = @_;
14945: if ($lonid eq '') {
14946: $lonid = $perlvar{'lonHostID'};
14947: }
14948: if (!defined(&hostname($lonid))) {
14949: return;
14950: }
14951: if ($lonid ne '') {
14952: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434 raeburn 14953: if ($cached) {
14954: return $alias;
14955: }
1.1494 raeburn 14956: my $dom = &host_domain($lonid);
1.1434 raeburn 14957: if ($dom ne '') {
14958: my $cachetime = 60*60*24;
14959: my %domconfig =
1.1494 raeburn 14960: &get_dom('configuration',['wafproxy'],$dom);
1.1437 raeburn 14961: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14962: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450 raeburn 14963: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
14964: }
14965: }
14966: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
14967: }
14968: }
14969: return;
14970: }
14971:
14972: sub use_proxy_alias {
14973: my ($r,$lonid) = @_;
14974: my $alias = &get_proxy_alias($lonid);
14975: if ($alias) {
14976: my $dom = &host_domain($lonid);
14977: if ($dom ne '') {
1.1467 raeburn 14978: my $proxyinfo = &get_proxy_settings($dom);
1.1450 raeburn 14979: my ($vpnint,$remote_ip);
14980: if (ref($proxyinfo) eq 'HASH') {
14981: $vpnint = $proxyinfo->{'vpnint'};
14982: if ($vpnint) {
14983: $remote_ip = &get_requestor_ip($r,1,1);
1.1434 raeburn 14984: }
14985: }
1.1450 raeburn 14986: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14987: return $alias;
14988: }
1.1434 raeburn 14989: }
14990: }
14991: return;
14992: }
14993:
1.1474 raeburn 14994: sub alias_sso {
1.1467 raeburn 14995: my ($lonid) = @_;
14996: if ($lonid eq '') {
14997: $lonid = $perlvar{'lonHostID'};
14998: }
14999: if (!defined(&hostname($lonid))) {
15000: return;
15001: }
15002: if ($lonid ne '') {
15003: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15004: if ($cached) {
15005: return $use_alias;
15006: }
1.1494 raeburn 15007: my $dom = &host_domain($lonid);
1.1467 raeburn 15008: if ($dom ne '') {
15009: my $cachetime = 60*60*24;
15010: my %domconfig =
1.1494 raeburn 15011: &get_dom('configuration',['wafproxy'],$dom);
1.1467 raeburn 15012: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15013: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15014: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15015: }
15016: }
15017: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15018: }
15019: }
15020: return;
15021: }
15022:
1.1465 raeburn 15023: sub get_saml_landing {
15024: my ($lonid) = @_;
15025: if ($lonid eq '') {
15026: my $defdom = &default_login_domain();
15027: my @hosts = ¤t_machine_ids();
15028: if (@hosts > 1) {
15029: foreach my $hostid (@hosts) {
15030: if (&host_domain($hostid) eq $defdom) {
15031: $lonid = $hostid;
15032: last;
15033: }
15034: }
15035: } else {
15036: $lonid = $perlvar{'lonHostID'};
15037: }
15038: if ($lonid) {
1.1494 raeburn 15039: unless (&host_domain($lonid) eq $defdom) {
1.1465 raeburn 15040: return;
15041: }
15042: } else {
15043: return;
15044: }
15045: } elsif (!defined(&hostname($lonid))) {
15046: return;
15047: }
15048: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15049: if ($cached) {
15050: return $landing;
15051: }
1.1494 raeburn 15052: my $dom = &host_domain($lonid);
1.1465 raeburn 15053: if ($dom ne '') {
15054: my $cachetime = 60*60*24;
15055: my %domconfig =
1.1494 raeburn 15056: &get_dom('configuration',['login'],$dom);
1.1465 raeburn 15057: if (ref($domconfig{'login'}) eq 'HASH') {
15058: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15059: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15060: $landing = 1;
15061: }
15062: }
15063: }
15064: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15065: }
15066: return;
15067: }
15068:
1.31 www 15069: # ------------------------------------------------------------- Declutters URLs
15070:
15071: sub declutter {
15072: my $thisfn=shift;
1.569 albertel 15073: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 15074: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15075: $thisfn=~s{^/home/httpd/html}{};
15076: }
1.31 www 15077: $thisfn=~s/^\///;
1.697 albertel 15078: $thisfn=~s|^adm/wrapper/||;
15079: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 15080: $thisfn=~s/^res\///;
1.1172 bisitz 15081: $thisfn=~s/^priv\///;
1.1032 raeburn 15082: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15083: $thisfn=~s/\?.+$//;
15084: }
1.268 www 15085: return $thisfn;
15086: }
15087:
15088: # ------------------------------------------------------------- Clutter up URLs
15089:
15090: sub clutter {
15091: my $thisfn='/'.&declutter(shift);
1.887 albertel 15092: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 15093: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 15094: $thisfn='/res'.$thisfn;
15095: }
1.1031 raeburn 15096: if ($thisfn !~m|^/adm|) {
15097: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 15098: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 15099: } else {
15100: my ($ext) = ($thisfn =~ /\.(\w+)$/);
15101: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 15102: if ($embstyle eq 'ssi'
15103: || ($embstyle eq 'hdn')
15104: || ($embstyle eq 'rat')
15105: || ($embstyle eq 'prv')
15106: || ($embstyle eq 'ign')) {
15107: #do nothing with these
15108: } elsif (($embstyle eq 'img')
1.695 albertel 15109: || ($embstyle eq 'emb')
15110: || ($embstyle eq 'wrp')) {
15111: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 15112: } elsif ($embstyle eq 'unk'
15113: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 15114: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 15115: } else {
1.718 www 15116: # &logthis("Got a blank emb style");
1.695 albertel 15117: }
1.694 albertel 15118: }
1.1343 raeburn 15119: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 15120: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 15121: }
1.31 www 15122: return $thisfn;
1.12 www 15123: }
15124:
1.787 albertel 15125: sub clutter_with_no_wrapper {
15126: my $uri = &clutter(shift);
15127: if ($uri =~ m-^/adm/-) {
15128: $uri =~ s-^/adm/wrapper/-/-;
15129: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
15130: }
15131: return $uri;
15132: }
15133:
1.557 albertel 15134: sub freeze_escape {
15135: my ($value)=@_;
15136: if (ref($value)) {
15137: $value=&nfreeze($value);
15138: return '__FROZEN__'.&escape($value);
15139: }
15140: return &escape($value);
15141: }
15142:
1.11 www 15143:
1.557 albertel 15144: sub thaw_unescape {
15145: my ($value)=@_;
15146: if ($value =~ /^__FROZEN__/) {
15147: substr($value,0,10,undef);
15148: $value=&unescape($value);
15149: return &thaw($value);
15150: }
15151: return &unescape($value);
15152: }
15153:
1.436 albertel 15154: sub correct_line_ends {
15155: my ($result)=@_;
15156: $$result =~s/\r\n/\n/mg;
15157: $$result =~s/\r/\n/mg;
1.415 albertel 15158: }
1.1 albertel 15159: # ================================================================ Main Program
15160:
1.184 www 15161: sub goodbye {
1.204 albertel 15162: &logthis("Starting Shut down");
1.443 albertel 15163: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 15164: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 15165: #converted
1.599 albertel 15166: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 15167: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15168: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15169: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 15170: #1.1 only
1.870 albertel 15171: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15172: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15173: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15174: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15175: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 15176: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15177: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 15178: &flushcourselogs();
15179: &logthis("Shutting down");
15180: }
15181:
1.852 albertel 15182: sub get_dns {
1.1210 raeburn 15183: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 15184: if (!$ignore_cache) {
15185: my ($content,$cached)=
1.1494 raeburn 15186: &is_cached_new('dns',$url);
1.869 albertel 15187: if ($cached) {
1.1210 raeburn 15188: &$func($content,$hashref);
1.869 albertel 15189: return;
15190: }
15191: }
15192:
15193: my %alldns;
1.1379 raeburn 15194: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15195: foreach my $dns (<$config>) {
15196: next if ($dns !~ /^\^(\S*)/x);
15197: my $line = $1;
15198: my ($host,$protocol) = split(/:/,$line);
15199: if ($protocol ne 'https') {
15200: $protocol = 'http';
15201: }
15202: $alldns{$host} = $protocol;
1.979 raeburn 15203: }
1.1379 raeburn 15204: close($config);
1.869 albertel 15205: }
15206: while (%alldns) {
1.1263 raeburn 15207: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456 raeburn 15208: my ($contents,@content);
15209: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15210: my $command = (split('/',$url))[3];
15211: my ($dir,$file) = &parse_getdns_url($command,$url);
15212: delete($alldns{$dns});
15213: next if (($dir eq '') || ($file eq ''));
15214: if (open(my $config,'<',"$dir/$file")) {
1.1457 raeburn 15215: @content = <$config>;
1.1456 raeburn 15216: close($config);
15217: }
15218: if ($url eq '/adm/dns/loncapaCRL') {
15219: $contents = join('',@content);
15220: }
15221: } else {
15222: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15223: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15224: delete($alldns{$dns});
15225: next if ($response->is_error());
15226: if ($url eq '/adm/dns/loncapaCRL') {
15227: $contents = $response->content;
15228: } else {
15229: @content = split("\n",$response->content);
15230: }
15231: }
1.1379 raeburn 15232: if ($url eq '/adm/dns/loncapaCRL') {
1.1456 raeburn 15233: return &$func($contents);
1.1379 raeburn 15234: } else {
15235: unless ($nocache) {
15236: &do_cache_new('dns',$url,\@content,30*24*60*60);
15237: }
15238: &$func(\@content,$hashref);
15239: return;
15240: }
15241: }
15242: my $which = (split('/',$url,4))[3];
15243: if ($which eq 'loncapaCRL') {
15244: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15245: if (-e $diskfile) {
15246: &logthis("unable to contact DNS, on disk file $diskfile not updated");
15247: } else {
15248: &logthis("unable to contact DNS, no on disk file $diskfile available");
15249: }
15250: } else {
15251: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15252: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15253: my @content = <$config>;
15254: close($config);
15255: &$func(\@content,$hashref);
15256: }
1.852 albertel 15257: }
1.1210 raeburn 15258: return;
15259: }
15260:
15261: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 15262: sub parse_dns_checksums_tab {
1.1210 raeburn 15263: my ($lines,$hashref) = @_;
1.1264 raeburn 15264: my $lonhost = $perlvar{'lonHostID'};
1.1494 raeburn 15265: my $machine_dom = &host_domain($lonhost);
1.1210 raeburn 15266: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 15267: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15268: my $webconfdir = '/etc/httpd/conf';
15269: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15270: $webconfdir = '/etc/apache2';
15271: } elsif ($distro =~ /^sles(\d+)$/) {
15272: if ($1 >= 10) {
15273: $webconfdir = '/etc/apache2';
15274: }
15275: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15276: if ($1 >= 10.0) {
15277: $webconfdir = '/etc/apache2';
15278: }
15279: }
1.1210 raeburn 15280: my ($release,$timestamp) = split(/\-/,$loncaparev);
15281: my (%chksum,%revnum);
15282: if (ref($lines) eq 'ARRAY') {
15283: chomp(@{$lines});
1.1238 raeburn 15284: my $version = shift(@{$lines});
15285: if ($version eq $release) {
1.1210 raeburn 15286: foreach my $line (@{$lines}) {
1.1238 raeburn 15287: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 15288: if ($file =~ m{^/etc/httpd/conf}) {
15289: if ($webconfdir eq '/etc/apache2') {
15290: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15291: }
15292: }
1.1238 raeburn 15293: $chksum{$file} = $shasum;
15294: $revnum{$file} = $version;
1.1210 raeburn 15295: }
15296: if (ref($hashref) eq 'HASH') {
15297: %{$hashref} = (
15298: sums => \%chksum,
15299: versions => \%revnum,
15300: );
15301: }
15302: }
15303: }
1.869 albertel 15304: return;
1.852 albertel 15305: }
1.1210 raeburn 15306:
15307: sub fetch_dns_checksums {
1.1238 raeburn 15308: my %checksums;
1.1494 raeburn 15309: my $machine_dom = &host_domain($perlvar{'lonHostID'});
1.1260 raeburn 15310: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 15311: my ($release,$timestamp) = split(/\-/,$loncaparev);
15312: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 15313: \%checksums);
1.1210 raeburn 15314: return \%checksums;
15315: }
15316:
1.1379 raeburn 15317: sub fetch_crl_pemfile {
15318: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15319: }
15320:
15321: sub save_crl_pem {
1.1456 raeburn 15322: my ($content) = @_;
1.1380 raeburn 15323: my ($msg,$hadchanges);
1.1456 raeburn 15324: if ($content ne '') {
1.1379 raeburn 15325: my $now = time;
15326: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15327: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15328: if (open(my $fh,'>',"$tmpcrl")) {
1.1456 raeburn 15329: print $fh $content;
1.1379 raeburn 15330: close($fh);
15331: if (-e $lonca) {
15332: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15333: my $check = <PIPE>;
15334: close(PIPE);
15335: chomp($check);
15336: if ($check eq 'verify OK') {
15337: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380 raeburn 15338: my $backup;
1.1379 raeburn 15339: if (-e $dest) {
1.1380 raeburn 15340: if (&File::Copy::move($dest,"$dest.bak")) {
15341: $backup = 'ok';
15342: }
1.1379 raeburn 15343: }
15344: if (&File::Copy::move($tmpcrl,$dest)) {
15345: $msg = 'ok';
1.1380 raeburn 15346: if ($backup) {
15347: my (%oldnums,%newnums);
15348: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15349: while (<PIPE>) {
15350: $oldnums{(split(/:/))[1]} = 1;
15351: }
15352: close(PIPE);
15353: }
15354: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15355: while(<PIPE>) {
15356: $newnums{(split(/:/))[1]} = 1;
15357: }
15358: close(PIPE);
15359: }
15360: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15361: unless (exists($oldnums{$key})) {
15362: $hadchanges = 1;
15363: last;
15364: }
15365: }
15366: unless ($hadchanges) {
15367: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15368: unless (exists($newnums{$key})) {
15369: $hadchanges = 1;
15370: last;
15371: }
15372: }
15373: }
15374: }
1.1379 raeburn 15375: }
15376: } else {
15377: unlink($tmpcrl);
15378: }
15379: } else {
15380: unlink($tmpcrl);
15381: }
15382: } else {
15383: unlink($tmpcrl);
15384: }
15385: }
15386: }
1.1380 raeburn 15387: return ($msg,$hadchanges);
1.1379 raeburn 15388: }
15389:
1.1456 raeburn 15390: sub parse_getdns_url {
15391: my ($command,$url) = @_;
15392: my $dir = $perlvar{'lonTabDir'};
15393: my $file;
15394: if ($command eq 'hosts') {
15395: $file = 'dns_hosts.tab';
15396: } elsif ($command eq 'domain') {
15397: $file = 'dns_domain.tab';
15398: } elsif ($command eq 'checksums') {
15399: my $version = (split('/',$url))[4];
15400: $file = "dns_checksums/$version.tab",
15401: } elsif ($command eq 'loncapaCRL') {
15402: $dir = $perlvar{'lonCertificateDirectory'};
15403: $file = $perlvar{'lonnetCertRevocationList'};
15404: }
15405: return ($dir,$file);
15406: }
15407:
1.327 albertel 15408: # ------------------------------------------------------------ Read domain file
15409: {
1.852 albertel 15410: my $loaded;
1.846 albertel 15411: my %domain;
15412:
1.852 albertel 15413: sub parse_domain_tab {
15414: my ($lines) = @_;
15415: foreach my $line (@$lines) {
15416: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 15417:
1.846 albertel 15418: chomp($line);
1.852 albertel 15419: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 15420: my %this_domain;
15421: foreach my $field ('description', 'auth_def', 'auth_arg_def',
15422: 'lang_def', 'city', 'longi', 'lati',
15423: 'primary') {
15424: $this_domain{$field} = shift(@elements);
15425: }
15426: $domain{$name} = \%this_domain;
1.852 albertel 15427: }
15428: }
1.864 albertel 15429:
15430: sub reset_domain_info {
15431: undef($loaded);
15432: undef(%domain);
15433: }
15434:
1.852 albertel 15435: sub load_domain_tab {
1.1293 raeburn 15436: my ($ignore_cache,$nocache) = @_;
15437: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 15438: my $fh;
1.1359 raeburn 15439: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 15440: my @lines = <$fh>;
15441: &parse_domain_tab(\@lines);
1.448 albertel 15442: }
1.852 albertel 15443: close($fh);
15444: $loaded = 1;
1.327 albertel 15445: }
1.846 albertel 15446:
15447: sub domain {
1.852 albertel 15448: &load_domain_tab() if (!$loaded);
15449:
1.846 albertel 15450: my ($name,$what) = @_;
15451: return if ( !exists($domain{$name}) );
15452:
15453: if (!$what) {
15454: return $domain{$name}{'description'};
15455: }
15456: return $domain{$name}{$what};
15457: }
1.974 raeburn 15458:
15459: sub domain_info {
15460: &load_domain_tab() if (!$loaded);
15461: return %domain;
15462: }
15463:
1.327 albertel 15464: }
15465:
15466:
1.1 albertel 15467: # ------------------------------------------------------------- Read hosts file
15468: {
1.838 albertel 15469: my %hostname;
1.844 albertel 15470: my %hostdom;
1.845 albertel 15471: my %libserv;
1.852 albertel 15472: my $loaded;
1.888 albertel 15473: my %name_to_host;
1.1074 raeburn 15474: my %internetdom;
1.1107 raeburn 15475: my %LC_dns_serv;
1.852 albertel 15476:
15477: sub parse_hosts_tab {
15478: my ($file) = @_;
15479: foreach my $configline (@$file) {
15480: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 15481: chomp($configline);
15482: if ($configline =~ /^\^/) {
15483: if ($configline =~ /^\^([\w.\-]+)/) {
15484: $LC_dns_serv{$1} = 1;
15485: }
15486: next;
15487: }
1.1074 raeburn 15488: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 15489: $name=~s/\s//g;
15490: if ($id && $domain && $role && $name) {
1.1351 raeburn 15491: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15492: my $curr = $hostname{$id};
15493: my $skip;
15494: if (ref($name_to_host{$curr}) eq 'ARRAY') {
15495: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15496: $skip = 1;
15497: } else {
15498: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15499: }
15500: }
15501: unless ($skip) {
15502: push(@{$name_to_host{$name}},$id);
15503: }
15504: } else {
15505: push(@{$name_to_host{$name}},$id);
15506: }
1.852 albertel 15507: $hostname{$id}=$name;
15508: $hostdom{$id}=$domain;
15509: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 15510: if (defined($protocol)) {
15511: if ($protocol eq 'https') {
15512: $protocol{$id} = $protocol;
15513: } else {
15514: $protocol{$id} = 'http';
15515: }
1.968 raeburn 15516: } else {
1.969 raeburn 15517: $protocol{$id} = 'http';
1.968 raeburn 15518: }
1.1074 raeburn 15519: if (defined($intdom)) {
15520: $internetdom{$id} = $intdom;
15521: }
1.852 albertel 15522: }
15523: }
15524: }
1.864 albertel 15525:
15526: sub reset_hosts_info {
1.897 albertel 15527: &purge_remembered();
1.864 albertel 15528: &reset_domain_info();
15529: &reset_hosts_ip_info();
1.1339 raeburn 15530: undef(%internetdom);
1.892 albertel 15531: undef(%name_to_host);
1.864 albertel 15532: undef(%hostname);
15533: undef(%hostdom);
15534: undef(%libserv);
15535: undef($loaded);
15536: }
1.1 albertel 15537:
1.852 albertel 15538: sub load_hosts_tab {
1.1293 raeburn 15539: my ($ignore_cache,$nocache) = @_;
15540: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359 raeburn 15541: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 15542: my @config = <$config>;
15543: &parse_hosts_tab(\@config);
15544: close($config);
15545: $loaded=1;
1.1 albertel 15546: }
1.852 albertel 15547:
1.838 albertel 15548: sub hostname {
1.852 albertel 15549: &load_hosts_tab() if (!$loaded);
15550:
1.838 albertel 15551: my ($lonid) = @_;
15552: return $hostname{$lonid};
15553: }
1.845 albertel 15554:
1.838 albertel 15555: sub all_hostnames {
1.852 albertel 15556: &load_hosts_tab() if (!$loaded);
15557:
1.838 albertel 15558: return %hostname;
15559: }
1.845 albertel 15560:
1.888 albertel 15561: sub all_names {
1.1293 raeburn 15562: my ($ignore_cache,$nocache) = @_;
15563: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 15564:
15565: return %name_to_host;
15566: }
15567:
1.974 raeburn 15568: sub all_host_domain {
15569: &load_hosts_tab() if (!$loaded);
15570: return %hostdom;
15571: }
15572:
1.1339 raeburn 15573: sub all_host_intdom {
15574: &load_hosts_tab() if (!$loaded);
15575: return %internetdom;
15576: }
15577:
1.845 albertel 15578: sub is_library {
1.852 albertel 15579: &load_hosts_tab() if (!$loaded);
15580:
1.845 albertel 15581: return exists($libserv{$_[0]});
15582: }
15583:
15584: sub all_library {
1.852 albertel 15585: &load_hosts_tab() if (!$loaded);
15586:
1.845 albertel 15587: return %libserv;
15588: }
15589:
1.1062 droeschl 15590: sub unique_library {
15591: #2x reverse removes all hostnames that appear more than once
15592: my %unique = reverse &all_library();
15593: return reverse %unique;
15594: }
15595:
1.841 albertel 15596: sub get_servers {
1.852 albertel 15597: &load_hosts_tab() if (!$loaded);
15598:
1.841 albertel 15599: my ($domain,$type) = @_;
15600: my %possible_hosts = ($type eq 'library') ? %libserv
15601: : %hostname;
15602: my %result;
1.842 albertel 15603: if (ref($domain) eq 'ARRAY') {
15604: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 15605: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 15606: $result{$host} = $hostname;
15607: }
15608: }
15609: } else {
15610: while ( my ($host,$hostname) = each(%possible_hosts)) {
15611: if ($hostdom{$host} eq $domain) {
15612: $result{$host} = $hostname;
15613: }
1.841 albertel 15614: }
15615: }
15616: return %result;
15617: }
1.845 albertel 15618:
1.1062 droeschl 15619: sub get_unique_servers {
15620: my %unique = reverse &get_servers(@_);
15621: return reverse %unique;
15622: }
15623:
1.844 albertel 15624: sub host_domain {
1.852 albertel 15625: &load_hosts_tab() if (!$loaded);
15626:
1.844 albertel 15627: my ($lonid) = @_;
15628: return $hostdom{$lonid};
15629: }
15630:
1.841 albertel 15631: sub all_domains {
1.852 albertel 15632: &load_hosts_tab() if (!$loaded);
15633:
1.841 albertel 15634: my %seen;
15635: my @uniq = grep(!$seen{$_}++, values(%hostdom));
15636: return @uniq;
15637: }
1.1074 raeburn 15638:
15639: sub internet_dom {
15640: &load_hosts_tab() if (!$loaded);
15641:
15642: my ($lonid) = @_;
15643: return $internetdom{$lonid};
15644: }
1.1107 raeburn 15645:
15646: sub is_LC_dns {
15647: &load_hosts_tab() if (!$loaded);
15648:
15649: my ($hostname) = @_;
15650: return exists($LC_dns_serv{$hostname});
15651: }
15652:
1.1 albertel 15653: }
15654:
1.847 albertel 15655: {
15656: my %iphost;
1.856 albertel 15657: my %name_to_ip;
15658: my %lonid_to_ip;
1.869 albertel 15659:
1.847 albertel 15660: sub get_hosts_from_ip {
15661: my ($ip) = @_;
15662: my %iphosts = &get_iphost();
15663: if (ref($iphosts{$ip})) {
15664: return @{$iphosts{$ip}};
15665: }
15666: return;
1.839 albertel 15667: }
1.864 albertel 15668:
15669: sub reset_hosts_ip_info {
15670: undef(%iphost);
15671: undef(%name_to_ip);
15672: undef(%lonid_to_ip);
15673: }
1.856 albertel 15674:
15675: sub get_host_ip {
15676: my ($lonid) = @_;
15677: if (exists($lonid_to_ip{$lonid})) {
15678: return $lonid_to_ip{$lonid};
15679: }
15680: my $name=&hostname($lonid);
15681: my $ip = gethostbyname($name);
15682: return if (!$ip || length($ip) ne 4);
15683: $ip=inet_ntoa($ip);
15684: $name_to_ip{$name} = $ip;
15685: $lonid_to_ip{$lonid} = $ip;
15686: return $ip;
15687: }
1.847 albertel 15688:
15689: sub get_iphost {
1.1293 raeburn 15690: my ($ignore_cache,$nocache) = @_;
1.894 albertel 15691:
1.869 albertel 15692: if (!$ignore_cache) {
15693: if (%iphost) {
15694: return %iphost;
15695: }
15696: my ($ip_info,$cached)=
1.1494 raeburn 15697: &is_cached_new('iphost','iphost');
1.869 albertel 15698: if ($cached) {
15699: %iphost = %{$ip_info->[0]};
15700: %name_to_ip = %{$ip_info->[1]};
15701: %lonid_to_ip = %{$ip_info->[2]};
15702: return %iphost;
15703: }
15704: }
1.894 albertel 15705:
15706: # get yesterday's info for fallback
15707: my %old_name_to_ip;
15708: my ($ip_info,$cached)=
1.1495 raeburn 15709: &is_cached_new('iphost','iphost');
1.894 albertel 15710: if ($cached) {
15711: %old_name_to_ip = %{$ip_info->[1]};
15712: }
15713:
1.1293 raeburn 15714: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 15715: foreach my $name (keys(%name_to_host)) {
1.847 albertel 15716: my $ip;
15717: if (!exists($name_to_ip{$name})) {
15718: $ip = gethostbyname($name);
15719: if (!$ip || length($ip) ne 4) {
1.894 albertel 15720: if (defined($old_name_to_ip{$name})) {
15721: $ip = $old_name_to_ip{$name};
15722: &logthis("Can't find $name defaulting to old $ip");
15723: } else {
15724: &logthis("Name $name no IP found");
15725: next;
15726: }
15727: } else {
15728: $ip=inet_ntoa($ip);
1.847 albertel 15729: }
15730: $name_to_ip{$name} = $ip;
15731: } else {
15732: $ip = $name_to_ip{$name};
1.653 albertel 15733: }
1.888 albertel 15734: foreach my $id (@{ $name_to_host{$name} }) {
15735: $lonid_to_ip{$id} = $ip;
15736: }
15737: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 15738: }
1.1293 raeburn 15739: unless ($nocache) {
15740: &do_cache_new('iphost','iphost',
15741: [\%iphost,\%name_to_ip,\%lonid_to_ip],
15742: 48*60*60);
15743: }
1.869 albertel 15744:
1.847 albertel 15745: return %iphost;
1.598 albertel 15746: }
15747:
1.992 raeburn 15748: #
15749: # Given a DNS returns the loncapa host name for that DNS
15750: #
15751: sub host_from_dns {
15752: my ($dns) = @_;
15753: my @hosts;
15754: my $ip;
15755:
1.993 raeburn 15756: if (exists($name_to_ip{$dns})) {
1.992 raeburn 15757: $ip = $name_to_ip{$dns};
15758: }
15759: if (!$ip) {
15760: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15761: if (length($ip) == 4) {
15762: $ip = &IO::Socket::inet_ntoa($ip);
15763: }
15764: }
15765: if ($ip) {
15766: @hosts = get_hosts_from_ip($ip);
15767: return $hosts[0];
15768: }
15769: return undef;
1.986 foxr 15770: }
1.992 raeburn 15771:
1.1074 raeburn 15772: sub get_internet_names {
15773: my ($lonid) = @_;
15774: return if ($lonid eq '');
15775: my ($idnref,$cached)=
1.1494 raeburn 15776: &is_cached_new('internetnames',$lonid);
1.1074 raeburn 15777: if ($cached) {
15778: return $idnref;
15779: }
15780: my $ip = &get_host_ip($lonid);
15781: my @hosts = &get_hosts_from_ip($ip);
15782: my %iphost = &get_iphost();
15783: my (@idns,%seen);
15784: foreach my $id (@hosts) {
15785: my $dom = &host_domain($id);
15786: my $prim_id = &domain($dom,'primary');
15787: my $prim_ip = &get_host_ip($prim_id);
15788: next if ($seen{$prim_ip});
15789: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15790: foreach my $id (@{$iphost{$prim_ip}}) {
15791: my $intdom = &internet_dom($id);
15792: unless (grep(/^\Q$intdom\E$/,@idns)) {
15793: push(@idns,$intdom);
15794: }
15795: }
15796: }
15797: $seen{$prim_ip} = 1;
15798: }
1.1219 raeburn 15799: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 15800: }
15801:
1.986 foxr 15802: }
15803:
1.1079 raeburn 15804: sub all_loncaparevs {
1.1249 raeburn 15805: 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 15806: }
15807:
1.1227 raeburn 15808: # ---------------------------------------------------------- Read loncaparev table
15809: {
15810: sub load_loncaparevs {
15811: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359 raeburn 15812: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227 raeburn 15813: while (my $configline=<$config>) {
15814: chomp($configline);
15815: my ($hostid,$loncaparev)=split(/:/,$configline);
15816: $loncaparevs{$hostid}=$loncaparev;
15817: }
15818: close($config);
15819: }
15820: }
15821: }
15822: }
15823:
15824: # ---------------------------------------------------------- Read serverhostID table
15825: {
15826: sub load_serverhomeIDs {
15827: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359 raeburn 15828: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227 raeburn 15829: while (my $configline=<$config>) {
15830: chomp($configline);
15831: my ($name,$id)=split(/:/,$configline);
15832: $serverhomeIDs{$name}=$id;
15833: }
15834: close($config);
15835: }
15836: }
15837: }
15838: }
15839:
15840:
1.862 albertel 15841: BEGIN {
15842:
15843: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15844: unless ($readit) {
15845: {
15846: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15847: %perlvar = (%perlvar,%{$configvars});
15848: }
15849:
15850:
1.1 albertel 15851: # ------------------------------------------------------ Read spare server file
15852: {
1.1359 raeburn 15853: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 15854:
15855: while (my $configline=<$config>) {
15856: chomp($configline);
1.284 matthew 15857: if ($configline) {
1.784 albertel 15858: my ($host,$type) = split(':',$configline,2);
1.785 albertel 15859: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 15860: push(@{ $spareid{$type} }, $host);
1.1 albertel 15861: }
15862: }
1.448 albertel 15863: close($config);
1.1 albertel 15864: }
1.11 www 15865: # ------------------------------------------------------------ Read permissions
15866: {
1.1359 raeburn 15867: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 15868:
15869: while (my $configline=<$config>) {
1.448 albertel 15870: chomp($configline);
15871: if ($configline) {
15872: my ($role,$perm)=split(/ /,$configline);
15873: if ($perm ne '') { $pr{$role}=$perm; }
15874: }
1.11 www 15875: }
1.448 albertel 15876: close($config);
1.11 www 15877: }
15878:
15879: # -------------------------------------------- Read plain texts for permissions
15880: {
1.1359 raeburn 15881: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 15882:
15883: while (my $configline=<$config>) {
1.448 albertel 15884: chomp($configline);
15885: if ($configline) {
1.742 raeburn 15886: my ($short,@plain)=split(/:/,$configline);
15887: %{$prp{$short}} = ();
15888: if (@plain > 0) {
15889: $prp{$short}{'std'} = $plain[0];
15890: for (my $i=1; $i<@plain; $i++) {
15891: $prp{$short}{'alt'.$i} = $plain[$i];
15892: }
15893: }
1.448 albertel 15894: }
1.135 www 15895: }
1.448 albertel 15896: close($config);
1.135 www 15897: }
15898:
15899: # ---------------------------------------------------------- Read package table
15900: {
1.1359 raeburn 15901: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 15902:
15903: while (my $configline=<$config>) {
1.483 albertel 15904: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 15905: chomp($configline);
15906: my ($short,$plain)=split(/:/,$configline);
15907: my ($pack,$name)=split(/\&/,$short);
15908: if ($plain ne '') {
15909: $packagetab{$pack.'&'.$name.'&name'}=$name;
15910: $packagetab{$short}=$plain;
15911: }
1.11 www 15912: }
1.448 albertel 15913: close($config);
1.329 matthew 15914: }
15915:
1.1073 raeburn 15916: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 15917:
15918: &load_loncaparevs();
1.1073 raeburn 15919:
1.1074 raeburn 15920: # ---------------------------------------------------------- Read serverhostID table
15921:
1.1227 raeburn 15922: &load_serverhomeIDs();
15923:
15924: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 15925: {
15926: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15927: if (-e $file) {
15928: my $parser = HTML::LCParser->new($file);
15929: while (my $token = $parser->get_token()) {
15930: if ($token->[0] eq 'S') {
15931: my $item = $token->[1];
15932: my $name = $token->[2]{'name'};
15933: my $value = $token->[2]{'value'};
1.1285 raeburn 15934: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 15935: my $namematch = $token->[2]{'namematch'};
15936: if ($item eq 'parameter') {
15937: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15938: my $release = $parser->get_text();
15939: $release =~ s/(^\s*|\s*$ )//gx;
15940: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15941: }
15942: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 15943: my $release = $parser->get_text();
15944: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 15945: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 15946: }
15947: }
15948: }
15949: }
1.1073 raeburn 15950: }
15951:
1.1138 raeburn 15952: # ---------------------------------------------------------- Read managers table
15953: {
15954: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359 raeburn 15955: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 15956: while (my $configline=<$config>) {
15957: chomp($configline);
15958: next if ($configline =~ /^\#/);
15959: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15960: $managerstab{$configline} = 1;
15961: }
15962: }
15963: close($config);
15964: }
15965: }
15966: }
15967:
1.329 matthew 15968: # ------------- set up temporary directory
15969: {
1.1117 foxr 15970: $tmpdir = LONCAPA::tempdir();
1.329 matthew 15971:
1.11 www 15972: }
15973:
1.1405 raeburn 15974: # ------------- set default texengine (domain default overrides this)
15975: {
15976: $deftex = LONCAPA::texengine();
15977: }
15978:
1.1416 raeburn 15979: # ------------- set default minimum length for passwords for internal auth users
15980: {
15981: $passwdmin = LONCAPA::passwd_min();
15982: }
15983:
1.794 albertel 15984: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
15985: 'compress_threshold'=> 20_000,
15986: });
1.185 www 15987:
1.281 www 15988: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 15989: $dumpcount=0;
1.958 www 15990: $locknum=0;
1.22 www 15991:
1.163 harris41 15992: &logtouch();
1.672 albertel 15993: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 15994: $readit=1;
1.564 albertel 15995: {
15996: use integer;
15997: my $test=(2**32)+1;
1.568 albertel 15998: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 15999: &logthis(" Detected 64bit platform ($_64bit)");
16000: }
1.195 www 16001: }
1.1 albertel 16002: }
1.179 www 16003:
1.1 albertel 16004: 1;
1.191 harris41 16005: __END__
16006:
1.243 albertel 16007: =pod
16008:
1.191 harris41 16009: =head1 NAME
16010:
1.243 albertel 16011: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 16012:
16013: =head1 SYNOPSIS
16014:
1.243 albertel 16015: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 16016:
16017: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16018:
1.243 albertel 16019: Common parameters:
16020:
16021: =over 4
16022:
16023: =item *
16024:
16025: $uname : an internal username (if $cname expecting a course Id specifically)
16026:
16027: =item *
16028:
16029: $udom : a domain (if $cdom expecting a course's domain specifically)
16030:
16031: =item *
16032:
16033: $symb : a resource instance identifier
16034:
16035: =item *
16036:
16037: $namespace : the name of a .db file that contains the data needed or
16038: being set.
16039:
16040: =back
16041:
1.394 bowersj2 16042: =head1 OVERVIEW
1.191 harris41 16043:
1.394 bowersj2 16044: lonnet provides subroutines which interact with the
16045: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16046: about classes, users, and resources.
1.243 albertel 16047:
16048: For many of these objects you can also use this to store data about
16049: them or modify them in various ways.
1.191 harris41 16050:
1.394 bowersj2 16051: =head2 Symbs
1.191 harris41 16052:
1.394 bowersj2 16053: To identify a specific instance of a resource, LON-CAPA uses symbols
16054: or "symbs"X<symb>. These identifiers are built from the URL of the
16055: map, the resource number of the resource in the map, and the URL of
16056: the resource itself. The latter is somewhat redundant, but might help
16057: if maps change.
16058:
16059: An example is
16060:
16061: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16062:
16063: The respective map entry is
16064:
16065: <resource id="19" src="/res/msu/korte/tests/part12.problem"
16066: title="Problem 2">
16067: </resource>
16068:
16069: Symbs are used by the random number generator, as well as to store and
16070: restore data specific to a certain instance of for example a problem.
16071:
16072: =head2 Storing And Retrieving Data
16073:
16074: X<store()>X<cstore()>X<restore()>Three of the most important functions
16075: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16076: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16077: is is the non-critical message twin of cstore. These functions are for
16078: handlers to store a perl hash to a user's permanent data space in an
16079: easy manner, and to retrieve it again on another call. It is expected
16080: that a handler would use this once at the beginning to retrieve data,
16081: and then again once at the end to send only the new data back.
16082:
16083: The data is stored in the user's data directory on the user's
16084: homeserver under the ID of the course.
16085:
16086: The hash that is returned by restore will have all of the previous
16087: value for all of the elements of the hash.
16088:
16089: Example:
16090:
16091: #creating a hash
16092: my %hash;
16093: $hash{'foo'}='bar';
16094:
16095: #storing it
16096: &Apache::lonnet::cstore(\%hash);
16097:
16098: #changing a value
16099: $hash{'foo'}='notbar';
16100:
16101: #adding a new value
16102: $hash{'bar'}='foo';
16103: &Apache::lonnet::cstore(\%hash);
16104:
16105: #retrieving the hash
16106: my %history=&Apache::lonnet::restore();
16107:
16108: #print the hash
16109: foreach my $key (sort(keys(%history))) {
16110: print("\%history{$key} = $history{$key}");
16111: }
16112:
16113: Will print out:
1.191 harris41 16114:
1.394 bowersj2 16115: %history{1:foo} = bar
16116: %history{1:keys} = foo:timestamp
16117: %history{1:timestamp} = 990455579
16118: %history{2:bar} = foo
16119: %history{2:foo} = notbar
16120: %history{2:keys} = foo:bar:timestamp
16121: %history{2:timestamp} = 990455580
16122: %history{bar} = foo
16123: %history{foo} = notbar
16124: %history{timestamp} = 990455580
16125: %history{version} = 2
16126:
16127: Note that the special hash entries C<keys>, C<version> and
16128: C<timestamp> were added to the hash. C<version> will be equal to the
16129: total number of versions of the data that have been stored. The
16130: C<timestamp> attribute will be the UNIX time the hash was
16131: stored. C<keys> is available in every historical section to list which
16132: keys were added or changed at a specific historical revision of a
16133: hash.
16134:
16135: B<Warning>: do not store the hash that restore returns directly. This
16136: will cause a mess since it will restore the historical keys as if the
16137: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 16138:
1.394 bowersj2 16139: Calling convention:
1.191 harris41 16140:
1.1225 raeburn 16141: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 16142: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 16143:
1.394 bowersj2 16144: For more detailed information, see lonnet specific documentation.
1.191 harris41 16145:
1.394 bowersj2 16146: =head1 RETURN MESSAGES
1.191 harris41 16147:
1.394 bowersj2 16148: =over 4
1.191 harris41 16149:
1.394 bowersj2 16150: =item * B<con_lost>: unable to contact remote host
1.191 harris41 16151:
1.394 bowersj2 16152: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16153: when the connection is brought back up
1.191 harris41 16154:
1.394 bowersj2 16155: =item * B<con_failed>: unable to contact remote host and unable to save message
16156: for later delivery
1.191 harris41 16157:
1.967 bisitz 16158: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 16159:
1.394 bowersj2 16160: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 16161: that was requested
1.191 harris41 16162:
1.243 albertel 16163: =back
1.191 harris41 16164:
1.243 albertel 16165: =head1 PUBLIC SUBROUTINES
1.191 harris41 16166:
1.243 albertel 16167: =head2 Session Environment Functions
1.191 harris41 16168:
1.243 albertel 16169: =over 4
1.191 harris41 16170:
1.394 bowersj2 16171: =item *
16172: X<appenv()>
1.949 raeburn 16173: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 16174: the user envirnoment file, and will be restored for each access this
1.620 albertel 16175: user makes during this session, also modifies the %env for the current
1.949 raeburn 16176: process. Optional rolesarrayref - if defined contains a reference to an array
16177: of roles which are exempt from the restriction on modifying user.role entries
16178: in the user's environment.db and in %env.
1.191 harris41 16179:
16180: =item *
1.394 bowersj2 16181: X<delenv()>
1.987 raeburn 16182: B<delenv($delthis,$regexp)>: removes all items from the session
16183: environment file that begin with $delthis. If the
16184: optional second arg - $regexp - is true, $delthis is treated as a
16185: regular expression, otherwise \Q$delthis\E is used.
16186: The values are also deleted from the current processes %env.
1.191 harris41 16187:
1.795 albertel 16188: =item * get_env_multiple($name)
16189:
16190: gets $name from the %env hash, it seemlessly handles the cases where multiple
16191: values may be defined and end up as an array ref.
16192:
16193: returns an array of values
16194:
1.243 albertel 16195: =back
16196:
16197: =head2 User Information
1.191 harris41 16198:
1.243 albertel 16199: =over 4
1.191 harris41 16200:
16201: =item *
1.394 bowersj2 16202: X<queryauthenticate()>
16203: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 16204: authentication scheme
16205:
16206: =item *
1.394 bowersj2 16207: X<authenticate()>
1.1073 raeburn 16208: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 16209: authenticate user from domain's lib servers (first use the current
16210: one). C<$upass> should be the users password.
1.1073 raeburn 16211: $checkdefauth is optional (value is 1 if a check should be made to
16212: authenticate user using default authentication method, and allow
16213: account creation if username does not have account in the domain).
16214: $clientcancheckhost is optional (value is 1 if checking whether the
16215: server can host will occur on the client side in lonauth.pm).
1.191 harris41 16216:
16217: =item *
1.394 bowersj2 16218: X<homeserver()>
16219: B<homeserver($uname,$udom)>: find the server which has
16220: the user's directory and files (there must be only one), this caches
16221: the answer, and also caches if there is a borken connection.
1.191 harris41 16222:
16223: =item *
1.394 bowersj2 16224: X<idget()>
1.1300 raeburn 16225: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
16226: a list of student/employee IDs or clicker IDs
16227: (student/employee IDs are a unique resource in a domain, there must be
16228: only 1 ID per username, and only 1 username per ID in a specific domain).
16229: clickerIDs are not necessarily unique, as students might share clickers.
16230: (returns hash: id=>name,id=>name)
1.191 harris41 16231:
16232: =item *
1.394 bowersj2 16233: X<idrget()>
16234: B<idrget($udom,@unames)>: find the IDs behind a list of
16235: usernames (returns hash: name=>id,name=>id)
1.191 harris41 16236:
16237: =item *
1.394 bowersj2 16238: X<idput()>
1.1300 raeburn 16239: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
16240: names and associated student/employee IDs or clicker IDs.
16241:
16242: =item *
16243: X<iddel()>
16244: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
16245: student/employee ID or clicker ID username look-ups from domain.
16246: The homeserver ($uhome) and namespace ($namespace) are optional.
16247: If no $uhome is provided, it will be determined usig &homeserver()
16248: for each user. If no $namespace is provided, the default is ids.
16249:
16250: =item *
16251: X<updateclickers()>
16252: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
16253: clicker ID-to-username look-ups in clickers.db on library server.
16254: Permitted actions are add or del (i.e., add or delete). The
16255: clickers.db contains clickerID as keys (escaped), and each corresponding
16256: value is an escaped comma-separated list of usernames (for whom the
16257: library server is the homeserver), who registered that particular ID.
16258: If $critical is true, the update will be sent via &critical, otherwise
16259: &reply() will be used.
1.191 harris41 16260:
16261: =item *
1.394 bowersj2 16262: X<rolesinit()>
1.1169 droeschl 16263: B<rolesinit($udom,$username)>: get user privileges.
16264: returns user role, first access and timer interval hashes
1.243 albertel 16265:
16266: =item *
1.1171 droeschl 16267: X<privileged()>
16268: B<privileged($username,$domain)>: returns a true if user has a
16269: privileged and active role (i.e. su or dc), false otherwise.
16270:
16271: =item *
1.551 albertel 16272: X<getsection()>
16273: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 16274: course $cname, return section name/number or '' for "not in course"
16275: and '-1' for "no section"
16276:
16277: =item *
1.394 bowersj2 16278: X<userenvironment()>
16279: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 16280: passed in @what from the requested user's environment, returns a hash
16281:
1.858 raeburn 16282: =item *
16283: X<userlog_query()>
1.859 albertel 16284: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16285: activity.log file. %filters defines filters applied when parsing the
16286: log file. These can be start or end timestamps, or the type of action
16287: - log to look for Login or Logout events, check for Checkin or
16288: Checkout, role for role selection. The response is in the form
16289: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
16290: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 16291:
1.243 albertel 16292: =back
16293:
16294: =head2 User Roles
16295:
16296: =over 4
16297:
16298: =item *
16299:
1.1284 raeburn 16300: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
16301: returns codes for allowed actions.
16302:
16303: The first argument is required, all others are optional.
16304:
16305: $priv is the privilege being checked.
16306: $uri contains additional information about what is being checked for access (e.g.,
16307: URL, course ID etc.).
16308: $symb is the unique resource instance identifier in a course; if needed,
16309: but not provided, it will be retrieved via a call to &symbread().
16310: $role is the role for which a priv is being checked (only used if priv is evb).
16311: $clientip is the user's IP address (only used when checking for access to portfolio
16312: files).
16313: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
16314: prevents recursive calls to &allowed.
16315:
1.243 albertel 16316: F: full access
16317: U,I,K: authentication modes (cxx only)
16318: '': forbidden
16319: 1: user needs to choose course
16320: 2: browse allowed
1.766 albertel 16321: A: passphrase authentication needed
1.1284 raeburn 16322: B: access temporarily blocked because of a blocking event in a course.
1.1402 raeburn 16323: D: access blocked because access is required via session initiated via deep-link
1.243 albertel 16324:
16325: =item *
16326:
1.1192 raeburn 16327: constructaccess($url,$setpriv) : check for access to construction space URL
16328:
16329: See if the owner domain and name in the URL match those in the
16330: expected environment. If so, return three element list
16331: ($ownername,$ownerdomain,$ownerhome).
16332:
16333: Otherwise return the null string.
16334:
16335: If second argument 'setpriv' is true, it assigns the privileges,
16336: and returns the same three element list, unless the owner has
16337: blocked "ad hoc" Domain Coordinator access to the Author Space,
16338: in which case the null string is returned.
16339:
16340: =item *
16341:
1.1326 raeburn 16342: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16343: define a custom role rolename set privileges in format of lonTabs/roles.tab
16344: for system, domain, and course level. $uname and $udom are optional (current
16345: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 16346:
16347: =item *
16348:
1.988 raeburn 16349: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
16350: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 16351: $type is Course (default) or Community.
1.988 raeburn 16352: If $forcedefault evaluates to true, text returned will be default
16353: text for $type. Otherwise, if this is a course, the text returned
16354: will be a custom name for the role (if defined in the course's
16355: environment). If no custom name is defined the default is returned.
16356:
1.832 raeburn 16357: =item *
16358:
1.1219 raeburn 16359: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 16360: All arguments are optional. Returns a hash of a roles, either for
16361: co-author/assistant author roles for a user's Construction Space
1.906 albertel 16362: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 16363: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16364: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16365: For each key, value is set to colon-separated start and end times for
16366: the role. If no username and domain are specified, will default to
1.934 raeburn 16367: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 16368: of role statuses (active, future or previous), roles
16369: (e.g., cc,in, st etc.) and domains of the roles which can be used
16370: to restrict the list of roles reported. If no array ref is
16371: provided for types, will default to return only active roles.
1.834 albertel 16372:
1.1195 raeburn 16373: =item *
16374:
16375: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 16376: user: $uname:$udom has a role in the course: $cdom_$cnum.
16377:
16378: Additional optional arguments are: $type (if role checking is to be restricted
16379: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 16380: available roles) or future (roles available in the future), and
16381: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 16382: have active Domain Coordinator role in course's domain or in additional
16383: domains (specified in 'Domains to check for privileged users' in course
16384: environment -- set via: Course Settings -> Classlists and staff listing).
16385:
16386: =item *
16387:
16388: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16389: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16390: $possdomains and $possroles are optional array refs -- to domains to check and
16391: roles to check. If $possdomains is not specified, a dump will be done of the
16392: users' roles.db to check for a dc or su role in any domain. This can be
16393: time consuming if &privileged is called repeatedly (e.g., when displaying a
16394: classlist), so in such cases, supplying a $possdomains array is preferred, as
16395: this then allows &privileged_by_domain() to be used, which caches the identity
16396: of privileged users, eliminating the need for repeated calls to &dump().
16397:
16398: =item *
16399:
16400: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16401: where the outer hash keys are domains specified in the $possdomains array ref,
16402: next inner hash keys are privileged roles specified in the $roles array ref,
16403: and the innermost hash contains key = value pairs for username:domain = end:start
16404: for active or future "privileged" users with that role in that domain. To avoid
16405: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16406: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 16407:
1.243 albertel 16408: =back
16409:
16410: =head2 User Modification
16411:
16412: =over 4
16413:
16414: =item *
16415:
1.957 raeburn 16416: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 16417: user for the level given by URL. Optional start and end dates (leave empty
16418: string or zero for "no date")
1.191 harris41 16419:
16420: =item *
16421:
1.243 albertel 16422: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16423: change a users, password, possible return values are: ok,
16424: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16425: refused
1.191 harris41 16426:
16427: =item *
16428:
1.243 albertel 16429: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 16430:
16431: =item *
16432:
1.1058 raeburn 16433: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16434: $forceid,$desiredhome,$email,$inststatus,$candelete) :
16435:
16436: will update user information (firstname,middlename,lastname,generation,
16437: permanentemail), and if forceid is true, student/employee ID also.
16438: A user's institutional affiliation(s) can also be updated.
16439: User information fields will not be overwritten with empty entries
16440: unless the field is included in the $candelete array reference.
16441: This array is included when a single user is modified via "Manage Users",
16442: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 16443:
16444: =item *
16445:
1.286 matthew 16446: modifystudent
16447:
1.957 raeburn 16448: modify a student's enrollment and identification information.
1.1235 raeburn 16449: The course id is resolved based on the current user's environment.
16450: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 16451: associated with a course.
16452:
1.297 matthew 16453: This call is essentially a wrapper for lonnet::modifyuser and
16454: lonnet::modify_student_enrollment
1.286 matthew 16455:
16456: Inputs:
16457:
16458: =over 4
16459:
1.957 raeburn 16460: =item B<$udom> Student's loncapa domain
1.286 matthew 16461:
1.957 raeburn 16462: =item B<$uname> Student's loncapa login name
1.286 matthew 16463:
1.964 bisitz 16464: =item B<$uid> Student/Employee ID
1.286 matthew 16465:
1.957 raeburn 16466: =item B<$umode> Student's authentication mode
1.286 matthew 16467:
1.957 raeburn 16468: =item B<$upass> Student's password
1.286 matthew 16469:
1.957 raeburn 16470: =item B<$first> Student's first name
1.286 matthew 16471:
1.957 raeburn 16472: =item B<$middle> Student's middle name
1.286 matthew 16473:
1.957 raeburn 16474: =item B<$last> Student's last name
1.286 matthew 16475:
1.957 raeburn 16476: =item B<$gene> Student's generation
1.286 matthew 16477:
1.957 raeburn 16478: =item B<$usec> Student's section in course
1.286 matthew 16479:
16480: =item B<$end> Unix time of the roles expiration
16481:
16482: =item B<$start> Unix time of the roles start date
16483:
16484: =item B<$forceid> If defined, allow $uid to be changed
16485:
16486: =item B<$desiredhome> server to use as home server for student
16487:
1.957 raeburn 16488: =item B<$email> Student's permanent e-mail address
16489:
16490: =item B<$type> Type of enrollment (auto or manual)
16491:
1.963 raeburn 16492: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
16493:
16494: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 16495:
1.963 raeburn 16496: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 16497:
1.963 raeburn 16498: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 16499:
1.1216 raeburn 16500: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16501:
16502: =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 16503:
1.286 matthew 16504: =back
1.297 matthew 16505:
16506: =item *
16507:
16508: modify_student_enrollment
16509:
1.1235 raeburn 16510: Change a student's enrollment status in a class. The environment variable
1.297 matthew 16511: 'role.request.course' must be defined for this function to proceed.
16512:
16513: Inputs:
16514:
16515: =over 4
16516:
1.1235 raeburn 16517: =item $udom, student's domain
1.297 matthew 16518:
1.1235 raeburn 16519: =item $uname, student's name
1.297 matthew 16520:
1.1235 raeburn 16521: =item $uid, student's user id
1.297 matthew 16522:
1.1235 raeburn 16523: =item $first, student's first name
1.297 matthew 16524:
16525: =item $middle
16526:
16527: =item $last
16528:
16529: =item $gene
16530:
16531: =item $usec
16532:
16533: =item $end
16534:
16535: =item $start
16536:
1.957 raeburn 16537: =item $type
16538:
16539: =item $locktype
16540:
16541: =item $cid
16542:
16543: =item $selfenroll
16544:
16545: =item $context
16546:
1.1216 raeburn 16547: =item $credits, number of credits student will earn from this class
16548:
1.1314 raeburn 16549: =item $instsec, institutional course section code for student
16550:
1.297 matthew 16551: =back
16552:
1.191 harris41 16553:
16554: =item *
16555:
1.243 albertel 16556: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16557: custom role; give a custom role to a user for the level given by URL. Specify
16558: name and domain of role author, and role name
1.191 harris41 16559:
16560: =item *
16561:
1.243 albertel 16562: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 16563:
16564: =item *
16565:
1.243 albertel 16566: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16567:
16568: =back
16569:
16570: =head2 Course Infomation
16571:
16572: =over 4
1.191 harris41 16573:
16574: =item *
16575:
1.1118 foxr 16576: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 16577: specified course id, including all environment settings for the
16578: course, the description of the course will be in the hash under the
16579: key 'description'
1.191 harris41 16580:
1.1118 foxr 16581: $options is an optional parameter that if supplied is a hash reference that controls
16582: what how this function works. It has the following key/values:
16583:
16584: =over 4
16585:
16586: =item freshen_cache
16587:
16588: If defined, and the environment cache for the course is valid, it is
16589: returned in the returned hash.
16590:
16591: =item one_time
16592:
16593: If defined, the last cache time is set to _now_
16594:
16595: =item user
16596:
16597: If defined, the supplied username is used instead of the current user.
16598:
16599:
16600: =back
16601:
1.191 harris41 16602: =item *
16603:
1.624 albertel 16604: resdata($name,$domain,$type,@which) : request for current parameter
16605: setting for a specific $type, where $type is either 'course' or 'user',
16606: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 16607: answers for 10 minutes.
1.243 albertel 16608:
1.877 foxr 16609: =item *
16610:
16611: get_courseresdata($courseid, $domain) : dump the entire course resource
16612: data base, returning a hash that is keyed by the resource name and has
16613: values that are the resource value. I believe that the timestamps and
16614: versions are also returned.
16615:
1.243 albertel 16616: =back
16617:
16618: =head2 Course Modification
16619:
16620: =over 4
1.191 harris41 16621:
16622: =item *
16623:
1.243 albertel 16624: writecoursepref($courseid,%prefs) : write preferences (environment
16625: database) for a course
1.191 harris41 16626:
16627: =item *
16628:
1.1011 raeburn 16629: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16630:
16631: =item *
16632:
1.1038 raeburn 16633: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 16634:
1.1167 droeschl 16635: =item *
16636:
16637: is_course($courseid), is_course($cdom, $cnum)
16638:
16639: Accepts either a combined $courseid (in the form of domain_courseid) or the
16640: two component version $cdom, $cnum. It checks if the specified course exists.
16641:
16642: Returns:
16643: undef if the course doesn't exist, otherwise
16644: in scalar context the combined courseid.
16645: in list context the two components of the course identifier, domain and
16646: courseid.
16647:
1.243 albertel 16648: =back
16649:
1.1401 raeburn 16650: =head2 Bubblesheet Configuration
16651:
16652: =over 4
16653:
16654: =item *
16655:
16656: get_scantron_config($which)
16657:
16658: $which - the name of the configuration to parse from the file.
16659:
16660: Parses and returns the bubblesheet configuration line selected as a
16661: hash of configuration file fields.
16662:
16663:
16664: Returns:
16665: If the named configuration is not in the file, an empty
16666: hash is returned.
16667:
16668: a hash with the fields
16669: name - internal name for the this configuration setup
16670: description - text to display to operator that describes this config
16671: CODElocation - if 0 or the string 'none'
16672: - no CODE exists for this config
16673: if -1 || the string 'letter'
16674: - a CODE exists for this config and is
16675: a string of letters
16676: Unsupported value (but planned for future support)
16677: if a positive integer
16678: - The CODE exists as the first n items from
16679: the question section of the form
16680: if the string 'number'
16681: - The CODE exists for this config and is
16682: a string of numbers
16683: CODEstart - (only matter if a CODE exists) column in the line where
16684: the CODE starts
16685: CODElength - length of the CODE
16686: IDstart - column where the student/employee ID starts
16687: IDlength - length of the student/employee ID info
16688: Qstart - column where the information from the bubbled
16689: 'questions' start
16690: Qlength - number of columns comprising a single bubble line from
16691: the sheet. (usually either 1 or 10)
16692: Qon - either a single character representing the character used
16693: to signal a bubble was chosen in the positional setup, or
16694: the string 'letter' if the letter of the chosen bubble is
16695: in the final, or 'number' if a number representing the
16696: chosen bubble is in the file (1->A 0->J)
16697: Qoff - the character used to represent that a bubble was
16698: left blank
16699: PaperID - if the scanning process generates a unique number for each
16700: sheet scanned the column that this ID number starts in
16701: PaperIDlength - number of columns that comprise the unique ID number
16702: for the sheet of paper
16703: FirstName - column that the first name starts in
16704: FirstNameLength - number of columns that the first name spans
16705: LastName - column that the last name starts in
16706: LastNameLength - number of columns that the last name spans
16707: BubblesPerRow - number of bubbles available in each row used to
16708: bubble an answer. (If not specified, 10 assumed).
16709:
16710:
16711: =item *
16712:
16713: get_scantronformat_file($cdom)
16714:
16715: $cdom - the course's domain (optional); if not supplied, uses
16716: domain for current $env{'request.course.id'}.
16717:
16718: Returns an array containing lines from the scantron format file for
16719: the domain of the course.
16720:
16721: If a url for a custom.tab file is listed in domain's configuration.db,
16722: lines are from this file.
16723:
16724: Otherwise, if a default.tab has been published in RES space by the
16725: domainconfig user, lines are from this file.
16726:
16727: Otherwise, fall back to getting lines from the legacy file on the
16728: local server: /home/httpd/lonTabs/default_scantronformat.tab
16729:
16730: =back
16731:
1.243 albertel 16732: =head2 Resource Subroutines
16733:
16734: =over 4
1.191 harris41 16735:
16736: =item *
16737:
1.243 albertel 16738: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 16739:
16740: =item *
16741:
1.243 albertel 16742: repcopy($filename) : subscribes to the requested file, and attempts to
16743: replicate from the owning library server, Might return
1.607 raeburn 16744: 'unavailable', 'not_found', 'forbidden', 'ok', or
16745: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 16746: resource. Expects the local filesystem pathname
16747: (/home/httpd/html/res/....)
16748:
16749: =back
16750:
16751: =head2 Resource Information
16752:
16753: =over 4
1.191 harris41 16754:
16755: =item *
16756:
1.1228 raeburn 16757: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
16758: and returns the value of a variety of different possible values,
16759: $varname should be a request string, and the other parameters can be
16760: used to specify who and what one is asking about. Ordinarily, $cid
16761: does not need to be specified, as it is retrived from
16762: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16763: within lonuserstate::loadmap() when initializing a course, before
16764: $env{'request.course.id'} has been set, so it needs to be provided
16765: in that one case.
1.243 albertel 16766:
16767: Possible values for $varname are environment.lastname (or other item
16768: from the envirnment hash), user.name (or someother aspect about the
16769: user), resource.0.maxtries (or some other part and parameter of a
16770: resource)
1.204 albertel 16771:
16772: =item *
16773:
1.243 albertel 16774: directcondval($number) : get current value of a condition; reads from a state
16775: string
1.204 albertel 16776:
16777: =item *
16778:
1.243 albertel 16779: condval($condidx) : value of condition index based on state
1.204 albertel 16780:
16781: =item *
16782:
1.1362 raeburn 16783: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243 albertel 16784: resource's metadata, $what should be either a specific key, or either
16785: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362 raeburn 16786: packages that this resource currently uses, the last 3 arguments are
16787: only used internally for recursive metadata.
16788:
16789: the toolsymb is only used where the uri is for an external tool (for which
16790: the uri as well as the symb are guaranteed to be unique).
1.243 albertel 16791:
1.1371 raeburn 16792: this function automatically caches all requests except any made recursively
16793: to retrieve a list of metadata keys for an imported library file ($liburi is
16794: defined).
1.191 harris41 16795:
16796: =item *
16797:
1.243 albertel 16798: metadata_query($query,$custom,$customshow) : make a metadata query against the
16799: network of library servers; returns file handle of where SQL and regex results
16800: will be stored for query
1.191 harris41 16801:
16802: =item *
16803:
1.1282 raeburn 16804: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
16805: return symbolic list entry (all arguments optional).
16806:
16807: Args: filename is the filename (including path) for the file for which a symb
16808: is required; donotrecurse, if true will prevent calls to allowed() being made
16809: to check access status if more than one resource was found in the bighash
16810: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
16811: a randompick); ignorecachednull, if true will prevent a symb of '' being
16812: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16813: cause possible symbs to be checked to determine if they are subject to content
16814: blocking, if so they will not be included as possible symbs; possibles is a
16815: ref to a hash, which, as a side effect, will be populated with all possible
16816: symbs (content blocking not tested).
16817:
1.243 albertel 16818: returns the data handle
1.191 harris41 16819:
16820: =item *
16821:
1.1190 raeburn 16822: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16823: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 16824: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 16825: on failure, user must be in a course, as it assumes the existence of
16826: the course initial hash, and uses $env('request.course.id'}. The third
16827: arg is an optional reference to a scalar. If this arg is passed in the
16828: call to symbverify, it will be set to 1 if the symb has been set to be
16829: encrypted; otherwise it will be null.
1.191 harris41 16830:
16831: =item *
16832:
1.243 albertel 16833: symbclean($symb) : removes versions numbers from a symb, returns the
16834: cleaned symb
1.191 harris41 16835:
16836: =item *
16837:
1.243 albertel 16838: is_on_map($uri) : checks if the $uri is somewhere on the current
16839: course map, user must be in a course for it to work.
1.191 harris41 16840:
16841: =item *
16842:
1.243 albertel 16843: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 16844:
16845: =item *
16846:
1.243 albertel 16847: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16848: a random seed, all arguments are optional, if they aren't sent it uses the
16849: environment to derive them. Note: if symb isn't sent and it can't get one
16850: from &symbread it will use the current time as its return value
1.191 harris41 16851:
16852: =item *
16853:
1.243 albertel 16854: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16855: unfakeable, receipt
1.191 harris41 16856:
16857: =item *
16858:
1.620 albertel 16859: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 16860:
16861: =item *
16862:
1.243 albertel 16863: countacc($url) : count the number of accesses to a given URL
1.191 harris41 16864:
16865: =item *
16866:
1.243 albertel 16867: 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 16868:
16869: =item *
16870:
1.243 albertel 16871: 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 16872:
16873: =item *
16874:
1.243 albertel 16875: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 16876:
16877: =item *
16878:
1.243 albertel 16879: devalidate($symb) : devalidate temporary spreadsheet calculations,
16880: forcing spreadsheet to reevaluate the resource scores next time.
16881:
1.1195 raeburn 16882: =item *
16883:
1.1196 raeburn 16884: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16885: when viewing in course context.
1.1195 raeburn 16886:
1.1196 raeburn 16887: input: six args -- filename (decluttered), course number, course domain,
16888: url, symb (if registered) and group (if this is a
16889: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 16890:
1.1196 raeburn 16891: output: array of five scalars --
1.1195 raeburn 16892: $cfile -- url for file editing if editable on current server
16893: $home -- homeserver of resource (i.e., for author if published,
16894: or course if uploaded.).
16895: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 16896: $forceedit -- 1 if icon/link should be to go to edit mode
16897: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 16898:
16899: =item *
16900:
16901: is_course_upload($file,$cnum,$cdom)
16902:
16903: Used in course context to determine if current file was uploaded to
16904: the course (i.e., would be found in /userfiles/docs on the course's
16905: homeserver.
16906:
16907: input: 3 args -- filename (decluttered), course number and course domain.
16908: output: boolean -- 1 if file was uploaded.
16909:
1.243 albertel 16910: =back
16911:
16912: =head2 Storing/Retreiving Data
16913:
16914: =over 4
1.191 harris41 16915:
16916: =item *
16917:
1.1269 raeburn 16918: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16919: permanently for this url; hashref needs to be given and should be a \%hashname;
16920: the remaining args aren't required and if they aren't passed or are '' they will
16921: be derived from the env (with the exception of $laststore, which is an
16922: optional arg used when a user's submission is stored in grading).
16923: $laststore is $version=$timestamp, where $version is the most recent version
16924: number retrieved for the corresponding $symb in the $namespace db file, and
16925: $timestamp is the timestamp for that transaction (UNIX time).
16926: $laststore is currently only passed when cstore() is called by
16927: structuretags::finalize_storage().
1.191 harris41 16928:
16929: =item *
16930:
1.1269 raeburn 16931: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16932: but uses critical subroutine
1.191 harris41 16933:
16934: =item *
16935:
1.243 albertel 16936: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16937: all args are optional
1.191 harris41 16938:
16939: =item *
16940:
1.717 albertel 16941: dumpstore($namespace,$udom,$uname,$regexp,$range) :
16942: dumps the complete (or key matching regexp) namespace into a hash
16943: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16944: normally &store()ed into
16945:
16946: $range should be either an integer '100' (give me the first 100
16947: matching records)
16948: or be two integers sperated by a - with no spaces
16949: '30-50' (give me the 30th through the 50th matching
16950: records)
16951:
16952:
16953: =item *
16954:
1.1269 raeburn 16955: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 16956: replaces a &store() version of data with a replacement set of data
16957: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 16958: reference. If $tolog is true, the transaction is logged in the courselog
16959: with an action=PUTSTORE.
1.717 albertel 16960:
16961: =item *
16962:
1.243 albertel 16963: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16964: works very similar to store/cstore, but all data is stored in a
16965: temporary location and can be reset using tmpreset, $storehash should
16966: be a hash reference, returns nothing on success
1.191 harris41 16967:
16968: =item *
16969:
1.243 albertel 16970: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16971: similar to restore, but all data is stored in a temporary location and
16972: can be reset using tmpreset. Returns a hash of values on success,
16973: error string otherwise.
1.191 harris41 16974:
16975: =item *
16976:
1.243 albertel 16977: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16978: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 16979:
16980: =item *
16981:
1.243 albertel 16982: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16983: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 16984:
16985: =item *
16986:
1.243 albertel 16987: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16988: namesp ($udom and $uname are optional)
1.191 harris41 16989:
16990: =item *
16991:
1.702 albertel 16992: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 16993: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 16994: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 16995:
1.702 albertel 16996: $range should be either an integer '100' (give me the first 100
16997: matching records)
16998: or be two integers sperated by a - with no spaces
16999: '30-50' (give me the 30th through the 50th matching
17000: records)
1.449 matthew 17001: =item *
17002:
17003: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17004: $store can be a scalar, an array reference, or if the amount to be
17005: incremented is > 1, a hash reference.
17006:
17007: ($udom and $uname are optional)
1.191 harris41 17008:
17009: =item *
17010:
1.243 albertel 17011: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17012: ($udom and $uname are optional)
1.191 harris41 17013:
17014: =item *
17015:
1.243 albertel 17016: cput($namespace,$storehash,$udom,$uname) : critical put
17017: ($udom and $uname are optional)
1.191 harris41 17018:
17019: =item *
17020:
1.748 albertel 17021: newput($namespace,$storehash,$udom,$uname) :
17022:
17023: Attempts to store the items in the $storehash, but only if they don't
17024: currently exist, if this succeeds you can be certain that you have
17025: successfully created a new key value pair in the $namespace db.
17026:
17027:
17028: Args:
17029: $namespace: name of database to store values to
17030: $storehash: hashref to store to the db
17031: $udom: (optional) domain of user containing the db
17032: $uname: (optional) name of user caontaining the db
17033:
17034: Returns:
17035: 'ok' -> succeeded in storing all keys of $storehash
17036: 'key_exists: <key>' -> failed to anything out of $storehash, as at
17037: least <key> already existed in the db (other
17038: requested keys may also already exist)
1.967 bisitz 17039: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 17040: 'con_lost' -> unable to contact request server
17041: 'refused' -> action was not allowed by remote machine
17042:
17043:
17044: =item *
17045:
1.243 albertel 17046: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17047: reference filled in from namesp (encrypts the return communication)
17048: ($udom and $uname are optional)
1.191 harris41 17049:
17050: =item *
17051:
1.243 albertel 17052: log($udom,$name,$home,$message) : write to permanent log for user; use
17053: critical subroutine
17054:
1.806 raeburn 17055: =item *
17056:
1.860 raeburn 17057: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17058: array reference filled in from namespace found in domain level on either
17059: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 17060:
17061: =item *
17062:
1.860 raeburn 17063: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
17064: domain level either on specified domain server ($uhome) or primary domain
17065: server ($udom and $uhome are optional)
1.806 raeburn 17066:
1.943 raeburn 17067: =item *
17068:
1.1240 raeburn 17069: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
17070: for: authentication, language, quotas, timezone, date locale, and portal URL in
17071: the target domain.
17072:
17073: May also include additional key => value pairs for the following groups:
17074:
17075: =over
17076:
17077: =item
17078: disk quotas (MB allocated by default to portfolios and authoring spaces).
17079:
17080: =over
17081:
17082: =item defaultquota, authorquota
17083:
17084: =back
17085:
17086: =item
17087: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17088: portfolio for users).
17089:
17090: =over
17091:
17092: =item
17093: aboutme, blog, webdav, portfolio
17094:
17095: =back
17096:
17097: =item
17098: requestcourses: ability to request courses, and how requests are processed.
17099:
17100: =over
17101:
17102: =item
1.1305 raeburn 17103: official, unofficial, community, textbook, placement
1.1240 raeburn 17104:
17105: =back
17106:
17107: =item
17108: inststatus: types of institutional affiliation, and order in which they are displayed.
17109:
17110: =over
17111:
17112: =item
1.1256 raeburn 17113: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 17114:
17115: =back
17116:
17117: =item
17118: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17119: for course's uploaded content.
17120:
17121: =over
17122:
17123: =item
1.1246 raeburn 17124: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 17125: communityquota, textbookquota, placementquota
1.1240 raeburn 17126:
17127: =back
17128:
17129: =item
17130: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17131: on your servers.
17132:
17133: =over
17134:
17135: =item
17136: remotesessions, hostedsessions
17137:
17138: =back
17139:
17140: =back
17141:
17142: In cases where a domain coordinator has never used the "Set Domain Configuration"
17143: utility to create a configuration.db file on a domain's primary library server
17144: only the following domain defaults: auth_def, auth_arg_def, lang_def
17145: -- corresponding values are authentication type (internal, krb4, krb5,
17146: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
17147: will be available. Values are retrieved from cache (if current), unless the
17148: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17149: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17150:
17151: Typical usage:
1.943 raeburn 17152:
1.1240 raeburn 17153: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 17154:
1.243 albertel 17155: =back
17156:
17157: =head2 Network Status Functions
17158:
17159: =over 4
1.191 harris41 17160:
17161: =item *
17162:
1.1137 raeburn 17163: dirlist() : return directory list based on URI (first arg).
17164:
17165: Inputs: 1 required, 5 optional.
17166:
17167: =over
17168:
17169: =item
17170: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17171:
17172: =item
17173: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
17174:
17175: =item
17176: $username - username of user/course to be listed. Extracted from $uri if absent.
17177:
17178: =item
17179: $getpropath - boolean: 1 if prepend path using &propath().
17180:
17181: =item
17182: $getuserdir - boolean: 1 if prepend path for "userfiles".
17183:
17184: =item
17185: $alternateRoot - path to prepend in place of path from $uri.
17186:
17187: =back
17188:
17189: Returns: Array of up to two items.
17190:
17191: =over
17192:
17193: a reference to an array of files/subdirectories
17194:
17195: =over
17196:
17197: Each element in the array of files/subdirectories is a & separated list of
17198: item name and the result of running stat on the item. If dirlist was requested
17199: for a file instead of a directory, the item name will be ''. For a directory
17200: listing, if the item is a metadata file, the element will end &N&M
17201: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17202: default copyright set (1).
17203:
17204: =back
17205:
17206: a scalar containing error condition (if encountered).
17207:
17208: =over
17209:
17210: =item
17211: no_host (no homeserver identified for $username:$domain).
17212:
17213: =item
17214: no_such_host (server contacted for listing not identified as valid host).
17215:
17216: =item
17217: con_lost (connection to remote server failed).
17218:
17219: =item
17220: refused (invalid $username:$domain received on lond side).
17221:
17222: =item
17223: no_such_dir (directory at specified path on lond side does not exist).
17224:
17225: =item
17226: empty (directory at specified path on lond side is empty).
17227:
17228: =over
17229:
17230: This is currently not encountered because the &ls3, &ls2,
17231: &ls (_handler) routines on the lond side do not filter out
17232: . and .. from a directory listing.
17233:
17234: =back
17235:
17236: =back
17237:
17238: =back
1.191 harris41 17239:
17240: =item *
17241:
1.243 albertel 17242: spareserver() : find server with least workload from spare.tab
17243:
1.986 foxr 17244:
17245: =item *
17246:
17247: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17248: if there is no corresponding loncapa host.
17249:
1.243 albertel 17250: =back
17251:
1.986 foxr 17252:
1.243 albertel 17253: =head2 Apache Request
17254:
17255: =over 4
1.191 harris41 17256:
17257: =item *
17258:
1.243 albertel 17259: ssi($url,%hash) : server side include, does a complete request cycle on url to
17260: localhost, posts hash
17261:
17262: =back
17263:
17264: =head2 Data to String to Data
17265:
17266: =over 4
1.191 harris41 17267:
17268: =item *
17269:
1.243 albertel 17270: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17271: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 17272:
17273: =item *
17274:
1.243 albertel 17275: hashref2str($hashref) : convert a hashref into a string complete with
17276: escaping and '=' and '&' separators, supports elements that are
17277: arrayrefs and hashrefs
1.191 harris41 17278:
17279: =item *
17280:
1.243 albertel 17281: arrayref2str($arrayref) : convert an arrayref into a string complete
17282: with escaping and '&' separators, supports elements that are arrayrefs
17283: and hashrefs
1.191 harris41 17284:
17285: =item *
17286:
1.243 albertel 17287: str2hash($string) : convert string to hash using unescaping and
17288: splitting on '=' and '&', supports elements that are arrayrefs and
17289: hashrefs
1.191 harris41 17290:
17291: =item *
17292:
1.243 albertel 17293: str2array($string) : convert string to hash using unescaping and
17294: splitting on '&', supports elements that are arrayrefs and hashrefs
17295:
17296: =back
17297:
17298: =head2 Logging Routines
17299:
17300:
17301: These routines allow one to make log messages in the lonnet.log and
17302: lonnet.perm logfiles.
1.191 harris41 17303:
1.1119 foxr 17304: =over 4
17305:
1.191 harris41 17306: =item *
17307:
1.243 albertel 17308: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 17309:
17310: =item *
17311:
1.243 albertel 17312: logthis() : append message to the normal lonnet.log file, it gets
17313: preiodically rolled over and deleted.
1.191 harris41 17314:
17315: =item *
17316:
1.243 albertel 17317: logperm() : append a permanent message to lonnet.perm.log, this log
17318: file never gets deleted by any automated portion of the system, only
17319: messages of critical importance should go in here.
17320:
1.1119 foxr 17321:
1.243 albertel 17322: =back
17323:
17324: =head2 General File Helper Routines
17325:
17326: =over 4
1.191 harris41 17327:
17328: =item *
17329:
1.481 raeburn 17330: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17331: (a) files in /uploaded
17332: (i) If a local copy of the file exists -
17333: compares modification date of local copy with last-modified date for
17334: definitive version stored on home server for course. If local copy is
17335: stale, requests a new version from the home server and stores it.
17336: If the original has been removed from the home server, then local copy
17337: is unlinked.
17338: (ii) If local copy does not exist -
17339: requests the file from the home server and stores it.
17340:
17341: If $caller is 'uploadrep':
17342: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17343: for request for files originally uploaded via DOCS.
17344: - returns 'ok' if fresh local copy now available, -1 otherwise.
17345:
17346: Otherwise:
17347: This indicates a call from the content generation phase of the request.
17348: - returns the entire contents of the file or -1.
17349:
17350: (b) files in /res
17351: - returns the entire contents of a file or -1;
17352: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 17353:
1.712 albertel 17354:
17355: =item *
17356:
17357: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17358: reference
17359:
17360: returns either a stat() list of data about the file or an empty list
17361: if the file doesn't exist or couldn't find out about it (connection
17362: problems or user unknown)
17363:
1.191 harris41 17364: =item *
17365:
1.243 albertel 17366: filelocation($dir,$file) : returns file system location of a file
17367: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17368: directory that relative $file lookups are to looked in ($dir of /a/dir
17369: and a file of ../bob will become /a/bob)
1.191 harris41 17370:
17371: =item *
17372:
17373: hreflocation($dir,$file) : returns file system location or a URL; same as
17374: filelocation except for hrefs
17375:
17376: =item *
17377:
1.1261 raeburn 17378: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17379: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 17380:
1.243 albertel 17381: =back
17382:
1.608 albertel 17383: =head2 Usererfile file routines (/uploaded*)
17384:
17385: =over 4
17386:
17387: =item *
17388:
17389: userfileupload(): main rotine for putting a file in a user or course's
17390: filespace, arguments are,
17391:
1.620 albertel 17392: formname - required - this is the name of the element in $env where the
1.608 albertel 17393: filename, and the contents of the file to create/modifed exist
1.620 albertel 17394: the filename is in $env{'form.'.$formname.'.filename'} and the
17395: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 17396: context - if coursedoc, store the file in the course of the active role
17397: of the current user;
17398: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17399: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 17400: subdir - required - subdirectory to put the file in under ../userfiles/
17401: if undefined, it will be placed in "unknown"
17402:
17403: (This routine calls clean_filename() to remove any dangerous
17404: characters from the filename, and then calls finuserfileupload() to
17405: complete the transaction)
17406:
17407: returns either the url of the uploaded file (/uploaded/....) if successful
17408: and /adm/notfound.html if unsuccessful
17409:
17410: =item *
17411:
17412: clean_filename(): routine for cleaing a filename up for storage in
17413: userfile space, argument is:
17414:
17415: filename - proposed filename
17416:
17417: returns: the new clean filename
17418:
17419: =item *
17420:
1.1090 raeburn 17421: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 17422: userspace, probably shouldn't be called directly
17423:
17424: docuname: username or courseid of destination for the file
17425: docudom: domain of user/course of destination for the file
17426: formname: same as for userfileupload()
1.1090 raeburn 17427: fname: filename (including subdirectories) for the file
17428: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401 raeburn 17429: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 17430: allfiles: reference to hash used to store objects found by parser
17431: codebase: reference to hash used for codebases of java objects found by parser
17432: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17433: thumbheight: height (pixels) of thumbnail to be created for uploaded image
17434: resizewidth: width to be used to resize image using resizeImage from ImageMagick
17435: resizeheight: height to be used to resize image using resizeImage from ImageMagick
17436: context: if 'overwrite', will move the uploaded file from its temporary location to
17437: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 17438: mimetype: reference to scalar to accommodate mime type determined
17439: from File::MMagic if $parser = parse.
1.608 albertel 17440:
17441: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 17442: and /adm/notfound.html if unsuccessful (or an error message if context
17443: was 'overwrite').
17444:
1.608 albertel 17445:
17446: =item *
17447:
17448: renameuserfile(): renames an existing userfile to a new name
17449:
17450: Args:
17451: docuname: username or courseid of destination for the file
17452: docudom: domain of user/course of destination for the file
17453: old: current file name (including any subdirs under userfiles)
17454: new: desired file name (including any subdirs under userfiles)
17455:
17456: =item *
17457:
17458: mkdiruserfile(): creates a directory is a userfiles dir
17459:
17460: Args:
17461: docuname: username or courseid of destination for the file
17462: docudom: domain of user/course of destination for the file
17463: dir: dir to create (including any subdirs under userfiles)
17464:
17465: =item *
17466:
17467: removeuserfile(): removes a file that exists in userfiles
17468:
17469: Args:
17470: docuname: username or courseid of destination for the file
17471: docudom: domain of user/course of destination for the file
17472: fname: filname to delete (including any subdirs under userfiles)
17473:
17474: =item *
17475:
17476: removeuploadedurl(): convience function for removeuserfile()
17477:
17478: Args:
17479: url: a full /uploaded/... url to delete
17480:
1.747 albertel 17481: =item *
17482:
17483: get_portfile_permissions():
17484: Args:
17485: domain: domain of user or course contain the portfolio files
17486: user: name of user or num of course contain the portfolio files
17487: Returns:
17488: hashref of a dump of the proper file_permissions.db
17489:
17490:
17491: =item *
17492:
17493: get_access_controls():
17494:
17495: Args:
17496: current_permissions: the hash ref returned from get_portfile_permissions()
17497: group: (optional) the group you want the files associated with
17498: file: (optional) the file you want access info on
17499:
17500: Returns:
1.749 raeburn 17501: a hash (keys are file names) of hashes containing
17502: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17503: values are XML containing access control settings (see below)
1.747 albertel 17504:
17505: Internal notes:
17506:
1.749 raeburn 17507: access controls are stored in file_permissions.db as key=value pairs.
17508: key -> path to file/file_name\0uniqueID:scope_end_start
17509: where scope -> public,guest,course,group,domains or users.
17510: end -> UNIX time for end of access (0 -> no end date)
17511: start -> UNIX time for start of access
17512:
17513: value -> XML description of access control
17514: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17515: <start></start>
17516: <end></end>
17517:
17518: <password></password> for scope type = guest
17519:
17520: <domain></domain> for scope type = course or group
17521: <number></number>
17522: <roles id="">
17523: <role></role>
17524: <access></access>
17525: <section></section>
17526: <group></group>
17527: </roles>
17528:
17529: <dom></dom> for scope type = domains
17530:
17531: <users> for scope type = users
17532: <user>
17533: <uname></uname>
17534: <udom></udom>
17535: </user>
17536: </users>
17537: </scope>
17538:
17539: Access data is also aggregated for each file in an additional key=value pair:
17540: key -> path to file/file_name\0accesscontrol
17541: value -> reference to hash
17542: hash contains key = value pairs
17543: where key = uniqueID:scope_end_start
17544: value = UNIX time record was last updated
17545:
17546: Used to improve speed of look-ups of access controls for each file.
17547:
17548: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17549:
1.1198 raeburn 17550: =item *
17551:
1.749 raeburn 17552: modify_access_controls():
17553:
17554: Modifies access controls for a portfolio file
17555: Args
17556: 1. file name
17557: 2. reference to hash of required changes,
17558: 3. domain
17559: 4. username
17560: where domain,username are the domain of the portfolio owner
17561: (either a user or a course)
17562:
17563: Returns:
17564: 1. result of additions or updates ('ok' or 'error', with error message).
17565: 2. result of deletions ('ok' or 'error', with error message).
17566: 3. reference to hash of any new or updated access controls.
17567: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17568: key = integer (inbound ID)
1.1198 raeburn 17569: value = uniqueID
17570:
17571: =item *
17572:
17573: get_timebased_id():
17574:
17575: Attempts to get a unique timestamp-based suffix for use with items added to a
17576: course via the Course Editor (e.g., folders, composite pages,
17577: group bulletin boards).
17578:
17579: Args: (first three required; six others optional)
17580:
17581: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17582: docssequence, or name of group
17583:
17584: 2. keyid (alphanumeric): name of temporary locking key in hash,
17585: e.g., num, boardids
17586:
17587: 3. namespace: name of gdbm file used to store suffixes already assigned;
17588: file will be named nohist_namespace.db
17589:
17590: 4. cdom: domain of course; default is current course domain from %env
17591:
17592: 5. cnum: course number; default is current course number from %env
17593:
17594: 6. idtype: set to concat if an additional digit is to be appended to the
17595: unix timestamp to form the suffix, if the plain timestamp is already
17596: in use. Default is to not do this, but simply increment the unix
17597: timestamp by 1 until a unique key is obtained.
17598:
17599: 7. who: holder of locking key; defaults to user:domain for user.
17600:
17601: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
17602: retrying); default is 3.
17603:
17604: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
17605:
17606: Returns:
17607:
17608: 1. suffix obtained (numeric)
17609:
17610: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17611:
17612: 3. error: contains (localized) error message if an error occurred.
17613:
1.747 albertel 17614:
1.608 albertel 17615: =back
17616:
1.243 albertel 17617: =head2 HTTP Helper Routines
17618:
17619: =over 4
17620:
1.191 harris41 17621: =item *
17622:
17623: escape() : unpack non-word characters into CGI-compatible hex codes
17624:
17625: =item *
17626:
17627: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17628:
1.243 albertel 17629: =back
17630:
17631: =head1 PRIVATE SUBROUTINES
17632:
17633: =head2 Underlying communication routines (Shouldn't call)
17634:
17635: =over 4
17636:
17637: =item *
17638:
17639: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17640:
17641: =item *
17642:
17643: reply() : uses subreply to send a message to remote machine, logs all failures
17644:
17645: =item *
17646:
17647: critical() : passes a critical message to another server; if cannot
17648: get through then place message in connection buffer directory and
17649: returns con_delayed, if incapable of saving message, returns
17650: con_failed
17651:
17652: =item *
17653:
17654: reconlonc() : tries to reconnect lonc client processes.
17655:
17656: =back
17657:
17658: =head2 Resource Access Logging
17659:
17660: =over 4
17661:
17662: =item *
17663:
17664: flushcourselogs() : flush (save) buffer logs and access logs
17665:
17666: =item *
17667:
17668: courselog($what) : save message for course in hash
17669:
17670: =item *
17671:
17672: courseacclog($what) : save message for course using &courselog(). Perform
17673: special processing for specific resource types (problems, exams, quizzes, etc).
17674:
1.191 harris41 17675: =item *
17676:
17677: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17678: as a PerlChildExitHandler
1.243 albertel 17679:
17680: =back
17681:
17682: =head2 Other
17683:
17684: =over 4
17685:
17686: =item *
17687:
17688: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 17689:
17690: =back
17691:
17692: =cut
1.877 foxr 17693:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>