Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1507
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1507 ! raeburn 4: # $Id: lonnet.pm,v 1.1506 2023/03/27 21:32:41 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.486 www 74: use HTTP::Date;
1.977 amueller 75: use Image::Magick;
1.1389 raeburn 76: use CGI::Cookie;
1.1182 foxr 77:
1.1173 foxr 78: use Encode;
79:
1.1405 raeburn 80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138 raeburn 81: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1416 raeburn 82: %managerstab $passwdmin);
1.871 albertel 83:
84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
85: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
86: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 87: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 88:
1.1 albertel 89: use IO::Socket;
1.31 www 90: use GDBM_File;
1.208 albertel 91: use HTML::LCParser;
1.88 www 92: use Fcntl qw(:flock);
1.870 albertel 93: use Storable qw(thaw nfreeze);
1.1289 damieng 94: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 95: use Cache::Memcached;
1.676 albertel 96: use Digest::MD5;
1.790 albertel 97: use Math::Random;
1.1024 raeburn 98: use File::MMagic;
1.1434 raeburn 99: use Net::CIDR;
1.1456 raeburn 100: use Sys::Hostname::FQDN();
1.807 albertel 101: use LONCAPA qw(:DEFAULT :match);
1.740 www 102: use LONCAPA::Configuration;
1.1160 www 103: use LONCAPA::lonmetadata;
1.1167 droeschl 104: use LONCAPA::Lond;
1.1345 raeburn 105: use LONCAPA::LWPReq;
1.1406 raeburn 106: use LONCAPA::transliterate;
1.1117 foxr 107:
1.1090 raeburn 108: use File::Copy;
1.676 albertel 109:
1.195 www 110: my $readit;
1.1288 damieng 111: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 112:
1.619 albertel 113: require Exporter;
114:
115: our @ISA = qw (Exporter);
116: our @EXPORT = qw(%env);
117:
1.449 matthew 118:
1.1187 raeburn 119: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 120: {
121: my $logid;
1.1187 raeburn 122: sub write_log {
1.1188 raeburn 123: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 124: if ($context eq 'course') {
125: if (($cnum eq '') || ($cdom eq '')) {
126: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
127: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
128: }
1.957 raeburn 129: }
1.1184 raeburn 130: $logid ++;
1.957 raeburn 131: my $now = time();
132: my $id=$now.'00000'.$$.'00000'.$logid;
1.1434 raeburn 133: my $ip = &get_requestor_ip();
1.1184 raeburn 134: my $logentry = {
135: $id => {
136: 'exe_uname' => $env{'user.name'},
137: 'exe_udom' => $env{'user.domain'},
138: 'exe_time' => $now,
1.1434 raeburn 139: 'exe_ip' => $ip,
1.1184 raeburn 140: 'delflag' => $delflag,
141: 'logentry' => $storehash,
142: 'uname' => $uname,
143: 'udom' => $udom,
144: }
145: };
146: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 147: }
148: }
1.1 albertel 149:
1.163 harris41 150: sub logtouch {
151: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 152: unless (-e "$execdir/logs/lonnet.log") {
1.1359 raeburn 153: open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 154: close $fh;
155: }
156: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
157: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
158: }
159:
1.1 albertel 160: sub logthis {
161: my $message=shift;
162: my $execdir=$perlvar{'lonDaemons'};
163: my $now=time;
164: my $local=localtime($now);
1.1359 raeburn 165: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 166: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
167: print $fh $logstring;
1.448 albertel 168: close($fh);
169: }
1.1 albertel 170: return 1;
171: }
172:
173: sub logperm {
174: my $message=shift;
175: my $execdir=$perlvar{'lonDaemons'};
176: my $now=time;
177: my $local=localtime($now);
1.1359 raeburn 178: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 179: print $fh "$now:$message:$local\n";
180: close($fh);
181: }
1.1 albertel 182: return 1;
183: }
184:
1.850 albertel 185: sub create_connection {
1.853 albertel 186: my ($hostname,$lonid) = @_;
1.851 albertel 187: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 188: Type => SOCK_STREAM,
189: Timeout => 10);
190: return 0 if (!$client);
1.1399 raeburn 191: print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
1.850 albertel 192: my $result = <$client>;
193: chomp($result);
194: return 1 if ($result eq 'done');
195: return 0;
196: }
197:
1.983 raeburn 198: sub get_server_timezone {
199: my ($cnum,$cdom) = @_;
200: my $home=&homeserver($cnum,$cdom);
201: if ($home ne 'no_host') {
202: my $cachetime = 24*3600;
203: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
204: if (defined($cached)) {
205: return $timezone;
206: } else {
207: my $timezone = &reply('servertimezone',$home);
208: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
209: }
210: }
211: }
1.850 albertel 212:
1.1106 raeburn 213: sub get_server_distarch {
214: my ($lonhost,$ignore_cache) = @_;
215: if (defined($lonhost)) {
216: if (!defined(&hostname($lonhost))) {
217: return;
218: }
219: my $cachetime = 12*3600;
220: if (!$ignore_cache) {
221: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
222: if (defined($cached)) {
223: return $distarch;
224: }
225: }
226: my $rep = &reply('serverdistarch',$lonhost);
227: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
228: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
229: $rep eq '') {
230: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
231: }
232: }
233: return;
234: }
235:
1.1315 raeburn 236: sub get_servercerts_info {
1.1383 raeburn 237: my ($lonhost,$hostname,$context) = @_;
238: return if ($lonhost eq '');
239: if ($hostname eq '') {
240: $hostname = &hostname($lonhost);
241: }
242: return if ($hostname eq '');
1.1315 raeburn 243: my ($rep,$uselocal);
1.1388 raeburn 244: if ($context eq 'install') {
1.1387 raeburn 245: $uselocal = 1;
246: } elsif (grep { $_ eq $lonhost } ¤t_machine_ids()) {
1.1315 raeburn 247: $uselocal = 1;
248: }
1.1387 raeburn 249: if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315 raeburn 250: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323 raeburn 251: if ($distro eq '') {
252: $uselocal = 0;
253: } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315 raeburn 254: if ($1 < 6) {
255: $uselocal = 0;
256: }
1.1346 raeburn 257: } elsif ($distro =~ /^(?:sles)(\d+)$/) {
258: if ($1 < 12) {
259: $uselocal = 0;
260: }
1.1315 raeburn 261: }
262: }
263: if ($uselocal) {
1.1383 raeburn 264: $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315 raeburn 265: } else {
266: $rep=&reply('servercerts',$lonhost);
267: }
268: my ($result,%returnhash);
269: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
270: ($rep eq 'unknown_cmd')) {
271: $result = $rep;
272: } else {
273: $result = 'ok';
274: my @pairs=split(/\&/,$rep);
275: foreach my $item (@pairs) {
276: my ($key,$value)=split(/=/,$item,2);
277: my $what = &unescape($key);
278: $returnhash{$what}=&thaw_unescape($value);
279: }
280: }
281: return ($result,\%returnhash);
282: }
283:
1.993 raeburn 284: sub get_server_loncaparev {
1.1073 raeburn 285: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 286: if (defined($lonhost)) {
287: if (!defined(&hostname($lonhost))) {
288: undef($lonhost);
289: }
290: }
291: if (!defined($lonhost)) {
292: if (defined(&domain($dom,'primary'))) {
293: $lonhost=&domain($dom,'primary');
294: if ($lonhost eq 'no_host') {
295: undef($lonhost);
296: }
297: }
298: }
299: if (defined($lonhost)) {
1.1073 raeburn 300: my $cachetime = 12*3600;
301: if (!$ignore_cache) {
302: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
303: if (defined($cached)) {
304: return $loncaparev;
305: }
306: }
307: my ($answer,$loncaparev);
308: my @ids=¤t_machine_ids();
309: if (grep(/^\Q$lonhost\E$/,@ids)) {
310: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 311: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 312: $loncaparev = $1;
313: }
314: } else {
315: $answer = &reply('serverloncaparev',$lonhost);
316: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
317: if ($caller eq 'loncron') {
1.1397 raeburn 318: my $hostname = &hostname($lonhost);
1.1073 raeburn 319: my $protocol = $protocol{$lonhost};
320: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 321: my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073 raeburn 322: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 323: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073 raeburn 324: unless ($response->is_error()) {
325: my $content = $response->content;
1.1081 raeburn 326: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 327: $loncaparev = $1;
328: }
329: }
330: } else {
331: $loncaparev = $loncaparevs{$lonhost};
332: }
1.1081 raeburn 333: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 334: $loncaparev = $1;
335: }
1.993 raeburn 336: }
1.1073 raeburn 337: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 338: }
339: }
340:
1.1074 raeburn 341: sub get_server_homeID {
342: my ($hostname,$ignore_cache,$caller) = @_;
343: unless ($ignore_cache) {
344: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
345: if (defined($cached)) {
346: return $serverhomeID;
347: }
348: }
349: my $cachetime = 12*3600;
350: my $serverhomeID;
351: if ($caller eq 'loncron') {
352: my @machine_ids = &machine_ids($hostname);
353: foreach my $id (@machine_ids) {
354: my $response = &reply('serverhomeID',$id);
355: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
356: $serverhomeID = $response;
357: last;
358: }
359: }
360: if ($serverhomeID eq '') {
361: $serverhomeID = $machine_ids[-1];
362: }
363: } else {
364: $serverhomeID = $serverhomeIDs{$hostname};
365: }
366: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
367: }
368:
1.1121 raeburn 369: sub get_remote_globals {
370: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 371: my ($result,%returnhash,%whatneeded);
372: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 373: foreach my $what (sort(keys(%{$whathash}))) {
374: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 375: my ($response,$cached);
1.1121 raeburn 376: unless ($ignore_cache) {
1.1125 raeburn 377: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 378: }
379: if (defined($cached)) {
1.1125 raeburn 380: $returnhash{$what} = $response;
1.1121 raeburn 381: } else {
1.1125 raeburn 382: $whatneeded{$what} = 1;
1.1121 raeburn 383: }
384: }
1.1125 raeburn 385: if (keys(%whatneeded) == 0) {
386: $result = 'ok';
387: } else {
1.1121 raeburn 388: my $requested = &freeze_escape(\%whatneeded);
389: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 390: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
391: ($rep eq 'unknown_cmd')) {
392: $result = $rep;
393: } else {
394: $result = 'ok';
1.1121 raeburn 395: my @pairs=split(/\&/,$rep);
1.1125 raeburn 396: foreach my $item (@pairs) {
397: my ($key,$value)=split(/=/,$item,2);
398: my $what = &unescape($key);
399: my $hashid = $lonhost.'-'.$what;
400: $returnhash{$what}=&thaw_unescape($value);
401: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 402: }
403: }
404: }
405: }
1.1125 raeburn 406: return ($result,\%returnhash);
1.1121 raeburn 407: }
408:
1.1124 raeburn 409: sub remote_devalidate_cache {
1.1241 raeburn 410: my ($lonhost,$cachekeys) = @_;
411: my $items;
412: return unless (ref($cachekeys) eq 'ARRAY');
413: my $cachestr = join('&',@{$cachekeys});
414: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 415: return $response;
416: }
417:
1.1 albertel 418: # -------------------------------------------------- Non-critical communication
419: sub subreply {
420: my ($cmd,$server)=@_;
1.838 albertel 421: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 422: #
423: # With loncnew process trimming, there's a timing hole between lonc server
424: # process exit and the master server picking up the listen on the AF_UNIX
425: # socket. In that time interval, a lock file will exist:
426:
427: my $lockfile=$peerfile.".lock";
428: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1289 damieng 429: sleep(0.1);
1.549 foxr 430: }
431: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 432: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 433: #
1.550 foxr 434: # We'll give the connection a few tries before abandoning it. If
435: # connection is not possible, we'll con_lost back to the client.
436: #
437: my $client;
438: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
439: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
440: Type => SOCK_STREAM,
441: Timeout => 10);
1.869 albertel 442: if ($client) {
1.550 foxr 443: last; # Connected!
1.850 albertel 444: } else {
1.853 albertel 445: &create_connection(&hostname($server),$server);
1.550 foxr 446: }
1.1289 damieng 447: sleep(0.1); # Try again later if failed connection.
1.550 foxr 448: }
449: my $answer;
450: if ($client) {
1.704 albertel 451: print $client "sethost:$server:$cmd\n";
1.550 foxr 452: $answer=<$client>;
453: if (!$answer) { $answer="con_lost"; }
454: chomp($answer);
455: } else {
456: $answer = 'con_lost'; # Failed connection.
457: }
1.1 albertel 458: return $answer;
459: }
460:
461: sub reply {
462: my ($cmd,$server)=@_;
1.838 albertel 463: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 464: my $answer=subreply($cmd,$server);
1.65 www 465: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396 raeburn 466: my $logged = $cmd;
467: if ($cmd =~ /^encrypt:([^:]+):/) {
468: my $subcmd = $1;
469: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
470: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462 raeburn 471: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
472: ($subcmd eq 'put')) {
1.1396 raeburn 473: (undef,undef,my @rest) = split(/:/,$cmd);
474: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
475: splice(@rest,2,1,'Hidden');
476: } elsif ($subcmd eq 'passwd') {
477: splice(@rest,2,2,('Hidden','Hidden'));
478: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462 raeburn 479: ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
1.1396 raeburn 480: splice(@rest,3,1,'Hidden');
481: }
482: $logged = join(':',('encrypt:'.$subcmd,@rest));
483: }
484: }
485: &logthis("<font color=\"blue\">WARNING:".
486: " $logged to $server returned $answer</font>");
1.12 www 487: }
1.1 albertel 488: return $answer;
489: }
490:
491: # ----------------------------------------------------------- Send USR1 to lonc
492:
493: sub reconlonc {
1.891 albertel 494: my ($lonid) = @_;
495: if ($lonid) {
1.1295 raeburn 496: my $hostname = &hostname($lonid);
1.891 albertel 497: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
498: if ($hostname && -e $peerfile) {
499: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
500: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
501: Type => SOCK_STREAM,
502: Timeout => 10);
503: if ($client) {
504: print $client ("reset_retries\n");
505: my $answer=<$client>;
506: #reset just this one.
507: }
508: }
509: return;
510: }
511:
1.836 www 512: &logthis("Trying to reconnect lonc");
1.1 albertel 513: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359 raeburn 514: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 515: my $loncpid=<$fh>;
516: chomp($loncpid);
517: if (kill 0 => $loncpid) {
518: &logthis("lonc at pid $loncpid responding, sending USR1");
519: kill USR1 => $loncpid;
520: sleep 1;
1.1295 raeburn 521: } else {
1.12 www 522: &logthis(
1.672 albertel 523: "<font color=\"blue\">WARNING:".
1.12 www 524: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 525: }
526: } else {
1.836 www 527: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 528: }
529: }
530:
531: # ------------------------------------------------------ Critical communication
1.12 www 532:
1.1 albertel 533: sub critical {
534: my ($cmd,$server)=@_;
1.838 albertel 535: unless (&hostname($server)) {
1.672 albertel 536: &logthis("<font color=\"blue\">WARNING:".
1.89 www 537: " Critical message to unknown server ($server)</font>");
538: return 'no_such_host';
539: }
1.1 albertel 540: my $answer=reply($cmd,$server);
541: if ($answer eq 'con_lost') {
1.1295 raeburn 542: &reconlonc($server);
1.589 albertel 543: my $answer=reply($cmd,$server);
1.1 albertel 544: if ($answer eq 'con_lost') {
545: my $now=time;
546: my $middlename=$cmd;
1.5 www 547: $middlename=substr($middlename,0,16);
1.1 albertel 548: $middlename=~s/\W//g;
549: my $dfilename=
1.305 www 550: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
551: $dumpcount++;
1.1 albertel 552: {
1.448 albertel 553: my $dfh;
1.1359 raeburn 554: if (open($dfh,">",$dfilename)) {
1.448 albertel 555: print $dfh "$cmd\n";
556: close($dfh);
557: }
1.1 albertel 558: }
1.1288 damieng 559: sleep 1;
1.1 albertel 560: my $wcmd='';
561: {
1.448 albertel 562: my $dfh;
1.1359 raeburn 563: if (open($dfh,"<",$dfilename)) {
1.448 albertel 564: $wcmd=<$dfh>;
565: close($dfh);
566: }
1.1 albertel 567: }
568: chomp($wcmd);
1.7 www 569: if ($wcmd eq $cmd) {
1.672 albertel 570: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 571: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 572: &logperm("D:$server:$cmd");
573: return 'con_delayed';
574: } else {
1.672 albertel 575: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 576: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 577: &logperm("F:$server:$cmd");
578: return 'con_failed';
579: }
580: }
581: }
582: return $answer;
1.405 albertel 583: }
584:
1.755 albertel 585: # ------------------------------------------- check if return value is an error
586:
587: sub error {
588: my ($result) = @_;
1.756 albertel 589: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 590: if ($2 == 2) { return undef; }
591: return $1;
592: }
593: return undef;
594: }
595:
1.783 albertel 596: sub convert_and_load_session_env {
597: my ($lonidsdir,$handle)=@_;
598: my @profile;
599: {
1.917 albertel 600: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
601: if (!$opened) {
1.915 albertel 602: return 0;
603: }
1.783 albertel 604: flock($idf,LOCK_SH);
605: @profile=<$idf>;
606: close($idf);
607: }
608: my %temp_env;
609: foreach my $line (@profile) {
1.786 albertel 610: if ($line !~ m/=/) {
611: return 0;
612: }
1.783 albertel 613: chomp($line);
614: my ($envname,$envvalue)=split(/=/,$line,2);
615: $temp_env{&unescape($envname)} = &unescape($envvalue);
616: }
617: unlink("$lonidsdir/$handle.id");
618: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
619: 0640)) {
620: %disk_env = %temp_env;
621: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
622: untie(%disk_env);
623: }
1.786 albertel 624: return 1;
1.783 albertel 625: }
626:
1.374 www 627: # ------------------------------------------- Transfer profile into environment
1.780 albertel 628: my $env_loaded;
629: sub transfer_profile_to_env {
1.788 albertel 630: my ($lonidsdir,$handle,$force_transfer) = @_;
631: if (!$force_transfer && $env_loaded) { return; }
1.374 www 632:
1.720 albertel 633: if (!defined($lonidsdir)) {
634: $lonidsdir = $perlvar{'lonIDsDir'};
635: }
636: if (!defined($handle)) {
637: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
638: }
639:
1.786 albertel 640: my $convert;
641: {
1.917 albertel 642: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
643: if (!$opened) {
1.915 albertel 644: return;
645: }
1.786 albertel 646: flock($idf,LOCK_SH);
647: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
648: &GDBM_READER(),0640)) {
649: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
650: untie(%disk_env);
651: } else {
652: $convert = 1;
653: }
654: }
655: if ($convert) {
656: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
657: &logthis("Failed to load session, or convert session.");
658: }
1.374 www 659: }
1.783 albertel 660:
1.786 albertel 661: my %remove;
1.783 albertel 662: while ( my $envname = each(%env) ) {
1.433 matthew 663: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
664: if ($time < time-300) {
1.783 albertel 665: $remove{$key}++;
1.433 matthew 666: }
667: }
668: }
1.783 albertel 669:
1.619 albertel 670: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 671: $env_loaded=1;
1.783 albertel 672: foreach my $expired_key (keys(%remove)) {
1.433 matthew 673: &delenv($expired_key);
1.374 www 674: }
1.1 albertel 675: }
676:
1.916 albertel 677: # ---------------------------------------------------- Check for valid session
678: sub check_for_valid_session {
1.1355 raeburn 679: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 680: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378 raeburn 681: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
682: if ($name eq 'lonDAV') {
683: $lonidsdir=$r->dir_config('lonDAVsessDir');
684: } else {
685: $lonidsdir=$r->dir_config('lonIDsDir');
686: if ($name eq '') {
687: $name = 'lonID';
688: }
689: }
690: if ($name eq 'lonID') {
691: $secure = 'lonSID';
1.1337 raeburn 692: $linkname = 'lonLinkID';
693: $pubname = 'lonPubID';
1.1378 raeburn 694: if (exists($cookies{$secure})) {
695: $lonid=$cookies{$secure};
696: } elsif (exists($cookies{$name})) {
697: $lonid=$cookies{$name};
1.1400 raeburn 698: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337 raeburn 699: $lonid=$cookies{$linkname};
1.1378 raeburn 700: } elsif (exists($cookies{$pubname})) {
701: $lonid=$cookies{$pubname};
1.1337 raeburn 702: }
1.1378 raeburn 703: } else {
704: $lonid=$cookies{$name};
1.1337 raeburn 705: }
1.916 albertel 706: return undef if (!$lonid);
707:
708: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378 raeburn 709: if (-l "$lonidsdir/$handle.id") {
710: my $link = readlink("$lonidsdir/$handle.id");
711: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
712: $handle = $1;
713: }
1.1155 raeburn 714: }
1.1355 raeburn 715: if (!-e "$lonidsdir/$handle.id") {
716: if ((ref($domref)) && ($name eq 'lonID') &&
717: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
718: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
719: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
720: $$domref = $possudom;
721: }
722: }
723: return undef;
724: }
1.916 albertel 725:
1.917 albertel 726: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
727: return undef if (!$opened);
1.916 albertel 728:
729: flock($idf,LOCK_SH);
730: my %disk_env;
731: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
732: &GDBM_READER(),0640)) {
733: return undef;
734: }
735:
736: if (!defined($disk_env{'user.name'})
737: || !defined($disk_env{'user.domain'})) {
1.1394 raeburn 738: untie(%disk_env);
1.916 albertel 739: return undef;
740: }
1.1245 raeburn 741:
742: if (ref($userhashref) eq 'HASH') {
743: $userhashref->{'name'} = $disk_env{'user.name'};
744: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1448 raeburn 745: if ($disk_env{'request.role'}) {
746: $userhashref->{'role'} = $disk_env{'request.role'};
747: }
1.1361 raeburn 748: $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375 raeburn 749: if ($userhashref->{'lti'}) {
750: $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
751: $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
752: }
1.1212 raeburn 753: }
1.1394 raeburn 754: untie(%disk_env);
1.1245 raeburn 755:
1.916 albertel 756: return $handle;
757: }
758:
1.830 albertel 759: sub timed_flock {
760: my ($file,$lock_type) = @_;
761: my $failed=0;
762: eval {
763: local $SIG{__DIE__}='DEFAULT';
764: local $SIG{ALRM}=sub {
765: $failed=1;
766: die("failed lock");
767: };
768: alarm(13);
769: flock($file,$lock_type);
770: alarm(0);
771: };
772: if ($failed) {
773: return undef;
774: } else {
775: return 1;
776: }
777: }
778:
1.1392 raeburn 779: sub get_sessionfile_vars {
780: my ($handle,$lonidsdir,$storearr) = @_;
781: my %returnhash;
782: unless (ref($storearr) eq 'ARRAY') {
783: return %returnhash;
784: }
785: if (-l "$lonidsdir/$handle.id") {
786: my $link = readlink("$lonidsdir/$handle.id");
787: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
788: $handle = $1;
789: }
790: }
791: if ((-e "$lonidsdir/$handle.id") &&
792: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
793: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
794: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
795: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
796: flock($idf,LOCK_SH);
797: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
798: &GDBM_READER(),0640)) {
799: foreach my $item (@{$storearr}) {
800: $returnhash{$item} = $disk_env{$item};
801: }
802: untie(%disk_env);
803: }
804: }
805: }
806: }
807: return %returnhash;
808: }
809:
1.5 www 810: # ---------------------------------------------------------- Append Environment
811:
812: sub appenv {
1.949 raeburn 813: my ($newenv,$roles) = @_;
814: if (ref($newenv) eq 'HASH') {
815: foreach my $key (keys(%{$newenv})) {
816: my $refused = 0;
817: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
818: $refused = 1;
819: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 820: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 821: if (grep(/^\Q$role\E$/,@{$roles})) {
822: $refused = 0;
823: }
824: }
825: }
826: if ($refused) {
827: &logthis("<font color=\"blue\">WARNING: ".
828: "Attempt to modify environment ".$key." to ".$newenv->{$key}
829: .'</font>');
830: delete($newenv->{$key});
831: } else {
832: $env{$key}=$newenv->{$key};
833: }
834: }
1.1376 raeburn 835: my $lonids = $perlvar{'lonIDsDir'};
836: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
837: my $opened = open(my $env_file,'+<',$env{'user.environment'});
838: if ($opened
839: && &timed_flock($env_file,LOCK_EX)
840: &&
841: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
842: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
843: while (my ($key,$value) = each(%{$newenv})) {
844: $disk_env{$key} = $value;
845: }
846: untie(%disk_env);
847: }
1.35 www 848: }
1.191 harris41 849: }
1.56 www 850: return 'ok';
851: }
852: # ----------------------------------------------------- Delete from Environment
853:
854: sub delenv {
1.1104 raeburn 855: my ($delthis,$regexp,$roles) = @_;
856: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
857: my $refused = 1;
858: if (ref($roles) eq 'ARRAY') {
859: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
860: if (grep(/^\Q$role\E$/,@{$roles})) {
861: $refused = 0;
862: }
863: }
864: if ($refused) {
865: &logthis("<font color=\"blue\">WARNING: ".
866: "Attempt to delete from environment ".$delthis);
867: return 'error';
868: }
1.56 www 869: }
1.917 albertel 870: my $opened = open(my $env_file,'+<',$env{'user.environment'});
871: if ($opened
1.915 albertel 872: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 873: &&
874: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
875: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 876: foreach my $key (keys(%disk_env)) {
1.987 raeburn 877: if ($regexp) {
878: if ($key=~/^$delthis/) {
879: delete($env{$key});
880: delete($disk_env{$key});
881: }
882: } else {
883: if ($key=~/^\Q$delthis\E/) {
884: delete($env{$key});
885: delete($disk_env{$key});
886: }
887: }
1.448 albertel 888: }
1.783 albertel 889: untie(%disk_env);
1.5 www 890: }
891: return 'ok';
1.369 albertel 892: }
893:
1.790 albertel 894: sub get_env_multiple {
895: my ($name) = @_;
896: my @values;
897: if (defined($env{$name})) {
898: # exists is it an array
899: if (ref($env{$name})) {
900: @values=@{ $env{$name} };
901: } else {
902: $values[0]=$env{$name};
903: }
904: }
905: return(@values);
906: }
907:
1.958 www 908: # ------------------------------------------------------------------- Locking
909:
910: sub set_lock {
911: my ($text)=@_;
912: $locknum++;
913: my $id=$$.'-'.$locknum;
914: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
915: 'session.lock.'.$id => $text});
916: return $id;
917: }
918:
919: sub get_locks {
920: my $num=0;
921: my %texts=();
922: foreach my $lock (split(/\,/,$env{'session.locks'})) {
923: if ($lock=~/\w/) {
924: $num++;
925: $texts{$lock}=$env{'session.lock.'.$lock};
926: }
927: }
928: return ($num,%texts);
929: }
930:
931: sub remove_lock {
932: my ($id)=@_;
933: my $newlocks='';
934: foreach my $lock (split(/\,/,$env{'session.locks'})) {
935: if (($lock=~/\w/) && ($lock ne $id)) {
936: $newlocks.=','.$lock;
937: }
938: }
939: &appenv({'session.locks' => $newlocks});
940: &delenv('session.lock.'.$id);
941: }
942:
943: sub remove_all_locks {
944: my $activelocks=$env{'session.locks'};
945: foreach my $lock (split(/\,/,$env{'session.locks'})) {
946: if ($lock=~/\w/) {
947: &remove_lock($lock);
948: }
949: }
950: }
951:
952:
1.369 albertel 953: # ------------------------------------------ Find out current server userload
954: sub userload {
955: my $numusers=0;
956: {
957: opendir(LONIDS,$perlvar{'lonIDsDir'});
958: my $filename;
959: my $curtime=time;
960: while ($filename=readdir(LONIDS)) {
1.925 albertel 961: next if ($filename eq '.' || $filename eq '..');
962: next if ($filename =~ /publicuser_\d+\.id/);
1.1390 raeburn 963: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 964: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 965: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 966: }
967: closedir(LONIDS);
968: }
969: my $userloadpercent=0;
970: my $maxuserload=$perlvar{'lonUserLoadLim'};
971: if ($maxuserload) {
1.371 albertel 972: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 973: }
1.372 albertel 974: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 975: return $userloadpercent;
1.283 www 976: }
977:
1.1 albertel 978: # ------------------------------ Find server with least workload from spare.tab
1.11 www 979:
1.1 albertel 980: sub spareserver {
1.1451 raeburn 981: my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 982: my $spare_server;
1.370 albertel 983: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 984: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
985: : $userloadpercent;
1.1083 raeburn 986: my ($uint_dom,$remotesessions);
987: if (($udom ne '') && (&domain($udom) ne '')) {
1.1494 raeburn 988: my $uprimary_id = &domain($udom,'primary');
989: $uint_dom = &internet_dom($uprimary_id);
990: my %udomdefaults = &get_domain_defaults($udom);
1.1083 raeburn 991: $remotesessions = $udomdefaults{'remotesessions'};
992: }
1.1123 raeburn 993: my $spareshash = &this_host_spares($udom);
994: if (ref($spareshash) eq 'HASH') {
995: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
996: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 997: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
998: $try_server));
1.1123 raeburn 999: ($spare_server, $lowest_load) =
1000: &compare_server_load($try_server, $spare_server, $lowest_load);
1001: }
1.1083 raeburn 1002: }
1.784 albertel 1003:
1.1123 raeburn 1004: my $found_server = ($spare_server ne '' && $lowest_load < 100);
1005:
1006: if (!$found_server) {
1007: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1008: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 1009: next unless (&spare_can_host($udom,$uint_dom,
1010: $remotesessions,$try_server));
1.1123 raeburn 1011: ($spare_server, $lowest_load) =
1012: &compare_server_load($try_server, $spare_server, $lowest_load);
1013: }
1014: }
1015: }
1.784 albertel 1016: }
1017:
1018: if (!$want_server_name) {
1.1001 raeburn 1019: if (defined($spare_server)) {
1020: my $hostname = &hostname($spare_server);
1.1083 raeburn 1021: if (defined($hostname)) {
1.1397 raeburn 1022: my $protocol = 'http';
1023: if ($protocol{$spare_server} eq 'https') {
1024: $protocol = $protocol{$spare_server};
1025: }
1.1494 raeburn 1026: my $alias = &use_proxy_alias($r,$spare_server);
1.1451 raeburn 1027: $hostname = $alias if ($alias ne '');
1.1001 raeburn 1028: $spare_server = $protocol.'://'.$hostname;
1029: }
1030: }
1.784 albertel 1031: }
1032: return $spare_server;
1033: }
1034:
1035: sub compare_server_load {
1.1253 raeburn 1036: my ($try_server, $spare_server, $lowest_load, $required) = @_;
1037:
1038: if ($required) {
1039: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
1040: my $remoterev = &get_server_loncaparev(undef,$try_server);
1041: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
1042: if (($major eq '' && $minor eq '') ||
1043: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
1044: return ($spare_server,$lowest_load);
1045: }
1046: }
1.784 albertel 1047:
1048: my $loadans = &reply('load', $try_server);
1049: my $userloadans = &reply('userload',$try_server);
1050:
1051: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 1052: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 1053: }
1054:
1055: my $load;
1056: if ($loadans =~ /\d/) {
1057: if ($userloadans =~ /\d/) {
1058: #both are numbers, pick the bigger one
1059: $load = ($loadans > $userloadans) ? $loadans
1060: : $userloadans;
1.411 albertel 1061: } else {
1.784 albertel 1062: $load = $loadans;
1.411 albertel 1063: }
1.784 albertel 1064: } else {
1065: $load = $userloadans;
1066: }
1067:
1068: if (($load =~ /\d/) && ($load < $lowest_load)) {
1069: $spare_server = $try_server;
1070: $lowest_load = $load;
1.370 albertel 1071: }
1.784 albertel 1072: return ($spare_server,$lowest_load);
1.202 matthew 1073: }
1.914 albertel 1074:
1075: # --------------------------- ask offload servers if user already has a session
1076: sub find_existing_session {
1077: my ($udom,$uname) = @_;
1.1123 raeburn 1078: my $spareshash = &this_host_spares($udom);
1079: if (ref($spareshash) eq 'HASH') {
1080: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1081: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1082: return $try_server if (&has_user_session($try_server, $udom, $uname));
1083: }
1084: }
1085: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1086: foreach my $try_server (@{ $spareshash->{'default'} }) {
1087: return $try_server if (&has_user_session($try_server, $udom, $uname));
1088: }
1089: }
1.914 albertel 1090: }
1091: return;
1092: }
1093:
1.1411 raeburn 1094: sub delusersession {
1095: my ($lonid,$udom,$uname) = @_;
1096: my $uprimary_id = &domain($udom,'primary');
1097: my $uintdom = &internet_dom($uprimary_id);
1098: my $intdom = &internet_dom($lonid);
1099: my $serverhomedom = &host_domain($lonid);
1100: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1101: return &reply(join(':','delusersession',
1102: map {&escape($_)} ($udom,$uname)),$lonid);
1103: }
1104: return;
1105: }
1106:
1.1389 raeburn 1107: # check if user's browser sent load balancer cookie and server still has session
1108: # and is not overloaded.
1109: sub check_for_balancer_cookie {
1110: my ($r,$update_mtime) = @_;
1111: my ($otherserver,$cookie);
1112: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1113: if (exists($cookies{'balanceID'})) {
1114: my $balid = $cookies{'balanceID'};
1115: $cookie=&LONCAPA::clean_handle($balid->value);
1116: my $balancedir=$r->dir_config('lonBalanceDir');
1117: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1118: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1119: my ($possudom,$possuname) = ($1,$2);
1120: my $has_session = 0;
1121: if ((&domain($possudom) ne '') &&
1122: (&homeserver($possuname,$possudom) ne 'no_host')) {
1123: my $try_server;
1124: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1125: if ($opened) {
1126: flock($idf,LOCK_SH);
1127: while (my $line = <$idf>) {
1128: chomp($line);
1129: if (&hostname($line) ne '') {
1130: $try_server = $line;
1131: last;
1132: }
1133: }
1134: close($idf);
1135: if (($try_server) &&
1136: (&has_user_session($try_server,$possudom,$possuname))) {
1137: my $lowest_load = 30000;
1138: ($otherserver,$lowest_load) =
1139: &compare_server_load($try_server,undef,$lowest_load);
1140: if ($otherserver ne '' && $lowest_load < 100) {
1141: $has_session = 1;
1142: } else {
1143: undef($otherserver);
1144: }
1145: }
1146: }
1147: }
1148: if ($has_session) {
1149: if ($update_mtime) {
1150: my $atime = my $mtime = time;
1151: utime($atime,$mtime,"$balancedir/$cookie.id");
1152: }
1153: } else {
1154: unlink("$balancedir/$cookie.id");
1155: }
1156: }
1157: }
1158: }
1159: return ($otherserver,$cookie);
1160: }
1161:
1.1431 raeburn 1162: sub updatebalcookie {
1163: my ($cookie,$balancer,$lastentry)=@_;
1164: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1165: my ($udom,$uname) = ($1,$2);
1166: my $uprimary_id = &domain($udom,'primary');
1167: my $uintdom = &internet_dom($uprimary_id);
1168: my $intdom = &internet_dom($balancer);
1169: my $serverhomedom = &host_domain($balancer);
1170: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1171: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1172: }
1173: }
1174: return;
1175: }
1176:
1.1389 raeburn 1177: sub delbalcookie {
1178: my ($cookie,$balancer) =@_;
1179: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1180: my ($udom,$uname) = ($1,$2);
1181: my $uprimary_id = &domain($udom,'primary');
1182: my $uintdom = &internet_dom($uprimary_id);
1183: my $intdom = &internet_dom($balancer);
1184: my $serverhomedom = &host_domain($balancer);
1185: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1431 raeburn 1186: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1389 raeburn 1187: }
1188: }
1189: }
1190:
1.914 albertel 1191: # -------------------------------- ask if server already has a session for user
1192: sub has_user_session {
1193: my ($lonid,$udom,$uname) = @_;
1194: my $result = &reply(join(':','userhassession',
1195: map {&escape($_)} ($udom,$uname)),$lonid);
1196: return 1 if ($result eq 'ok');
1197:
1198: return 0;
1199: }
1200:
1.1076 raeburn 1201: # --------- determine least loaded server in a user's domain which allows login
1202:
1203: sub choose_server {
1.1259 raeburn 1204: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1205: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1206: my %servers = &get_servers($udom);
1.1076 raeburn 1207: my $lowest_load = 30000;
1.1259 raeburn 1208: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1209: if ($skiploadbal) {
1210: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1211: unless (defined($cached)) {
1212: my $cachetime = 60*60*24;
1213: my %domconfig =
1.1494 raeburn 1214: &get_dom('configuration',['loadbalancing'],$udom);
1.1259 raeburn 1215: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1216: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1217: $cachetime);
1218: }
1219: }
1220: }
1.1076 raeburn 1221: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1222: if ($skiploadbal) {
1223: if (ref($balancers) eq 'HASH') {
1224: next if (exists($balancers->{$lonhost}));
1225: }
1.1389 raeburn 1226: }
1.1115 raeburn 1227: my $loginvia;
1228: if ($checkloginvia) {
1229: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1230: if ($loginvia) {
1231: my ($server,$path) = split(/:/,$loginvia);
1232: ($login_host, $lowest_load) =
1.1253 raeburn 1233: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1234: if ($login_host eq $server) {
1235: $portal_path = $path;
1.1151 raeburn 1236: $isredirect = 1;
1.1116 raeburn 1237: }
1238: } else {
1239: ($login_host, $lowest_load) =
1.1253 raeburn 1240: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1241: if ($login_host eq $lonhost) {
1242: $portal_path = '';
1.1151 raeburn 1243: $isredirect = '';
1.1116 raeburn 1244: }
1245: }
1246: } else {
1.1076 raeburn 1247: ($login_host, $lowest_load) =
1.1253 raeburn 1248: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1249: }
1250: }
1251: if ($login_host ne '') {
1.1116 raeburn 1252: $hostname = &hostname($login_host);
1.1076 raeburn 1253: }
1.1331 raeburn 1254: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1255: }
1256:
1.1420 raeburn 1257: sub get_course_sessions {
1258: my ($cnum,$cdom,$lastactivity) = @_;
1259: my %servers = &internet_dom_servers($cdom);
1260: my %returnhash;
1261: foreach my $server (sort(keys(%servers))) {
1262: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1263: my @pairs=split(/\&/,$rep);
1264: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1265: foreach my $item (@pairs) {
1266: my ($key,$value)=split(/=/,$item,2);
1267: $key = &unescape($key);
1268: next if ($key =~ /^error: 2 /);
1269: if (exists($returnhash{$key})) {
1270: next if ($value < $returnhash{$key});
1271: }
1272: $returnhash{$key}=$value;
1273: }
1274: }
1275: }
1276: return %returnhash;
1277: }
1278:
1.202 matthew 1279: # --------------------------------------------- Try to change a user's password
1280:
1281: sub changepass {
1.799 raeburn 1282: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1283: $currentpass = &escape($currentpass);
1284: $newpass = &escape($newpass);
1.1030 raeburn 1285: my $lonhost = $perlvar{'lonHostID'};
1286: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1287: $server);
1288: if (! $answer) {
1289: &logthis("No reply on password change request to $server ".
1290: "by $uname in domain $udom.");
1291: } elsif ($answer =~ "^ok") {
1292: &logthis("$uname in $udom successfully changed their password ".
1293: "on $server.");
1294: } elsif ($answer =~ "^pwchange_failure") {
1295: &logthis("$uname in $udom was unable to change their password ".
1296: "on $server. The action was blocked by either lcpasswd ".
1297: "or pwchange");
1298: } elsif ($answer =~ "^non_authorized") {
1299: &logthis("$uname in $udom did not get their password correct when ".
1300: "attempting to change it on $server.");
1301: } elsif ($answer =~ "^auth_mode_error") {
1302: &logthis("$uname in $udom attempted to change their password despite ".
1303: "not being locally or internally authenticated on $server.");
1304: } elsif ($answer =~ "^unknown_user") {
1305: &logthis("$uname in $udom attempted to change their password ".
1306: "on $server but were unable to because $server is not ".
1307: "their home server.");
1308: } elsif ($answer =~ "^refused") {
1309: &logthis("$server refused to change $uname in $udom password because ".
1310: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1311: } elsif ($answer =~ "invalid_client") {
1312: &logthis("$server refused to change $uname in $udom password because ".
1313: "it was a reset by e-mail originating from an invalid server.");
1.1408 raeburn 1314: } elsif ($answer =~ "^prioruse") {
1315: &logthis("$server refused to change $uname in $udom password because ".
1316: "the password had been used before");
1.202 matthew 1317: }
1318: return $answer;
1.1 albertel 1319: }
1320:
1.169 harris41 1321: # ----------------------- Try to determine user's current authentication scheme
1322:
1323: sub queryauthenticate {
1324: my ($uname,$udom)=@_;
1.456 albertel 1325: my $uhome=&homeserver($uname,$udom);
1.1484 raeburn 1326: if ((!$uhome) || ($uhome eq 'no_host')) {
1.456 albertel 1327: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1328: return 'no_host';
1329: }
1330: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1331: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1332: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1333: }
1.456 albertel 1334: return $answer;
1.169 harris41 1335: }
1336:
1.1 albertel 1337: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1338:
1.1 albertel 1339: sub authenticate {
1.1073 raeburn 1340: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1341: $upass=&escape($upass);
1342: $uname= &LONCAPA::clean_username($uname);
1.836 www 1343: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1344: my $newhome;
1.836 www 1345: if ((!$uhome) || ($uhome eq 'no_host')) {
1346: # Maybe the machine was offline and only re-appeared again recently?
1347: &reconlonc();
1348: # One more
1.952 raeburn 1349: $uhome=&homeserver($uname,$udom,1);
1350: if (($uhome eq 'no_host') && $checkdefauth) {
1351: if (defined(&domain($udom,'primary'))) {
1352: $newhome=&domain($udom,'primary');
1353: }
1354: if ($newhome ne '') {
1355: $uhome = $newhome;
1356: }
1357: }
1.836 www 1358: if ((!$uhome) || ($uhome eq 'no_host')) {
1359: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1360: return 'no_host';
1361: }
1.1 albertel 1362: }
1.1073 raeburn 1363: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1364: if ($answer eq 'authorized') {
1.952 raeburn 1365: if ($newhome) {
1366: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1367: return 'no_account_on_host';
1368: } else {
1369: &logthis("User $uname at $udom authorized by $uhome");
1370: return $uhome;
1371: }
1.471 albertel 1372: }
1373: if ($answer eq 'non_authorized') {
1374: &logthis("User $uname at $udom rejected by $uhome");
1.1484 raeburn 1375: return 'no_host';
1.9 www 1376: }
1.471 albertel 1377: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1378: return 'no_host';
1379: }
1380:
1.1491 raeburn 1381: sub can_switchserver {
1382: my ($udom,$home) = @_;
1383: my ($canswitch,@intdoms);
1384: my $internet_names = &get_internet_names($home);
1385: if (ref($internet_names) eq 'ARRAY') {
1386: @intdoms = @{$internet_names};
1387: }
1388: my $uint_dom = &internet_dom(&domain($udom,'primary'));
1389: if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1390: $canswitch = 1;
1391: } else {
1392: my $serverhomeID = &get_server_homeID(&hostname($home));
1393: my $serverhomedom = &host_domain($serverhomeID);
1394: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1395: my %udomdefaults = &get_domain_defaults($udom);
1396: my $remoterev = &get_server_loncaparev('',$home);
1397: $canswitch = &can_host_session($udom,$home,$remoterev,
1398: $udomdefaults{'remotesessions'},
1399: $defdomdefaults{'hostedsessions'});
1400: }
1401: return $canswitch;
1402: }
1403:
1.1073 raeburn 1404: sub can_host_session {
1.1074 raeburn 1405: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1406: my $canhost = 1;
1.1494 raeburn 1407: my $host_idn = &internet_dom($lonhost);
1.1073 raeburn 1408: if (ref($remotesessions) eq 'HASH') {
1409: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1410: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1411: $canhost = 0;
1412: } else {
1413: $canhost = 1;
1414: }
1415: }
1416: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1417: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1418: $canhost = 1;
1419: } else {
1420: $canhost = 0;
1421: }
1422: }
1423: if ($canhost) {
1424: if ($remotesessions->{'version'} ne '') {
1425: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1426: if ($reqmajor ne '' && $reqminor ne '') {
1427: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1428: my $major = $1;
1429: my $minor = $2;
1430: if (($major < $reqmajor ) ||
1431: (($major == $reqmajor) && ($minor < $reqminor))) {
1432: $canhost = 0;
1433: }
1434: } else {
1435: $canhost = 0;
1436: }
1437: }
1438: }
1439: }
1440: }
1441: if ($canhost) {
1442: if (ref($hostedsessions) eq 'HASH') {
1.1494 raeburn 1443: my $uprimary_id = &domain($udom,'primary');
1444: my $uint_dom = &internet_dom($uprimary_id);
1.1073 raeburn 1445: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1446: if (($uint_dom ne '') &&
1447: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1448: $canhost = 0;
1449: } else {
1450: $canhost = 1;
1451: }
1452: }
1453: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1454: if (($uint_dom ne '') &&
1455: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1456: $canhost = 1;
1457: } else {
1458: $canhost = 0;
1459: }
1460: }
1461: }
1462: }
1463: return $canhost;
1464: }
1465:
1.1083 raeburn 1466: sub spare_can_host {
1467: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1468: my $canhost=1;
1.1279 raeburn 1469: my $try_server_hostname = &hostname($try_server);
1470: my $serverhomeID = &get_server_homeID($try_server_hostname);
1471: my $serverhomedom = &host_domain($serverhomeID);
1472: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1473: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1474: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1475: $canhost = 0;
1476: }
1477: }
1.1439 raeburn 1478: if ($canhost) {
1479: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1480: if ($defdomdefaults{'offloadoth'}{$try_server}) {
1481: unless (&shared_institution($udom,$try_server)) {
1482: $canhost = 0;
1483: }
1484: }
1485: }
1486: }
1.1279 raeburn 1487: if (($canhost) && ($uint_dom)) {
1488: my @intdoms;
1489: my $internet_names = &get_internet_names($try_server);
1490: if (ref($internet_names) eq 'ARRAY') {
1491: @intdoms = @{$internet_names};
1492: }
1493: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1494: my $remoterev = &get_server_loncaparev(undef,$try_server);
1495: $canhost = &can_host_session($udom,$try_server,$remoterev,
1496: $remotesessions,
1497: $defdomdefaults{'hostedsessions'});
1498: }
1.1083 raeburn 1499: }
1500: return $canhost;
1501: }
1502:
1.1123 raeburn 1503: sub this_host_spares {
1504: my ($dom) = @_;
1.1126 raeburn 1505: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1506: my @hosts = ¤t_machine_ids();
1507: foreach my $lonhost (@hosts) {
1508: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1509: $dom_in_use = $dom;
1510: $lonhost_in_use = $lonhost;
1.1123 raeburn 1511: last;
1512: }
1513: }
1.1126 raeburn 1514: if ($dom_in_use ne '') {
1515: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1516: }
1517: if (ref($result) ne 'HASH') {
1518: $lonhost_in_use = $perlvar{'lonHostID'};
1519: $dom_in_use = &host_domain($lonhost_in_use);
1520: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1521: if (ref($result) ne 'HASH') {
1522: $result = \%spareid;
1523: }
1524: }
1525: return $result;
1526: }
1527:
1528: sub spares_for_offload {
1529: my ($dom_in_use,$lonhost_in_use) = @_;
1530: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1531: if (defined($cached)) {
1532: return $result;
1533: } else {
1.1126 raeburn 1534: my $cachetime = 60*60*24;
1535: my %domconfig =
1.1494 raeburn 1536: &get_dom('configuration',['usersessions'],$dom_in_use);
1.1126 raeburn 1537: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1538: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1539: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1540: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1541: }
1542: }
1543: }
1544: }
1.1126 raeburn 1545: return;
1.1123 raeburn 1546: }
1547:
1.1129 raeburn 1548: sub get_lonbalancer_config {
1549: my ($servers) = @_;
1550: my ($currbalancer,$currtargets);
1551: if (ref($servers) eq 'HASH') {
1552: foreach my $server (keys(%{$servers})) {
1553: my %what = (
1554: spareid => 1,
1555: perlvar => 1,
1556: );
1557: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1558: if ($result eq 'ok') {
1559: if (ref($returnhash) eq 'HASH') {
1560: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1561: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1562: $currbalancer = $server;
1563: $currtargets = {};
1564: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1565: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1566: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1567: }
1568: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1569: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1570: }
1571: }
1572: last;
1573: }
1574: }
1575: }
1576: }
1577: }
1578: }
1579: return ($currbalancer,$currtargets);
1580: }
1581:
1582: sub check_loadbalancing {
1.1331 raeburn 1583: my ($uname,$udom,$caller) = @_;
1.1191 raeburn 1584: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391 raeburn 1585: $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129 raeburn 1586: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1587: my @hosts = ¤t_machine_ids();
1.1494 raeburn 1588: my $uprimary_id = &domain($udom,'primary');
1589: my $uintdom = &internet_dom($uprimary_id);
1590: my $intdom = &internet_dom($lonhost);
1.1129 raeburn 1591: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1592: my $domneedscache;
1.1129 raeburn 1593: my $cachetime = 60*60*24;
1594:
1595: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1596: $dom_in_use = $udom;
1597: $homeintdom = 1;
1598: } else {
1599: $dom_in_use = $serverhomedom;
1600: }
1601: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1602: unless (defined($cached)) {
1603: my %domconfig =
1.1494 raeburn 1604: &get_dom('configuration',['loadbalancing'],$dom_in_use);
1.1129 raeburn 1605: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1606: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1607: } else {
1608: $domneedscache = $dom_in_use;
1.1129 raeburn 1609: }
1610: }
1611: if (ref($result) eq 'HASH') {
1.1391 raeburn 1612: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1613: &check_balancer_result($result,@hosts);
1.1129 raeburn 1614: if ($is_balancer) {
1615: if (ref($currrules) eq 'HASH') {
1616: if ($homeintdom) {
1617: if ($uname ne '') {
1618: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1619: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1620: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1621: $rule_in_effect = $currrules->{'_LC_author'};
1622: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1623: $rule_in_effect = $currrules->{'_LC_adv'}
1624: }
1625: }
1626: if ($rule_in_effect eq '') {
1627: my %userenv = &userenvironment($udom,$uname,'inststatus');
1628: if ($userenv{'inststatus'} ne '') {
1629: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1630: my ($othertitle,$usertypes,$types) =
1631: &Apache::loncommon::sorted_inst_types($udom);
1632: if (ref($types) eq 'ARRAY') {
1633: foreach my $type (@{$types}) {
1634: if (grep(/^\Q$type\E$/,@statuses)) {
1635: if (exists($currrules->{$type})) {
1636: $rule_in_effect = $currrules->{$type};
1637: }
1638: }
1639: }
1640: }
1641: } else {
1642: if (exists($currrules->{'default'})) {
1643: $rule_in_effect = $currrules->{'default'};
1644: }
1645: }
1646: }
1647: } else {
1648: if (exists($currrules->{'default'})) {
1649: $rule_in_effect = $currrules->{'default'};
1650: }
1651: }
1652: } else {
1653: if ($currrules->{'_LC_external'} ne '') {
1654: $rule_in_effect = $currrules->{'_LC_external'};
1655: }
1656: }
1657: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1658: $uname,$udom);
1659: }
1660: }
1661: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1662: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1663: unless (defined($cached)) {
1664: my %domconfig =
1.1494 raeburn 1665: &get_dom('configuration',['loadbalancing'],$serverhomedom);
1.1129 raeburn 1666: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1667: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1668: } else {
1669: $domneedscache = $serverhomedom;
1.1129 raeburn 1670: }
1671: }
1672: if (ref($result) eq 'HASH') {
1.1391 raeburn 1673: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1674: &check_balancer_result($result,@hosts);
1675: if ($is_balancer) {
1.1129 raeburn 1676: if (ref($currrules) eq 'HASH') {
1677: if ($currrules->{'_LC_internetdom'} ne '') {
1678: $rule_in_effect = $currrules->{'_LC_internetdom'};
1679: }
1680: }
1681: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1682: $uname,$udom);
1683: }
1684: } else {
1685: if ($perlvar{'lonBalancer'} eq 'yes') {
1686: $is_balancer = 1;
1687: $offloadto = &this_host_spares($dom_in_use);
1688: }
1.1307 raeburn 1689: unless (defined($cached)) {
1690: $domneedscache = $serverhomedom;
1691: }
1.1129 raeburn 1692: }
1693: } else {
1694: if ($perlvar{'lonBalancer'} eq 'yes') {
1695: $is_balancer = 1;
1696: $offloadto = &this_host_spares($dom_in_use);
1697: }
1.1307 raeburn 1698: unless (defined($cached)) {
1699: $domneedscache = $serverhomedom;
1700: }
1701: }
1702: if ($domneedscache) {
1703: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1704: }
1.1430 raeburn 1705: if (($is_balancer) && ($caller ne 'switchserver')) {
1.1176 raeburn 1706: my $lowest_load = 30000;
1707: if (ref($offloadto) eq 'HASH') {
1708: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1709: foreach my $try_server (@{$offloadto->{'primary'}}) {
1710: ($otherserver,$lowest_load) =
1711: &compare_server_load($try_server,$otherserver,$lowest_load);
1712: }
1.1129 raeburn 1713: }
1.1176 raeburn 1714: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1715:
1.1176 raeburn 1716: if (!$found_server) {
1717: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1718: foreach my $try_server (@{$offloadto->{'default'}}) {
1719: ($otherserver,$lowest_load) =
1720: &compare_server_load($try_server,$otherserver,$lowest_load);
1721: }
1722: }
1723: }
1724: } elsif (ref($offloadto) eq 'ARRAY') {
1725: if (@{$offloadto} == 1) {
1726: $otherserver = $offloadto->[0];
1727: } elsif (@{$offloadto} > 1) {
1728: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1729: ($otherserver,$lowest_load) =
1730: &compare_server_load($try_server,$otherserver,$lowest_load);
1731: }
1732: }
1733: }
1.1331 raeburn 1734: unless ($caller eq 'login') {
1735: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1736: $is_balancer = 0;
1737: if ($uname ne '' && $udom ne '') {
1738: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389 raeburn 1739: &appenv({'user.loadbalexempt' => $lonhost,
1.1331 raeburn 1740: 'user.loadbalcheck.time' => time});
1741: }
1.1176 raeburn 1742: }
1.1129 raeburn 1743: }
1744: }
1.1430 raeburn 1745: }
1746: if (($is_balancer) && (!$homeintdom)) {
1747: undef($setcookie);
1.1129 raeburn 1748: }
1.1391 raeburn 1749: return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129 raeburn 1750: }
1751:
1.1191 raeburn 1752: sub check_balancer_result {
1753: my ($result,@hosts) = @_;
1.1391 raeburn 1754: my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1755: if (ref($result) eq 'HASH') {
1756: if ($result->{'lonhost'} ne '') {
1757: my $currbalancer = $result->{'lonhost'};
1758: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1759: $is_balancer = 1;
1760: $currtargets = $result->{'targets'};
1761: $currrules = $result->{'rules'};
1762: }
1.1391 raeburn 1763: $dom_balancers = $currbalancer;
1.1191 raeburn 1764: } else {
1.1391 raeburn 1765: if (keys(%{$result})) {
1766: foreach my $key (keys(%{$result})) {
1767: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1768: (ref($result->{$key}) eq 'HASH')) {
1769: $is_balancer = 1;
1770: $currrules = $result->{$key}{'rules'};
1771: $currtargets = $result->{$key}{'targets'};
1772: $setcookie = $result->{$key}{'cookie'};
1773: last;
1774: }
1.1191 raeburn 1775: }
1.1391 raeburn 1776: $dom_balancers = join(',',sort(keys(%{$result})));
1.1191 raeburn 1777: }
1778: }
1779: }
1.1391 raeburn 1780: return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1781: }
1782:
1.1129 raeburn 1783: sub get_loadbalancer_targets {
1784: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1785: my $offloadto;
1.1175 raeburn 1786: if ($rule_in_effect eq 'none') {
1787: return [$perlvar{'lonHostID'}];
1788: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1789: $offloadto = $currtargets;
1790: } else {
1791: if ($rule_in_effect eq 'homeserver') {
1792: my $homeserver = &homeserver($uname,$udom);
1793: if ($homeserver ne 'no_host') {
1794: $offloadto = [$homeserver];
1795: }
1796: } elsif ($rule_in_effect eq 'externalbalancer') {
1797: my %domconfig =
1.1494 raeburn 1798: &get_dom('configuration',['loadbalancing'],$udom);
1.1129 raeburn 1799: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1800: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1801: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1802: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1803: }
1804: }
1805: } else {
1.1178 raeburn 1806: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1807: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1808: if (&hostname($remotebalancer) ne '') {
1809: $offloadto = [$remotebalancer];
1810: }
1811: }
1812: } elsif (&hostname($rule_in_effect) ne '') {
1813: $offloadto = [$rule_in_effect];
1814: }
1815: }
1816: return $offloadto;
1817: }
1818:
1.1127 raeburn 1819: sub internet_dom_servers {
1820: my ($dom) = @_;
1821: my (%uniqservers,%servers);
1822: my $primaryserver = &hostname(&domain($dom,'primary'));
1823: my @machinedoms = &machine_domains($primaryserver);
1824: foreach my $mdom (@machinedoms) {
1825: my %currservers = %servers;
1826: my %server = &get_servers($mdom);
1827: %servers = (%currservers,%server);
1828: }
1829: my %by_hostname;
1830: foreach my $id (keys(%servers)) {
1831: push(@{$by_hostname{$servers{$id}}},$id);
1832: }
1833: foreach my $hostname (sort(keys(%by_hostname))) {
1834: if (@{$by_hostname{$hostname}} > 1) {
1835: my $match = 0;
1836: foreach my $id (@{$by_hostname{$hostname}}) {
1837: if (&host_domain($id) eq $dom) {
1838: $uniqservers{$id} = $hostname;
1839: $match = 1;
1840: }
1841: }
1842: unless ($match) {
1843: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1844: }
1845: } else {
1846: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1847: }
1848: }
1849: return %uniqservers;
1850: }
1851:
1.1347 raeburn 1852: sub trusted_domains {
1853: my ($cmdtype,$calldom) = @_;
1.1349 raeburn 1854: my ($trusted,$untrusted);
1.1347 raeburn 1855: if (&domain($calldom) eq '') {
1.1349 raeburn 1856: return ($trusted,$untrusted);
1.1347 raeburn 1857: }
1.1395 raeburn 1858: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349 raeburn 1859: return ($trusted,$untrusted);
1.1347 raeburn 1860: }
1861: my $callprimary = &domain($calldom,'primary');
1.1494 raeburn 1862: my $intcalldom = &internet_dom($callprimary);
1.1347 raeburn 1863: if ($intcalldom eq '') {
1.1349 raeburn 1864: return ($trusted,$untrusted);
1.1347 raeburn 1865: }
1866:
1.1494 raeburn 1867: my ($trustconfig,$cached)=&is_cached_new('trust',$calldom);
1.1347 raeburn 1868: unless (defined($cached)) {
1.1494 raeburn 1869: my %domconfig = &get_dom('configuration',['trust'],$calldom);
1870: &do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1.1347 raeburn 1871: $trustconfig = $domconfig{'trust'};
1872: }
1873: if (ref($trustconfig)) {
1874: my (%possexc,%possinc,@allexc,@allinc);
1875: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1876: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1877: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1878: }
1879: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395 raeburn 1880: $possinc{$intcalldom} = 1;
1.1347 raeburn 1881: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1882: }
1883: }
1884: if (keys(%possexc)) {
1885: if (keys(%possinc)) {
1886: foreach my $key (sort(keys(%possexc))) {
1887: next if ($key eq $intcalldom);
1888: unless ($possinc{$key}) {
1889: push(@allexc,$key);
1890: }
1891: }
1892: } else {
1893: @allexc = sort(keys(%possexc));
1894: }
1895: }
1896: if (keys(%possinc)) {
1897: $possinc{$intcalldom} = 1;
1898: @allinc = sort(keys(%possinc));
1899: }
1900: if ((@allexc > 0) || (@allinc > 0)) {
1901: my %doms_by_intdom;
1902: my %allintdoms = &all_host_intdom();
1903: my %alldoms = &all_host_domain();
1904: foreach my $key (%allintdoms) {
1905: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1906: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1907: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1908: }
1909: } else {
1910: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1911: }
1912: }
1913: foreach my $exc (@allexc) {
1914: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395 raeburn 1915: push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347 raeburn 1916: }
1917: }
1918: foreach my $inc (@allinc) {
1919: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395 raeburn 1920: push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347 raeburn 1921: }
1922: }
1923: }
1924: }
1.1349 raeburn 1925: return ($trusted,$untrusted);
1.1347 raeburn 1926: }
1927:
1928: sub will_trust {
1929: my ($cmdtype,$domain,$possdom) = @_;
1930: return 1 if ($domain eq $possdom);
1931: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1932: my $willtrust;
1933: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1934: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1935: $willtrust = 1;
1936: }
1937: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1938: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1939: $willtrust = 1;
1940: }
1941: } else {
1942: $willtrust = 1;
1943: }
1944: return $willtrust;
1945: }
1946:
1.1 albertel 1947: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1948:
1.599 albertel 1949: my %homecache;
1.1 albertel 1950: sub homeserver {
1.230 stredwic 1951: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1952: my $index="$uname:$udom";
1.426 albertel 1953:
1.599 albertel 1954: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1955:
1956: my %servers = &get_servers($udom,'library');
1957: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1958: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1959: exists($badServerCache{$tryserver}));
1.841 albertel 1960:
1961: my $answer=reply("home:$udom:$uname",$tryserver);
1962: if ($answer eq 'found') {
1963: delete($badServerCache{$tryserver});
1964: return $homecache{$index}=$tryserver;
1965: } elsif ($answer eq 'no_host') {
1966: $badServerCache{$tryserver}=1;
1967: }
1.1 albertel 1968: }
1969: return 'no_host';
1.70 www 1970: }
1971:
1.1300 raeburn 1972: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1973:
1974: sub idget {
1.1300 raeburn 1975: my ($udom,$idsref,$namespace)=@_;
1.70 www 1976: my %returnhash=();
1.1300 raeburn 1977: my @ids=();
1978: if (ref($idsref) eq 'ARRAY') {
1979: @ids = @{$idsref};
1980: } else {
1981: return %returnhash;
1982: }
1983: if ($namespace eq '') {
1984: $namespace = 'ids';
1985: }
1.70 www 1986:
1.841 albertel 1987: my %servers = &get_servers($udom,'library');
1988: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1989: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1990: if ($namespace eq 'ids') {
1991: $idlist=~tr/A-Z/a-z/;
1992: }
1993: my $reply;
1994: if ($namespace eq 'ids') {
1995: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1996: } else {
1997: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1998: }
1.841 albertel 1999: my @answer=();
2000: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
2001: @answer=split(/\&/,$reply);
2002: } ;
2003: my $i;
2004: for ($i=0;$i<=$#ids;$i++) {
2005: if ($answer[$i]) {
1.1299 raeburn 2006: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 2007: }
1.841 albertel 2008: }
1.1300 raeburn 2009: }
1.70 www 2010: return %returnhash;
2011: }
2012:
2013: # ------------------------------------- Find the IDs behind a list of usernames
2014:
2015: sub idrget {
2016: my ($udom,@unames)=@_;
2017: my %returnhash=();
1.800 albertel 2018: foreach my $uname (@unames) {
2019: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 2020: }
1.70 www 2021: return %returnhash;
2022: }
2023:
1.1300 raeburn 2024: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 2025:
2026: sub idput {
1.1300 raeburn 2027: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 2028: my %servers=();
1.1300 raeburn 2029: my %ids=();
2030: my %byid = ();
2031: if (ref($idsref) eq 'HASH') {
2032: %ids=%{$idsref};
2033: }
2034: if ($namespace eq '') {
2035: $namespace = 'ids';
2036: }
1.800 albertel 2037: foreach my $uname (keys(%ids)) {
2038: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 2039: if ($uhom eq '') {
2040: $uhom=&homeserver($uname,$udom);
2041: }
1.70 www 2042: if ($uhom ne 'no_host') {
1.800 albertel 2043: my $esc_unam=&escape($uname);
1.1300 raeburn 2044: if ($namespace eq 'ids') {
2045: my $id=&escape($ids{$uname});
2046: $id=~tr/A-Z/a-z/;
2047: my $esc_unam=&escape($uname);
2048: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 2049: } else {
1.1300 raeburn 2050: my @currids = split(/,/,$ids{$uname});
2051: foreach my $id (@currids) {
2052: $byid{$uhom}{$id} .= $uname.',';
2053: }
2054: }
2055: }
2056: }
2057: if ($namespace eq 'clickers') {
2058: foreach my $server (keys(%byid)) {
2059: if (ref($byid{$server}) eq 'HASH') {
2060: foreach my $id (keys(%{$byid{$server}})) {
2061: $byid{$server} =~ s/,$//;
2062: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
2063: }
1.70 www 2064: }
2065: }
1.191 harris41 2066: }
1.800 albertel 2067: foreach my $server (keys(%servers)) {
1.1300 raeburn 2068: $servers{$server} =~ s/\&$//;
2069: if ($namespace eq 'ids') {
2070: &critical('idput:'.$udom.':'.$servers{$server},$server);
2071: } else {
2072: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
2073: }
1.191 harris41 2074: }
1.344 www 2075: }
2076:
1.1300 raeburn 2077: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 2078:
2079: sub iddel {
1.1300 raeburn 2080: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 2081: my %result=();
1.1300 raeburn 2082: my %ids=();
2083: my %byid = ();
2084: if (ref($idshashref) eq 'HASH') {
2085: %ids=%{$idshashref};
2086: } else {
1.1231 raeburn 2087: return %result;
2088: }
1.1300 raeburn 2089: if ($namespace eq '') {
2090: $namespace = 'ids';
2091: }
1.1231 raeburn 2092: my %servers=();
1.1300 raeburn 2093: while (my ($id,$unamestr) = each(%ids)) {
2094: if ($namespace eq 'ids') {
2095: my $uhom = $uhome;
2096: if ($uhom eq '') {
2097: $uhom=&homeserver($unamestr,$udom);
2098: }
2099: if ($uhom ne 'no_host') {
2100: $servers{$uhom}.='&'.&escape($id);
2101: }
2102: } else {
2103: my @curritems = split(/,/,$ids{$id});
2104: foreach my $uname (@curritems) {
2105: my $uhom = $uhome;
2106: if ($uhom eq '') {
2107: $uhom=&homeserver($uname,$udom);
2108: }
2109: if ($uhom ne 'no_host') {
2110: $byid{$uhom}{$id} .= $uname.',';
2111: }
2112: }
1.1231 raeburn 2113: }
1.1300 raeburn 2114: }
2115: if ($namespace eq 'clickers') {
2116: foreach my $server (keys(%byid)) {
2117: if (ref($byid{$server}) eq 'HASH') {
2118: foreach my $id (keys(%{$byid{$server}})) {
2119: $byid{$server}{$id} =~ s/,$//;
2120: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
2121: }
1.1231 raeburn 2122: }
2123: }
2124: }
2125: foreach my $server (keys(%servers)) {
1.1300 raeburn 2126: $servers{$server} =~ s/\&$//;
2127: if ($namespace eq 'ids') {
2128: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
2129: } elsif ($namespace eq 'clickers') {
2130: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
2131: }
1.1231 raeburn 2132: }
2133: return %result;
2134: }
2135:
1.1300 raeburn 2136: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
2137:
2138: sub updateclickers {
2139: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
2140: my %clickers;
2141: if (ref($idshashref) eq 'HASH') {
2142: %clickers=%{$idshashref};
2143: } else {
2144: return;
2145: }
2146: my $items='';
2147: foreach my $item (keys(%clickers)) {
2148: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
2149: }
2150: $items=~s/\&$//;
2151: my $request = "updateclickers:$udom:$action:$items";
2152: if ($critical) {
2153: return &critical($request,$uhome);
2154: } else {
2155: return &reply($request,$uhome);
2156: }
2157: }
2158:
1.1023 raeburn 2159: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 2160: sub dump_dom {
1.1165 droeschl 2161: my ($namespace, $udom, $regexp) = @_;
2162:
2163: $udom ||= $env{'user.domain'};
2164:
2165: return () unless $udom;
2166:
2167: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 2168: }
2169:
1.1023 raeburn 2170: # ------------------------------------------ get items from domain db files
1.806 raeburn 2171:
2172: sub get_dom {
1.1462 raeburn 2173: my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1267 raeburn 2174: return if ($udom eq 'public');
1.806 raeburn 2175: my $items='';
2176: foreach my $item (@$storearr) {
2177: $items.=&escape($item).'&';
2178: }
2179: $items=~s/\&$//;
1.860 raeburn 2180: if (!$udom) {
2181: $udom=$env{'user.domain'};
1.1267 raeburn 2182: return if ($udom eq 'public');
1.860 raeburn 2183: if (defined(&domain($udom,'primary'))) {
2184: $uhome=&domain($udom,'primary');
2185: } else {
1.874 albertel 2186: undef($uhome);
1.860 raeburn 2187: }
2188: } else {
2189: if (!$uhome) {
2190: if (defined(&domain($udom,'primary'))) {
2191: $uhome=&domain($udom,'primary');
2192: }
2193: }
2194: }
2195: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344 raeburn 2196: my $rep;
1.1442 raeburn 2197: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
2198: # domain information is hosted on this machine
1.1462 raeburn 2199: $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1344 raeburn 2200: } else {
1.1462 raeburn 2201: if ($encrypt) {
1.1442 raeburn 2202: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
2203: } else {
2204: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
2205: }
1.1344 raeburn 2206: }
1.866 raeburn 2207: my %returnhash;
1.875 albertel 2208: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 2209: return %returnhash;
2210: }
1.806 raeburn 2211: my @pairs=split(/\&/,$rep);
2212: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2213: return @pairs;
2214: }
2215: my $i=0;
2216: foreach my $item (@$storearr) {
2217: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2218: $i++;
2219: }
2220: return %returnhash;
2221: } else {
1.880 banghart 2222: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 2223: }
2224: }
2225:
2226: # -------------------------------------------- put items in domain db files
2227:
2228: sub put_dom {
1.1462 raeburn 2229: my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860 raeburn 2230: if (!$udom) {
2231: $udom=$env{'user.domain'};
2232: if (defined(&domain($udom,'primary'))) {
2233: $uhome=&domain($udom,'primary');
2234: } else {
1.874 albertel 2235: undef($uhome);
1.860 raeburn 2236: }
2237: } else {
2238: if (!$uhome) {
2239: if (defined(&domain($udom,'primary'))) {
2240: $uhome=&domain($udom,'primary');
2241: }
2242: }
2243: }
2244: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 2245: my $items='';
2246: foreach my $item (keys(%$storehash)) {
2247: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2248: }
2249: $items=~s/\&$//;
1.1462 raeburn 2250: if ($encrypt) {
1.1344 raeburn 2251: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2252: } else {
2253: return &reply("putdom:$udom:$namespace:$items",$uhome);
2254: }
1.806 raeburn 2255: } else {
1.860 raeburn 2256: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 2257: }
2258: }
2259:
1.1023 raeburn 2260: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 2261: sub newput_dom {
1.1023 raeburn 2262: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 2263: my $result;
2264: if (!$udom) {
2265: $udom=$env{'user.domain'};
2266: }
1.1023 raeburn 2267: if ($udom) {
2268: my $uname = &get_domainconfiguser($udom);
2269: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 2270: }
2271: return $result;
2272: }
2273:
1.1023 raeburn 2274: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 2275: sub del_dom {
1.1023 raeburn 2276: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 2277: if (ref($storearr) eq 'ARRAY') {
2278: if (!$udom) {
2279: $udom=$env{'user.domain'};
2280: }
1.1023 raeburn 2281: if ($udom) {
2282: my $uname = &get_domainconfiguser($udom);
2283: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 2284: }
2285: }
2286: }
2287:
1.1481 raeburn 2288: sub store_dom {
1.1482 raeburn 2289: my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
1.1481 raeburn 2290: $$storehash{'ip'}=&get_requestor_ip();
2291: $$storehash{'host'}=$perlvar{'lonHostID'};
2292: my $namevalue='';
2293: foreach my $key (keys(%{$storehash})) {
2294: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2295: }
2296: $namevalue=~s/\&$//;
2297: if (grep { $_ eq $home } current_machine_ids()) {
2298: return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
2299: } else {
2300: if ($namespace eq 'private') {
2301: return 'refused';
1.1482 raeburn 2302: } elsif ($encrypt) {
2303: return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481 raeburn 2304: } else {
1.1482 raeburn 2305: return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481 raeburn 2306: }
2307: }
2308: }
2309:
1.1482 raeburn 2310: sub restore_dom {
2311: my ($id,$namespace,$dom,$home,$encrypt) = @_;
2312: my $answer;
2313: if (grep { $_ eq $home } current_machine_ids()) {
2314: $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
2315: } elsif ($namespace ne 'private') {
2316: if ($encrypt) {
2317: $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
2318: } else {
2319: $answer=&reply("restoredom:$dom:$namespace:$id",$home);
2320: }
2321: }
2322: my %returnhash=();
2323: unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') ||
2324: ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
2325: foreach my $line (split(/\&/,$answer)) {
2326: my ($name,$value)=split(/\=/,$line);
2327: $returnhash{&unescape($name)}=&thaw_unescape($value);
2328: }
2329: my $version;
2330: for ($version=1;$version<=$returnhash{'version'};$version++) {
2331: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2332: $returnhash{$item}=$returnhash{$version.':'.$item};
2333: }
2334: }
2335: }
2336: return %returnhash;
2337: }
2338:
1.1023 raeburn 2339: # ----------------------------------construct domainconfig user for a domain
2340: sub get_domainconfiguser {
2341: my ($udom) = @_;
2342: return $udom.'-domainconfig';
2343: }
2344:
1.837 raeburn 2345: sub retrieve_inst_usertypes {
2346: my ($udom) = @_;
2347: my (%returnhash,@order);
1.1494 raeburn 2348: my %domdefs = &get_domain_defaults($udom);
1.989 raeburn 2349: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2350: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 2351: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2352: } else {
2353: if (defined(&domain($udom,'primary'))) {
2354: my $uhome=&domain($udom,'primary');
2355: my $rep=&reply("inst_usertypes:$udom",$uhome);
2356: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 2357: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2358: return (\%returnhash,\@order);
2359: }
2360: my ($hashitems,$orderitems) = split(/:/,$rep);
2361: my @pairs=split(/\&/,$hashitems);
2362: foreach my $item (@pairs) {
2363: my ($key,$value)=split(/=/,$item,2);
2364: $key = &unescape($key);
2365: next if ($key =~ /^error: 2 /);
2366: $returnhash{$key}=&thaw_unescape($value);
2367: }
2368: my @esc_order = split(/\&/,$orderitems);
2369: foreach my $item (@esc_order) {
2370: push(@order,&unescape($item));
2371: }
2372: } else {
1.1256 raeburn 2373: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2374: }
1.1256 raeburn 2375: return (\%returnhash,\@order);
1.837 raeburn 2376: }
2377: }
2378:
1.868 raeburn 2379: sub is_domainimage {
2380: my ($url) = @_;
1.1468 raeburn 2381: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868 raeburn 2382: if (&domain($1) ne '') {
2383: return '1';
2384: }
2385: }
2386: return;
2387: }
2388:
1.899 raeburn 2389: sub inst_directory_query {
2390: my ($srch) = @_;
2391: my $udom = $srch->{'srchdomain'};
2392: my %results;
2393: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2394: my $outcome;
1.899 raeburn 2395: if ($homeserver ne '') {
1.1357 raeburn 2396: unless ($homeserver eq $perlvar{'lonHostID'}) {
2397: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2398: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357 raeburn 2399: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2400: if (($major eq '' && $minor eq '') || ($major < 2) ||
2401: (($major == 2) && ($minor < 12))) {
2402: return;
2403: }
2404: }
2405: }
1.904 albertel 2406: my $queryid=&reply("querysend:instdirsearch:".
2407: &escape($srch->{'srchby'}).':'.
2408: &escape($srch->{'srchterm'}).':'.
2409: &escape($srch->{'srchtype'}),$homeserver);
2410: my $host=&hostname($homeserver);
2411: if ($queryid !~/^\Q$host\E\_/) {
1.1343 raeburn 2412: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2413: return;
2414: }
2415: my $response = &get_query_reply($queryid);
2416: my $maxtries = 5;
2417: my $tries = 1;
2418: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2419: $response = &get_query_reply($queryid);
2420: $tries ++;
2421: }
2422:
2423: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2424: if ($response eq 'unavailable') {
2425: $outcome = $response;
2426: } else {
2427: $outcome = 'ok';
2428: my @matches = split(/\n/,$response);
2429: foreach my $match (@matches) {
2430: my ($key,$value) = split(/=/,$match);
2431: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2432: }
1.899 raeburn 2433: }
2434: }
2435: }
1.909 raeburn 2436: return ($outcome,%results);
1.899 raeburn 2437: }
2438:
2439: sub usersearch {
2440: my ($srch) = @_;
2441: my $dom = $srch->{'srchdomain'};
2442: my %results;
2443: my %libserv = &all_library();
2444: my $query = 'usersearch';
2445: foreach my $tryserver (keys(%libserv)) {
2446: if (&host_domain($tryserver) eq $dom) {
1.1357 raeburn 2447: unless ($tryserver eq $perlvar{'lonHostID'}) {
2448: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2449: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357 raeburn 2450: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2451: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2452: (($major == 2) && ($minor < 12)));
2453: }
2454: }
1.899 raeburn 2455: my $host=&hostname($tryserver);
2456: my $queryid=
1.911 raeburn 2457: &reply("querysend:".&escape($query).':'.
2458: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2459: &escape($srch->{'srchtype'}).':'.
2460: &escape($srch->{'srchterm'}),$tryserver);
2461: if ($queryid !~/^\Q$host\E\_/) {
2462: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2463: next;
1.899 raeburn 2464: }
2465: my $reply = &get_query_reply($queryid);
2466: my $maxtries = 1;
2467: my $tries = 1;
2468: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2469: $reply = &get_query_reply($queryid);
2470: $tries ++;
2471: }
2472: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2473: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2474: } else {
1.911 raeburn 2475: my @matches;
2476: if ($reply =~ /\n/) {
2477: @matches = split(/\n/,$reply);
2478: } else {
2479: @matches = split(/\&/,$reply);
2480: }
1.899 raeburn 2481: foreach my $match (@matches) {
2482: my ($uname,$udom,%userhash);
1.911 raeburn 2483: foreach my $entry (split(/:/,$match)) {
2484: my ($key,$value) =
2485: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2486: $userhash{$key} = $value;
2487: if ($key eq 'username') {
2488: $uname = $value;
2489: } elsif ($key eq 'domain') {
2490: $udom = $value;
1.911 raeburn 2491: }
1.899 raeburn 2492: }
2493: $results{$uname.':'.$udom} = \%userhash;
2494: }
2495: }
2496: }
2497: }
2498: return %results;
2499: }
2500:
1.912 raeburn 2501: sub get_instuser {
2502: my ($udom,$uname,$id) = @_;
2503: my $homeserver = &domain($udom,'primary');
2504: my ($outcome,%results);
2505: if ($homeserver ne '') {
2506: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2507: &escape($id).':'.&escape($udom),$homeserver);
2508: my $host=&hostname($homeserver);
2509: if ($queryid !~/^\Q$host\E\_/) {
2510: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2511: return;
2512: }
2513: my $response = &get_query_reply($queryid);
2514: my $maxtries = 5;
2515: my $tries = 1;
2516: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2517: $response = &get_query_reply($queryid);
2518: $tries ++;
2519: }
2520: if (!&error($response) && $response ne 'refused') {
2521: if ($response eq 'unavailable') {
2522: $outcome = $response;
2523: } else {
2524: $outcome = 'ok';
2525: my @matches = split(/\n/,$response);
2526: foreach my $match (@matches) {
2527: my ($key,$value) = split(/=/,$match);
2528: $results{&unescape($key)} = &thaw_unescape($value);
2529: }
2530: }
2531: }
2532: }
2533: my %userinfo;
2534: if (ref($results{$uname}) eq 'HASH') {
2535: %userinfo = %{$results{$uname}};
2536: }
2537: return ($outcome,%userinfo);
2538: }
2539:
1.1290 raeburn 2540: sub get_multiple_instusers {
2541: my ($udom,$users,$caller) = @_;
2542: my ($outcome,$results);
2543: if (ref($users) eq 'HASH') {
2544: my $count = keys(%{$users});
2545: my $requested = &freeze_escape($users);
2546: my $homeserver = &domain($udom,'primary');
2547: if ($homeserver ne '') {
2548: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2549: my $host=&hostname($homeserver);
2550: if ($queryid !~/^\Q$host\E\_/) {
2551: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2552: ' for host: '.$homeserver.'in domain '.$udom);
2553: return ($outcome,$results);
2554: }
2555: my $response = &get_query_reply($queryid);
2556: my $maxtries = 5;
2557: if ($count > 100) {
2558: $maxtries = 1+int($count/20);
2559: }
2560: my $tries = 1;
2561: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2562: $response = &get_query_reply($queryid);
2563: $tries ++;
2564: }
2565: if ($response eq '') {
2566: $results = {};
2567: foreach my $key (keys(%{$users})) {
2568: my ($uname,$id);
2569: if ($caller eq 'id') {
2570: $id = $key;
2571: } else {
2572: $uname = $key;
2573: }
2574: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2575: $outcome = $resp;
1.1290 raeburn 2576: if ($resp eq 'ok') {
2577: %{$results} = (%{$results}, %info);
2578: } else {
2579: last;
2580: }
2581: }
2582: } elsif(!&error($response) && ($response ne 'refused')) {
2583: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2584: $outcome = $response;
2585: } else {
1.1291 raeburn 2586: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2587: if ($outcome eq 'ok') {
2588: $results = &thaw_unescape($userdata);
2589: }
2590: }
2591: }
2592: }
2593: }
2594: return ($outcome,$results);
2595: }
2596:
1.912 raeburn 2597: sub inst_rulecheck {
1.923 raeburn 2598: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2599: my %returnhash;
2600: if ($udom ne '') {
2601: if (ref($rules) eq 'ARRAY') {
2602: @{$rules} = map {&escape($_);} (@{$rules});
2603: my $rulestr = join(':',@{$rules});
2604: my $homeserver=&domain($udom,'primary');
2605: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2606: my $response;
2607: if ($item eq 'username') {
2608: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2609: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2610: $homeserver));
1.923 raeburn 2611: } elsif ($item eq 'id') {
2612: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2613: ':'.&escape($id).':'.$rulestr,
2614: $homeserver));
1.945 raeburn 2615: } elsif ($item eq 'selfcreate') {
2616: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2617: &escape($udom).':'.&escape($uname).
2618: ':'.$rulestr,$homeserver));
1.1484 raeburn 2619: } elsif ($item eq 'unamemap') {
2620: $response=&unescape(&reply('instunamemapcheck:'.
2621: &escape($udom).':'.&escape($uname).
2622: ':'.$rulestr,$homeserver));
1.923 raeburn 2623: }
1.912 raeburn 2624: if ($response ne 'refused') {
2625: my @pairs=split(/\&/,$response);
2626: foreach my $item (@pairs) {
2627: my ($key,$value)=split(/=/,$item,2);
2628: $key = &unescape($key);
2629: next if ($key =~ /^error: 2 /);
2630: $returnhash{$key}=&thaw_unescape($value);
2631: }
2632: }
2633: }
2634: }
2635: }
2636: return %returnhash;
2637: }
2638:
2639: sub inst_userrules {
1.923 raeburn 2640: my ($udom,$check) = @_;
1.912 raeburn 2641: my (%ruleshash,@ruleorder);
2642: if ($udom ne '') {
2643: my $homeserver=&domain($udom,'primary');
2644: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2645: my $response;
2646: if ($check eq 'id') {
2647: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2648: $homeserver);
1.943 raeburn 2649: } elsif ($check eq 'email') {
2650: $response=&reply('instemailrules:'.&escape($udom),
2651: $homeserver);
1.1484 raeburn 2652: } elsif ($check eq 'unamemap') {
2653: $response=&reply('unamemaprules:'.&escape($udom),
2654: $homeserver);
1.923 raeburn 2655: } else {
2656: $response=&reply('instuserrules:'.&escape($udom),
2657: $homeserver);
2658: }
1.912 raeburn 2659: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2660: ($response ne 'unknown_cmd') &&
1.912 raeburn 2661: ($response ne 'no_such_host')) {
2662: my ($hashitems,$orderitems) = split(/:/,$response);
2663: my @pairs=split(/\&/,$hashitems);
2664: foreach my $item (@pairs) {
2665: my ($key,$value)=split(/=/,$item,2);
2666: $key = &unescape($key);
2667: next if ($key =~ /^error: 2 /);
2668: $ruleshash{$key}=&thaw_unescape($value);
2669: }
2670: my @esc_order = split(/\&/,$orderitems);
2671: foreach my $item (@esc_order) {
2672: push(@ruleorder,&unescape($item));
2673: }
2674: }
2675: }
2676: }
2677: return (\%ruleshash,\@ruleorder);
2678: }
2679:
1.976 raeburn 2680: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2681:
2682: sub get_domain_defaults {
1.1240 raeburn 2683: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2684: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2685: my $cachetime = 60*60*24;
1.1240 raeburn 2686: unless ($ignore_cache) {
2687: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2688: if (defined($cached)) {
2689: if (ref($result) eq 'HASH') {
2690: return %{$result};
2691: }
1.943 raeburn 2692: }
2693: }
2694: my %domdefaults;
2695: my %domconfig =
1.1494 raeburn 2696: &get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2697: 'requestcourses','inststatus',
1.1183 raeburn 2698: 'coursedefaults','usersessions',
1.1258 raeburn 2699: 'requestauthor','selfenrollment',
1.1320 raeburn 2700: 'coursecategories','ssl','autoenroll',
1.1504 raeburn 2701: 'trust','helpsettings','wafproxy',
2702: 'ltisec','toolsec'],$domain);
1.1305 raeburn 2703: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2704: if (ref($domconfig{'defaults'}) eq 'HASH') {
2705: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2706: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2707: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2708: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2709: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2710: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1492 raeburn 2711: $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
2712: $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
1.1340 raeburn 2713: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2714: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2715: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1484 raeburn 2716: $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943 raeburn 2717: } else {
2718: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2719: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2720: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2721: }
1.976 raeburn 2722: if (ref($domconfig{'quotas'}) eq 'HASH') {
2723: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2724: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2725: } else {
2726: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2727: }
1.1177 raeburn 2728: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2729: foreach my $item (@usertools) {
2730: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2731: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2732: }
2733: }
1.1229 raeburn 2734: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2735: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2736: }
1.976 raeburn 2737: }
1.985 raeburn 2738: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2739: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2740: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2741: }
2742: }
1.1183 raeburn 2743: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2744: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2745: }
1.989 raeburn 2746: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2747: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2748: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2749: }
2750: }
1.1047 raeburn 2751: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2752: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2753: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1476 raeburn 2754: $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1277 raeburn 2755: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2756: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2757: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2758: }
1.1254 raeburn 2759: foreach my $type (@coursetypes) {
2760: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2761: unless ($type eq 'community') {
2762: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2763: }
2764: }
2765: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2766: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2767: }
1.1277 raeburn 2768: if ($domdefaults{'postsubmit'} eq 'on') {
2769: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2770: $domdefaults{$type.'postsubtimeout'} =
2771: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2772: }
2773: }
1.1230 raeburn 2774: }
1.1286 raeburn 2775: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2776: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2777: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2778: if (@clonecodes) {
2779: $domdefaults{'canclone'} = join('+',@clonecodes);
2780: }
2781: }
2782: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2783: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2784: }
1.1356 raeburn 2785: if ($domconfig{'coursedefaults'}{'texengine'}) {
2786: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
1.1480 raeburn 2787: }
2788: if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
2789: $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
2790: }
1.1047 raeburn 2791: }
1.1073 raeburn 2792: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2793: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2794: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2795: }
2796: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2797: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2798: }
1.1279 raeburn 2799: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2800: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2801: }
1.1440 raeburn 2802: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439 raeburn 2803: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2804: }
1.1073 raeburn 2805: }
1.1254 raeburn 2806: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2807: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2808: my @settings = ('types','registered','enroll_dates','access_dates','section',
2809: 'approval','limit');
2810: foreach my $type (@coursetypes) {
2811: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2812: my @mgrdc = ();
2813: foreach my $item (@settings) {
2814: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2815: push(@mgrdc,$item);
2816: }
2817: }
2818: if (@mgrdc) {
2819: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2820: }
2821: }
2822: }
2823: }
2824: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2825: foreach my $type (@coursetypes) {
2826: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2827: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2828: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2829: }
2830: }
2831: }
2832: }
2833: }
1.1258 raeburn 2834: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2835: $domdefaults{'catauth'} = 'std';
2836: $domdefaults{'catunauth'} = 'std';
1.1413 raeburn 2837: if ($domconfig{'coursecategories'}{'auth'}) {
1.1258 raeburn 2838: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2839: }
2840: if ($domconfig{'coursecategories'}{'unauth'}) {
2841: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2842: }
2843: }
1.1315 raeburn 2844: if (ref($domconfig{'ssl'}) eq 'HASH') {
2845: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2846: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2847: }
1.1338 raeburn 2848: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2849: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2850: }
2851: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2852: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315 raeburn 2853: }
2854: }
1.1320 raeburn 2855: if (ref($domconfig{'trust'}) eq 'HASH') {
2856: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2857: foreach my $prefix (@prefixes) {
2858: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2859: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2860: }
2861: }
2862: }
1.1314 raeburn 2863: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2864: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1477 raeburn 2865: $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1314 raeburn 2866: }
1.1332 raeburn 2867: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2868: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2869: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2870: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2871: }
2872: }
1.1434 raeburn 2873: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1449 raeburn 2874: foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
1.1434 raeburn 2875: if ($domconfig{'wafproxy'}{$item}) {
2876: $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
2877: }
2878: }
1.1482 raeburn 2879: }
2880: if (ref($domconfig{'ltisec'}) eq 'HASH') {
2881: if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
2882: $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
2883: $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
2884: $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
2885: }
2886: if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
2887: if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
1.1504 raeburn 2888: $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
2889: }
2890: }
2891: }
2892: if (ref($domconfig{'toolsec'}) eq 'HASH') {
2893: if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
2894: $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
2895: $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
2896: }
2897: if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
2898: if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
2899: $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
1.1482 raeburn 2900: }
2901: }
2902: }
1.1219 raeburn 2903: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2904: return %domdefaults;
2905: }
2906:
1.1412 raeburn 2907: sub get_dom_cats {
2908: my ($dom) = @_;
2909: return unless (&domain($dom));
2910: my ($cats,$cached)=&is_cached_new('cats',$dom);
2911: unless (defined($cached)) {
2912: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2913: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2914: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2915: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2916: } else {
2917: $cats = {};
2918: }
2919: } else {
2920: $cats = {};
2921: }
1.1494 raeburn 2922: &do_cache_new('cats',$dom,$cats,3600);
1.1412 raeburn 2923: }
1.1413 raeburn 2924: return $cats;
2925: }
2926:
2927: sub get_dom_instcats {
2928: my ($dom) = @_;
2929: return unless (&domain($dom));
2930: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2931: unless (defined($cached)) {
2932: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2933: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2934: if ($totcodes > 0) {
2935: my $caller = 'global';
2936: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2937: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2938: $instcats = {
1.1503 raeburn 2939: totcodes => $totcodes,
1.1413 raeburn 2940: codes => \%codes,
2941: codetitles => \@codetitles,
2942: cat_titles => \%cat_titles,
2943: cat_order => \%cat_order,
2944: };
2945: &do_cache_new('instcats',$dom,$instcats,3600);
2946: }
2947: }
2948: }
2949: return $instcats;
2950: }
2951:
2952: sub retrieve_instcodes {
2953: my ($coursecodes,$dom) = @_;
2954: my $totcodes;
2955: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2956: foreach my $course (keys(%courses)) {
2957: if (ref($courses{$course}) eq 'HASH') {
2958: if ($courses{$course}{'inst_code'} ne '') {
2959: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2960: $totcodes ++;
2961: }
2962: }
2963: }
2964: return $totcodes;
1.1412 raeburn 2965: }
2966:
1.1311 raeburn 2967: sub course_portal_url {
1.1451 raeburn 2968: my ($cnum,$cdom,$r) = @_;
1.1311 raeburn 2969: my $chome = &homeserver($cnum,$cdom);
2970: my $hostname = &hostname($chome);
2971: my $protocol = $protocol{$chome};
2972: $protocol = 'http' if ($protocol ne 'https');
2973: my %domdefaults = &get_domain_defaults($cdom);
2974: my $firsturl;
2975: if ($domdefaults{'portal_def'}) {
2976: $firsturl = $domdefaults{'portal_def'};
2977: } else {
1.1494 raeburn 2978: my $alias = &use_proxy_alias($r,$chome);
1.1451 raeburn 2979: $hostname = $alias if ($alias ne '');
1.1311 raeburn 2980: $firsturl = $protocol.'://'.$hostname;
2981: }
2982: return $firsturl;
2983: }
2984:
1.1492 raeburn 2985: sub url_prefix {
2986: my ($r,$dom,$home,$context) = @_;
2987: my $prefix;
2988: my %domdefs = &get_domain_defaults($dom);
2989: if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
2990: if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
2991: $prefix = $1;
2992: }
2993: }
2994: if ($prefix eq '') {
2995: my $hostname = &hostname($home);
2996: my $protocol = $protocol{$home};
2997: $protocol = 'http' if ($protocol{$home} ne 'https');
2998: my $alias = &use_proxy_alias($r,$home);
2999: $hostname = $alias if ($alias ne '');
3000: $prefix = $protocol.'://'.$hostname;
3001: }
3002: return $prefix;
3003: }
3004:
1.1407 raeburn 3005: # --------------------------------------------- Get domain config for passwords
3006:
3007: sub get_passwdconf {
3008: my ($dom) = @_;
3009: my (%passwdconf,$gotconf,$lookup);
3010: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
3011: if (defined($cached)) {
3012: if (ref($result) eq 'HASH') {
3013: %passwdconf = %{$result};
3014: $gotconf = 1;
3015: }
3016: }
3017: unless ($gotconf) {
3018: my %domconfig = &get_dom('configuration',['passwords'],$dom);
3019: if (ref($domconfig{'passwords'}) eq 'HASH') {
3020: %passwdconf = %{$domconfig{'passwords'}};
3021: }
3022: my $cachetime = 24*60*60;
3023: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
3024: }
3025: return %passwdconf;
3026: }
3027:
1.344 www 3028: # --------------------------------------------------- Assign a key to a student
3029:
3030: sub assign_access_key {
1.364 www 3031: #
3032: # a valid key looks like uname:udom#comments
3033: # comments are being appended
3034: #
1.498 www 3035: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
3036: $kdom=
1.620 albertel 3037: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 3038: $knum=
1.620 albertel 3039: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 3040: $cdom=
1.620 albertel 3041: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3042: $cnum=
1.620 albertel 3043: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3044: $udom=$env{'user.name'} unless (defined($udom));
3045: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 3046: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 3047: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 3048: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 3049: # assigned to this person
3050: # - this should not happen,
1.345 www 3051: # unless something went wrong
3052: # the first time around
3053: # ready to assign
1.364 www 3054: $logentry=$1.'; '.$logentry;
1.496 www 3055: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 3056: $kdom,$knum) eq 'ok') {
1.345 www 3057: # key now belongs to user
1.346 www 3058: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 3059: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 3060: &appenv({'environment.'.$envkey => $ckey});
1.345 www 3061: return 'ok';
3062: } else {
3063: return
3064: 'error: Count not permanently assign key, will need to be re-entered later.';
3065: }
3066: } else {
3067: return 'error: Could not assign key, try again later.';
3068: }
1.364 www 3069: } elsif (!$existing{$ckey}) {
1.345 www 3070: # the key does not exist
3071: return 'error: The key does not exist';
3072: } else {
3073: # the key is somebody else's
3074: return 'error: The key is already in use';
3075: }
1.344 www 3076: }
3077:
1.364 www 3078: # ------------------------------------------ put an additional comment on a key
3079:
3080: sub comment_access_key {
3081: #
3082: # a valid key looks like uname:udom#comments
3083: # comments are being appended
3084: #
3085: my ($ckey,$cdom,$cnum,$logentry)=@_;
3086: $cdom=
1.620 albertel 3087: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 3088: $cnum=
1.620 albertel 3089: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 3090: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
3091: if ($existing{$ckey}) {
3092: $existing{$ckey}.='; '.$logentry;
3093: # ready to assign
1.367 www 3094: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 3095: $cdom,$cnum) eq 'ok') {
3096: return 'ok';
3097: } else {
3098: return 'error: Count not store comment.';
3099: }
3100: } else {
3101: # the key does not exist
3102: return 'error: The key does not exist';
3103: }
3104: }
3105:
1.344 www 3106: # ------------------------------------------------------ Generate a set of keys
3107:
3108: sub generate_access_keys {
1.364 www 3109: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 3110: $cdom=
1.620 albertel 3111: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3112: $cnum=
1.620 albertel 3113: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 3114: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 3115: unless (($cdom) && ($cnum)) { return 0; }
3116: if ($number>10000) { return 0; }
3117: sleep(2); # make sure don't get same seed twice
3118: srand(time()^($$+($$<<15))); # from "Programming Perl"
3119: my $total=0;
3120: for (my $i=1;$i<=$number;$i++) {
3121: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
3122: sprintf("%lx",int(100000*rand)).'-'.
3123: sprintf("%lx",int(100000*rand));
3124: $newkey=~s/1/g/g; # folks mix up 1 and l
3125: $newkey=~s/0/h/g; # and also 0 and O
3126: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
3127: if ($existing{$newkey}) {
3128: $i--;
3129: } else {
1.364 www 3130: if (&put('accesskeys',
3131: { $newkey => '# generated '.localtime().
1.620 albertel 3132: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 3133: '; '.$logentry },
3134: $cdom,$cnum) eq 'ok') {
1.344 www 3135: $total++;
3136: }
3137: }
3138: }
1.620 albertel 3139: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 3140: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
3141: return $total;
3142: }
3143:
3144: # ------------------------------------------------------- Validate an accesskey
3145:
3146: sub validate_access_key {
3147: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
3148: $cdom=
1.620 albertel 3149: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3150: $cnum=
1.620 albertel 3151: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3152: $udom=$env{'user.domain'} unless (defined($udom));
3153: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 3154: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 3155: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 3156: }
3157:
3158: # ------------------------------------- Find the section of student in a course
1.652 albertel 3159: sub devalidate_getsection_cache {
3160: my ($udom,$unam,$courseid)=@_;
3161: my $hashid="$udom:$unam:$courseid";
3162: &devalidate_cache_new('getsection',$hashid);
3163: }
1.298 matthew 3164:
1.815 albertel 3165: sub courseid_to_courseurl {
3166: my ($courseid) = @_;
3167: #already url style courseid
3168: return $courseid if ($courseid =~ m{^/});
3169:
3170: if (exists($env{'course.'.$courseid.'.num'})) {
3171: my $cnum = $env{'course.'.$courseid.'.num'};
3172: my $cdom = $env{'course.'.$courseid.'.domain'};
3173: return "/$cdom/$cnum";
3174: }
3175:
1.1494 raeburn 3176: my %courseinfo=&coursedescription($courseid);
1.815 albertel 3177: if (exists($courseinfo{'num'})) {
3178: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
3179: }
3180:
3181: return undef;
3182: }
3183:
1.298 matthew 3184: sub getsection {
3185: my ($udom,$unam,$courseid)=@_;
1.599 albertel 3186: my $cachetime=1800;
1.551 albertel 3187:
3188: my $hashid="$udom:$unam:$courseid";
1.599 albertel 3189: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 3190: if (defined($cached)) { return $result; }
3191:
1.298 matthew 3192: my %Pending;
3193: my %Expired;
3194: #
3195: # Each role can either have not started yet (pending), be active,
3196: # or have expired.
3197: #
3198: # If there is an active role, we are done.
3199: #
3200: # If there is more than one role which has not started yet,
3201: # choose the one which will start sooner
3202: # If there is one role which has not started yet, return it.
3203: #
3204: # If there is more than one expired role, choose the one which ended last.
3205: # If there is a role which has expired, return it.
3206: #
1.815 albertel 3207: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 3208: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 3209: foreach my $key (keys(%roleshash)) {
1.479 albertel 3210: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 3211: my $section=$1;
3212: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 3213: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 3214: my $now=time;
1.548 albertel 3215: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 3216: $Expired{$end}=$section;
3217: next;
3218: }
1.548 albertel 3219: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 3220: $Pending{$start}=$section;
3221: next;
3222: }
1.599 albertel 3223: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 3224: }
3225: #
3226: # Presumedly there will be few matching roles from the above
3227: # loop and the sorting time will be negligible.
3228: if (scalar(keys(%Pending))) {
3229: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 3230: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 3231: }
3232: if (scalar(keys(%Expired))) {
3233: my @sorted = sort {$a <=> $b} keys(%Expired);
3234: my $time = pop(@sorted);
1.599 albertel 3235: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 3236: }
1.599 albertel 3237: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 3238: }
1.70 www 3239:
1.599 albertel 3240: sub save_cache {
3241: &purge_remembered();
1.722 albertel 3242: #&Apache::loncommon::validate_page();
1.620 albertel 3243: undef(%env);
1.780 albertel 3244: undef($env_loaded);
1.599 albertel 3245: }
1.452 albertel 3246:
1.599 albertel 3247: my $to_remember=-1;
3248: my %remembered;
3249: my %accessed;
3250: my $kicks=0;
3251: my $hits=0;
1.849 albertel 3252: sub make_key {
3253: my ($name,$id) = @_;
1.872 albertel 3254: if (length($id) > 65
3255: && length(&escape($id)) > 200) {
3256: $id=length($id).':'.&Digest::MD5::md5_hex($id);
3257: }
1.849 albertel 3258: return &escape($name.':'.$id);
3259: }
3260:
1.599 albertel 3261: sub devalidate_cache_new {
3262: my ($name,$id,$debug) = @_;
3263: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 3264: my $remembered_id=$name.':'.$id;
1.849 albertel 3265: $id=&make_key($name,$id);
1.599 albertel 3266: $memcache->delete($id);
1.1319 damieng 3267: delete($remembered{$remembered_id});
3268: delete($accessed{$remembered_id});
1.599 albertel 3269: }
3270:
3271: sub is_cached_new {
3272: my ($name,$id,$debug) = @_;
1.1319 damieng 3273: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
3274: if (exists($remembered{$remembered_id})) {
3275: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
3276: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3277: $hits++;
1.1319 damieng 3278: return ($remembered{$remembered_id},1);
1.599 albertel 3279: }
1.1319 damieng 3280: $id=&make_key($name,$id);
1.599 albertel 3281: my $value = $memcache->get($id);
3282: if (!(defined($value))) {
3283: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 3284: return (undef,undef);
1.416 albertel 3285: }
1.599 albertel 3286: if ($value eq '__undef__') {
3287: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3288: $value=undef;
3289: }
1.1319 damieng 3290: &make_room($remembered_id,$value,$debug);
1.599 albertel 3291: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3292: return ($value,1);
3293: }
3294:
3295: sub do_cache_new {
3296: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 3297: my $remembered_id=$name.':'.$id;
1.849 albertel 3298: $id=&make_key($name,$id);
1.599 albertel 3299: my $setvalue=$value;
3300: if (!defined($setvalue)) {
3301: $setvalue='__undef__';
3302: }
1.623 albertel 3303: if (!defined($time) ) {
3304: $time=600;
3305: }
1.599 albertel 3306: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 3307: my $result = $memcache->set($id,$setvalue,$time);
3308: if (! $result) {
1.872 albertel 3309: &logthis("caching of id -> $id failed");
1.910 albertel 3310: $memcache->disconnect_all();
1.872 albertel 3311: }
1.600 albertel 3312: # need to make a copy of $value
1.1319 damieng 3313: &make_room($remembered_id,$value,$debug);
1.599 albertel 3314: return $value;
3315: }
3316:
3317: sub make_room {
1.1319 damieng 3318: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 3319:
1.1319 damieng 3320: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 3321: : $value;
1.599 albertel 3322: if ($to_remember<0) { return; }
1.1319 damieng 3323: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3324: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3325: my $to_kick;
3326: my $max_time=0;
3327: foreach my $other (keys(%accessed)) {
3328: if (&tv_interval($accessed{$other}) > $max_time) {
3329: $to_kick=$other;
3330: $max_time=&tv_interval($accessed{$other});
3331: }
3332: }
3333: delete($remembered{$to_kick});
3334: delete($accessed{$to_kick});
3335: $kicks++;
3336: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 3337: return;
3338: }
3339:
1.599 albertel 3340: sub purge_remembered {
1.604 albertel 3341: #&logthis("Tossing ".scalar(keys(%remembered)));
3342: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 3343: undef(%remembered);
3344: undef(%accessed);
1.428 albertel 3345: }
1.70 www 3346: # ------------------------------------- Read an entry from a user's environment
3347:
3348: sub userenvironment {
3349: my ($udom,$unam,@what)=@_;
1.976 raeburn 3350: my $items;
3351: foreach my $item (@what) {
3352: $items.=&escape($item).'&';
3353: }
3354: $items=~s/\&$//;
1.70 www 3355: my %returnhash=();
1.1009 raeburn 3356: my $uhome = &homeserver($unam,$udom);
3357: unless ($uhome eq 'no_host') {
3358: my @answer=split(/\&/,
3359: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 3360: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3361: return %returnhash;
3362: }
1.1009 raeburn 3363: my $i;
3364: for ($i=0;$i<=$#what;$i++) {
3365: $returnhash{$what[$i]}=&unescape($answer[$i]);
3366: }
1.70 www 3367: }
3368: return %returnhash;
1.1 albertel 3369: }
3370:
1.617 albertel 3371: # ---------------------------------------------------------- Get a studentphoto
3372: sub studentphoto {
3373: my ($udom,$unam,$ext) = @_;
1.1494 raeburn 3374: my $home=&homeserver($unam,$udom);
1.706 raeburn 3375: if (defined($env{'request.course.id'})) {
1.708 raeburn 3376: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 3377: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3378: return(&retrievestudentphoto($udom,$unam,$ext));
3379: } else {
3380: my ($result,$perm_reqd)=
1.1494 raeburn 3381: &auto_photo_permission($unam,$udom);
1.706 raeburn 3382: if ($result eq 'ok') {
3383: if (!($perm_reqd eq 'yes')) {
3384: return(&retrievestudentphoto($udom,$unam,$ext));
3385: }
3386: }
3387: }
3388: }
3389: } else {
3390: my ($result,$perm_reqd) =
1.1494 raeburn 3391: &auto_photo_permission($unam,$udom);
1.706 raeburn 3392: if ($result eq 'ok') {
3393: if (!($perm_reqd eq 'yes')) {
3394: return(&retrievestudentphoto($udom,$unam,$ext));
3395: }
3396: }
3397: }
3398: return '/adm/lonKaputt/lonlogo_broken.gif';
3399: }
3400:
3401: sub retrievestudentphoto {
3402: my ($udom,$unam,$ext,$type) = @_;
1.1494 raeburn 3403: my $home=&homeserver($unam,$udom);
3404: my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
1.706 raeburn 3405: if ($ret eq 'ok') {
3406: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3407: if ($type eq 'thumbnail') {
3408: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3409: }
1.1494 raeburn 3410: my $tokenurl=&tokenwrapper($url);
1.706 raeburn 3411: return $tokenurl;
3412: } else {
3413: if ($type eq 'thumbnail') {
3414: return '/adm/lonKaputt/genericstudent_tn.gif';
3415: } else {
3416: return '/adm/lonKaputt/lonlogo_broken.gif';
3417: }
1.617 albertel 3418: }
3419: }
3420:
1.263 www 3421: # -------------------------------------------------------------------- New chat
3422:
3423: sub chatsend {
1.724 raeburn 3424: my ($newentry,$anon,$group)=@_;
1.620 albertel 3425: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3426: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3427: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 3428: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 3429: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 3430: &escape($newentry)).':'.$group,$chome);
1.292 www 3431: }
3432:
3433: # ------------------------------------------ Find current version of a resource
3434:
3435: sub getversion {
3436: my $fname=&clutter(shift);
1.1189 raeburn 3437: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3438: return ¤tversion(&filelocation('',$fname));
3439: }
3440:
3441: sub currentversion {
3442: my $fname=shift;
3443: my $author=$fname;
3444: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3445: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3446: my $home=&homeserver($uname,$udom);
1.292 www 3447: if ($home eq 'no_host') {
3448: return -1;
3449: }
1.1112 www 3450: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3451: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3452: return -1;
3453: }
1.1112 www 3454: return $answer;
1.263 www 3455: }
3456:
1.1111 www 3457: #
3458: # Return special version number of resource if set by override, empty otherwise
3459: #
3460: sub usedversion {
3461: my $fname=shift;
3462: unless ($fname) { $fname=$env{'request.uri'}; }
3463: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3464: if ($urlversion) { return $urlversion; }
3465: return '';
3466: }
3467:
1.1 albertel 3468: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3469:
1.1 albertel 3470: sub subscribe {
3471: my $fname=shift;
1.761 raeburn 3472: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3473: $fname=~s/[\n\r]//g;
1.1 albertel 3474: my $author=$fname;
3475: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3476: my ($udom,$uname)=split(/\//,$author);
3477: my $home=homeserver($uname,$udom);
1.335 albertel 3478: if ($home eq 'no_host') {
3479: return 'not_found';
1.1 albertel 3480: }
3481: my $answer=reply("sub:$fname",$home);
1.64 www 3482: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3483: $answer.=' by '.$home;
3484: }
1.1 albertel 3485: return $answer;
3486: }
3487:
1.8 www 3488: # -------------------------------------------------------------- Replicate file
3489:
3490: sub repcopy {
3491: my $filename=shift;
1.23 www 3492: $filename=~s/\/+/\//g;
1.1142 raeburn 3493: my $londocroot = $perlvar{'lonDocRoot'};
3494: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3495: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3496: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3497: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3498: return &repcopy_userfile($filename);
3499: }
1.532 albertel 3500: $filename=~s/[\n\r]//g;
1.8 www 3501: my $transname="$filename.in.transfer";
1.828 www 3502: # FIXME: this should flock
1.607 raeburn 3503: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3504: my $remoteurl=subscribe($filename);
1.64 www 3505: if ($remoteurl =~ /^con_lost by/) {
3506: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3507: return 'unavailable';
1.8 www 3508: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3509: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3510: return 'not_found';
1.64 www 3511: } elsif ($remoteurl =~ /^rejected by/) {
3512: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3513: return 'forbidden';
1.20 www 3514: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3515: return 'ok';
1.8 www 3516: } else {
1.290 www 3517: my $author=$filename;
3518: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3519: my ($udom,$uname)=split(/\//,$author);
3520: my $home=homeserver($uname,$udom);
3521: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3522: my @parts=split(/\//,$filename);
3523: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3524: if ($path ne "$londocroot/res") {
1.8 www 3525: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3526: return 'bad_request';
1.8 www 3527: }
3528: my $count;
3529: for ($count=5;$count<$#parts;$count++) {
3530: $path.="/$parts[$count]";
3531: if ((-e $path)!=1) {
3532: mkdir($path,0777);
3533: }
3534: }
3535: my $request=new HTTP::Request('GET',"$remoteurl");
1.1345 raeburn 3536: my $response;
3537: if ($remoteurl =~ m{/raw/}) {
3538: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3539: } else {
3540: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3541: }
1.8 www 3542: if ($response->is_error()) {
3543: unlink($transname);
3544: my $message=$response->status_line;
1.672 albertel 3545: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3546: ." LWP get: $message: $filename</font>");
1.607 raeburn 3547: return 'unavailable';
1.8 www 3548: } else {
1.16 www 3549: if ($remoteurl!~/\.meta$/) {
3550: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345 raeburn 3551: my $mresponse;
3552: if ($remoteurl =~ m{/raw/}) {
3553: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3554: } else {
3555: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3556: }
1.16 www 3557: if ($mresponse->is_error()) {
3558: unlink($filename.'.meta');
3559: &logthis(
1.672 albertel 3560: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3561: }
3562: }
1.8 www 3563: rename($transname,$filename);
1.607 raeburn 3564: return 'ok';
1.8 www 3565: }
1.290 www 3566: }
1.8 www 3567: }
1.330 www 3568: }
3569:
1.1422 raeburn 3570: # ------------------------------------------------- Unsubscribe from a resource
3571:
3572: sub unsubscribe {
3573: my ($fname) = @_;
3574: my $answer;
3575: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3576: $fname=~s/[\n\r]//g;
3577: my $author=$fname;
3578: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3579: my ($udom,$uname)=split(/\//,$author);
3580: my $home=homeserver($uname,$udom);
3581: if ($home eq 'no_host') {
3582: $answer = 'no_host';
3583: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3584: $answer = 'home';
3585: } else {
3586: my $defdom = $perlvar{'lonDefDomain'};
3587: if (&will_trust('content',$defdom,$udom)) {
3588: $answer = reply("unsub:$fname",$home);
3589: } else {
3590: $answer = 'untrusted';
3591: }
3592: }
3593: return $answer;
3594: }
3595:
1.330 www 3596: # ------------------------------------------------ Get server side include body
3597: sub ssi_body {
1.381 albertel 3598: my ($filelink,%form)=@_;
1.606 matthew 3599: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3600: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3601: }
1.953 www 3602: my $output='';
3603: my $response;
1.980 raeburn 3604: if ($filelink=~/^https?\:/) {
1.954 raeburn 3605: ($output,$response)=&externalssi($filelink);
1.953 www 3606: } else {
1.1004 droeschl 3607: $filelink .= $filelink=~/\?/ ? '&' : '?';
3608: $filelink .= 'inhibitmenu=yes';
1.953 www 3609: ($output,$response)=&ssi($filelink,%form);
3610: }
1.778 albertel 3611: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3612: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3613: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3614: if (wantarray) {
3615: return ($output, $response);
3616: } else {
3617: return $output;
3618: }
1.8 www 3619: }
3620:
1.15 www 3621: # --------------------------------------------------------- Server Side Include
3622:
1.782 albertel 3623: sub absolute_url {
1.1447 raeburn 3624: my ($host_name,$unalias,$keep_proto) = @_;
1.782 albertel 3625: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3626: if ($host_name eq '') {
3627: $host_name = $ENV{'SERVER_NAME'};
3628: }
1.1447 raeburn 3629: if ($unalias) {
3630: my $alias = &get_proxy_alias();
3631: if ($alias eq $host_name) {
3632: my $lonhost = $perlvar{'lonHostID'};
3633: my $hostname = &hostname($lonhost);
3634: my $lcproto;
3635: if (($keep_proto) || ($hostname eq '')) {
3636: $lcproto = $protocol;
3637: } else {
3638: $lcproto = $protocol{$lonhost};
3639: $lcproto = 'http' if ($lcproto ne 'https');
3640: $lcproto .= '://';
3641: }
3642: unless ($hostname eq '') {
3643: return $lcproto.$hostname;
3644: }
3645: }
3646: }
1.782 albertel 3647: return $protocol.$host_name;
3648: }
3649:
1.942 foxr 3650: #
3651: # Server side include.
3652: # Parameters:
3653: # fn Possibly encrypted resource name/id.
3654: # form Hash that describes how the rendering should be done
3655: # and other things.
1.944 foxr 3656: # Returns:
1.950 raeburn 3657: # Scalar context: The content of the response.
3658: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3659: #
1.15 www 3660: sub ssi {
3661:
1.944 foxr 3662: my ($fn,%form)=@_;
1.1447 raeburn 3663: my ($host,$request,$response);
3664: $host = &absolute_url('',1);
1.711 albertel 3665:
3666: $form{'no_update_last_known'}=1;
1.895 albertel 3667: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3668: if (%form) {
1.1447 raeburn 3669: $request=new HTTP::Request('POST',$host.$fn);
1.1272 droeschl 3670: $request->content(join('&',map {
3671: my $name = escape($_);
3672: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3673: ? join("&$name=", map {escape($_) } @{$form{$_}})
3674: : &escape($form{$_}) );
3675: } keys(%form)));
1.23 www 3676: } else {
1.1447 raeburn 3677: $request=new HTTP::Request('GET',$host.$fn);
1.23 www 3678: }
3679:
1.15 www 3680: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345 raeburn 3681: my $lonhost = $perlvar{'lonHostID'};
1.1385 raeburn 3682: my $islocal;
3683: if (($env{'request.course.id'}) &&
3684: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3685: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3686: ($form{'grade_symb'} ne '') &&
1.1494 raeburn 3687: (&allowed('mgr',$env{'request.course.id'}.
3688: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1385 raeburn 3689: $islocal = 1;
3690: }
1.1447 raeburn 3691: $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
3692: '','','',$islocal);
1.1182 foxr 3693:
1.944 foxr 3694: if (wantarray) {
1.1345 raeburn 3695: return ($response->content, $response);
1.944 foxr 3696: } else {
1.1345 raeburn 3697: return $response->content;
1.942 foxr 3698: }
1.324 www 3699: }
3700:
3701: sub externalssi {
3702: my ($url)=@_;
3703: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 3704: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954 raeburn 3705: if (wantarray) {
3706: return ($response->content, $response);
3707: } else {
3708: return $response->content;
3709: }
1.15 www 3710: }
1.254 www 3711:
1.1354 raeburn 3712:
3713: # If the local copy of a replicated resource is outdated, trigger a
3714: # connection from the homeserver to flush the delayed queue. If no update
3715: # happens, remove local copies of outdated resource (and corresponding
3716: # metadata file).
3717:
1.1352 raeburn 3718: sub remove_stale_resfile {
3719: my ($url) = @_;
1.1354 raeburn 3720: my $removed;
1.1352 raeburn 3721: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3722: my $audom = $1;
3723: my $auname = $2;
1.1353 raeburn 3724: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352 raeburn 3725: my $homeserver = &homeserver($auname,$audom);
3726: unless (($homeserver eq 'no_host') ||
3727: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3728: my $fname = &filelocation('',$url);
3729: if (-e $fname) {
3730: my $hostname = &hostname($homeserver);
3731: if ($hostname) {
1.1397 raeburn 3732: my $protocol = $protocol{$homeserver};
3733: $protocol = 'http' if ($protocol ne 'https');
1.1352 raeburn 3734: my $uri = &declutter($url);
3735: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3736: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3737: if ($response->is_success()) {
3738: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3739: my $locmodtime = (stat($fname))[9];
3740: if ($locmodtime < $remmodtime) {
1.1354 raeburn 3741: my $stale;
3742: my $answer = &reply('pong',$homeserver);
3743: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3744: sleep(0.2);
3745: $locmodtime = (stat($fname))[9];
3746: if ($locmodtime < $remmodtime) {
3747: my $posstransfer = $fname.'.in.transfer';
3748: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3749: $removed = 1;
3750: } else {
3751: $stale = 1;
3752: }
3753: } else {
3754: $removed = 1;
3755: }
3756: } else {
3757: $stale = 1;
3758: }
3759: if ($stale) {
1.1421 raeburn 3760: if (unlink($fname)) {
3761: if ($uri!~/\.meta$/) {
3762: if (-e $fname.'.meta') {
3763: unlink($fname.'.meta');
3764: }
3765: }
1.1422 raeburn 3766: my $unsubresult = &unsubscribe($fname);
3767: unless ($unsubresult eq 'ok') {
3768: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3769: }
1.1421 raeburn 3770: $removed = 1;
1.1354 raeburn 3771: }
1.1352 raeburn 3772: }
3773: }
3774: }
3775: }
3776: }
3777: }
3778: }
3779: }
1.1354 raeburn 3780: return $removed;
1.1352 raeburn 3781: }
3782:
1.492 albertel 3783: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3784:
3785: sub allowuploaded {
3786: my ($srcurl,$url)=@_;
3787: $url=&clutter(&declutter($url));
3788: my $dir=$url;
3789: $dir=~s/\/[^\/]+$//;
3790: my %httpref=();
3791: my $httpurl=&hreflocation('',$url);
3792: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3793: &Apache::lonnet::appenv(\%httpref);
1.254 www 3794: }
1.477 raeburn 3795:
1.1193 raeburn 3796: #
3797: # Determine if the current user should be able to edit a particular resource,
3798: # when viewing in course context.
3799: # (a) When viewing resource used to determine if "Edit" item is included in
3800: # Functions.
3801: # (b) When displaying folder contents in course editor, used to determine if
3802: # "Edit" link will be displayed alongside resource.
3803: #
1.1196 raeburn 3804: # input: six args -- filename (decluttered), course number, course domain,
3805: # url, symb (if registered) and group (if this is a group
3806: # item -- e.g., bulletin board, group page etc.).
3807: # output: array of five scalars --
1.1193 raeburn 3808: # $cfile -- url for file editing if editable on current server
3809: # $home -- homeserver of resource (i.e., for author if published,
3810: # or course if uploaded.).
3811: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3812: # $forceedit -- 1 if icon/link should be to go to edit mode
3813: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3814: #
3815:
3816: sub can_edit_resource {
1.1194 raeburn 3817: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3818: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3819: #
3820: # For aboutme pages user can only edit his/her own.
3821: #
1.1199 raeburn 3822: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3823: my ($sdom,$sname) = ($1,$2);
3824: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3825: $home = $env{'user.home'};
3826: $cfile = $resurl;
3827: if ($env{'form.forceedit'}) {
3828: $forceview = 1;
3829: } else {
3830: $forceedit = 1;
3831: }
3832: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3833: } else {
3834: return;
3835: }
3836: }
3837:
3838: if ($env{'request.course.id'}) {
1.1494 raeburn 3839: my $crsedit = &allowed('mdc',$env{'request.course.id'});
1.1194 raeburn 3840: if ($group ne '') {
3841: # if this is a group homepage or group bulletin board, check group privs
3842: my $allowed = 0;
1.1197 raeburn 3843: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3844: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3845: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3846: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3847: $allowed = 1;
3848: }
1.1197 raeburn 3849: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3850: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3851: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3852: $allowed = 1;
3853: }
3854: }
3855: if ($allowed) {
3856: $home=&homeserver($cnum,$cdom);
3857: if ($env{'form.forceedit'}) {
3858: $forceview = 1;
3859: } else {
3860: $forceedit = 1;
3861: }
3862: $cfile = $resurl;
3863: } else {
3864: return;
3865: }
3866: } else {
1.1208 raeburn 3867: if ($resurl =~ m{^/?adm/viewclasslist$}) {
1.1494 raeburn 3868: unless (&allowed('opa',$env{'request.course.id'})) {
1.1208 raeburn 3869: return;
3870: }
3871: } elsif (!$crsedit) {
1.1507 ! raeburn 3872: if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
1.1194 raeburn 3873: #
3874: # No edit allowed where CC has switched to student role.
3875: #
1.1507 ! raeburn 3876: return;
! 3877: } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
! 3878: ($resurl =~ m{^/res/lib/templates/})) {
! 3879: return;
! 3880: }
1.1194 raeburn 3881: }
3882: }
3883: }
3884:
1.1193 raeburn 3885: if ($file ne '') {
3886: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3887: if (&is_course_upload($file,$cnum,$cdom)) {
3888: $uploaded = 1;
3889: $incourse = 1;
1.1193 raeburn 3890: if ($file =~/\.(htm|html|css|js|txt)$/) {
3891: $cfile = &hreflocation('',$file);
1.1201 raeburn 3892: if ($env{'form.forceedit'}) {
3893: $forceview = 1;
3894: } else {
3895: $forceedit = 1;
3896: }
1.1194 raeburn 3897: }
3898: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3899: $incourse = 1;
3900: if ($env{'form.forceedit'}) {
3901: $forceview = 1;
3902: } else {
3903: $forceedit = 1;
3904: }
3905: $cfile = $resurl;
1.1507 ! raeburn 3906: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
1.1194 raeburn 3907: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3908: $incourse = 1;
3909: if ($env{'form.forceedit'}) {
3910: $forceview = 1;
3911: } else {
3912: $forceedit = 1;
3913: }
3914: $cfile = $resurl;
1.1199 raeburn 3915: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3916: $incourse = 1;
3917: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3918: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3919: $incourse = 1;
1.1199 raeburn 3920: if ($env{'form.forceedit'}) {
3921: $forceview = 1;
3922: } else {
3923: $forceedit = 1;
3924: }
3925: $cfile = $resurl;
1.1419 raeburn 3926: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3927: my ($map,$id,$res) = &decode_symb($symb);
3928: if ($map =~ /\.page$/) {
3929: $incourse = 1;
3930: if ($env{'form.forceedit'}) {
3931: $forceview = 1;
3932: $cfile = $map;
3933: } else {
3934: $forceedit = 1;
3935: $cfile = '/adm/wrapper'.$resurl;
3936: }
3937: }
1.1343 raeburn 3938: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3939: $incourse = 1;
3940: if ($env{'form.forceedit'}) {
3941: $forceview = 1;
3942: } else {
3943: $forceedit = 1;
3944: }
3945: $cfile = $resurl;
1.1208 raeburn 3946: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3947: $incourse = 1;
3948: if ($env{'form.forceedit'}) {
3949: $forceview = 1;
3950: } else {
3951: $forceedit = 1;
3952: }
3953: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3954: }
3955: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3956: my $template = '/res/lib/templates/simpleproblem.problem';
3957: if (&is_on_map($template)) {
3958: $incourse = 1;
3959: $forceview = 1;
3960: $cfile = $template;
1.1193 raeburn 3961: }
1.1199 raeburn 3962: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418 raeburn 3963: $incourse = 1;
3964: if ($env{'form.forceedit'}) {
3965: $forceview = 1;
3966: } else {
3967: $forceedit = 1;
3968: }
3969: $cfile = $resurl;
1.1343 raeburn 3970: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298 raeburn 3971: $incourse = 1;
3972: if ($env{'form.forceedit'}) {
3973: $forceview = 1;
3974: } else {
3975: $forceedit = 1;
3976: }
3977: $cfile = $resurl;
1.1199 raeburn 3978: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3979: $incourse = 1;
3980: $forceview = 1;
3981: if ($symb) {
3982: my ($map,$id,$res)=&decode_symb($symb);
3983: $env{'request.symb'} = $symb;
3984: $cfile = &clutter($res);
3985: } else {
3986: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3987: my $escfile = &unescape($cfile);
1.1343 raeburn 3988: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3989: $cfile = '/adm/wrapper'.$escfile;
3990: } else {
3991: $escfile =~ s{^http://}{};
3992: $cfile = &escape("/adm/wrapper/ext/$escfile");
3993: }
1.1199 raeburn 3994: }
1.1234 raeburn 3995: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3996: if ($env{'form.forceedit'}) {
3997: $forceview = 1;
3998: } else {
3999: $forceedit = 1;
4000: }
4001: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 4002: }
4003: }
1.1194 raeburn 4004: if ($uploaded || $incourse) {
4005: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 4006: } elsif ($file !~ m{/$}) {
1.1193 raeburn 4007: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
4008: $file=~s{^($match_domain/$match_username)}{/priv/$1};
4009: # Check that the user has permission to edit this resource
4010: my $setpriv = 1;
4011: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
4012: if (defined($cfudom)) {
4013: $home=&homeserver($cfuname,$cfudom);
4014: $cfile=$file;
4015: }
4016: }
1.1194 raeburn 4017: if (($cfile ne '') && (!$incourse || $uploaded) &&
4018: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 4019: my @ids=¤t_machine_ids();
4020: unless (grep(/^\Q$home\E$/,@ids)) {
4021: $switchserver=1;
4022: }
4023: }
4024: }
1.1194 raeburn 4025: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 4026: }
4027:
4028: sub is_course_upload {
4029: my ($file,$cnum,$cdom) = @_;
4030: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
4031: $uploadpath =~ s{^\/}{};
1.1201 raeburn 4032: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
4033: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 4034: return 1;
4035: }
4036: return;
4037: }
4038:
1.1194 raeburn 4039: sub in_course {
1.1195 raeburn 4040: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
4041: if ($hideprivileged) {
4042: my $skipuser;
1.1219 raeburn 4043: my %coursehash = &coursedescription($cdom.'_'.$cnum);
4044: my @possdoms = ($cdom);
4045: if ($coursehash{'checkforpriv'}) {
4046: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4047: }
4048: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 4049: $skipuser = 1;
4050: if ($coursehash{'nothideprivileged'}) {
4051: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4052: my $user;
4053: if ($item =~ /:/) {
4054: $user = $item;
4055: } else {
4056: $user = join(':',split(/[\@]/,$item));
4057: }
4058: if ($user eq $uname.':'.$udom) {
4059: undef($skipuser);
4060: last;
4061: }
4062: }
4063: }
4064: if ($skipuser) {
4065: return 0;
4066: }
4067: }
4068: }
1.1194 raeburn 4069: $type ||= 'any';
4070: if (!defined($cdom) || !defined($cnum)) {
4071: my $cid = $env{'request.course.id'};
4072: $cdom = $env{'course.'.$cid.'.domain'};
4073: $cnum = $env{'course.'.$cid.'.num'};
4074: }
4075: my $typesref;
1.1195 raeburn 4076: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 4077: $typesref = ['active','previous','future'];
4078: } elsif ($type eq 'previous' || $type eq 'future') {
4079: $typesref = [$type];
4080: }
4081: my %roles = &get_my_roles($uname,$udom,'userroles',
4082: $typesref,undef,[$cdom]);
4083: my ($tmp) = keys(%roles);
4084: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
4085: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
4086: if (@course_roles > 0) {
4087: return 1;
4088: }
4089: return 0;
4090: }
4091:
1.478 albertel 4092: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 4093: # input: action, courseID, current domain, intended
1.637 raeburn 4094: # path to file, source of file, instruction to parse file for objects,
4095: # ref to hash for embedded objects,
4096: # ref to hash for codebase of java objects.
1.1095 raeburn 4097: # reference to scalar to accommodate mime type determined
4098: # from File::MMagic if $parser = parse.
1.637 raeburn 4099: #
1.485 raeburn 4100: # output: url to file (if action was uploaddoc),
4101: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 4102: #
1.478 albertel 4103: # Allows directory structure to be used within lonUsers/../userfiles/ for a
4104: # course.
1.477 raeburn 4105: #
1.478 albertel 4106: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4107: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
4108: # course's home server.
1.477 raeburn 4109: #
1.478 albertel 4110: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
4111: # be copied from $source (current location) to
4112: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4113: # and will then be copied to
4114: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
4115: # course's home server.
1.485 raeburn 4116: #
1.481 raeburn 4117: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 4118: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 4119: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4120: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
4121: # in course's home server.
1.637 raeburn 4122: #
1.477 raeburn 4123:
4124: sub process_coursefile {
1.1095 raeburn 4125: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
4126: $mimetype)=@_;
1.477 raeburn 4127: my $fetchresult;
1.638 albertel 4128: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 4129: if ($action eq 'propagate') {
1.638 albertel 4130: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4131: $home);
1.481 raeburn 4132: } else {
1.477 raeburn 4133: my $fpath = '';
4134: my $fname = $file;
1.478 albertel 4135: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 4136: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 4137: my $filepath = &build_filepath($fpath);
1.481 raeburn 4138: if ($action eq 'copy') {
4139: if ($source eq '') {
4140: $fetchresult = 'no source file';
4141: return $fetchresult;
4142: } else {
4143: my $destination = $filepath.'/'.$fname;
4144: rename($source,$destination);
4145: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4146: $home);
1.481 raeburn 4147: }
4148: } elsif ($action eq 'uploaddoc') {
1.1359 raeburn 4149: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 4150: print $fh $env{'form.'.$source};
1.481 raeburn 4151: close($fh);
1.637 raeburn 4152: if ($parser eq 'parse') {
1.1024 raeburn 4153: my $mm = new File::MMagic;
1.1095 raeburn 4154: my $type = $mm->checktype_filename($filepath.'/'.$fname);
4155: if ($type eq 'text/html') {
1.1024 raeburn 4156: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
4157: unless ($parse_result eq 'ok') {
4158: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
4159: }
1.637 raeburn 4160: }
1.1095 raeburn 4161: if (ref($mimetype)) {
4162: $$mimetype = $type;
4163: }
1.637 raeburn 4164: }
1.477 raeburn 4165: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4166: $home);
1.481 raeburn 4167: if ($fetchresult eq 'ok') {
4168: return '/uploaded/'.$fpath.'/'.$fname;
4169: } else {
4170: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4171: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 4172: return '/adm/notfound.html';
4173: }
1.477 raeburn 4174: }
4175: }
1.485 raeburn 4176: unless ( $fetchresult eq 'ok') {
1.477 raeburn 4177: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4178: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 4179: }
4180: return $fetchresult;
4181: }
4182:
1.637 raeburn 4183: sub build_filepath {
4184: my ($fpath) = @_;
4185: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
4186: unless ($fpath eq '') {
4187: my @parts=split('/',$fpath);
4188: foreach my $part (@parts) {
4189: $filepath.= '/'.$part;
4190: if ((-e $filepath)!=1) {
4191: mkdir($filepath,0777);
4192: }
4193: }
4194: }
4195: return $filepath;
4196: }
4197:
4198: sub store_edited_file {
1.638 albertel 4199: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 4200: my $file = $primary_url;
4201: $file =~ s#^/uploaded/$docudom/$docuname/##;
4202: my $fpath = '';
4203: my $fname = $file;
4204: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
4205: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
4206: my $filepath = &build_filepath($fpath);
1.1359 raeburn 4207: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 4208: print $fh $content;
4209: close($fh);
1.638 albertel 4210: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 4211: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4212: $home);
1.637 raeburn 4213: if ($$fetchresult eq 'ok') {
4214: return '/uploaded/'.$fpath.'/'.$fname;
4215: } else {
1.638 albertel 4216: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4217: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 4218: return '/adm/notfound.html';
4219: }
4220: }
4221:
1.531 albertel 4222: sub clean_filename {
1.831 albertel 4223: my ($fname,$args)=@_;
1.315 www 4224: # Replace Windows backslashes by forward slashes
1.257 www 4225: $fname=~s/\\/\//g;
1.831 albertel 4226: if (!$args->{'keep_path'}) {
4227: # Get rid of everything but the actual filename
4228: $fname=~s/^.*\/([^\/]+)$/$1/;
4229: }
1.315 www 4230: # Replace spaces by underscores
4231: $fname=~s/\s+/\_/g;
1.1406 raeburn 4232: # Transliterate non-ascii text to ascii
4233: my $lang = &Apache::lonlocal::current_language();
4234: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 4235: # Replace all other weird characters by nothing
1.831 albertel 4236: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 4237: # Replace all .\d. sequences with _\d. so they no longer look like version
4238: # numbers
4239: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443 raeburn 4240: # Replace three or more adjacent underscores with one for consistency
4241: # with loncfile::filename_check() so complete url can be extracted by
4242: # lonnet::decode_symb()
4243: $fname=~s/_{3,}/_/g;
1.531 albertel 4244: return $fname;
4245: }
1.1406 raeburn 4246:
1.1051 raeburn 4247: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4248: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4249: # image with the same aspect ratio as the original, but with dimensions which do
4250: # not exceed $resizewidth and $resizeheight.
4251:
1.984 neumanie 4252: sub resizeImage {
1.1051 raeburn 4253: my ($img_path,$resizewidth,$resizeheight) = @_;
4254: my $ima = Image::Magick->new;
4255: my $resized;
4256: if (-e $img_path) {
4257: $ima->Read($img_path);
4258: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4259: my $width = $ima->Get('width');
4260: my $height = $ima->Get('height');
4261: if ($width > $resizewidth) {
4262: my $factor = $width/$resizewidth;
4263: my $newheight = $height/$factor;
4264: $ima->Scale(width=>$resizewidth,height=>$newheight);
4265: $resized = 1;
4266: }
4267: }
4268: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4269: my $width = $ima->Get('width');
4270: my $height = $ima->Get('height');
4271: if ($height > $resizeheight) {
4272: my $factor = $height/$resizeheight;
4273: my $newwidth = $width/$factor;
4274: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4275: $resized = 1;
4276: }
4277: }
4278: if ($resized) {
4279: $ima->Write($img_path);
4280: }
4281: }
4282: return;
1.977 amueller 4283: }
4284:
1.608 albertel 4285: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 4286: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 4287: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 4288: # $context - possible values: coursedoc, existingfile, overwrite,
1.1504 raeburn 4289: # canceloverwrite, scantron, toollogo or ''.
1.1090 raeburn 4290: # if 'coursedoc': upload to the current course
4291: # if 'existingfile': write file to tmp/overwrites directory
4292: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4293: # $context is passed as argument to &finishuserfileupload
1.686 albertel 4294: # $subdir - directory in userfile to store the file into
1.1401 raeburn 4295: # $parser - instruction to parse file for objects ($parser = parse) or
4296: # if context is 'scantron', $parser is hashref of csv column mapping
4297: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4298: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 4299: # $allfiles - reference to hash for embedded objects
4300: # $codebase - reference to hash for codebase of java objects
1.1504 raeburn 4301: # $destuname - username for permanent storage of uploaded file
4302: # $destudom - domain for permanaent storage of uploaded file
1.860 raeburn 4303: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4304: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 4305: # $resizewidth - width (pixels) to which to resize uploaded image
4306: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 4307: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 4308: # from File::MMagic.
1.858 raeburn 4309: #
1.686 albertel 4310: # output: url of file in userspace, or error: <message>
4311: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 4312:
1.531 albertel 4313: sub userfileupload {
1.1090 raeburn 4314: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 4315: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 4316: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 4317: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 4318: $fname=&clean_filename($fname);
1.1090 raeburn 4319: # See if there is anything left
1.257 www 4320: unless ($fname) { return 'error: no uploaded file'; }
1.1406 raeburn 4321: # If filename now begins with a . prepend unix timestamp _ milliseconds
4322: if ($fname =~ /^\./) {
4323: my ($s,$usec) = &gettimeofday();
4324: while (length($usec) < 6) {
4325: $usec = '0'.$usec;
4326: }
4327: $fname = $s.'_'.substr($usec,0,3).$fname;
4328: }
1.1090 raeburn 4329: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4330: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4331: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4332: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 4333: my $now = time;
1.1090 raeburn 4334: my $filepath;
1.1095 raeburn 4335: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 4336: $filepath = 'tmp/helprequests/'.$now;
4337: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4338: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4339: '_'.$env{'user.domain'}.'/pending';
4340: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4341: my ($docuname,$docudom);
1.1350 raeburn 4342: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 4343: $docudom = $destudom;
4344: } else {
4345: $docudom = $env{'user.domain'};
4346: }
1.1350 raeburn 4347: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 4348: $docuname = $destuname;
4349: } else {
4350: $docuname = $env{'user.name'};
4351: }
4352: if (exists($env{'form.group'})) {
4353: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4354: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4355: }
4356: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4357: if ($context eq 'canceloverwrite') {
4358: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4359: if (-e $tempfile) {
4360: my @info = stat($tempfile);
4361: if ($info[9] eq $env{'form.timestamp'}) {
4362: unlink($tempfile);
4363: }
4364: }
4365: return;
1.523 raeburn 4366: }
4367: }
1.1090 raeburn 4368: # Create the directory if not present
1.741 raeburn 4369: my @parts=split(/\//,$filepath);
4370: my $fullpath = $perlvar{'lonDaemons'};
4371: for (my $i=0;$i<@parts;$i++) {
4372: $fullpath .= '/'.$parts[$i];
4373: if ((-e $fullpath)!=1) {
4374: mkdir($fullpath,0777);
4375: }
4376: }
1.1359 raeburn 4377: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 4378: print $fh $env{'form.'.$formname};
4379: close($fh);
1.1090 raeburn 4380: if ($context eq 'existingfile') {
4381: my @info = stat($fullpath.'/'.$fname);
4382: return ($fullpath.'/'.$fname,$info[9]);
4383: } else {
4384: return $fullpath.'/'.$fname;
4385: }
1.523 raeburn 4386: }
1.995 raeburn 4387: if ($subdir eq 'scantron') {
4388: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 4389: } else {
1.995 raeburn 4390: $fname="$subdir/$fname";
4391: }
1.1090 raeburn 4392: if ($context eq 'coursedoc') {
1.638 albertel 4393: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4394: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 4395: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 4396: return &finishuserfileupload($docuname,$docudom,
4397: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 4398: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 4399: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 4400: } else {
1.1218 raeburn 4401: if ($env{'form.folder'}) {
4402: $fname=$env{'form.folder'}.'/'.$fname;
4403: }
1.638 albertel 4404: return &process_coursefile('uploaddoc',$docuname,$docudom,
4405: $fname,$formname,$parser,
1.1095 raeburn 4406: $allfiles,$codebase,$mimetype);
1.481 raeburn 4407: }
1.719 banghart 4408: } elsif (defined($destuname)) {
4409: my $docuname=$destuname;
4410: my $docudom=$destudom;
1.860 raeburn 4411: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4412: $parser,$allfiles,$codebase,
1.1051 raeburn 4413: $thumbwidth,$thumbheight,
1.1095 raeburn 4414: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4415: } else {
1.638 albertel 4416: my $docuname=$env{'user.name'};
4417: my $docudom=$env{'user.domain'};
1.1220 raeburn 4418: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 4419: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4420: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4421: }
1.860 raeburn 4422: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4423: $parser,$allfiles,$codebase,
1.1051 raeburn 4424: $thumbwidth,$thumbheight,
1.1095 raeburn 4425: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4426: }
1.271 www 4427: }
4428:
4429: sub finishuserfileupload {
1.860 raeburn 4430: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4431: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4432: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4433: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4434:
1.860 raeburn 4435: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4436: $file=$fname;
4437: if ($fname=~m|/|) {
4438: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4439: $path.=$fnamepath.'/';
4440: }
1.259 www 4441: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4442: my $count;
4443: for ($count=4;$count<=$#parts;$count++) {
4444: $filepath.="/$parts[$count]";
4445: if ((-e $filepath)!=1) {
4446: mkdir($filepath,0777);
4447: }
4448: }
1.984 neumanie 4449:
1.258 www 4450: # Save the file
4451: {
1.1359 raeburn 4452: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4453: &logthis('Failed to create '.$filepath.'/'.$file);
4454: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4455: return '/adm/notfound.html';
4456: }
1.1090 raeburn 4457: if ($context eq 'overwrite') {
1.1117 foxr 4458: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4459: my $target = $filepath.'/'.$file;
4460: if (-e $source) {
4461: my @info = stat($source);
4462: if ($info[9] eq $env{'form.timestamp'}) {
4463: unless (&File::Copy::move($source,$target)) {
4464: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4465: return "Moving from $source failed";
4466: }
4467: } else {
4468: return "Temporary file: $source had unexpected date/time for last modification";
4469: }
4470: } else {
4471: return "Temporary file: $source missing";
4472: }
4473: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4474: &logthis('Failed to write to '.$filepath.'/'.$file);
4475: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4476: return '/adm/notfound.html';
4477: }
1.570 albertel 4478: close(FH);
1.1051 raeburn 4479: if ($resizewidth && $resizeheight) {
4480: my $mm = new File::MMagic;
4481: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4482: if ($mime_type =~ m{^image/}) {
4483: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4484: }
1.977 amueller 4485: }
1.258 www 4486: }
1.1152 raeburn 4487: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4488: if (ref($mimetype)) {
4489: if ($$mimetype eq '') {
4490: my $mm = new File::MMagic;
4491: my $type = $mm->checktype_filename($filepath.'/'.$file);
4492: $$mimetype = $type;
4493: }
4494: }
4495: }
1.1401 raeburn 4496: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4497: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4498: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4499: $allfiles,$codebase);
4500: unless ($parse_result eq 'ok') {
4501: &logthis('Failed to parse '.$filepath.$file.
4502: ' for embedded media: '.$parse_result);
4503: }
1.637 raeburn 4504: }
1.1401 raeburn 4505: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4506: my $format = $env{'form.scantron_format'};
4507: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4508: }
1.860 raeburn 4509: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4510: my $input = $filepath.'/'.$file;
4511: my $output = $filepath.'/'.'tn-'.$file;
1.1504 raeburn 4512: my $makethumb;
1.860 raeburn 4513: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1504 raeburn 4514: if ($context eq 'toollogo') {
4515: my ($fullwidth,$fullheight) = &check_dimensions($input);
4516: if ($fullwidth ne '' && $fullheight ne '') {
4517: if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
4518: $makethumb = 1;
4519: }
4520: }
4521: } else {
4522: $makethumb = 1;
4523: }
4524: if ($makethumb) {
4525: my @args = ('convert','-sample',$thumbsize,$input,$output);
4526: system({$args[0]} @args);
4527: if (-e $filepath.'/'.'tn-'.$file) {
4528: $fetchthumb = 1;
4529: }
1.860 raeburn 4530: }
4531: }
1.858 raeburn 4532:
1.259 www 4533: # Notify homeserver to grep it
4534: #
1.984 neumanie 4535: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4536: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4537: if ($fetchresult eq 'ok') {
1.860 raeburn 4538: if ($fetchthumb) {
4539: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4540: if ($thumbresult ne 'ok') {
4541: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4542: $docuhome.': '.$thumbresult);
4543: }
4544: }
1.259 www 4545: #
1.258 www 4546: # Return the URL to it
1.494 albertel 4547: return '/uploaded/'.$path.$file;
1.263 www 4548: } else {
1.494 albertel 4549: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4550: ': '.$fetchresult);
1.263 www 4551: return '/adm/notfound.html';
1.858 raeburn 4552: }
1.493 albertel 4553: }
4554:
1.637 raeburn 4555: sub extract_embedded_items {
1.961 raeburn 4556: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4557: my @state = ();
1.1164 raeburn 4558: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4559: my %javafiles = (
4560: codebase => '',
4561: code => '',
4562: archive => ''
4563: );
4564: my %mediafiles = (
4565: src => '',
4566: movie => '',
4567: );
1.648 raeburn 4568: my $p;
4569: if ($content) {
4570: $p = HTML::LCParser->new($content);
4571: } else {
1.961 raeburn 4572: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4573: }
1.641 albertel 4574: while (my $t=$p->get_token()) {
1.640 albertel 4575: if ($t->[0] eq 'S') {
4576: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4577: push(@state, $tagname);
1.648 raeburn 4578: if (lc($tagname) eq 'allow') {
4579: &add_filetype($allfiles,$attr->{'src'},'src');
4580: }
1.640 albertel 4581: if (lc($tagname) eq 'img') {
4582: &add_filetype($allfiles,$attr->{'src'},'src');
4583: }
1.886 albertel 4584: if (lc($tagname) eq 'a') {
1.1222 raeburn 4585: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 4586: &add_filetype($allfiles,$attr->{'href'},'href');
4587: }
1.886 albertel 4588: }
1.645 raeburn 4589: if (lc($tagname) eq 'script') {
1.1164 raeburn 4590: my $src;
1.645 raeburn 4591: if ($attr->{'archive'} =~ /\.jar$/i) {
4592: &add_filetype($allfiles,$attr->{'archive'},'archive');
4593: } else {
1.1164 raeburn 4594: if ($attr->{'src'} ne '') {
4595: $src = $attr->{'src'};
4596: &add_filetype($allfiles,$src,'src');
4597: }
4598: }
4599: my $text = $p->get_trimmed_text();
4600: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4601: my @swfargs = split(/,/,$1);
4602: foreach my $item (@swfargs) {
4603: $item =~ s/["']//g;
4604: $item =~ s/^\s+//;
4605: $item =~ s/\s+$//;
4606: }
4607: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4608: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4609: push(@{$related{$swfargs[0]}},$swfargs[2]);
4610: } else {
4611: $related{$swfargs[0]} = [$swfargs[2]];
4612: }
4613: }
1.645 raeburn 4614: }
4615: }
4616: if (lc($tagname) eq 'link') {
4617: if (lc($attr->{'rel'}) eq 'stylesheet') {
4618: &add_filetype($allfiles,$attr->{'href'},'href');
4619: }
4620: }
1.640 albertel 4621: if (lc($tagname) eq 'object' ||
4622: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4623: foreach my $item (keys(%javafiles)) {
4624: $javafiles{$item} = '';
4625: }
1.1164 raeburn 4626: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4627: $lastids{lc($tagname)} = $attr->{'id'};
4628: }
1.640 albertel 4629: }
4630: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4631: my $name = lc($attr->{'name'});
4632: foreach my $item (keys(%javafiles)) {
4633: if ($name eq $item) {
4634: $javafiles{$item} = $attr->{'value'};
4635: last;
4636: }
4637: }
1.1164 raeburn 4638: my $pathfrom;
1.640 albertel 4639: foreach my $item (keys(%mediafiles)) {
4640: if ($name eq $item) {
1.1164 raeburn 4641: $pathfrom = $attr->{'value'};
4642: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4643: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4644: last;
4645: }
4646: }
1.1164 raeburn 4647: if ($name eq 'flashvars') {
4648: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4649: }
4650: if ($pathfrom ne '') {
4651: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4652: $pathfrom);
4653: }
1.640 albertel 4654: }
4655: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4656: foreach my $item (keys(%javafiles)) {
4657: if ($attr->{$item}) {
4658: $javafiles{$item} = $attr->{$item};
4659: last;
4660: }
4661: }
4662: foreach my $item (keys(%mediafiles)) {
4663: if ($attr->{$item}) {
4664: &add_filetype($allfiles,$attr->{$item},$item);
4665: last;
4666: }
4667: }
1.1164 raeburn 4668: if (lc($tagname) eq 'embed') {
4669: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4670: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4671: $attr->{'src'});
4672: }
4673: }
1.640 albertel 4674: }
1.1243 raeburn 4675: if (lc($tagname) eq 'iframe') {
4676: my $src = $attr->{'src'} ;
4677: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4678: &add_filetype($allfiles,$src,'src');
4679: } elsif ($src =~ m{^/}) {
4680: if ($env{'request.course.id'}) {
4681: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4682: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4683: my $url = &hreflocation('',$fullpath);
4684: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4685: my $relpath = $1;
4686: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4687: &add_filetype($allfiles,$1,'src');
4688: }
4689: }
4690: }
4691: }
4692: }
1.1164 raeburn 4693: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 4694: pop(@state);
1.1164 raeburn 4695: }
1.640 albertel 4696: } elsif ($t->[0] eq 'E') {
4697: my ($tagname) = ($t->[1]);
4698: if ($javafiles{'codebase'} ne '') {
4699: $javafiles{'codebase'} .= '/';
4700: }
4701: if (lc($tagname) eq 'applet' ||
4702: lc($tagname) eq 'object' ||
4703: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4704: ) {
4705: foreach my $item (keys(%javafiles)) {
4706: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4707: my $file=$javafiles{'codebase'}.$javafiles{$item};
4708: &add_filetype($allfiles,$file,$item);
4709: }
4710: }
4711: }
4712: pop @state;
4713: }
4714: }
1.1164 raeburn 4715: foreach my $id (sort(keys(%flashvars))) {
4716: if ($shockwave{$id} ne '') {
4717: my @pairs = split(/\&/,$flashvars{$id});
4718: foreach my $pair (@pairs) {
4719: my ($key,$value) = split(/\=/,$pair);
4720: if ($key eq 'thumb') {
4721: &add_filetype($allfiles,$value,$key);
4722: } elsif ($key eq 'content') {
4723: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4724: my ($ext) = ($value =~ /\.([^.]+)$/);
4725: if ($ext ne '') {
4726: &add_filetype($allfiles,$path.$value,$ext);
4727: }
4728: }
4729: }
4730: }
4731: }
1.637 raeburn 4732: return 'ok';
4733: }
4734:
1.639 albertel 4735: sub add_filetype {
4736: my ($allfiles,$file,$type)=@_;
4737: if (exists($allfiles->{$file})) {
4738: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4739: push(@{$allfiles->{$file}}, &escape($type));
4740: }
4741: } else {
4742: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4743: }
4744: }
4745:
1.1164 raeburn 4746: sub embedded_dependency {
4747: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4748: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4749: if (($identifier ne '') &&
4750: (ref($related->{$identifier}) eq 'ARRAY') &&
4751: ($pathfrom ne '')) {
4752: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4753: foreach my $dep (@{$related->{$identifier}}) {
4754: &add_filetype($allfiles,$path.$dep,'object');
4755: }
4756: }
4757: }
4758: return;
4759: }
4760:
1.1504 raeburn 4761: sub check_dimensions {
4762: my ($inputfile) = @_;
4763: my ($fullwidth,$fullheight);
4764: if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
4765: my $mm = new File::MMagic;
4766: my $mime_type = $mm->checktype_filename($inputfile);
4767: if ($mime_type =~ m{^image/}) {
4768: if (open(PIPE,"identify $inputfile 2>&1 |")) {
4769: my $imageinfo = <PIPE>;
4770: if (!close(PIPE)) {
4771: &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
4772: }
4773: chomp($imageinfo);
4774: my ($fullsize) =
4775: ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
4776: if ($fullsize) {
4777: ($fullwidth,$fullheight) = split(/x/,$fullsize);
4778: }
4779: }
4780: }
4781: }
4782: return ($fullwidth,$fullheight);
4783: }
4784:
1.1401 raeburn 4785: sub bubblesheet_converter {
4786: my ($cdom,$fullpath,$config,$format) = @_;
4787: if ((&domain($cdom) ne '') &&
1.1403 raeburn 4788: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401 raeburn 4789: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404 raeburn 4790: my (%csvcols,%csvoptions);
4791: if (ref($config->{'fields'}) eq 'HASH') {
4792: %csvcols = %{$config->{'fields'}};
4793: }
4794: if (ref($config->{'options'}) eq 'HASH') {
4795: %csvoptions = %{$config->{'options'}};
4796: }
1.1401 raeburn 4797: my %csvbynum = reverse(%csvcols);
4798: my %scantronconf = &get_scantron_config($format,$cdom);
4799: if (keys(%scantronconf)) {
4800: my %bynum = (
4801: $scantronconf{CODEstart} => 'CODEstart',
4802: $scantronconf{IDstart} => 'IDstart',
4803: $scantronconf{PaperID} => 'PaperID',
4804: $scantronconf{FirstName} => 'FirstName',
4805: $scantronconf{LastName} => 'LastName',
4806: $scantronconf{Qstart} => 'Qstart',
4807: );
4808: my @ordered;
4809: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403 raeburn 4810: push(@ordered,$bynum{$item});
1.1401 raeburn 4811: }
4812: my %mapstart = (
4813: CODEstart => 'CODE',
4814: IDstart => 'ID',
4815: PaperID => 'PaperID',
4816: FirstName => 'FirstName',
4817: LastName => 'LastName',
4818: Qstart => 'FirstQuestion',
4819: );
4820: my %maplength = (
4821: CODEstart => 'CODElength',
4822: IDstart => 'IDlength',
4823: PaperID => 'PaperIDlength',
4824: FirstName => 'FirstNamelength',
4825: LastName => 'LastNamelength',
4826: );
4827: if (open(my $fh,'<',$fullpath)) {
4828: my $output;
1.1403 raeburn 4829: my %lettdig = &letter_to_digits();
4830: my %diglett = reverse(%lettdig);
4831: my $numletts = scalar(keys(%lettdig));
1.1404 raeburn 4832: my $num = 0;
1.1401 raeburn 4833: while (my $line=<$fh>) {
1.1404 raeburn 4834: $num ++;
4835: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401 raeburn 4836: $line =~ s{[\r\n]+$}{};
4837: my %found;
1.1475 raeburn 4838: my @values = split(/,/,$line,-1);
1.1401 raeburn 4839: my ($qstart,$record);
4840: for (my $i=0; $i<@values; $i++) {
1.1403 raeburn 4841: if ((($qstart ne '') && ($i > $qstart)) ||
4842: ($csvbynum{$i} eq 'FirstQuestion')) {
4843: if ($values[$i] eq '') {
4844: $values[$i] = $scantronconf{'Qoff'};
4845: } elsif ($scantronconf{'Qon'} eq 'number') {
4846: if ($values[$i] =~ /^[A-Ja-j]$/) {
4847: $values[$i] = $lettdig{uc($values[$i])};
4848: }
4849: } elsif ($scantronconf{'Qon'} eq 'letter') {
4850: if ($values[$i] =~ /^[0-9]$/) {
4851: $values[$i] = $diglett{$values[$i]};
4852: }
4853: } else {
4854: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4855: my $digit;
4856: if ($values[$i] =~ /^[A-Ja-j]$/) {
4857: $digit = $lettdig{uc($values[$i])}-1;
4858: if ($values[$i] eq 'J') {
4859: $digit += $numletts;
4860: }
4861: } elsif ($values[$i] =~ /^[0-9]$/) {
4862: $digit = $values[$i]-1;
4863: if ($values[$i] eq '0') {
4864: $digit += $numletts;
4865: }
4866: }
4867: my $qval='';
4868: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4869: if ($j == $digit) {
4870: $qval .= $scantronconf{'Qon'};
4871: } else {
4872: $qval .= $scantronconf{'Qoff'};
4873: }
4874: }
4875: $values[$i] = $qval;
4876: }
4877: }
4878: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4879: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4880: }
4881: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4882: if ($numblank > 0) {
4883: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4884: }
1.1401 raeburn 4885: if ($csvbynum{$i} eq 'FirstQuestion') {
4886: $qstart = $i;
1.1403 raeburn 4887: $found{$csvbynum{$i}} = $values[$i];
1.1401 raeburn 4888: } else {
1.1403 raeburn 4889: $found{'FirstQuestion'} .= $values[$i];
4890: }
4891: } elsif (exists($csvbynum{$i})) {
1.1404 raeburn 4892: if ($csvoptions{'rem'}) {
4893: $values[$i] =~ s/^\s+//;
4894: }
4895: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403 raeburn 4896: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4897: $values[$i] = '0'.$values[$i];
1.1401 raeburn 4898: }
4899: }
4900: $found{$csvbynum{$i}} = $values[$i];
4901: }
4902: }
4903: foreach my $item (@ordered) {
4904: my $currlength = 1+length($record);
4905: my $numspaces = $scantronconf{$item} - $currlength;
4906: if ($numspaces > 0) {
4907: $record .= (' ' x $numspaces);
4908: }
4909: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4910: unless ($item eq 'Qstart') {
4911: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4912: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4913: }
4914: }
4915: $record .= $found{$mapstart{$item}};
4916: }
4917: }
4918: $output .= "$record\n";
4919: }
4920: close($fh);
4921: if ($output) {
4922: if (open(my $fh,'>',$fullpath)) {
4923: print $fh $output;
4924: close($fh);
4925: }
4926: }
4927: }
4928: }
4929: return;
4930: }
4931: }
4932:
1.1403 raeburn 4933: sub letter_to_digits {
4934: my %lettdig = (
4935: A => 1,
4936: B => 2,
4937: C => 3,
4938: D => 4,
4939: E => 5,
4940: F => 6,
4941: G => 7,
4942: H => 8,
4943: I => 9,
4944: J => 0,
4945: );
4946: return %lettdig;
4947: }
4948:
1.1401 raeburn 4949: sub get_scantron_config {
4950: my ($which,$cdom) = @_;
4951: my @lines = &get_scantronformat_file($cdom);
4952: my %config;
4953: #FIXME probably should move to XML it has already gotten a bit much now
4954: foreach my $line (@lines) {
4955: my ($name,$descrip)=split(/:/,$line);
4956: if ($name ne $which ) { next; }
4957: chomp($line);
4958: my @config=split(/:/,$line);
4959: $config{'name'}=$config[0];
4960: $config{'description'}=$config[1];
4961: $config{'CODElocation'}=$config[2];
4962: $config{'CODEstart'}=$config[3];
4963: $config{'CODElength'}=$config[4];
4964: $config{'IDstart'}=$config[5];
4965: $config{'IDlength'}=$config[6];
4966: $config{'Qstart'}=$config[7];
4967: $config{'Qlength'}=$config[8];
4968: $config{'Qoff'}=$config[9];
4969: $config{'Qon'}=$config[10];
4970: $config{'PaperID'}=$config[11];
4971: $config{'PaperIDlength'}=$config[12];
4972: $config{'FirstName'}=$config[13];
4973: $config{'FirstNamelength'}=$config[14];
4974: $config{'LastName'}=$config[15];
4975: $config{'LastNamelength'}=$config[16];
4976: $config{'BubblesPerRow'}=$config[17];
4977: last;
4978: }
4979: return %config;
4980: }
4981:
4982: sub get_scantronformat_file {
4983: my ($cdom) = @_;
4984: if ($cdom eq '') {
4985: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4986: }
4987: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4988: my $gottab = 0;
4989: my @lines;
4990: if (ref($domconfig{'scantron'}) eq 'HASH') {
4991: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4992: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4993: if ($formatfile ne '-1') {
4994: @lines = split("\n",$formatfile,-1);
4995: $gottab = 1;
4996: }
4997: }
4998: }
4999: if (!$gottab) {
5000: my $confname = $cdom.'-domainconfig';
5001: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
5002: my $formatfile = &getfile($default);
5003: if ($formatfile ne '-1') {
5004: @lines = split("\n",$formatfile,-1);
5005: $gottab = 1;
5006: }
5007: }
5008: if (!$gottab) {
5009: my @domains = ¤t_machine_domains();
5010: if (grep(/^\Q$cdom\E$/,@domains)) {
5011: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
5012: @lines = <$fh>;
5013: close($fh);
1.1403 raeburn 5014: }
1.1401 raeburn 5015: } else {
5016: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
5017: @lines = <$fh>;
5018: close($fh);
5019: }
5020: }
1.1488 raeburn 5021: chomp(@lines);
1.1401 raeburn 5022: }
5023: return @lines;
5024: }
5025:
1.493 albertel 5026: sub removeuploadedurl {
1.984 neumanie 5027: my ($url)=@_;
5028: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 5029: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 5030: }
5031:
5032: sub removeuserfile {
5033: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 5034: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 5035: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 5036: if ($result eq 'ok') {
1.798 raeburn 5037: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
5038: my $metafile = $fname.'.meta';
5039: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 5040: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 5041: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 5042: my $sqlresult =
1.823 albertel 5043: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 5044: 'portfolio_metadata',$group,
5045: 'delete');
1.798 raeburn 5046: }
5047: }
5048: return $result;
1.257 www 5049: }
1.15 www 5050:
1.530 albertel 5051: sub mkdiruserfile {
5052: my ($docuname,$docudom,$dir)=@_;
5053: my $home=&homeserver($docuname,$docudom);
5054: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
5055: }
5056:
1.531 albertel 5057: sub renameuserfile {
5058: my ($docuname,$docudom,$old,$new)=@_;
5059: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 5060: my $result = &reply("renameuserfile:$docudom:$docuname:".
5061: &escape("$old").':'.&escape("$new"),$home);
5062: if ($result eq 'ok') {
5063: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
5064: my $oldmeta = $old.'.meta';
5065: my $newmeta = $new.'.meta';
5066: my $metaresult =
5067: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 5068: my $url = "/uploaded/$docudom/$docuname/$old";
5069: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 5070: my $sqlresult =
1.823 albertel 5071: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 5072: 'portfolio_metadata',$group,
5073: 'delete');
1.798 raeburn 5074: }
5075: }
5076: return $result;
1.531 albertel 5077: }
5078:
1.14 www 5079: # ------------------------------------------------------------------------- Log
5080:
5081: sub log {
5082: my ($dom,$nam,$hom,$what)=@_;
1.47 www 5083: return critical("log:$dom:$nam:$what",$hom);
1.157 www 5084: }
5085:
5086: # ------------------------------------------------------------------ Course Log
1.352 www 5087: #
5088: # This routine flushes several buffers of non-mission-critical nature
5089: #
1.157 www 5090:
5091: sub flushcourselogs {
1.352 www 5092: &logthis('Flushing log buffers');
5093: #
5094: # course logs
5095: # This is a log of all transactions in a course, which can be used
5096: # for data mining purposes
5097: #
5098: # It also collects the courseid database, which lists last transaction
5099: # times and course titles for all courseids
5100: #
5101: my %courseidbuffer=();
1.921 raeburn 5102: foreach my $crsid (keys(%courselogs)) {
1.352 www 5103: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 5104: &escape($courselogs{$crsid}),
5105: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 5106: delete $courselogs{$crsid};
5107: } else {
5108: &logthis('Failed to flush log buffer for '.$crsid);
5109: if (length($courselogs{$crsid})>40000) {
1.672 albertel 5110: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 5111: " exceeded maximum size, deleting.</font>");
5112: delete $courselogs{$crsid};
5113: }
1.352 www 5114: }
1.920 raeburn 5115: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 5116: 'description' => $coursedescrbuf{$crsid},
5117: 'inst_code' => $courseinstcodebuf{$crsid},
5118: 'type' => $coursetypebuf{$crsid},
5119: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 5120: };
1.191 harris41 5121: }
1.352 www 5122: #
5123: # Write course id database (reverse lookup) to homeserver of courses
5124: # Is used in pickcourse
5125: #
1.840 albertel 5126: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 5127: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 5128: $courseidbuffer{$crs_home},
5129: $crs_home,'timeonly');
1.352 www 5130: }
5131: #
5132: # File accesses
5133: # Writes to the dynamic metadata of resources to get hit counts, etc.
5134: #
1.449 matthew 5135: foreach my $entry (keys(%accesshash)) {
1.458 matthew 5136: if ($entry =~ /___count$/) {
5137: my ($dom,$name);
1.807 albertel 5138: ($dom,$name,undef)=
1.811 albertel 5139: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 5140: if (! defined($dom) || $dom eq '' ||
5141: ! defined($name) || $name eq '') {
1.620 albertel 5142: my $cid = $env{'request.course.id'};
1.1472 raeburn 5143: #
5144: # FIXME 11/29/2021
5145: # Typo in rev. 1.458 (2003/12/09)??
5146: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
5147: #
5148: # While these ramain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
5149: # $dom and $name will always be null, so the &inc() call will default to storing this data
5150: # in a nohist_accesscount.db file for the user rather than the course.
5151: #
5152: # That said there is a lot of noise in the data being stored.
5153: # So counts for prtspool/ and adm/ etc. are recorded.
5154: #
5155: # A review of which items ending '___count' are written to %accesshash should likely be
5156: # made before deciding whether to set these to 'course.' instead of 'request.'
5157: #
5158: # Under the current scheme each user receives a nohist_accesscount.db file listing
5159: # accesses for things which are not published resources, regardless of course, and
5160: # there is not a nohist_accesscount.db file in a course, which might log accesses from
5161: # anyone in the course for things which are not published resources.
5162: #
5163: # For an author, nohist_accesscount.db ends up having records for other items
5164: # mixed up with the legitimate access counts for the author's published resources.
5165: #
1.620 albertel 5166: $dom = $env{'request.'.$cid.'.domain'};
5167: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 5168: }
1.450 matthew 5169: my $value = $accesshash{$entry};
5170: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
5171: my %temphash=($url => $value);
1.449 matthew 5172: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
5173: if ($result eq 'ok') {
5174: delete $accesshash{$entry};
5175: }
5176: } else {
1.811 albertel 5177: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 5178: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 5179: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 5180: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
5181: delete $accesshash{$entry};
5182: }
1.185 www 5183: }
1.191 harris41 5184: }
1.352 www 5185: #
5186: # Roles
5187: # Reverse lookup of user roles for course faculty/staff and co-authorship
5188: #
1.800 albertel 5189: foreach my $entry (keys(%userrolehash)) {
1.351 www 5190: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 5191: split(/\:/,$entry);
1.1494 raeburn 5192: if (&put('nohist_userroles',
1.351 www 5193: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 5194: $rudom,$runame) eq 'ok') {
5195: delete $userrolehash{$entry};
5196: }
5197: }
1.662 raeburn 5198: #
1.1334 raeburn 5199: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 5200: #
5201: my %domrolebuffer = ();
1.1000 raeburn 5202: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 5203: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 5204: if ($domrolebuffer{$rudom}) {
5205: $domrolebuffer{$rudom}.='&'.&escape($entry).
5206: '='.&escape($domainrolehash{$entry});
5207: } else {
5208: $domrolebuffer{$rudom}.=&escape($entry).
5209: '='.&escape($domainrolehash{$entry});
5210: }
5211: delete $domainrolehash{$entry};
5212: }
5213: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 5214: my %servers;
5215: if (defined(&domain($dom,'primary'))) {
5216: my $primary=&domain($dom,'primary');
5217: my $hostname=&hostname($primary);
5218: $servers{$primary} = $hostname;
5219: } else {
5220: %servers = &get_servers($dom,'library');
5221: }
1.841 albertel 5222: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 5223: if (&reply('domroleput:'.$dom.':'.
5224: $domrolebuffer{$dom},$tryserver) eq 'ok') {
5225: last;
5226: } else {
1.841 albertel 5227: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
5228: }
1.662 raeburn 5229: }
5230: }
1.186 www 5231: $dumpcount++;
1.157 www 5232: }
5233:
5234: sub courselog {
5235: my $what=shift;
1.158 www 5236: $what=time.':'.$what;
1.620 albertel 5237: unless ($env{'request.course.id'}) { return ''; }
5238: $coursedombuf{$env{'request.course.id'}}=
5239: $env{'course.'.$env{'request.course.id'}.'.domain'};
5240: $coursenumbuf{$env{'request.course.id'}}=
5241: $env{'course.'.$env{'request.course.id'}.'.num'};
5242: $coursehombuf{$env{'request.course.id'}}=
5243: $env{'course.'.$env{'request.course.id'}.'.home'};
5244: $coursedescrbuf{$env{'request.course.id'}}=
5245: $env{'course.'.$env{'request.course.id'}.'.description'};
5246: $courseinstcodebuf{$env{'request.course.id'}}=
5247: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
5248: $courseownerbuf{$env{'request.course.id'}}=
5249: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 5250: $coursetypebuf{$env{'request.course.id'}}=
5251: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 5252: if (defined $courselogs{$env{'request.course.id'}}) {
5253: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 5254: } else {
1.620 albertel 5255: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 5256: }
1.620 albertel 5257: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 5258: &flushcourselogs();
5259: }
1.158 www 5260: }
5261:
5262: sub courseacclog {
5263: my $fnsymb=shift;
1.620 albertel 5264: unless ($env{'request.course.id'}) { return ''; }
5265: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 5266: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 5267: $what.=':POST';
1.583 matthew 5268: # FIXME: Probably ought to escape things....
1.800 albertel 5269: foreach my $key (keys(%env)) {
5270: if ($key=~/^form\.(.*)/) {
1.975 raeburn 5271: my $formitem = $1;
5272: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
5273: $what.=':'.$formitem.'='.$env{$key};
5274: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432 raeburn 5275: if ($formitem eq 'proctorpassword') {
1.1433 raeburn 5276: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432 raeburn 5277: } else {
5278: $what.=':'.$formitem.'='.$env{$key};
5279: }
1.975 raeburn 5280: }
1.158 www 5281: }
1.191 harris41 5282: }
1.583 matthew 5283: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
5284: # FIXME: We should not be depending on a form parameter that someone
5285: # editing lonsearchcat.pm might change in the future.
1.620 albertel 5286: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 5287: $what.= ':POST';
5288: # FIXME: Probably ought to escape things....
5289: foreach my $element ('courseexp','crsfulltext','crsrelated',
5290: 'crsdiscuss') {
1.620 albertel 5291: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 5292: }
5293: }
1.158 www 5294: }
5295: &courselog($what);
1.149 www 5296: }
5297:
1.185 www 5298: sub countacc {
5299: my $url=&declutter(shift);
1.458 matthew 5300: return if (! defined($url) || $url eq '');
1.620 albertel 5301: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 5302: #
5303: # Mark that this url was used in this course
5304: #
1.620 albertel 5305: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 5306: #
5307: # Increase the access count for this resource in this child process
5308: #
1.281 www 5309: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 5310: $accesshash{$key}++;
1.185 www 5311: }
1.349 www 5312:
1.361 www 5313: sub linklog {
5314: my ($from,$to)=@_;
5315: $from=&declutter($from);
5316: $to=&declutter($to);
5317: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5318: $accesshash{$to.'___'.$from.'___goto'}=1;
5319: }
1.1160 www 5320:
5321: sub statslog {
5322: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5323: if ($users<2) { return; }
5324: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5325: 'course' => $env{'request.course.id'},
5326: 'sections' => '"all"',
5327: 'num_students' => $users,
5328: 'part' => $part,
5329: 'symb' => $symb,
5330: 'mean_tries' => $av_attempts,
5331: 'deg_of_diff' => $degdiff});
5332: foreach my $key (keys(%dynstore)) {
5333: $accesshash{$key}=$dynstore{$key};
5334: }
5335: }
1.361 www 5336:
1.349 www 5337: sub userrolelog {
5338: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 5339: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 5340: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5341: $userrolehash
5342: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 5343: =$tend.':'.$tstart;
1.662 raeburn 5344: }
1.1169 droeschl 5345: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 5346: $userrolehash
5347: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5348: =$tend.':'.$tstart;
5349: }
1.1334 raeburn 5350: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 5351: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5352: $domainrolehash
5353: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5354: = $tend.':'.$tstart;
5355: }
1.351 www 5356: }
5357:
1.957 raeburn 5358: sub courserolelog {
5359: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 5360: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5361: my $cdom = $1;
5362: my $cnum = $2;
5363: my $sec = $3;
5364: my $namespace = 'rolelog';
5365: my %storehash = (
5366: role => $trole,
5367: start => $tstart,
5368: end => $tend,
5369: selfenroll => $selfenroll,
5370: context => $context,
5371: );
5372: if ($trole eq 'gr') {
5373: $namespace = 'groupslog';
5374: $storehash{'group'} = $sec;
5375: } else {
5376: $storehash{'section'} = $sec;
5377: }
1.1188 raeburn 5378: &write_log('course',$namespace,\%storehash,$delflag,$username,
5379: $domain,$cnum,$cdom);
1.1184 raeburn 5380: if (($trole ne 'st') || ($sec ne '')) {
5381: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 5382: }
5383: }
5384: return;
5385: }
5386:
1.1184 raeburn 5387: sub domainrolelog {
5388: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5389: if ($area =~ m{^/($match_domain)/$}) {
5390: my $cdom = $1;
1.1494 raeburn 5391: my $domconfiguser = &get_domainconfiguser($cdom);
1.1184 raeburn 5392: my $namespace = 'rolelog';
5393: my %storehash = (
5394: role => $trole,
5395: start => $tstart,
5396: end => $tend,
5397: context => $context,
5398: );
1.1188 raeburn 5399: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5400: $domain,$domconfiguser,$cdom);
1.1184 raeburn 5401: }
5402: return;
5403:
5404: }
5405:
5406: sub coauthorrolelog {
5407: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5408: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5409: my $audom = $1;
5410: my $auname = $2;
5411: my $namespace = 'rolelog';
5412: my %storehash = (
5413: role => $trole,
5414: start => $tstart,
5415: end => $tend,
5416: context => $context,
5417: );
1.1188 raeburn 5418: &write_log('author',$namespace,\%storehash,$delflag,$username,
5419: $domain,$auname,$audom);
1.1184 raeburn 5420: }
5421: return;
5422: }
5423:
1.351 www 5424: sub get_course_adv_roles {
1.948 raeburn 5425: my ($cid,$codes) = @_;
1.620 albertel 5426: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 5427: my %coursehash=&coursedescription($cid);
1.988 raeburn 5428: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 5429: my %nothide=();
1.800 albertel 5430: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 5431: if ($user !~ /:/) {
5432: $nothide{join(':',split(/[\@]/,$user))}=1;
5433: } else {
5434: $nothide{$user}=1;
5435: }
1.470 www 5436: }
1.1219 raeburn 5437: my @possdoms = ($coursehash{'domain'});
5438: if ($coursehash{'checkforpriv'}) {
5439: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5440: }
1.351 www 5441: my %returnhash=();
5442: my %dumphash=
5443: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5444: my $now=time;
1.997 raeburn 5445: my %privileged;
1.1000 raeburn 5446: foreach my $entry (keys(%dumphash)) {
1.800 albertel 5447: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 5448: if (($tstart) && ($tstart<0)) { next; }
5449: if (($tend) && ($tend<$now)) { next; }
5450: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 5451: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 5452: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 5453: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 5454: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 5455: if ($role eq 'cr') { next; }
1.948 raeburn 5456: if ($codes) {
5457: if ($section) { $role .= ':'.$section; }
5458: if ($returnhash{$role}) {
5459: $returnhash{$role}.=','.$username.':'.$domain;
5460: } else {
5461: $returnhash{$role}=$username.':'.$domain;
5462: }
1.351 www 5463: } else {
1.988 raeburn 5464: my $key=&plaintext($role,$crstype);
1.973 bisitz 5465: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 5466: if ($returnhash{$key}) {
5467: $returnhash{$key}.=','.$username.':'.$domain;
5468: } else {
5469: $returnhash{$key}=$username.':'.$domain;
5470: }
1.351 www 5471: }
1.948 raeburn 5472: }
1.400 www 5473: return %returnhash;
5474: }
5475:
5476: sub get_my_roles {
1.937 raeburn 5477: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5478: unless (defined($uname)) { $uname=$env{'user.name'}; }
5479: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5480: my (%dumphash,%nothide);
1.1086 raeburn 5481: if ($context eq 'userroles') {
1.1166 raeburn 5482: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5483: } else {
1.1219 raeburn 5484: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5485: if ($hidepriv) {
5486: my %coursehash=&coursedescription($udom.'_'.$uname);
5487: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5488: if ($user !~ /:/) {
5489: $nothide{join(':',split(/[\@]/,$user))} = 1;
5490: } else {
5491: $nothide{$user} = 1;
5492: }
5493: }
5494: }
1.858 raeburn 5495: }
1.400 www 5496: my %returnhash=();
5497: my $now=time;
1.999 raeburn 5498: my %privileged;
1.800 albertel 5499: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5500: my ($role,$tend,$tstart);
5501: if ($context eq 'userroles') {
1.1149 raeburn 5502: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5503: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5504: } else {
5505: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5506: }
1.400 www 5507: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5508: my $status = 'active';
1.939 raeburn 5509: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5510: $status = 'previous';
5511: }
5512: if (($tstart) && ($now<$tstart)) {
5513: $status = 'future';
5514: }
5515: if (ref($types) eq 'ARRAY') {
5516: if (!grep(/^\Q$status\E$/,@{$types})) {
5517: next;
5518: }
5519: } else {
5520: if ($status ne 'active') {
5521: next;
5522: }
5523: }
1.867 raeburn 5524: my ($rolecode,$username,$domain,$section,$area);
5525: if ($context eq 'userroles') {
1.1186 raeburn 5526: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5527: (undef,$domain,$username,$section) = split(/\//,$area);
5528: } else {
5529: ($role,$username,$domain,$section) = split(/\:/,$entry);
5530: }
1.832 raeburn 5531: if (ref($roledoms) eq 'ARRAY') {
5532: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5533: next;
5534: }
5535: }
5536: if (ref($roles) eq 'ARRAY') {
5537: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5538: if ($role =~ /^cr\//) {
5539: if (!grep(/^cr$/,@{$roles})) {
5540: next;
5541: }
1.1104 raeburn 5542: } elsif ($role =~ /^gr\//) {
5543: if (!grep(/^gr$/,@{$roles})) {
5544: next;
5545: }
1.922 raeburn 5546: } else {
5547: next;
5548: }
1.832 raeburn 5549: }
1.867 raeburn 5550: }
1.937 raeburn 5551: if ($hidepriv) {
1.1219 raeburn 5552: my @privroles = ('dc','su');
1.999 raeburn 5553: if ($context eq 'userroles') {
1.1219 raeburn 5554: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5555: } else {
1.1219 raeburn 5556: my $possdoms = [$domain];
5557: if (ref($roledoms) eq 'ARRAY') {
5558: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5559: }
1.1219 raeburn 5560: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5561: if (!$nothide{$username.':'.$domain}) {
5562: next;
5563: }
5564: }
1.937 raeburn 5565: }
5566: }
1.933 raeburn 5567: if ($withsec) {
5568: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5569: $tstart.':'.$tend;
5570: } else {
5571: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5572: }
1.832 raeburn 5573: }
1.373 www 5574: return %returnhash;
1.399 www 5575: }
5576:
1.1333 raeburn 5577: sub get_all_adhocroles {
5578: my ($dom) = @_;
5579: my @roles_by_num = ();
5580: my %domdefaults = &get_domain_defaults($dom);
5581: my (%description,%access_in_dom,%access_info);
5582: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5583: my $count = 0;
5584: my %domcurrent = %{$domdefaults{'adhocroles'}};
5585: my %ordered;
5586: foreach my $role (sort(keys(%domcurrent))) {
5587: my ($order,$desc,$access_in_dom);
5588: if (ref($domcurrent{$role}) eq 'HASH') {
5589: $order = $domcurrent{$role}{'order'};
5590: $desc = $domcurrent{$role}{'desc'};
5591: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5592: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5593: }
5594: if ($order eq '') {
5595: $order = $count;
5596: }
5597: $ordered{$order} = $role;
5598: if ($desc ne '') {
5599: $description{$role} = $desc;
5600: } else {
5601: $description{$role}= $role;
5602: }
5603: $count++;
5604: }
5605: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5606: push(@roles_by_num,$ordered{$item});
5607: }
5608: }
5609: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5610: }
5611:
1.1332 raeburn 5612: sub get_my_adhocroles {
1.1333 raeburn 5613: my ($cid,$checkreg) = @_;
5614: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5615: if ($env{'request.course.id'} eq $cid) {
5616: $cdom = $env{'course.'.$cid.'.domain'};
5617: $cnum = $env{'course.'.$cid.'.num'};
5618: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5619: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5620: $cdom = $1;
5621: $cnum = $2;
1.1494 raeburn 5622: %info = &get('environment',['internal.coursecode'],
5623: $cdom,$cnum);
1.1333 raeburn 5624: }
5625: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5626: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5627: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5628: if ($rosterhash{$user} ne '') {
5629: my $type = (split(/:/,$rosterhash{$user}))[5];
5630: return ([],{}) if ($type eq 'auto');
5631: }
5632: }
5633: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 5634: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 5635: my $then=$env{'user.login.time'};
5636: my $update=$env{'user.update.time'};
1.1335 raeburn 5637: if (!$update) {
5638: $update = $then;
5639: }
5640: my @liveroles;
1.1334 raeburn 5641: foreach my $role ('dh','da') {
5642: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 5643: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 5644: my $limit = $update;
5645: if ($env{'request.role'} eq "$role./$cdom/") {
5646: $limit = $then;
5647: }
1.1335 raeburn 5648: my $activerole = 1;
5649: if ($tstart && $tstart>$limit) { $activerole = 0; }
5650: if ($tend && $tend <$limit) { $activerole = 0; }
5651: if ($activerole) {
5652: push(@liveroles,$role);
5653: }
1.1334 raeburn 5654: }
1.1332 raeburn 5655: }
1.1335 raeburn 5656: if (@liveroles) {
1.1332 raeburn 5657: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 5658: my ($accessref,$accessinfo,%access_in_dom);
5659: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5660: if (ref($roles_by_num) eq 'ARRAY') {
5661: if (@{$roles_by_num}) {
1.1332 raeburn 5662: my %settings;
5663: if ($env{'request.course.id'} eq $cid) {
5664: foreach my $envkey (keys(%env)) {
5665: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5666: $settings{$1} = $env{$envkey};
5667: }
5668: }
5669: } else {
5670: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5671: }
5672: my %setincrs;
5673: if ($settings{'internal.adhocaccess'}) {
5674: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5675: }
5676: my @statuses;
5677: if ($env{'environment.inststatus'}) {
5678: @statuses = split(/,/,$env{'environment.inststatus'});
5679: }
5680: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 5681: if (ref($accessref) eq 'HASH') {
5682: %access_in_dom = %{$accessref};
5683: }
5684: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 5685: my ($curraccess,@okstatus,@personnel);
5686: if ($setincrs{$role}) {
5687: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5688: if ($curraccess eq 'status') {
5689: @okstatus = split(/\&/,$rest);
5690: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5691: @personnel = split(/\&/,$rest);
5692: }
5693: } else {
5694: $curraccess = $access_in_dom{$role};
1.1333 raeburn 5695: if (ref($accessinfo) eq 'HASH') {
5696: if ($curraccess eq 'status') {
5697: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5698: @okstatus = @{$accessinfo->{$role}};
5699: }
5700: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5701: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5702: @personnel = @{$accessinfo->{$role}};
5703: }
1.1332 raeburn 5704: }
5705: }
5706: }
5707: if ($curraccess eq 'none') {
5708: next;
5709: } elsif ($curraccess eq 'all') {
5710: push(@possroles,$role);
1.1336 raeburn 5711: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 5712: if (grep(/^dh$/,@liveroles)) {
5713: push(@possroles,$role);
5714: } else {
5715: next;
5716: }
1.1336 raeburn 5717: } elsif ($curraccess eq 'da') {
1.1335 raeburn 5718: if (grep(/^da$/,@liveroles)) {
5719: push(@possroles,$role);
5720: } else {
5721: next;
5722: }
1.1332 raeburn 5723: } elsif ($curraccess eq 'status') {
5724: if (@okstatus) {
5725: if (!@statuses) {
5726: if (grep(/^default$/,@okstatus)) {
5727: push(@possroles,$role);
5728: }
5729: } else {
5730: foreach my $status (@okstatus) {
5731: if (grep(/^\Q$status\E$/,@statuses)) {
5732: push(@possroles,$role);
5733: last;
5734: }
5735: }
5736: }
5737: }
5738: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5739: if (grep(/^\Q$user\E$/,@personnel)) {
5740: if ($curraccess eq 'exc') {
5741: push(@possroles,$role);
5742: }
5743: } elsif ($curraccess eq 'inc') {
5744: push(@possroles,$role);
5745: }
5746: }
5747: }
5748: }
5749: }
5750: }
5751: }
5752: }
5753: }
1.1333 raeburn 5754: unless (ref($description) eq 'HASH') {
5755: if (ref($roles_by_num) eq 'ARRAY') {
5756: my %desc;
5757: map { $desc{$_} = $_; } (@{$roles_by_num});
5758: $description = \%desc;
5759: } else {
5760: $description = {};
5761: }
5762: }
5763: return (\@possroles,$description);
1.1332 raeburn 5764: }
5765:
1.399 www 5766: # ----------------------------------------------------- Frontpage Announcements
5767: #
5768: #
5769:
5770: sub postannounce {
5771: my ($server,$text)=@_;
1.844 albertel 5772: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5773: unless ($text=~/\w/) { $text=''; }
5774: return &reply('setannounce:'.&escape($text),$server);
5775: }
5776:
5777: sub getannounce {
1.448 albertel 5778:
1.1359 raeburn 5779: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5780: my $announcement='';
1.800 albertel 5781: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5782: close($fh);
1.399 www 5783: if ($announcement=~/\w/) {
5784: return
5785: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5786: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5787: } else {
5788: return '';
5789: }
5790: } else {
5791: return '';
5792: }
1.351 www 5793: }
1.353 www 5794:
5795: # ---------------------------------------------------------- Course ID routines
5796: # Deal with domain's nohist_courseid.db files
5797: #
5798:
5799: sub courseidput {
1.921 raeburn 5800: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5801: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5802: my $outcome;
5803: if ($caller eq 'timeonly') {
5804: my $cids = '';
5805: foreach my $item (keys(%$storehash)) {
5806: $cids.=&escape($item).'&';
5807: }
5808: $cids=~s/\&$//;
5809: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5810: $coursehome);
5811: } else {
5812: my $items = '';
5813: foreach my $item (keys(%$storehash)) {
5814: $items.= &escape($item).'='.
5815: &freeze_escape($$storehash{$item}).'&';
5816: }
5817: $items=~s/\&$//;
5818: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5819: $coursehome);
1.918 raeburn 5820: }
5821: if ($outcome eq 'unknown_cmd') {
5822: my $what;
5823: foreach my $cid (keys(%$storehash)) {
5824: $what .= &escape($cid).'=';
1.921 raeburn 5825: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5826: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5827: }
5828: $what =~ s/\:$/&/;
5829: }
5830: $what =~ s/\&$//;
5831: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5832: } else {
5833: return $outcome;
5834: }
1.353 www 5835: }
5836:
5837: sub courseiddump {
1.921 raeburn 5838: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5839: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5840: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 5841: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 5842: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5843: my $as_hash = 1;
5844: my %returnhash;
5845: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5846: my %libserv = &all_library();
5847: foreach my $tryserver (keys(%libserv)) {
5848: if ( ( $hostidflag == 1
5849: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5850: || (!defined($hostidflag)) ) {
5851:
1.918 raeburn 5852: if (($domfilter eq '') ||
5853: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 5854: my $rep;
5855: if (grep { $_ eq $tryserver } current_machine_ids()) {
5856: $rep = LONCAPA::Lond::dump_course_id_handler(
5857: join(":", (&host_domain($tryserver), $sincefilter,
5858: &escape($descfilter), &escape($instcodefilter),
5859: &escape($ownerfilter), &escape($coursefilter),
5860: &escape($typefilter), &escape($regexp_ok),
5861: $as_hash, &escape($selfenrollonly),
5862: &escape($catfilter), $showhidden, $caller,
5863: &escape($cloner), &escape($cc_clone), $cloneonly,
5864: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 5865: &escape($creationcontext),$domcloner,$hasuniquecode,
5866: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 5867: } else {
5868: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5869: $sincefilter.':'.&escape($descfilter).':'.
5870: &escape($instcodefilter).':'.&escape($ownerfilter).
5871: ':'.&escape($coursefilter).':'.&escape($typefilter).
5872: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5873: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5874: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5875: &escape($cc_clone).':'.$cloneonly.':'.
5876: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 5877: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5878: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 5879: }
5880:
1.918 raeburn 5881: my @pairs=split(/\&/,$rep);
5882: foreach my $item (@pairs) {
5883: my ($key,$value)=split(/\=/,$item,2);
5884: $key = &unescape($key);
5885: next if ($key =~ /^error: 2 /);
5886: my $result = &thaw_unescape($value);
5887: if (ref($result) eq 'HASH') {
5888: $returnhash{$key}=$result;
5889: } else {
1.921 raeburn 5890: my @responses = split(/:/,$value);
5891: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5892: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5893: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5894: }
1.1008 raeburn 5895: }
1.353 www 5896: }
5897: }
5898: }
5899: }
5900: return %returnhash;
5901: }
5902:
1.1055 raeburn 5903: sub courselastaccess {
5904: my ($cdom,$cnum,$hostidref) = @_;
5905: my %returnhash;
5906: if ($cdom && $cnum) {
5907: my $chome = &homeserver($cnum,$cdom);
5908: if ($chome ne 'no_host') {
5909: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5910: &extract_lastaccess(\%returnhash,$rep);
5911: }
5912: } else {
5913: if (!$cdom) { $cdom=''; }
5914: my %libserv = &all_library();
5915: foreach my $tryserver (keys(%libserv)) {
5916: if (ref($hostidref) eq 'ARRAY') {
5917: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5918: }
5919: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5920: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5921: &extract_lastaccess(\%returnhash,$rep);
5922: }
5923: }
5924: }
5925: return %returnhash;
5926: }
5927:
5928: sub extract_lastaccess {
5929: my ($returnhash,$rep) = @_;
5930: if (ref($returnhash) eq 'HASH') {
5931: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5932: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5933: $rep eq '') {
5934: my @pairs=split(/\&/,$rep);
5935: foreach my $item (@pairs) {
5936: my ($key,$value)=split(/\=/,$item,2);
5937: $key = &unescape($key);
5938: next if ($key =~ /^error: 2 /);
5939: $returnhash->{$key} = &thaw_unescape($value);
5940: }
5941: }
5942: }
5943: return;
5944: }
5945:
1.658 raeburn 5946: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5947:
5948: sub dcmailput {
1.685 raeburn 5949: my ($domain,$msgid,$message,$server)=@_;
1.1494 raeburn 5950: my $status = &critical(
1.740 www 5951: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5952: &escape($message),$server);
1.662 raeburn 5953: return $status;
5954: }
5955:
1.658 raeburn 5956: sub dcmaildump {
5957: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5958: my %returnhash=();
1.846 albertel 5959:
5960: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5961: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5962: &escape($enddate).':';
5963: my @esc_senders=map { &escape($_)} @$senders;
5964: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5965: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5966: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5967: if (($key) && ($value)) {
5968: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5969: }
5970: }
5971: }
5972: return %returnhash;
5973: }
1.662 raeburn 5974: # ---------------------------------------------------------- Domain roles
5975:
5976: sub get_domain_roles {
5977: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5978: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5979: $startdate = '.';
5980: }
1.1018 raeburn 5981: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5982: $enddate = '.';
5983: }
1.922 raeburn 5984: my $rolelist;
5985: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 5986: $rolelist = join('&',@{$roles});
1.922 raeburn 5987: }
1.662 raeburn 5988: my %personnel = ();
1.841 albertel 5989:
5990: my %servers = &get_servers($dom,'library');
5991: foreach my $tryserver (keys(%servers)) {
5992: %{$personnel{$tryserver}}=();
5993: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5994: &escape($startdate).':'.
5995: &escape($enddate).':'.
5996: &escape($rolelist), $tryserver))) {
5997: my ($key,$value) = split(/\=/,$line,2);
5998: if (($key) && ($value)) {
5999: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
6000: }
6001: }
1.662 raeburn 6002: }
6003: return %personnel;
6004: }
1.658 raeburn 6005:
1.1332 raeburn 6006: sub get_active_domroles {
6007: my ($dom,$roles) = @_;
6008: return () unless (ref($roles) eq 'ARRAY');
6009: my $now = time;
6010: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
6011: my %domroles;
6012: foreach my $server (keys(%dompersonnel)) {
6013: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
6014: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
6015: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
6016: }
6017: }
6018: return %domroles;
6019: }
6020:
1.1057 www 6021: # ----------------------------------------------------------- Interval timing
1.149 www 6022:
1.1153 www 6023: {
6024: # Caches needed for speedup of navmaps
6025: # We don't want to cache this for very long at all (5 seconds at most)
6026: #
6027: # The user for whom we cache
6028: my $cachedkey='';
6029: # The cached times for this user
6030: my %cachedtimes=();
6031: # When this was last done
1.1282 raeburn 6032: my $cachedtime='';
1.1153 www 6033:
6034: sub load_all_first_access {
1.1308 raeburn 6035: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 6036: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 6037: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
6038: (!$ignorecache)) {
1.1154 raeburn 6039: return;
6040: }
6041: $cachedtime=time;
6042: $cachedkey=$uname.':'.$udom;
6043: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 6044: }
6045:
1.504 albertel 6046: sub get_first_access {
1.1308 raeburn 6047: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 6048: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 6049: if ($argsymb) { $symb=$argsymb; }
6050: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 6051: if ($argmap) { $map = $argmap; }
1.926 albertel 6052: if ($type eq 'course') {
6053: $res='course';
6054: } elsif ($type eq 'map') {
1.588 albertel 6055: $res=&symbread($map);
6056: } else {
6057: $res=$symb;
6058: }
1.1308 raeburn 6059: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 6060: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 6061: }
6062:
6063: sub set_first_access {
1.1162 raeburn 6064: my ($type,$interval)=@_;
1.790 albertel 6065: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 6066: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 6067: if ($type eq 'course') {
6068: $res='course';
6069: } elsif ($type eq 'map') {
1.588 albertel 6070: $res=&symbread($map);
6071: } else {
6072: $res=$symb;
6073: }
1.1153 www 6074: $cachedkey='';
1.1162 raeburn 6075: my $firstaccess=&get_first_access($type,$symb,$map);
1.1386 raeburn 6076: if ($firstaccess) {
6077: &logthis("First access time already set ($firstaccess) when attempting ".
1.1393 raeburn 6078: "to set new value (type: $type, extent: $res) for $uname:$udom ".
6079: "in $courseid");
1.1386 raeburn 6080: return 'already_set';
6081: } else {
1.1162 raeburn 6082: my $start = time;
6083: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
6084: $udom,$uname);
6085: if ($putres eq 'ok') {
6086: &put('timerinterval',{"$courseid\0$res"=>$interval},
6087: $udom,$uname);
6088: &appenv(
6089: {
6090: 'course.'.$courseid.'.firstaccess.'.$res => $start,
6091: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
6092: }
6093: );
1.1365 raeburn 6094: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
6095: $cachedtimes{"$courseid\0$res"} = $start;
6096: }
1.1386 raeburn 6097: } elsif ($putres ne 'refused') {
6098: &logthis("Result: $putres when attempting to set first access time ".
6099: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 6100: }
6101: return $putres;
1.505 albertel 6102: }
6103: return 'already_set';
1.504 albertel 6104: }
1.1153 www 6105: }
1.1282 raeburn 6106:
1.110 www 6107: # --------------------------------------------- Set Expire Date for Spreadsheet
6108:
6109: sub expirespread {
6110: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 6111: my $cid=$env{'request.course.id'};
1.110 www 6112: if ($cid) {
6113: my $now=time;
6114: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 6115: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
6116: $env{'course.'.$cid.'.num'}.
1.110 www 6117: ':nohist_expirationdates:'.
6118: &escape($key).'='.$now,
1.620 albertel 6119: $env{'course.'.$cid.'.home'})
1.110 www 6120: }
6121: return 'ok';
1.14 www 6122: }
6123:
1.109 www 6124: # ----------------------------------------------------- Devalidate Spreadsheets
6125:
6126: sub devalidate {
1.325 www 6127: my ($symb,$uname,$udom)=@_;
1.620 albertel 6128: my $cid=$env{'request.course.id'};
1.109 www 6129: if ($cid) {
1.391 matthew 6130: # delete the stored spreadsheets for
6131: # - the student level sheet of this user in course's homespace
6132: # - the assessment level sheet for this resource
6133: # for this user in user's homespace
1.553 albertel 6134: # - current conditional state info
1.325 www 6135: my $key=$uname.':'.$udom.':';
1.109 www 6136: my $status=
1.299 matthew 6137: &del('nohist_calculatedsheets',
1.391 matthew 6138: [$key.'studentcalc:'],
1.620 albertel 6139: $env{'course.'.$cid.'.domain'},
6140: $env{'course.'.$cid.'.num'})
1.133 albertel 6141: .' '.
6142: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 6143: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 6144: unless ($status eq 'ok ok') {
6145: &logthis('Could not devalidate spreadsheet '.
1.325 www 6146: $uname.' at '.$udom.' for '.
1.109 www 6147: $symb.': '.$status);
1.133 albertel 6148: }
1.553 albertel 6149: &delenv('user.state.'.$cid);
1.109 www 6150: }
6151: }
6152:
1.265 albertel 6153: sub get_scalar {
6154: my ($string,$end) = @_;
6155: my $value;
6156: if ($$string =~ s/^([^&]*?)($end)/$2/) {
6157: $value = $1;
6158: } elsif ($$string =~ s/^([^&]*?)&//) {
6159: $value = $1;
6160: }
6161: return &unescape($value);
6162: }
6163:
6164: sub array2str {
6165: my (@array) = @_;
6166: my $result=&arrayref2str(\@array);
6167: $result=~s/^__ARRAY_REF__//;
6168: $result=~s/__END_ARRAY_REF__$//;
6169: return $result;
6170: }
6171:
1.204 albertel 6172: sub arrayref2str {
6173: my ($arrayref) = @_;
1.265 albertel 6174: my $result='__ARRAY_REF__';
1.204 albertel 6175: foreach my $elem (@$arrayref) {
1.265 albertel 6176: if(ref($elem) eq 'ARRAY') {
6177: $result.=&arrayref2str($elem).'&';
6178: } elsif(ref($elem) eq 'HASH') {
6179: $result.=&hashref2str($elem).'&';
6180: } elsif(ref($elem)) {
6181: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 6182: } else {
6183: $result.=&escape($elem).'&';
6184: }
6185: }
6186: $result=~s/\&$//;
1.265 albertel 6187: $result .= '__END_ARRAY_REF__';
1.204 albertel 6188: return $result;
6189: }
6190:
1.168 albertel 6191: sub hash2str {
1.204 albertel 6192: my (%hash) = @_;
6193: my $result=&hashref2str(\%hash);
1.265 albertel 6194: $result=~s/^__HASH_REF__//;
6195: $result=~s/__END_HASH_REF__$//;
1.204 albertel 6196: return $result;
6197: }
6198:
6199: sub hashref2str {
6200: my ($hashref)=@_;
1.265 albertel 6201: my $result='__HASH_REF__';
1.800 albertel 6202: foreach my $key (sort(keys(%$hashref))) {
6203: if (ref($key) eq 'ARRAY') {
6204: $result.=&arrayref2str($key).'=';
6205: } elsif (ref($key) eq 'HASH') {
6206: $result.=&hashref2str($key).'=';
6207: } elsif (ref($key)) {
1.265 albertel 6208: $result.='=';
1.800 albertel 6209: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 6210: } else {
1.1132 raeburn 6211: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 6212: }
6213:
1.800 albertel 6214: if(ref($hashref->{$key}) eq 'ARRAY') {
6215: $result.=&arrayref2str($hashref->{$key}).'&';
6216: } elsif(ref($hashref->{$key}) eq 'HASH') {
6217: $result.=&hashref2str($hashref->{$key}).'&';
6218: } elsif(ref($hashref->{$key})) {
1.265 albertel 6219: $result.='&';
1.800 albertel 6220: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 6221: } else {
1.800 albertel 6222: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 6223: }
6224: }
1.168 albertel 6225: $result=~s/\&$//;
1.265 albertel 6226: $result .= '__END_HASH_REF__';
1.168 albertel 6227: return $result;
6228: }
6229:
6230: sub str2hash {
1.265 albertel 6231: my ($string)=@_;
6232: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
6233: return %$hash;
6234: }
6235:
6236: sub str2hashref {
1.168 albertel 6237: my ($string) = @_;
1.265 albertel 6238:
6239: my %hash;
6240:
6241: if($string !~ /^__HASH_REF__/) {
6242: if (! ($string eq '' || !defined($string))) {
6243: $hash{'error'}='Not hash reference';
6244: }
6245: return (\%hash, $string);
6246: }
6247:
6248: $string =~ s/^__HASH_REF__//;
6249:
6250: while($string !~ /^__END_HASH_REF__/) {
6251: #key
6252: my $key='';
6253: if($string =~ /^__HASH_REF__/) {
6254: ($key, $string)=&str2hashref($string);
6255: if(defined($key->{'error'})) {
6256: $hash{'error'}='Bad data';
6257: return (\%hash, $string);
6258: }
6259: } elsif($string =~ /^__ARRAY_REF__/) {
6260: ($key, $string)=&str2arrayref($string);
6261: if($key->[0] eq 'Array reference error') {
6262: $hash{'error'}='Bad data';
6263: return (\%hash, $string);
6264: }
6265: } else {
6266: $string =~ s/^(.*?)=//;
1.267 albertel 6267: $key=&unescape($1);
1.265 albertel 6268: }
6269: $string =~ s/^=//;
6270:
6271: #value
6272: my $value='';
6273: if($string =~ /^__HASH_REF__/) {
6274: ($value, $string)=&str2hashref($string);
6275: if(defined($value->{'error'})) {
6276: $hash{'error'}='Bad data';
6277: return (\%hash, $string);
6278: }
6279: } elsif($string =~ /^__ARRAY_REF__/) {
6280: ($value, $string)=&str2arrayref($string);
6281: if($value->[0] eq 'Array reference error') {
6282: $hash{'error'}='Bad data';
6283: return (\%hash, $string);
6284: }
6285: } else {
6286: $value=&get_scalar(\$string,'__END_HASH_REF__');
6287: }
6288: $string =~ s/^&//;
6289:
6290: $hash{$key}=$value;
1.204 albertel 6291: }
1.265 albertel 6292:
6293: $string =~ s/^__END_HASH_REF__//;
6294:
6295: return (\%hash, $string);
1.204 albertel 6296: }
6297:
6298: sub str2array {
1.265 albertel 6299: my ($string)=@_;
6300: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
6301: return @$array;
6302: }
6303:
6304: sub str2arrayref {
1.204 albertel 6305: my ($string) = @_;
1.265 albertel 6306: my @array;
6307:
6308: if($string !~ /^__ARRAY_REF__/) {
6309: if (! ($string eq '' || !defined($string))) {
6310: $array[0]='Array reference error';
6311: }
6312: return (\@array, $string);
6313: }
6314:
6315: $string =~ s/^__ARRAY_REF__//;
6316:
6317: while($string !~ /^__END_ARRAY_REF__/) {
6318: my $value='';
6319: if($string =~ /^__HASH_REF__/) {
6320: ($value, $string)=&str2hashref($string);
6321: if(defined($value->{'error'})) {
6322: $array[0] ='Array reference error';
6323: return (\@array, $string);
6324: }
6325: } elsif($string =~ /^__ARRAY_REF__/) {
6326: ($value, $string)=&str2arrayref($string);
6327: if($value->[0] eq 'Array reference error') {
6328: $array[0] ='Array reference error';
6329: return (\@array, $string);
6330: }
6331: } else {
6332: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6333: }
6334: $string =~ s/^&//;
6335:
6336: push(@array, $value);
1.191 harris41 6337: }
1.265 albertel 6338:
6339: $string =~ s/^__END_ARRAY_REF__//;
6340:
6341: return (\@array, $string);
1.168 albertel 6342: }
6343:
1.167 albertel 6344: # -------------------------------------------------------------------Temp Store
6345:
1.168 albertel 6346: sub tmpreset {
6347: my ($symb,$namespace,$domain,$stuname) = @_;
6348: if (!$symb) {
6349: $symb=&symbread();
1.620 albertel 6350: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6351: }
6352: $symb=escape($symb);
6353:
1.620 albertel 6354: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 6355: $namespace=~s/\//\_/g;
6356: $namespace=~s/\W//g;
6357:
1.620 albertel 6358: if (!$domain) { $domain=$env{'user.domain'}; }
6359: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6360: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6361: $stuname=&get_requestor_ip();
1.591 albertel 6362: }
1.1117 foxr 6363: my $path=LONCAPA::tempdir();
1.168 albertel 6364: my %hash;
6365: if (tie(%hash,'GDBM_File',
6366: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6367: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 6368: foreach my $key (keys(%hash)) {
1.180 albertel 6369: if ($key=~ /:$symb/) {
1.168 albertel 6370: delete($hash{$key});
6371: }
6372: }
6373: }
6374: }
6375:
1.167 albertel 6376: sub tmpstore {
1.168 albertel 6377: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6378:
6379: if (!$symb) {
6380: $symb=&symbread();
1.620 albertel 6381: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6382: }
6383: $symb=escape($symb);
6384:
6385: if (!$namespace) {
6386: # I don't think we would ever want to store this for a course.
6387: # it seems this will only be used if we don't have a course.
1.620 albertel 6388: #$namespace=$env{'request.course.id'};
1.168 albertel 6389: #if (!$namespace) {
1.620 albertel 6390: $namespace=$env{'request.state'};
1.168 albertel 6391: #}
6392: }
6393: $namespace=~s/\//\_/g;
6394: $namespace=~s/\W//g;
1.620 albertel 6395: if (!$domain) { $domain=$env{'user.domain'}; }
6396: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6397: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6398: $stuname=&get_requestor_ip();
1.591 albertel 6399: }
1.168 albertel 6400: my $now=time;
6401: my %hash;
1.1117 foxr 6402: my $path=LONCAPA::tempdir();
1.168 albertel 6403: if (tie(%hash,'GDBM_File',
6404: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6405: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6406: $hash{"version:$symb"}++;
6407: my $version=$hash{"version:$symb"};
6408: my $allkeys='';
6409: foreach my $key (keys(%$storehash)) {
6410: $allkeys.=$key.':';
1.591 albertel 6411: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6412: }
6413: $hash{"$version:$symb:timestamp"}=$now;
6414: $allkeys.='timestamp';
6415: $hash{"$version:keys:$symb"}=$allkeys;
6416: if (untie(%hash)) {
6417: return 'ok';
6418: } else {
6419: return "error:$!";
6420: }
6421: } else {
6422: return "error:$!";
6423: }
6424: }
1.167 albertel 6425:
1.168 albertel 6426: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6427:
1.168 albertel 6428: sub tmprestore {
6429: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6430:
1.168 albertel 6431: if (!$symb) {
6432: $symb=&symbread();
1.620 albertel 6433: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6434: }
6435: $symb=escape($symb);
6436:
1.620 albertel 6437: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6438:
1.620 albertel 6439: if (!$domain) { $domain=$env{'user.domain'}; }
6440: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6441: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6442: $stuname=&get_requestor_ip();
1.591 albertel 6443: }
1.168 albertel 6444: my %returnhash;
6445: $namespace=~s/\//\_/g;
6446: $namespace=~s/\W//g;
6447: my %hash;
1.1117 foxr 6448: my $path=LONCAPA::tempdir();
1.168 albertel 6449: if (tie(%hash,'GDBM_File',
6450: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6451: &GDBM_READER(),0640)) {
1.168 albertel 6452: my $version=$hash{"version:$symb"};
6453: $returnhash{'version'}=$version;
6454: my $scope;
6455: for ($scope=1;$scope<=$version;$scope++) {
6456: my $vkeys=$hash{"$scope:keys:$symb"};
6457: my @keys=split(/:/,$vkeys);
6458: my $key;
6459: $returnhash{"$scope:keys"}=$vkeys;
6460: foreach $key (@keys) {
1.591 albertel 6461: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6462: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6463: }
6464: }
1.168 albertel 6465: if (!(untie(%hash))) {
6466: return "error:$!";
6467: }
6468: } else {
6469: return "error:$!";
6470: }
6471: return %returnhash;
1.167 albertel 6472: }
6473:
1.9 www 6474: # ----------------------------------------------------------------------- Store
6475:
6476: sub store {
1.1269 raeburn 6477: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6478: my $home='';
6479:
1.168 albertel 6480: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6481:
1.213 www 6482: $symb=&symbclean($symb);
1.122 albertel 6483: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6484:
1.620 albertel 6485: if (!$domain) { $domain=$env{'user.domain'}; }
6486: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6487:
6488: &devalidate($symb,$stuname,$domain);
1.109 www 6489:
6490: $symb=escape($symb);
1.187 www 6491: if (!$namespace) {
1.620 albertel 6492: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6493: return '';
6494: }
6495: }
1.620 albertel 6496: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6497:
1.1434 raeburn 6498: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6499: $$storehash{'host'}=$perlvar{'lonHostID'};
6500:
1.12 www 6501: my $namevalue='';
1.800 albertel 6502: foreach my $key (keys(%$storehash)) {
6503: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6504: }
1.12 www 6505: $namevalue=~s/\&$//;
1.187 www 6506: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 6507: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6508: }
6509:
1.47 www 6510: # -------------------------------------------------------------- Critical Store
6511:
6512: sub cstore {
1.1269 raeburn 6513: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6514: my $home='';
6515:
1.168 albertel 6516: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6517:
1.213 www 6518: $symb=&symbclean($symb);
1.122 albertel 6519: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6520:
1.620 albertel 6521: if (!$domain) { $domain=$env{'user.domain'}; }
6522: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6523:
6524: &devalidate($symb,$stuname,$domain);
1.109 www 6525:
6526: $symb=escape($symb);
1.187 www 6527: if (!$namespace) {
1.620 albertel 6528: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6529: return '';
6530: }
6531: }
1.620 albertel 6532: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6533:
1.1434 raeburn 6534: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6535: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6536:
1.47 www 6537: my $namevalue='';
1.800 albertel 6538: foreach my $key (keys(%$storehash)) {
6539: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6540: }
1.47 www 6541: $namevalue=~s/\&$//;
1.187 www 6542: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6543: return critical
1.1269 raeburn 6544: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6545: }
6546:
1.9 www 6547: # --------------------------------------------------------------------- Restore
6548:
6549: sub restore {
1.124 www 6550: my ($symb,$namespace,$domain,$stuname) = @_;
6551: my $home='';
6552:
1.168 albertel 6553: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6554:
1.122 albertel 6555: if (!$symb) {
1.1224 raeburn 6556: return if ($namespace eq 'courserequests');
6557: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6558: } else {
1.1224 raeburn 6559: unless ($namespace eq 'courserequests') {
6560: $symb=&escape(&symbclean($symb));
6561: }
1.122 albertel 6562: }
1.188 www 6563: if (!$namespace) {
1.620 albertel 6564: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6565: return '';
6566: }
6567: }
1.620 albertel 6568: if (!$domain) { $domain=$env{'user.domain'}; }
6569: if (!$stuname) { $stuname=$env{'user.name'}; }
6570: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6571: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6572:
1.12 www 6573: my %returnhash=();
1.800 albertel 6574: foreach my $line (split(/\&/,$answer)) {
6575: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6576: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6577: }
1.75 www 6578: my $version;
6579: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6580: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6581: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6582: }
1.75 www 6583: }
1.13 www 6584: return %returnhash;
1.34 www 6585: }
6586:
6587: # ---------------------------------------------------------- Course Description
1.1118 foxr 6588: #
6589: #
1.34 www 6590:
6591: sub coursedescription {
1.731 albertel 6592: my ($courseid,$args)=@_;
1.34 www 6593: $courseid=~s/^\///;
1.49 www 6594: $courseid=~s/\_/\//g;
1.34 www 6595: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6596: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6597: my $normalid=$cdomain.'_'.$cnum;
6598: # need to always cache even if we get errors otherwise we keep
6599: # trying and trying and trying to get the course description.
6600: my %envhash=();
6601: my %returnhash=();
1.731 albertel 6602:
6603: my $expiretime=600;
6604: if ($env{'request.course.id'} eq $normalid) {
6605: $expiretime=120;
6606: }
6607:
6608: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6609: if (!$args->{'freshen_cache'}
6610: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6611: foreach my $key (keys(%env)) {
6612: next if ($key !~ /^\Q$prefix\E(.*)/);
6613: my ($setting) = $1;
6614: $returnhash{$setting} = $env{$key};
6615: }
6616: return %returnhash;
6617: }
6618:
1.1118 foxr 6619: # get the data again
6620:
1.731 albertel 6621: if (!$args->{'one_time'}) {
6622: $envhash{'course.'.$normalid.'.last_cache'}=time;
6623: }
1.811 albertel 6624:
1.34 www 6625: if ($chome ne 'no_host') {
1.302 albertel 6626: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6627: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6628: my $username = $env{'user.name'}; # Defult username
6629: if(defined $args->{'user'}) {
6630: $username = $args->{'user'};
6631: }
1.129 albertel 6632: $returnhash{'home'}= $chome;
6633: $returnhash{'domain'} = $cdomain;
6634: $returnhash{'num'} = $cnum;
1.741 raeburn 6635: if (!defined($returnhash{'type'})) {
6636: $returnhash{'type'} = 'Course';
6637: }
1.130 albertel 6638: while (my ($name,$value) = each %returnhash) {
1.53 www 6639: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6640: }
1.270 www 6641: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6642: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6643: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6644: $envhash{'course.'.$normalid.'.home'}=$chome;
6645: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6646: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6647: }
6648: }
1.731 albertel 6649: if (!$args->{'one_time'}) {
1.949 raeburn 6650: &appenv(\%envhash);
1.731 albertel 6651: }
1.302 albertel 6652: return %returnhash;
1.461 www 6653: }
6654:
1.1080 raeburn 6655: sub update_released_required {
6656: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6657: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6658: $cid = $env{'request.course.id'};
6659: $cdom = $env{'course.'.$cid.'.domain'};
6660: $cnum = $env{'course.'.$cid.'.num'};
6661: $chome = $env{'course.'.$cid.'.home'};
6662: }
6663: if ($needsrelease) {
6664: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6665: my $needsupdate;
6666: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6667: $needsupdate = 1;
6668: } else {
6669: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6670: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6671: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6672: $needsupdate = 1;
6673: }
6674: }
6675: if ($needsupdate) {
6676: my %needshash = (
6677: 'internal.releaserequired' => $needsrelease,
6678: );
6679: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6680: if ($putresult eq 'ok') {
6681: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6682: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6683: if (ref($crsinfo{$cid}) eq 'HASH') {
6684: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6685: &courseidput($cdom,\%crsinfo,$chome,'notime');
6686: }
6687: }
6688: }
6689: }
6690: return;
6691: }
6692:
1.461 www 6693: # -------------------------------------------------See if a user is privileged
6694:
6695: sub privileged {
1.1219 raeburn 6696: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6697: my $now = time;
1.1219 raeburn 6698: my $roles;
6699: if (ref($possroles) eq 'ARRAY') {
6700: $roles = $possroles;
6701: } else {
6702: $roles = ['dc','su'];
6703: }
6704: if (ref($possdomains) eq 'ARRAY') {
6705: my %privileged = &privileged_by_domain($possdomains,$roles);
6706: foreach my $dom (@{$possdomains}) {
6707: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6708: (ref($privileged{$dom}) eq 'HASH')) {
6709: foreach my $role (@{$roles}) {
6710: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6711: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6712: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6713: return 1 unless (($end && $end < $now) ||
6714: ($start && $start > $now));
6715: }
6716: }
6717: }
6718: }
6719: }
6720: } else {
6721: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6722: my $now = time;
1.1170 droeschl 6723:
1.1275 musolffc 6724: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6725: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 6726: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 6727: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 6728: or ($tstart && $tstart > $now);
1.1170 droeschl 6729: }
1.1219 raeburn 6730: }
6731: }
6732: return 0;
6733: }
1.1170 droeschl 6734:
1.1219 raeburn 6735: sub privileged_by_domain {
6736: my ($domains,$roles) = @_;
6737: my %privileged = ();
6738: my $cachetime = 60*60*24;
6739: my $now = time;
6740: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6741: return %privileged;
6742: }
6743: foreach my $dom (@{$domains}) {
6744: next if (ref($privileged{$dom}) eq 'HASH');
6745: my $needroles;
6746: foreach my $role (@{$roles}) {
6747: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6748: if (defined($cached)) {
6749: if (ref($result) eq 'HASH') {
6750: $privileged{$dom}{$role} = $result;
6751: }
6752: } else {
6753: $needroles = 1;
6754: }
6755: }
6756: if ($needroles) {
6757: my %dompersonnel = &get_domain_roles($dom,$roles);
6758: $privileged{$dom} = {};
6759: foreach my $server (keys(%dompersonnel)) {
6760: if (ref($dompersonnel{$server}) eq 'HASH') {
6761: foreach my $item (keys(%{$dompersonnel{$server}})) {
6762: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6763: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6764: next if ($end && $end < $now);
6765: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6766: $dompersonnel{$server}{$item};
6767: }
6768: }
6769: }
6770: if (ref($privileged{$dom}) eq 'HASH') {
6771: foreach my $role (@{$roles}) {
6772: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6773: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6774: } else {
6775: my %hash = ();
6776: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6777: }
6778: }
6779: }
6780: }
6781: }
6782: return %privileged;
1.9 www 6783: }
1.1 albertel 6784:
1.103 harris41 6785: # -------------------------------------------------------- Get user privileges
1.11 www 6786:
6787: sub rolesinit {
1.1169 droeschl 6788: my ($domain, $username) = @_;
6789: my %userroles = ('user.login.time' => time);
6790: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6791:
6792: # firstaccess and timerinterval are related to timed maps/resources.
6793: # also, blocking can be triggered by an activating timer
6794: # it's saved in the user's %env.
6795: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6796: my %timerinterval = &dump('timerinterval', $domain, $username);
6797: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6798: %timerintchk, %timerintenv);
6799:
1.1162 raeburn 6800: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6801: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6802: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6803: }
1.1169 droeschl 6804:
1.1162 raeburn 6805: foreach my $key (keys(%timerinterval)) {
6806: my ($cid,$rest) = split(/\0/,$key);
6807: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6808: }
1.1169 droeschl 6809:
1.11 www 6810: my %allroles=();
1.1162 raeburn 6811: my %allgroups=();
1.11 www 6812:
1.1274 raeburn 6813: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6814: my $role = $rolesdump{$area};
6815: $area =~ s/\_\w\w$//;
6816:
6817: my ($trole, $tend, $tstart, $group_privs);
6818:
6819: if ($role =~ /^cr/) {
6820: # Custom role, defined by a user
6821: # e.g., user.role.cr/msu/smith/mynewrole
6822: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6823: $trole = $1;
6824: ($tend, $tstart) = split('_', $2);
6825: } else {
6826: $trole = $role;
6827: }
6828: } elsif ($role =~ m|^gr/|) {
6829: # Role of member in a group, defined within a course/community
6830: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6831: ($trole, $tend, $tstart) = split(/_/, $role);
6832: next if $tstart eq '-1';
6833: ($trole, $group_privs) = split(/\//, $trole);
6834: $group_privs = &unescape($group_privs);
6835: } else {
6836: # Just a normal role, defined in roles.tab
6837: ($trole, $tend, $tstart) = split(/_/,$role);
6838: }
6839:
6840: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6841: $username);
6842: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6843:
6844: # role expired or not available yet?
6845: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6846: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6847:
6848: next if $area eq '' or $trole eq '';
6849:
6850: my $spec = "$trole.$area";
6851: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6852:
6853: if ($trole =~ /^cr\//) {
6854: # Custom role, defined by a user
6855: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6856: } elsif ($trole eq 'gr') {
6857: # Role of a member in a group, defined within a course/community
6858: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6859: next;
6860: } else {
6861: # Normal role, defined in roles.tab
6862: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6863: }
6864:
6865: my $cid = $tdomain.'_'.$trest;
6866: unless ($firstaccchk{$cid}) {
6867: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6868: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6869: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6870: $coursetimerstarts{$cid}{$item};
6871: }
6872: }
6873: $firstaccchk{$cid} = 1;
6874: }
6875: unless ($timerintchk{$cid}) {
6876: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6877: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6878: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6879: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6880: }
1.12 www 6881: }
1.1169 droeschl 6882: $timerintchk{$cid} = 1;
1.191 harris41 6883: }
1.11 www 6884: }
1.1169 droeschl 6885:
1.1341 raeburn 6886: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6887: \%allroles, \%allgroups);
1.1169 droeschl 6888: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 6889: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6890:
1.1162 raeburn 6891: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6892: }
6893:
1.567 raeburn 6894: sub set_arearole {
1.1215 raeburn 6895: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6896: unless ($nolog) {
1.567 raeburn 6897: # log the associated role with the area
1.1215 raeburn 6898: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6899: }
1.743 albertel 6900: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6901: }
6902:
6903: sub custom_roleprivs {
6904: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6905: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 6906: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6907: if (&hostname($homsvr) ne '') {
1.567 raeburn 6908: my ($rdummy,$roledef)=
6909: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6910: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6911: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6912: if (defined($syspriv)) {
1.1043 raeburn 6913: if ($trest =~ /^$match_community$/) {
6914: $syspriv =~ s/bre\&S//;
6915: }
1.567 raeburn 6916: $$allroles{'cm./'}.=':'.$syspriv;
6917: $$allroles{$spec.'./'}.=':'.$syspriv;
6918: }
6919: if ($tdomain ne '') {
6920: if (defined($dompriv)) {
6921: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6922: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6923: }
6924: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 6925: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6926: my $rolename = $1;
6927: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6928: }
1.567 raeburn 6929: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6930: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6931: }
6932: }
6933: }
6934: }
6935: }
6936:
1.1332 raeburn 6937: sub course_adhocrole_privs {
6938: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6939: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6940: if ($overrides{"internal.adhocpriv.$rolename"}) {
6941: my (%currprivs,%storeprivs);
6942: foreach my $item (split(/:/,$coursepriv)) {
6943: my ($priv,$restrict) = split(/\&/,$item);
6944: $currprivs{$priv} = $restrict;
6945: }
6946: my (%possadd,%possremove,%full);
6947: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6948: my ($priv,$restrict)=split(/\&/,$item);
6949: $full{$priv} = $restrict;
6950: }
6951: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1490 raeburn 6952: next if ($item eq '');
6953: my ($rule,$rest) = split(/=/,$item);
6954: next unless (($rule eq 'off') || ($rule eq 'on'));
6955: foreach my $priv (split(/:/,$rest)) {
6956: if ($priv ne '') {
6957: if ($rule eq 'off') {
6958: $possremove{$priv} = 1;
6959: } else {
6960: $possadd{$priv} = 1;
6961: }
6962: }
6963: }
6964: }
6965: foreach my $priv (sort(keys(%full))) {
6966: if (exists($currprivs{$priv})) {
6967: unless (exists($possremove{$priv})) {
6968: $storeprivs{$priv} = $currprivs{$priv};
6969: }
6970: } elsif (exists($possadd{$priv})) {
6971: $storeprivs{$priv} = $full{$priv};
6972: }
6973: }
6974: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6975: }
6976: return $coursepriv;
1.1332 raeburn 6977: }
6978:
1.678 raeburn 6979: sub group_roleprivs {
6980: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6981: my $access = 1;
6982: my $now = time;
6983: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6984: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6985: if ($access) {
1.811 albertel 6986: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6987: $$allgroups{$course}{$group} .=':'.$group_privs;
6988: }
6989: }
1.567 raeburn 6990:
6991: sub standard_roleprivs {
6992: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6993: if (defined($pr{$trole.':s'})) {
6994: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6995: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6996: }
6997: if ($tdomain ne '') {
6998: if (defined($pr{$trole.':d'})) {
6999: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
7000: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
7001: }
7002: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
7003: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
7004: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
7005: }
7006: }
7007: }
7008:
7009: sub set_userprivs {
1.1064 raeburn 7010: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 7011: my $author=0;
7012: my $adv=0;
1.1341 raeburn 7013: my $rar=0;
1.678 raeburn 7014: my %grouproles = ();
7015: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 7016: my @groupkeys;
1.1000 raeburn 7017: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 7018: push(@groupkeys,$role);
7019: }
7020: if (ref($groups_roles) eq 'HASH') {
7021: foreach my $key (keys(%{$groups_roles})) {
7022: unless (grep(/^\Q$key\E$/,@groupkeys)) {
7023: push(@groupkeys,$key);
7024: }
7025: }
7026: }
7027: if (@groupkeys > 0) {
7028: foreach my $role (@groupkeys) {
7029: my ($trole,$area,$sec,$extendedarea);
7030: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
7031: $trole = $1;
7032: $area = $2;
7033: $sec = $3;
7034: $extendedarea = $area.$sec;
7035: if (exists($$allgroups{$area})) {
7036: foreach my $group (keys(%{$$allgroups{$area}})) {
7037: my $spec = $trole.'.'.$extendedarea;
7038: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 7039: $$allgroups{$area}{$group};
1.1064 raeburn 7040: }
1.678 raeburn 7041: }
7042: }
7043: }
7044: }
7045: }
1.800 albertel 7046: foreach my $group (keys(%grouproles)) {
7047: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 7048: }
1.800 albertel 7049: foreach my $role (keys(%{$allroles})) {
7050: my %thesepriv;
1.941 raeburn 7051: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 7052: foreach my $item (split(/:/,$$allroles{$role})) {
7053: if ($item ne '') {
7054: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 7055: if ($restrictions eq '') {
7056: $thesepriv{$privilege}='F';
7057: } elsif ($thesepriv{$privilege} ne 'F') {
7058: $thesepriv{$privilege}.=$restrictions;
7059: }
7060: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 7061: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 7062: }
7063: }
7064: my $thesestr='';
1.1104 raeburn 7065: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 7066: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
7067: }
7068: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 7069: }
1.1341 raeburn 7070: return ($author,$adv,$rar);
1.567 raeburn 7071: }
7072:
1.994 raeburn 7073: sub role_status {
1.1104 raeburn 7074: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 7075: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 7076: my ($one,$two) = split(m{\./},$rolekey,2);
7077: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 7078: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 7079: $$where = '/'.$two;
1.994 raeburn 7080: $$trolecode=$$role.'.'.$$where;
7081: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
7082: $$tstatus='is';
1.1104 raeburn 7083: if ($$tstart && $$tstart>$update) {
1.994 raeburn 7084: $$tstatus='future';
1.1034 raeburn 7085: if ($$tstart<$now) {
7086: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 7087: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 7088: my (%allroles,%allgroups,$group_privs,
7089: %groups_roles,@rolecodes);
1.1002 raeburn 7090: my %userroles = (
7091: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
7092: );
1.1064 raeburn 7093: @rolecodes = ('cm');
1.1002 raeburn 7094: my $spec=$$role.'.'.$$where;
7095: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
7096: if ($$role =~ /^cr\//) {
7097: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 7098: push(@rolecodes,'cr');
1.1002 raeburn 7099: } elsif ($$role eq 'gr') {
1.1064 raeburn 7100: push(@rolecodes,$$role);
1.1002 raeburn 7101: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
7102: $env{'user.name'});
1.1064 raeburn 7103: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 7104: (undef,my $group_privs) = split(/\//,$trole);
7105: $group_privs = &unescape($group_privs);
7106: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 7107: 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 7108: &get_groups_roles($tdomain,$trest,
7109: \%course_roles,\@rolecodes,
7110: \%groups_roles);
1.1002 raeburn 7111: } else {
1.1064 raeburn 7112: push(@rolecodes,$$role);
1.1002 raeburn 7113: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
7114: }
1.1341 raeburn 7115: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
7116: \%groups_roles);
1.1064 raeburn 7117: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 7118: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 7119: }
7120: }
1.1034 raeburn 7121: $$tstatus = 'is';
1.1002 raeburn 7122: }
1.994 raeburn 7123: }
7124: if ($$tend) {
1.1104 raeburn 7125: if ($$tend<$update) {
1.994 raeburn 7126: $$tstatus='expired';
7127: } elsif ($$tend<$now) {
7128: $$tstatus='will_not';
7129: }
7130: }
7131: }
7132: }
7133: }
7134:
1.1104 raeburn 7135: sub get_groups_roles {
7136: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
7137: return unless((ref($cdom_courseroles) eq 'HASH') &&
7138: (ref($rolecodes) eq 'ARRAY') &&
7139: (ref($groups_roles) eq 'HASH'));
7140: if (keys(%{$cdom_courseroles}) > 0) {
7141: my ($cnum) = ($rest =~ /^($match_courseid)/);
7142: if ($cdom ne '' && $cnum ne '') {
7143: foreach my $key (keys(%{$cdom_courseroles})) {
7144: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
7145: my $crsrole = $1;
7146: my $crssec = $2;
7147: if ($crsrole =~ /^cr/) {
7148: unless (grep(/^cr$/,@{$rolecodes})) {
7149: push(@{$rolecodes},'cr');
7150: }
7151: } else {
7152: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
7153: push(@{$rolecodes},$crsrole);
7154: }
7155: }
7156: my $rolekey = "$crsrole./$cdom/$cnum";
7157: if ($crssec ne '') {
7158: $rolekey .= "/$crssec";
7159: }
7160: $rolekey .= './';
7161: $groups_roles->{$rolekey} = $rolecodes;
7162: }
7163: }
7164: }
7165: }
7166: return;
7167: }
7168:
7169: sub delete_env_groupprivs {
7170: my ($where,$courseroles,$possroles) = @_;
7171: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
7172: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
7173: unless (ref($courseroles->{$udom}) eq 'HASH') {
7174: %{$courseroles->{$udom}} =
7175: &get_my_roles('','','userroles',['active'],
7176: $possroles,[$udom],1);
7177: }
7178: if (ref($courseroles->{$udom}) eq 'HASH') {
7179: foreach my $item (keys(%{$courseroles->{$udom}})) {
7180: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
7181: my $area = '/'.$cdom.'/'.$cnum;
7182: my $privkey = "user.priv.$crsrole.$area";
7183: if ($crssec ne '') {
7184: $privkey .= '/'.$crssec;
7185: }
7186: $privkey .= ".$area/$group";
7187: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
7188: }
7189: }
7190: return;
7191: }
7192:
1.994 raeburn 7193: sub check_adhoc_privs {
1.1329 raeburn 7194: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 7195: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 7196: if ($sec) {
7197: $cckey .= '/'.$sec;
7198: }
1.1185 raeburn 7199: my $setprivs;
1.994 raeburn 7200: if ($env{$cckey}) {
7201: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 7202: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 7203: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 7204: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7205: $setprivs = 1;
1.994 raeburn 7206: }
7207: } else {
1.1330 raeburn 7208: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7209: $setprivs = 1;
1.994 raeburn 7210: }
1.1185 raeburn 7211: return $setprivs;
1.994 raeburn 7212: }
7213:
7214: sub set_adhoc_privileges {
1.1326 raeburn 7215: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 7216: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 7217: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 7218: if ($sec ne '') {
7219: $area .= '/'.$sec;
7220: }
1.994 raeburn 7221: my $spec = $role.'.'.$area;
7222: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 7223: $env{'user.name'},1);
1.1326 raeburn 7224: my %rolehash = ();
1.1332 raeburn 7225: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
7226: my $rolename = $1;
1.1326 raeburn 7227: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 7228: my %domdef = &get_domain_defaults($dcdom);
7229: if (ref($domdef{'adhocroles'}) eq 'HASH') {
7230: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
7231: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
7232: }
7233: }
1.1326 raeburn 7234: } else {
7235: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
7236: }
1.1341 raeburn 7237: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 7238: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 7239: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402 raeburn 7240: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
7241: ($caller eq 'tiny')) {
1.1088 raeburn 7242: &appenv( {'request.role' => $spec,
7243: 'request.role.domain' => $dcdom,
1.1332 raeburn 7244: 'request.course.sec' => $sec,
1.1088 raeburn 7245: }
7246: );
7247: my $tadv=0;
7248: if (&allowed('adv') eq 'F') { $tadv=1; }
7249: &appenv({'request.role.adv' => $tadv});
7250: }
1.994 raeburn 7251: }
7252:
1.12 www 7253: # --------------------------------------------------------------- get interface
7254:
7255: sub get {
1.131 albertel 7256: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7257: my $items='';
1.800 albertel 7258: foreach my $item (@$storearr) {
7259: $items.=&escape($item).'&';
1.191 harris41 7260: }
1.12 www 7261: $items=~s/\&$//;
1.620 albertel 7262: if (!$udomain) { $udomain=$env{'user.domain'}; }
7263: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 7264: my $uhome=&homeserver($uname,$udomain);
7265:
1.133 albertel 7266: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7267: my @pairs=split(/\&/,$rep);
1.273 albertel 7268: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
7269: return @pairs;
7270: }
1.15 www 7271: my %returnhash=();
1.42 www 7272: my $i=0;
1.800 albertel 7273: foreach my $item (@$storearr) {
7274: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7275: $i++;
1.191 harris41 7276: }
1.15 www 7277: return %returnhash;
1.27 www 7278: }
7279:
7280: # --------------------------------------------------------------- del interface
7281:
7282: sub del {
1.133 albertel 7283: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 7284: my $items='';
1.800 albertel 7285: foreach my $item (@$storearr) {
7286: $items.=&escape($item).'&';
1.191 harris41 7287: }
1.984 neumanie 7288:
1.27 www 7289: $items=~s/\&$//;
1.620 albertel 7290: if (!$udomain) { $udomain=$env{'user.domain'}; }
7291: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7292: my $uhome=&homeserver($uname,$udomain);
7293: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7294: }
7295:
7296: # -------------------------------------------------------------- dump interface
7297:
1.1180 droeschl 7298: sub unserialize {
7299: my ($rep, $escapedkeys) = @_;
7300:
7301: return {} if $rep =~ /^error/;
7302:
7303: my %returnhash=();
1.1252 raeburn 7304: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 7305: my ($key, $value) = split(/=/, $item, 2);
7306: $key = unescape($key) unless $escapedkeys;
7307: next if $key =~ /^error: 2 /;
1.1252 raeburn 7308: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 7309: }
7310: #return %returnhash;
7311: return \%returnhash;
7312: }
7313:
7314: # see Lond::dump_with_regexp
7315: # if $escapedkeys hash keys won't get unescaped.
1.15 www 7316: sub dump {
1.1462 raeburn 7317: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755 albertel 7318: if (!$udomain) { $udomain=$env{'user.domain'}; }
7319: if (!$uname) { $uname=$env{'user.name'}; }
7320: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 7321:
1.1266 raeburn 7322: if ($regexp) {
7323: $regexp=&escape($regexp);
7324: } else {
7325: $regexp='.';
7326: }
1.1180 droeschl 7327: if (grep { $_ eq $uhome } current_machine_ids()) {
7328: # user is hosted on this machine
1.1266 raeburn 7329: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 7330: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 7331: return %{unserialize($reply, $escapedkeys)};
7332: }
1.1462 raeburn 7333: my $rep;
7334: if ($encrypt) {
7335: $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.1463 raeburn 7336: } else {
1.1462 raeburn 7337: $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7338: }
1.755 albertel 7339: my @pairs=split(/\&/,$rep);
7340: my %returnhash=();
1.1098 foxr 7341: if (!($rep =~ /^error/ )) {
7342: foreach my $item (@pairs) {
7343: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 7344: $key = unescape($key) unless $escapedkeys;
7345: #$key = &unescape($key);
1.1098 foxr 7346: next if ($key =~ /^error: 2 /);
7347: $returnhash{$key}=&thaw_unescape($value);
7348: }
1.755 albertel 7349: }
7350: return %returnhash;
1.407 www 7351: }
7352:
1.1098 foxr 7353:
1.717 albertel 7354: # --------------------------------------------------------- dumpstore interface
7355:
7356: sub dumpstore {
7357: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 7358: # same as dump but keys must be escaped. They may contain colon separated
7359: # lists of values that may themself contain colons (e.g. symbs).
7360: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 7361: }
7362:
1.407 www 7363: # -------------------------------------------------------------- keys interface
7364:
7365: sub getkeys {
7366: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 7367: if (!$udomain) { $udomain=$env{'user.domain'}; }
7368: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 7369: my $uhome=&homeserver($uname,$udomain);
7370: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7371: my @keyarray=();
1.800 albertel 7372: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 7373: next if ($key =~ /^error: 2 /);
1.800 albertel 7374: push(@keyarray,&unescape($key));
1.407 www 7375: }
7376: return @keyarray;
1.318 matthew 7377: }
7378:
1.319 matthew 7379: # --------------------------------------------------------------- currentdump
7380: sub currentdump {
1.328 matthew 7381: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 7382: $courseid = $env{'request.course.id'} if (! defined($courseid));
7383: $sdom = $env{'user.domain'} if (! defined($sdom));
7384: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 7385: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 7386: my $rep;
7387:
7388: if (grep { $_ eq $uhome } current_machine_ids()) {
7389: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7390: $courseid)));
7391: } else {
7392: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7393: }
7394:
1.318 matthew 7395: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7396: #
1.318 matthew 7397: my %returnhash=();
1.319 matthew 7398: #
1.1343 raeburn 7399: if ($rep eq 'unknown_cmd') {
1.319 matthew 7400: # an old lond will not know currentdump
7401: # Do a dump and make it look like a currentdump
1.822 albertel 7402: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7403: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7404: my %hash = @tmp;
7405: @tmp=();
1.424 matthew 7406: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7407: } else {
7408: my @pairs=split(/\&/,$rep);
1.800 albertel 7409: foreach my $pair (@pairs) {
7410: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7411: my ($symb,$param) = split(/:/,$key);
7412: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7413: &thaw_unescape($value);
1.319 matthew 7414: }
1.191 harris41 7415: }
1.12 www 7416: return %returnhash;
1.424 matthew 7417: }
7418:
7419: sub convert_dump_to_currentdump{
7420: my %hash = %{shift()};
7421: my %returnhash;
7422: # Code ripped from lond, essentially. The only difference
7423: # here is the unescaping done by lonnet::dump(). Conceivably
7424: # we might run in to problems with parameter names =~ /^v\./
7425: while (my ($key,$value) = each(%hash)) {
7426: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7427: $symb = &unescape($symb);
7428: $param = &unescape($param);
1.424 matthew 7429: next if ($v eq 'version' || $symb eq 'keys');
7430: next if (exists($returnhash{$symb}) &&
7431: exists($returnhash{$symb}->{$param}) &&
7432: $returnhash{$symb}->{'v.'.$param} > $v);
7433: $returnhash{$symb}->{$param}=$value;
7434: $returnhash{$symb}->{'v.'.$param}=$v;
7435: }
7436: #
7437: # Remove all of the keys in the hashes which keep track of
7438: # the version of the parameter.
7439: while (my ($symb,$param_hash) = each(%returnhash)) {
7440: # use a foreach because we are going to delete from the hash.
7441: foreach my $key (keys(%$param_hash)) {
7442: delete($param_hash->{$key}) if ($key =~ /^v\./);
7443: }
7444: }
7445: return \%returnhash;
1.12 www 7446: }
7447:
1.627 albertel 7448: # ------------------------------------------------------ critical inc interface
7449:
7450: sub cinc {
7451: return &inc(@_,'critical');
7452: }
7453:
1.449 matthew 7454: # --------------------------------------------------------------- inc interface
7455:
7456: sub inc {
1.627 albertel 7457: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7458: if (!$udomain) { $udomain=$env{'user.domain'}; }
7459: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7460: my $uhome=&homeserver($uname,$udomain);
7461: my $items='';
7462: if (! ref($store)) {
7463: # got a single value, so use that instead
7464: $items = &escape($store).'=&';
7465: } elsif (ref($store) eq 'SCALAR') {
7466: $items = &escape($$store).'=&';
7467: } elsif (ref($store) eq 'ARRAY') {
7468: $items = join('=&',map {&escape($_);} @{$store});
7469: } elsif (ref($store) eq 'HASH') {
7470: while (my($key,$value) = each(%{$store})) {
7471: $items.= &escape($key).'='.&escape($value).'&';
7472: }
7473: }
7474: $items=~s/\&$//;
1.627 albertel 7475: if ($critical) {
7476: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7477: } else {
7478: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7479: }
1.449 matthew 7480: }
7481:
1.12 www 7482: # --------------------------------------------------------------- put interface
7483:
7484: sub put {
1.1462 raeburn 7485: my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620 albertel 7486: if (!$udomain) { $udomain=$env{'user.domain'}; }
7487: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7488: my $uhome=&homeserver($uname,$udomain);
1.12 www 7489: my $items='';
1.800 albertel 7490: foreach my $item (keys(%$storehash)) {
7491: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7492: }
1.12 www 7493: $items=~s/\&$//;
1.1462 raeburn 7494: if ($encrypt) {
7495: return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
7496: } else {
7497: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7498: }
1.47 www 7499: }
7500:
1.631 albertel 7501: # ------------------------------------------------------------ newput interface
7502:
7503: sub newput {
7504: my ($namespace,$storehash,$udomain,$uname)=@_;
7505: if (!$udomain) { $udomain=$env{'user.domain'}; }
7506: if (!$uname) { $uname=$env{'user.name'}; }
7507: my $uhome=&homeserver($uname,$udomain);
7508: my $items='';
7509: foreach my $key (keys(%$storehash)) {
7510: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7511: }
7512: $items=~s/\&$//;
7513: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7514: }
7515:
7516: # --------------------------------------------------------- putstore interface
7517:
1.524 raeburn 7518: sub putstore {
1.1269 raeburn 7519: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7520: if (!$udomain) { $udomain=$env{'user.domain'}; }
7521: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7522: my $uhome=&homeserver($uname,$udomain);
7523: my $items='';
1.715 albertel 7524: foreach my $key (keys(%$storehash)) {
7525: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7526: }
1.715 albertel 7527: $items=~s/\&$//;
1.716 albertel 7528: my $esc_symb=&escape($symb);
7529: my $esc_v=&escape($version);
1.715 albertel 7530: my $reply =
1.716 albertel 7531: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7532: $uhome);
1.1269 raeburn 7533: if (($tolog) && ($reply eq 'ok')) {
7534: my $namevalue='';
7535: foreach my $key (keys(%{$storehash})) {
7536: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7537: }
1.1434 raeburn 7538: my $ip = &get_requestor_ip();
7539: $namevalue .= 'ip='.&escape($ip).
1.1269 raeburn 7540: '&host='.&escape($perlvar{'lonHostID'}).
7541: '&version='.$esc_v.
7542: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
1.1494 raeburn 7543: &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
1.1269 raeburn 7544: }
1.715 albertel 7545: if ($reply eq 'unknown_cmd') {
1.716 albertel 7546: # gfall back to way things use to be done
1.715 albertel 7547: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7548: $uname);
1.524 raeburn 7549: }
1.715 albertel 7550: return $reply;
7551: }
7552:
7553: sub old_putstore {
1.716 albertel 7554: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7555: if (!$udomain) { $udomain=$env{'user.domain'}; }
7556: if (!$uname) { $uname=$env{'user.name'}; }
7557: my $uhome=&homeserver($uname,$udomain);
7558: my %newstorehash;
1.800 albertel 7559: foreach my $item (keys(%$storehash)) {
7560: my $key = $version.':'.&escape($symb).':'.$item;
7561: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7562: }
7563: my $items='';
7564: my %allitems = ();
1.800 albertel 7565: foreach my $item (keys(%newstorehash)) {
7566: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7567: my $key = $1.':keys:'.$2;
7568: $allitems{$key} .= $3.':';
7569: }
1.800 albertel 7570: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7571: }
1.800 albertel 7572: foreach my $item (keys(%allitems)) {
7573: $allitems{$item} =~ s/\:$//;
7574: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7575: }
7576: $items=~s/\&$//;
7577: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7578: }
7579:
1.47 www 7580: # ------------------------------------------------------ critical put interface
7581:
7582: sub cput {
1.134 albertel 7583: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7584: if (!$udomain) { $udomain=$env{'user.domain'}; }
7585: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7586: my $uhome=&homeserver($uname,$udomain);
1.47 www 7587: my $items='';
1.800 albertel 7588: foreach my $item (keys(%$storehash)) {
7589: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7590: }
1.47 www 7591: $items=~s/\&$//;
1.134 albertel 7592: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7593: }
7594:
7595: # -------------------------------------------------------------- eget interface
7596:
7597: sub eget {
1.133 albertel 7598: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7599: my $items='';
1.800 albertel 7600: foreach my $item (@$storearr) {
7601: $items.=&escape($item).'&';
1.191 harris41 7602: }
1.12 www 7603: $items=~s/\&$//;
1.620 albertel 7604: if (!$udomain) { $udomain=$env{'user.domain'}; }
7605: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7606: my $uhome=&homeserver($uname,$udomain);
7607: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7608: my @pairs=split(/\&/,$rep);
7609: my %returnhash=();
1.42 www 7610: my $i=0;
1.800 albertel 7611: foreach my $item (@$storearr) {
7612: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7613: $i++;
1.191 harris41 7614: }
1.12 www 7615: return %returnhash;
7616: }
7617:
1.667 albertel 7618: # ------------------------------------------------------------ tmpput interface
7619: sub tmpput {
1.802 raeburn 7620: my ($storehash,$server,$context)=@_;
1.667 albertel 7621: my $items='';
1.800 albertel 7622: foreach my $item (keys(%$storehash)) {
7623: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7624: }
7625: $items=~s/\&$//;
1.802 raeburn 7626: if (defined($context)) {
7627: $items .= ':'.&escape($context);
7628: }
1.667 albertel 7629: return &reply("tmpput:$items",$server);
7630: }
7631:
7632: # ------------------------------------------------------------ tmpget interface
7633: sub tmpget {
1.688 albertel 7634: my ($token,$server)=@_;
7635: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7636: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7637: my %returnhash;
1.1328 raeburn 7638: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7639: return %returnhash;
7640: }
1.667 albertel 7641: foreach my $item (split(/\&/,$rep)) {
7642: my ($key,$value)=split(/=/,$item);
7643: $returnhash{&unescape($key)}=&thaw_unescape($value);
7644: }
7645: return %returnhash;
7646: }
7647:
1.1113 raeburn 7648: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7649: sub tmpdel {
7650: my ($token,$server)=@_;
7651: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7652: return &reply("tmpdel:$token",$server);
7653: }
7654:
1.1198 raeburn 7655: # ------------------------------------------------------------ get_timebased_id
7656:
7657: sub get_timebased_id {
7658: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7659: $maxtries) = @_;
7660: my ($newid,$error,$dellock);
7661: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7662: return ('','ok','invalid call to get suffix');
7663: }
7664:
7665: # set defaults for any optional args for which values were not supplied
7666: if ($who eq '') {
7667: $who = $env{'user.name'}.':'.$env{'user.domain'};
7668: }
7669: if (!$locktries) {
7670: $locktries = 3;
7671: }
7672: if (!$maxtries) {
7673: $maxtries = 10;
7674: }
7675:
7676: if (($cdom eq '') || ($cnum eq '')) {
7677: if ($env{'request.course.id'}) {
7678: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7679: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7680: }
7681: if (($cdom eq '') || ($cnum eq '')) {
7682: return ('','ok','call to get suffix not in course context');
7683: }
7684: }
7685:
7686: # construct locking item
7687: my $lockhash = {
7688: $prefix."\0".'locked_'.$keyid => $who,
7689: };
7690: my $tries = 0;
7691:
7692: # attempt to get lock on nohist_$namespace file
1.1494 raeburn 7693: my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198 raeburn 7694: while (($gotlock ne 'ok') && $tries <$locktries) {
7695: $tries ++;
7696: sleep 1;
1.1494 raeburn 7697: $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198 raeburn 7698: }
7699:
7700: # attempt to get unique identifier, based on current timestamp
7701: if ($gotlock eq 'ok') {
1.1494 raeburn 7702: my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
1.1198 raeburn 7703: my $id = time;
7704: $newid = $id;
1.1268 raeburn 7705: if ($idtype eq 'addcode') {
7706: $newid .= &sixnum_code();
7707: }
1.1198 raeburn 7708: my $idtries = 0;
7709: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7710: if ($idtype eq 'concat') {
7711: $newid = $id.$idtries;
1.1268 raeburn 7712: } elsif ($idtype eq 'addcode') {
7713: $newid = $newid.&sixnum_code();
1.1198 raeburn 7714: } else {
7715: $newid ++;
7716: }
7717: $idtries ++;
7718: }
7719: if (!exists($inuse{$prefix."\0".$newid})) {
7720: my %new_item = (
7721: $prefix."\0".$newid => $who,
7722: );
1.1494 raeburn 7723: my $putresult = &put('nohist_'.$namespace,\%new_item,
1.1198 raeburn 7724: $cdom,$cnum);
7725: if ($putresult ne 'ok') {
7726: undef($newid);
7727: $error = 'error saving new item: '.$putresult;
7728: }
7729: } else {
1.1268 raeburn 7730: undef($newid);
1.1198 raeburn 7731: $error = ('error: no unique suffix available for the new item ');
7732: }
7733: # remove lock
7734: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7735: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7736: } else {
7737: $error = "error: could not obtain lockfile\n";
7738: $dellock = 'ok';
1.1276 raeburn 7739: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7740: $dellock = 'nolock';
7741: }
1.1198 raeburn 7742: }
7743: return ($newid,$dellock,$error);
7744: }
7745:
1.1268 raeburn 7746: sub sixnum_code {
7747: my $code;
7748: for (0..6) {
7749: $code .= int( rand(9) );
7750: }
7751: return $code;
7752: }
7753:
1.765 albertel 7754: # -------------------------------------------------- portfolio access checking
7755:
7756: sub portfolio_access {
1.1270 raeburn 7757: my ($requrl,$clientip) = @_;
1.765 albertel 7758: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 7759: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7760: if ($result) {
7761: my %setters;
7762: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1473 raeburn 7763: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7764: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
7765: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7766: return 'B';
7767: }
7768: } else {
1.1473 raeburn 7769: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7770: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7771: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7772: return 'B';
7773: }
7774: }
7775: }
1.765 albertel 7776: if ($result eq 'ok') {
1.766 albertel 7777: return 'F';
1.765 albertel 7778: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7779: return 'A';
1.765 albertel 7780: }
1.766 albertel 7781: return '';
1.765 albertel 7782: }
7783:
7784: sub get_portfolio_access {
1.1270 raeburn 7785: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7786:
7787: if (!ref($access_hash)) {
7788: my $current_perms = &get_portfile_permissions($udom,$unum);
7789: my %access_controls = &get_access_controls($current_perms,$group,
7790: $file_name);
7791: $access_hash = $access_controls{$file_name};
7792: }
7793:
1.1270 raeburn 7794: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7795: my $now = time;
7796: if (ref($access_hash) eq 'HASH') {
7797: foreach my $key (keys(%{$access_hash})) {
7798: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7799: if ($start > $now) {
7800: next;
7801: }
7802: if ($end && $end<$now) {
7803: next;
7804: }
7805: if ($scope eq 'public') {
7806: $public = $key;
7807: last;
7808: } elsif ($scope eq 'guest') {
7809: $guest = $key;
7810: } elsif ($scope eq 'domains') {
7811: push(@domains,$key);
7812: } elsif ($scope eq 'users') {
7813: push(@users,$key);
7814: } elsif ($scope eq 'course') {
7815: push(@courses,$key);
7816: } elsif ($scope eq 'group') {
7817: push(@groups,$key);
1.1270 raeburn 7818: } elsif ($scope eq 'ip') {
7819: push(@ips,$key);
1.765 albertel 7820: }
7821: }
7822: if ($public) {
7823: return 'ok';
1.1270 raeburn 7824: } elsif (@ips > 0) {
7825: my $allowed;
7826: foreach my $ipkey (@ips) {
7827: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7828: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7829: $allowed = 1;
7830: last;
7831: }
7832: }
7833: }
7834: if ($allowed) {
7835: return 'ok';
7836: }
1.765 albertel 7837: }
7838: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7839: if ($guest) {
7840: return $guest;
7841: }
7842: } else {
7843: if (@domains > 0) {
7844: foreach my $domkey (@domains) {
7845: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7846: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7847: return 'ok';
7848: }
7849: }
7850: }
7851: }
7852: if (@users > 0) {
7853: foreach my $userkey (@users) {
1.865 raeburn 7854: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7855: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7856: if (ref($item) eq 'HASH') {
7857: if (($item->{'uname'} eq $env{'user.name'}) &&
7858: ($item->{'udom'} eq $env{'user.domain'})) {
7859: return 'ok';
7860: }
7861: }
7862: }
7863: }
1.765 albertel 7864: }
7865: }
7866: my %roleshash;
7867: my @courses_and_groups = @courses;
7868: push(@courses_and_groups,@groups);
7869: if (@courses_and_groups > 0) {
7870: my (%allgroups,%allroles);
7871: my ($start,$end,$role,$sec,$group);
7872: foreach my $envkey (%env) {
1.1060 raeburn 7873: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7874: my $cid = $2.'_'.$3;
7875: if ($1 eq 'gr') {
7876: $group = $4;
7877: $allgroups{$cid}{$group} = $env{$envkey};
7878: } else {
7879: if ($4 eq '') {
7880: $sec = 'none';
7881: } else {
7882: $sec = $4;
7883: }
7884: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7885: }
1.811 albertel 7886: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7887: my $cid = $2.'_'.$3;
7888: if ($4 eq '') {
7889: $sec = 'none';
7890: } else {
7891: $sec = $4;
7892: }
7893: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7894: }
7895: }
7896: if (keys(%allroles) == 0) {
7897: return;
7898: }
7899: foreach my $key (@courses_and_groups) {
7900: my %content = %{$$access_hash{$key}};
7901: my $cnum = $content{'number'};
7902: my $cdom = $content{'domain'};
7903: my $cid = $cdom.'_'.$cnum;
7904: if (!exists($allroles{$cid})) {
7905: next;
7906: }
7907: foreach my $role_id (keys(%{$content{'roles'}})) {
7908: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7909: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7910: my @status = @{$content{'roles'}{$role_id}{'access'}};
7911: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7912: foreach my $role (keys(%{$allroles{$cid}})) {
7913: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7914: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7915: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7916: if (grep/^all$/,@sections) {
7917: return 'ok';
7918: } else {
7919: if (grep/^$sec$/,@sections) {
7920: return 'ok';
7921: }
7922: }
7923: }
7924: }
7925: if (keys(%{$allgroups{$cid}}) == 0) {
7926: if (grep/^none$/,@groups) {
7927: return 'ok';
7928: }
7929: } else {
7930: if (grep/^all$/,@groups) {
7931: return 'ok';
7932: }
7933: foreach my $group (keys(%{$allgroups{$cid}})) {
7934: if (grep/^$group$/,@groups) {
7935: return 'ok';
7936: }
7937: }
7938: }
7939: }
7940: }
7941: }
7942: }
7943: }
7944: if ($guest) {
7945: return $guest;
7946: }
7947: }
7948: }
7949: return;
7950: }
7951:
7952: sub course_group_datechecker {
7953: my ($dates,$now,$status) = @_;
7954: my ($start,$end) = split(/\./,$dates);
7955: if (!$start && !$end) {
7956: return 'ok';
7957: }
7958: if (grep/^active$/,@{$status}) {
7959: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7960: return 'ok';
7961: }
7962: }
7963: if (grep/^previous$/,@{$status}) {
7964: if ($end > $now ) {
7965: return 'ok';
7966: }
7967: }
7968: if (grep/^future$/,@{$status}) {
7969: if ($start > $now) {
7970: return 'ok';
7971: }
7972: }
7973: return;
7974: }
7975:
7976: sub parse_portfolio_url {
7977: my ($url) = @_;
7978:
7979: my ($type,$udom,$unum,$group,$file_name);
7980:
1.823 albertel 7981: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7982: $type = 1;
7983: $udom = $1;
7984: $unum = $2;
7985: $file_name = $3;
1.823 albertel 7986: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7987: $type = 2;
7988: $udom = $1;
7989: $unum = $2;
7990: $group = $3;
7991: $file_name = $3.'/'.$4;
7992: }
7993: if (wantarray) {
7994: return ($type,$udom,$unum,$file_name,$group);
7995: }
7996: return $type;
7997: }
7998:
7999: sub is_portfolio_url {
8000: my ($url) = @_;
8001: return scalar(&parse_portfolio_url($url));
8002: }
8003:
1.798 raeburn 8004: sub is_portfolio_file {
8005: my ($file) = @_;
1.820 raeburn 8006: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 8007: return 1;
8008: }
8009: return;
8010: }
8011:
1.1504 raeburn 8012: sub is_coursetool_logo {
8013: my ($uri) = @_;
8014: if ($env{'request.course.id'}) {
8015: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8016: if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
8017: return 1;
8018: }
8019: }
8020: return;
8021: }
8022:
1.976 raeburn 8023: sub usertools_access {
1.1084 raeburn 8024: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 8025: my ($access,%tools);
8026: if ($context eq '') {
8027: $context = 'tools';
8028: }
8029: if ($context eq 'requestcourses') {
8030: %tools = (
8031: official => 1,
8032: unofficial => 1,
1.1006 raeburn 8033: community => 1,
1.1246 raeburn 8034: textbook => 1,
1.1305 raeburn 8035: placement => 1,
1.1368 raeburn 8036: lti => 1,
1.985 raeburn 8037: );
1.1183 raeburn 8038: } elsif ($context eq 'requestauthor') {
8039: %tools = (
8040: requestauthor => 1,
8041: );
1.985 raeburn 8042: } else {
8043: %tools = (
8044: aboutme => 1,
8045: blog => 1,
1.1177 raeburn 8046: webdav => 1,
1.985 raeburn 8047: portfolio => 1,
1.1489 raeburn 8048: timezone => 1,
1.985 raeburn 8049: );
8050: }
1.976 raeburn 8051: return if (!defined($tools{$tool}));
8052:
1.1242 raeburn 8053: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 8054: $udom = $env{'user.domain'};
8055: $uname = $env{'user.name'};
8056: }
8057:
1.978 raeburn 8058: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
8059: if ($action ne 'reload') {
1.985 raeburn 8060: if ($context eq 'requestcourses') {
8061: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 8062: } elsif ($context eq 'requestauthor') {
8063: return $env{'environment.canrequest.author'};
1.985 raeburn 8064: } else {
8065: return $env{'environment.availabletools.'.$tool};
8066: }
8067: }
1.976 raeburn 8068: }
8069:
1.1183 raeburn 8070: my ($toolstatus,$inststatus,$envkey);
8071: if ($context eq 'requestauthor') {
8072: $envkey = $context;
8073: } else {
8074: $envkey = $context.'.'.$tool;
8075: }
1.976 raeburn 8076:
1.985 raeburn 8077: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8078: ($action ne 'reload')) {
1.1183 raeburn 8079: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 8080: $inststatus = $env{'environment.inststatus'};
8081: } else {
1.1084 raeburn 8082: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 8083: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 8084: $inststatus = $userenvref->{'inststatus'};
8085: } else {
1.1183 raeburn 8086: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
8087: $toolstatus = $userenv{$envkey};
1.1084 raeburn 8088: $inststatus = $userenv{'inststatus'};
8089: }
1.976 raeburn 8090: }
8091:
8092: if ($toolstatus ne '') {
8093: if ($toolstatus) {
8094: $access = 1;
8095: } else {
8096: $access = 0;
8097: }
8098: return $access;
8099: }
8100:
1.1084 raeburn 8101: my ($is_adv,%domdef);
8102: if (ref($is_advref) eq 'HASH') {
8103: $is_adv = $is_advref->{'is_adv'};
8104: } else {
8105: $is_adv = &is_advanced_user($udom,$uname);
8106: }
8107: if (ref($domdefref) eq 'HASH') {
8108: %domdef = %{$domdefref};
8109: } else {
8110: %domdef = &get_domain_defaults($udom);
8111: }
1.976 raeburn 8112: if (ref($domdef{$tool}) eq 'HASH') {
8113: if ($is_adv) {
8114: if ($domdef{$tool}{'_LC_adv'} ne '') {
8115: if ($domdef{$tool}{'_LC_adv'}) {
8116: $access = 1;
8117: } else {
8118: $access = 0;
8119: }
8120: return $access;
8121: }
8122: }
8123: if ($inststatus ne '') {
8124: my ($hasaccess,$hasnoaccess);
8125: foreach my $affiliation (split(/:/,$inststatus)) {
8126: if ($domdef{$tool}{$affiliation} ne '') {
8127: if ($domdef{$tool}{$affiliation}) {
8128: $hasaccess = 1;
8129: } else {
8130: $hasnoaccess = 1;
8131: }
8132: }
8133: }
8134: if ($hasaccess || $hasnoaccess) {
8135: if ($hasaccess) {
8136: $access = 1;
8137: } elsif ($hasnoaccess) {
8138: $access = 0;
8139: }
8140: return $access;
8141: }
8142: } else {
8143: if ($domdef{$tool}{'default'} ne '') {
8144: if ($domdef{$tool}{'default'}) {
8145: $access = 1;
8146: } elsif ($domdef{$tool}{'default'} == 0) {
8147: $access = 0;
8148: }
8149: return $access;
8150: }
8151: }
8152: } else {
1.1177 raeburn 8153: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 8154: $access = 1;
8155: } else {
8156: $access = 0;
8157: }
1.976 raeburn 8158: return $access;
8159: }
8160: }
8161:
1.1050 raeburn 8162: sub is_course_owner {
8163: my ($cdom,$cnum,$udom,$uname) = @_;
8164: if (($udom eq '') || ($uname eq '')) {
8165: $udom = $env{'user.domain'};
8166: $uname = $env{'user.name'};
8167: }
8168: unless (($udom eq '') || ($uname eq '')) {
8169: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
8170: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
8171: return 1;
8172: } else {
1.1494 raeburn 8173: my %courseinfo = &coursedescription($cdom.'/'.$cnum);
1.1050 raeburn 8174: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
8175: return 1;
8176: }
8177: }
8178: }
8179: }
8180: return;
8181: }
8182:
1.976 raeburn 8183: sub is_advanced_user {
8184: my ($udom,$uname) = @_;
1.1085 raeburn 8185: if ($udom ne '' && $uname ne '') {
8186: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 8187: if (wantarray) {
8188: return ($env{'user.adv'},$env{'user.author'});
8189: } else {
8190: return $env{'user.adv'};
8191: }
1.1085 raeburn 8192: }
8193: }
1.976 raeburn 8194: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
8195: my %allroles;
1.1128 raeburn 8196: my ($is_adv,$is_author);
1.976 raeburn 8197: foreach my $role (keys(%roleshash)) {
8198: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
8199: my $area = '/'.$tdomain.'/'.$trest;
8200: if ($sec ne '') {
8201: $area .= '/'.$sec;
8202: }
8203: if (($area ne '') && ($trole ne '')) {
8204: my $spec=$trole.'.'.$area;
8205: if ($trole =~ /^cr\//) {
8206: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
8207: } elsif ($trole ne 'gr') {
8208: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
8209: }
1.1128 raeburn 8210: if ($trole eq 'au') {
8211: $is_author = 1;
8212: }
1.976 raeburn 8213: }
8214: }
8215: foreach my $role (keys(%allroles)) {
8216: last if ($is_adv);
8217: foreach my $item (split(/:/,$allroles{$role})) {
8218: if ($item ne '') {
8219: my ($privilege,$restrictions)=split(/&/,$item);
8220: if ($privilege eq 'adv') {
8221: $is_adv = 1;
8222: last;
8223: }
8224: }
8225: }
8226: }
1.1128 raeburn 8227: if (wantarray) {
8228: return ($is_adv,$is_author);
8229: }
1.976 raeburn 8230: return $is_adv;
8231: }
1.798 raeburn 8232:
1.1035 raeburn 8233: sub check_can_request {
1.1368 raeburn 8234: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035 raeburn 8235: my $canreq = 0;
1.1368 raeburn 8236: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8237: $uname = $env{'user.name'};
8238: $udom = $env{'user.domain'};
8239: }
1.1035 raeburn 8240: my ($types,$typename) = &Apache::loncommon::course_types();
8241: my @options = ('approval','validate','autolimit');
8242: my $optregex = join('|',@options);
8243: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
1.1486 raeburn 8244: my %willtrust;
1.1035 raeburn 8245: foreach my $type (@{$types}) {
1.1368 raeburn 8246: if (&usertools_access($uname,$udom,$type,undef,
8247: 'requestcourses')) {
1.1035 raeburn 8248: $canreq ++;
1.1036 raeburn 8249: if (ref($request_domains) eq 'HASH') {
1.1368 raeburn 8250: push(@{$request_domains->{$type}},$udom);
1.1036 raeburn 8251: }
1.1368 raeburn 8252: if ($dom eq $udom) {
1.1035 raeburn 8253: $can_request->{$type} = 1;
8254: }
8255: }
1.1368 raeburn 8256: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
8257: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035 raeburn 8258: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
8259: if (@curr > 0) {
1.1036 raeburn 8260: foreach my $item (@curr) {
8261: if (ref($request_domains) eq 'HASH') {
8262: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
8263: if ($otherdom ne '') {
1.1486 raeburn 8264: unless (exists($willtrust{$otherdom})) {
8265: $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
8266: }
8267: if ($willtrust{$otherdom}) {
8268: if (ref($request_domains->{$type}) eq 'ARRAY') {
8269: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
8270: push(@{$request_domains->{$type}},$otherdom);
8271: }
8272: } else {
1.1036 raeburn 8273: push(@{$request_domains->{$type}},$otherdom);
8274: }
8275: }
8276: }
8277: }
8278: }
1.1368 raeburn 8279: unless ($dom eq $env{'user.domain'}) {
1.1036 raeburn 8280: $canreq ++;
1.1035 raeburn 8281: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
8282: $can_request->{$type} = 1;
8283: }
8284: }
8285: }
8286: }
8287: }
8288: }
8289: return $canreq;
8290: }
8291:
1.341 www 8292: # ---------------------------------------------- Custom access rule evaluation
8293:
8294: sub customaccess {
8295: my ($priv,$uri)=@_;
1.807 albertel 8296: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 8297: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 8298: $udom = &LONCAPA::clean_domain($udom);
8299: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 8300: my $access=0;
1.800 albertel 8301: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 8302: my ($effect,$realm,$role,$type)=split(/\:/,$right);
8303: if ($type eq 'user') {
8304: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 8305: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 8306: if ($tdom) {
8307: if ($tdom ne $env{'user.domain'}) { next; }
8308: }
1.896 albertel 8309: if ($tuname) {
8310: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 8311: }
8312: $access=($effect eq 'allow');
8313: last;
8314: }
8315: } else {
8316: if ($role) {
8317: if ($role ne $urole) { next; }
8318: }
8319: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8320: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8321: if ($tdom) {
8322: if ($tdom ne $udom) { next; }
8323: }
8324: if ($tcrs) {
8325: if ($tcrs ne $ucrs) { next; }
8326: }
8327: if ($tsec) {
8328: if ($tsec ne $usec) { next; }
8329: }
8330: $access=($effect eq 'allow');
8331: last;
8332: }
8333: if ($realm eq '' && $role eq '') {
8334: $access=($effect eq 'allow');
8335: }
1.402 bowersj2 8336: }
1.341 www 8337: }
8338: return $access;
8339: }
8340:
1.103 harris41 8341: # ------------------------------------------------- Check for a user privilege
1.12 www 8342:
8343: sub allowed {
1.1461 raeburn 8344: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705 albertel 8345: my $ver_orguri=$uri;
1.439 www 8346: $uri=&deversion($uri);
1.152 www 8347: my $orguri=$uri;
1.52 www 8348: $uri=&declutter($uri);
1.809 raeburn 8349:
1.810 raeburn 8350: if ($priv eq 'evb') {
1.1478 raeburn 8351: # Evade communication block restrictions for specified role in a course or domain
1.810 raeburn 8352: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8353: return $1;
8354: } else {
8355: return;
8356: }
8357: }
8358:
1.620 albertel 8359: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 8360: # Free bre access to adm and meta resources
1.1436 raeburn 8361: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$}))
1.769 albertel 8362: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8363: && ($priv eq 'bre')) {
1.14 www 8364: return 'F';
1.159 www 8365: }
8366:
1.545 banghart 8367: # Free bre access to user's own portfolio contents
1.714 raeburn 8368: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 8369: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 8370: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 8371: my %setters;
1.1473 raeburn 8372: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
8373: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
8374: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 8375: return 'B';
8376: } else {
8377: return 'F';
8378: }
1.545 banghart 8379: }
8380:
1.762 raeburn 8381: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 8382: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8383: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8384: if (exists($env{'request.course.id'})) {
8385: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8386: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8387: if (($domain eq $cdom) && ($name eq $cnum)) {
8388: my $courseprivid=$env{'request.course.id'};
8389: $courseprivid=~s/\_/\//;
8390: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8391: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8392: return $1;
1.762 raeburn 8393: } else {
8394: if ($env{'request.course.sec'}) {
8395: $courseprivid.='/'.$env{'request.course.sec'};
8396: }
8397: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8398: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8399: return $2;
8400: }
1.714 raeburn 8401: }
8402: }
8403: }
8404: }
8405:
1.159 www 8406: # Free bre to public access
8407:
8408: if ($priv eq 'bre') {
1.1362 raeburn 8409: my $copyright;
8410: unless ($uri =~ /ext\.tool/) {
8411: $copyright=&metadata($uri,'copyright');
8412: }
1.620 albertel 8413: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 8414: return 'F';
8415: }
1.238 www 8416: if ($copyright eq 'priv') {
8417: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8418: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 8419: return '';
8420: }
8421: }
8422: if ($copyright eq 'domain') {
8423: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8424: unless (($env{'user.domain'} eq $1) ||
8425: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8426: return '';
8427: }
1.262 matthew 8428: }
1.620 albertel 8429: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8430: # Library role, so allow browsing of resources in this domain.
8431: return 'F';
1.238 www 8432: }
1.341 www 8433: if ($copyright eq 'custom') {
8434: unless (&customaccess($priv,$uri)) { return ''; }
8435: }
1.14 www 8436: }
1.264 matthew 8437: # Domain coordinator is trying to create a course
1.620 albertel 8438: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8439: # uri is the requested domain in this case.
8440: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8441: # a role of dc for the domain in question.
1.620 albertel 8442: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8443: }
1.29 www 8444:
1.52 www 8445: my $thisallowed='';
8446: my $statecond=0;
8447: my $courseprivid='';
8448:
1.1039 raeburn 8449: my $ownaccess;
1.1043 raeburn 8450: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8451: if (($priv eq 'bro') && ($env{'user.author'})) {
8452: if ($uri eq '') {
8453: $ownaccess = 1;
8454: } else {
8455: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8456: my $udom = $env{'user.domain'};
8457: my $uname = $env{'user.name'};
8458: if ($uri =~ m{^\Q$udom\E/?$}) {
8459: $ownaccess = 1;
1.1040 raeburn 8460: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8461: unless ($uri =~ m{\.\./}) {
8462: $ownaccess = 1;
8463: }
8464: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8465: my $now = time;
8466: if ($uri =~ m{^([^/]+)/?$}) {
8467: my $adom = $1;
8468: foreach my $key (keys(%env)) {
1.1042 raeburn 8469: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452 raeburn 8470: my ($start,$end) = split(/\./,$env{$key});
8471: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8472: $ownaccess = 1;
8473: last;
8474: }
8475: }
8476: }
8477: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8478: my $adom = $1;
8479: my $aname = $2;
1.1042 raeburn 8480: foreach my $role ('ca','aa') {
8481: if ($env{"user.role.$role./$adom/$aname"}) {
8482: my ($start,$end) =
1.1452 raeburn 8483: split(/\./,$env{"user.role.$role./$adom/$aname"});
8484: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8485: $ownaccess = 1;
8486: last;
8487: }
1.1039 raeburn 8488: }
8489: }
8490: }
8491: }
8492: }
8493: }
8494: }
8495:
1.52 www 8496: # Course
8497:
1.620 albertel 8498: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8499: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8500: $thisallowed.=$1;
8501: }
1.52 www 8502: }
1.29 www 8503:
1.52 www 8504: # Domain
8505:
1.620 albertel 8506: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8507: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8508: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8509: $thisallowed.=$1;
8510: }
1.12 www 8511: }
1.52 www 8512:
1.1141 raeburn 8513: # User who is not author or co-author might still be able to edit
8514: # resource of an author in the domain (e.g., if Domain Coordinator).
8515: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8516: (&allowed('mdc',$env{'request.course.id'}))) {
8517: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8518: $thisallowed.=$1;
8519: }
8520: }
8521:
1.52 www 8522: # Course: uri itself is a course
1.66 www 8523: my $courseuri=$uri;
8524: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8525: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8526:
1.620 albertel 8527: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8528: =~/\Q$priv\E\&([^\:]*)/) {
1.1409 raeburn 8529: if ($priv eq 'mip') {
8530: my $rem = $1;
8531: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8532: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8533: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8534: if ($cdom ne '') {
1.1410 raeburn 8535: my %passwdconf = &get_passwdconf($cdom);
8536: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8537: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8538: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8539: my @inststatuses = split(':',$env{'environment.inststatus'});
8540: unless (@inststatuses) {
8541: @inststatuses = ('default');
8542: }
8543: foreach my $status (@inststatuses) {
8544: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8545: $thisallowed.=$rem;
8546: }
8547: }
8548: }
8549: }
1.1409 raeburn 8550: }
8551: }
8552: }
8553: } else {
8554: unless (($priv eq 'bro') && (!$ownaccess)) {
8555: $thisallowed.=$1;
8556: }
1.1039 raeburn 8557: }
1.12 www 8558: }
1.29 www 8559:
1.665 albertel 8560: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8561: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8562: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8563: $thisallowed='';
1.671 raeburn 8564: my ($match)=&is_on_map($uri);
8565: if ($match) {
8566: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8567: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 8568: my $value = $1;
1.1461 raeburn 8569: my $deeplinkblock;
8570: unless ($nodeeplinkcheck) {
8571: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8572: }
1.1402 raeburn 8573: if ($deeplinkblock) {
8574: $thisallowed='D';
8575: } elsif ($noblockcheck) {
1.1281 raeburn 8576: $thisallowed.=$value;
1.1162 raeburn 8577: } else {
1.1424 raeburn 8578: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8579: if (@blockers > 0) {
8580: $thisallowed = 'B';
8581: } else {
8582: $thisallowed.=$value;
8583: }
1.1162 raeburn 8584: }
1.671 raeburn 8585: }
8586: } else {
1.705 albertel 8587: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8588: if ($refuri) {
8589: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8590: $thisallowed='F';
1.671 raeburn 8591: } else {
8592: $refuri=&declutter($refuri);
8593: my ($match) = &is_on_map($refuri);
8594: if ($match) {
1.1461 raeburn 8595: my $deeplinkblock;
8596: unless ($nodeeplinkcheck) {
8597: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8598: }
1.1402 raeburn 8599: if ($deeplinkblock) {
8600: $thisallowed='D';
8601: } elsif ($noblockcheck) {
1.1281 raeburn 8602: $thisallowed='F';
1.1162 raeburn 8603: } else {
1.1426 raeburn 8604: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8605: if (@blockers > 0) {
8606: $thisallowed = 'B';
8607: } else {
8608: $thisallowed='F';
8609: }
1.1162 raeburn 8610: }
1.671 raeburn 8611: }
1.669 raeburn 8612: }
1.671 raeburn 8613: }
8614: }
1.314 www 8615: }
1.492 albertel 8616:
1.766 albertel 8617: if ($priv eq 'bre'
8618: && $thisallowed ne 'F'
8619: && $thisallowed ne '2'
8620: && &is_portfolio_url($uri)) {
1.1270 raeburn 8621: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8622: }
1.1250 raeburn 8623:
1.52 www 8624: # Full access at system, domain or course-wide level? Exit.
1.29 www 8625: if ($thisallowed=~/F/) {
8626: return 'F';
8627: }
8628:
1.52 www 8629: # If this is generating or modifying users, exit with special codes
1.29 www 8630:
1.643 www 8631: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8632: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8633: my ($audom,$auname)=split('/',$uri);
1.643 www 8634: # no author name given, so this just checks on the general right to make a co-author in this domain
8635: unless ($auname) { return $thisallowed; }
8636: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8637: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8638: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8639: ($audom ne $env{'request.role.domain'}))) { return ''; }
8640: }
1.52 www 8641: return $thisallowed;
8642: }
8643: #
1.103 harris41 8644: # Gathered so far: system, domain and course wide privileges
1.52 www 8645: #
8646: # Course: See if uri or referer is an individual resource that is part of
8647: # the course
8648:
1.620 albertel 8649: if ($env{'request.course.id'}) {
1.232 www 8650:
1.1504 raeburn 8651: if ($priv eq 'bre') {
8652: if (&is_coursetool_logo($uri)) {
8653: return 'F';
8654: }
8655: }
8656:
1.1409 raeburn 8657: # If this is modifying password (internal auth) domains must match for user and user's role.
8658:
8659: if ($priv eq 'mip') {
8660: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8661: return $thisallowed;
8662: } else {
8663: return '';
8664: }
8665: }
8666:
1.620 albertel 8667: $courseprivid=$env{'request.course.id'};
8668: if ($env{'request.course.sec'}) {
8669: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8670: }
8671: $courseprivid=~s/\_/\//;
8672: my $checkreferer=1;
1.232 www 8673: my ($match,$cond)=&is_on_map($uri);
8674: if ($match) {
8675: $statecond=$cond;
1.620 albertel 8676: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8677: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8678: my $value = $1;
8679: if ($priv eq 'bre') {
1.1461 raeburn 8680: my $deeplinkblock;
8681: unless ($nodeeplinkcheck) {
8682: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8683: }
1.1458 raeburn 8684: if ($deeplinkblock) {
8685: $thisallowed = 'D';
8686: } elsif ($noblockcheck) {
1.1281 raeburn 8687: $thisallowed.=$value;
1.1162 raeburn 8688: } else {
1.1424 raeburn 8689: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8690: if (@blockers > 0) {
8691: $thisallowed = 'B';
8692: } else {
8693: $thisallowed.=$value;
8694: }
1.1162 raeburn 8695: }
8696: } else {
8697: $thisallowed.=$value;
8698: }
1.52 www 8699: $checkreferer=0;
8700: }
1.29 www 8701: }
1.1424 raeburn 8702:
1.148 www 8703: if ($checkreferer) {
1.620 albertel 8704: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8705: unless ($refuri) {
1.800 albertel 8706: foreach my $key (keys(%env)) {
8707: if ($key=~/^httpref\..*\*/) {
8708: my $pattern=$key;
1.156 www 8709: $pattern=~s/^httpref\.\/res\///;
1.148 www 8710: $pattern=~s/\*/\[\^\/\]\+/g;
8711: $pattern=~s/\//\\\//g;
1.152 www 8712: if ($orguri=~/$pattern/) {
1.800 albertel 8713: $refuri=$env{$key};
1.148 www 8714: }
8715: }
1.191 harris41 8716: }
1.148 www 8717: }
1.232 www 8718:
1.148 www 8719: if ($refuri) {
1.152 www 8720: $refuri=&declutter($refuri);
1.232 www 8721: my ($match,$cond)=&is_on_map($refuri);
8722: if ($match) {
8723: my $refstatecond=$cond;
1.620 albertel 8724: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8725: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8726: my $value = $1;
8727: if ($priv eq 'bre') {
1.1461 raeburn 8728: my $deeplinkblock;
8729: unless ($nodeeplinkcheck) {
8730: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8731: }
1.1402 raeburn 8732: if ($deeplinkblock) {
8733: $thisallowed = 'D';
8734: } elsif ($noblockcheck) {
1.1281 raeburn 8735: $thisallowed.=$value;
1.1162 raeburn 8736: } else {
1.1426 raeburn 8737: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8738: if (@blockers > 0) {
8739: $thisallowed = 'B';
8740: } else {
8741: $thisallowed.=$value;
8742: }
1.1162 raeburn 8743: }
8744: } else {
8745: $thisallowed.=$value;
8746: }
1.53 www 8747: $uri=$refuri;
8748: $statecond=$refstatecond;
1.52 www 8749: }
8750: }
1.148 www 8751: }
1.29 www 8752: }
1.52 www 8753: }
1.29 www 8754:
1.52 www 8755: #
1.103 harris41 8756: # Gathered now: all privileges that could apply, and condition number
1.52 www 8757: #
8758: #
8759: # Full or no access?
8760: #
1.29 www 8761:
1.52 www 8762: if ($thisallowed=~/F/) {
8763: return 'F';
8764: }
1.29 www 8765:
1.52 www 8766: unless ($thisallowed) {
8767: return '';
8768: }
1.29 www 8769:
1.52 www 8770: # Restrictions exist, deal with them
8771: #
8772: # C:according to course preferences
8773: # R:according to resource settings
8774: # L:unless locked
8775: # X:according to user session state
8776: #
8777:
8778: # Possibly locked functionality, check all courses
1.1454 raeburn 8779: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 8780: # Locks might take effect only after 10 minutes cache expiration for other
1.1454 raeburn 8781: # courses, and 2 minutes for current course, in which user has st or ta role
8782: # which is neither expired nor a future role (unless current course).
1.52 www 8783:
1.1454 raeburn 8784: my ($needlockcheck,$now,$crsonly);
1.52 www 8785: if ($thisallowed=~/L/) {
1.1454 raeburn 8786: $now = time;
8787: if ($priv eq 'bre') {
8788: if ($uri ne '') {
8789: if ($orguri =~ m{^/+res/}) {
8790: if ($uri =~ m{^lib/templates/}) {
8791: if ($env{'request.course.id'}) {
8792: $crsonly = 1;
8793: $needlockcheck = 1;
8794: }
8795: } else {
8796: $needlockcheck = 1;
8797: }
8798: } elsif ($env{'request.course.id'}) {
8799: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8800: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8801: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8802: $crsonly = 1;
8803: }
8804: $needlockcheck = 1;
8805: }
8806: }
8807: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8808: $needlockcheck = 1;
8809: }
8810: }
8811: if ($needlockcheck) {
1.1453 raeburn 8812: foreach my $envkey (keys(%env)) {
1.54 www 8813: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8814: my $courseid=$2;
8815: my $roleid=$1.'.'.$2;
1.92 www 8816: $courseid=~s/^\///;
1.1453 raeburn 8817: unless ($env{'request.role'} eq $roleid) {
8818: my ($start,$end) = split(/\./,$env{$envkey});
8819: next unless (($now >= $start) && (!$end || $end > $now));
8820: }
1.54 www 8821: my $expiretime=600;
1.620 albertel 8822: if ($env{'request.role'} eq $roleid) {
1.54 www 8823: $expiretime=120;
8824: }
8825: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8826: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8827: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8828: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8829: }
1.620 albertel 8830: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8831: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8832: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8833: &log($env{'user.domain'},$env{'user.name'},
8834: $env{'user.home'},
1.57 www 8835: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8836: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8837: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8838: return '';
8839: }
8840: }
1.620 albertel 8841: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8842: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455 raeburn 8843: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 8844: &log($env{'user.domain'},$env{'user.name'},
8845: $env{'user.home'},
1.57 www 8846: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8847: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8848: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8849: return '';
8850: }
8851: }
8852: }
1.29 www 8853: }
1.52 www 8854: }
1.1424 raeburn 8855:
1.52 www 8856: #
8857: # Rest of the restrictions depend on selected course
8858: #
8859:
1.620 albertel 8860: unless ($env{'request.course.id'}) {
1.766 albertel 8861: if ($thisallowed eq 'A') {
8862: return 'A';
1.814 raeburn 8863: } elsif ($thisallowed eq 'B') {
8864: return 'B';
1.766 albertel 8865: } else {
8866: return '1';
8867: }
1.52 www 8868: }
1.29 www 8869:
1.52 www 8870: #
8871: # Now user is definitely in a course
8872: #
1.53 www 8873:
8874:
8875: # Course preferences
8876:
8877: if ($thisallowed=~/C/) {
1.620 albertel 8878: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8879: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8880: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8881: =~/\Q$rolecode\E/) {
1.1304 raeburn 8882: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8883: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8884: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8885: $env{'request.course.id'});
8886: }
1.237 www 8887: return '';
8888: }
8889:
1.620 albertel 8890: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8891: =~/\Q$unamedom\E/) {
1.1304 raeburn 8892: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8893: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8894: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8895: $env{'request.course.id'});
8896: }
1.54 www 8897: return '';
8898: }
1.53 www 8899: }
8900:
8901: # Resource preferences
8902:
8903: if ($thisallowed=~/R/) {
1.620 albertel 8904: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8905: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8906: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8907: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8908: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8909: }
8910: return '';
1.54 www 8911: }
1.53 www 8912: }
1.30 www 8913:
1.1461 raeburn 8914: # Restricted for deeplinked session?
8915:
8916: if ($env{'request.deeplink.login'}) {
8917: if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
8918: if (!$symb) { $symb=&symbread($uri,1); }
8919: if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
8920: return '';
8921: }
8922: }
8923: }
8924:
1.246 www 8925: # Restricted by state or randomout?
1.30 www 8926:
1.52 www 8927: if ($thisallowed=~/X/) {
1.620 albertel 8928: if ($env{'acc.randomout'}) {
1.579 albertel 8929: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8930: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8931: return '';
8932: }
1.247 www 8933: }
8934: if (&condval($statecond)) {
1.52 www 8935: return '2';
8936: } else {
8937: return '';
8938: }
8939: }
1.30 www 8940:
1.766 albertel 8941: if ($thisallowed eq 'A') {
8942: return 'A';
1.814 raeburn 8943: } elsif ($thisallowed eq 'B') {
8944: return 'B';
1.1402 raeburn 8945: } elsif ($thisallowed eq 'D') {
8946: return 'D';
1.766 albertel 8947: }
1.52 www 8948: return 'F';
1.232 www 8949: }
1.1162 raeburn 8950:
1.1192 raeburn 8951: # ------------------------------------------- Check construction space access
8952:
8953: sub constructaccess {
8954: my ($url,$setpriv)=@_;
8955:
8956: # We do not allow editing of previous versions of files
8957: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8958:
8959: # Get username and domain from URL
8960: my ($ownername,$ownerdomain,$ownerhome);
8961:
8962: ($ownerdomain,$ownername) =
1.1325 raeburn 8963: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 8964:
8965: # The URL does not really point to any authorspace, forget it
8966: unless (($ownername) && ($ownerdomain)) { return ''; }
8967:
8968: # Now we need to see if the user has access to the authorspace of
8969: # $ownername at $ownerdomain
8970:
8971: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8972: # Real author for this?
8973: $ownerhome = $env{'user.home'};
8974: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8975: return ($ownername,$ownerdomain,$ownerhome);
8976: }
1.1506 raeburn 8977: } elsif (&is_course($ownerdomain,$ownername)) {
8978: # Course Authoring Space?
1.1312 raeburn 8979: if ($env{'request.course.id'}) {
8980: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
8981: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
8982: if (&allowed('mdc',$env{'request.course.id'})) {
8983: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
8984: return ($ownername,$ownerdomain,$ownerhome);
8985: }
8986: }
8987: }
1.1506 raeburn 8988: return '';
8989: } else {
8990: # Co-author for this?
8991: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8992: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8993: $ownerhome = &homeserver($ownername,$ownerdomain);
8994: return ($ownername,$ownerdomain,$ownerhome);
8995: }
1.1192 raeburn 8996: }
8997:
8998: # We don't have any access right now. If we are not possibly going to do anything about this,
8999: # we might as well leave
9000: unless ($setpriv) { return ''; }
9001:
9002: # Backdoor access?
9003: my $allowed=&allowed('eco',$ownerdomain);
9004: # Nope
9005: unless ($allowed) { return ''; }
9006: # Looks like we may have access, but could be locked by the owner of the construction space
9007: if ($allowed eq 'U') {
9008: my %blocked=&get('environment',['domcoord.author'],
9009: $ownerdomain,$ownername);
9010: # Is blocked by owner
9011: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
9012: }
9013: if (($allowed eq 'F') || ($allowed eq 'U')) {
9014: # Grant temporary access
9015: my $then=$env{'user.login.time'};
1.1209 raeburn 9016: my $update=$env{'user.update.time'};
1.1192 raeburn 9017: if (!$update) { $update = $then; }
9018: my $refresh=$env{'user.refresh.time'};
9019: if (!$refresh) { $refresh = $update; }
9020: my $now = time;
9021: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
9022: $now,'ca','constructaccess');
9023: $ownerhome = &homeserver($ownername,$ownerdomain);
9024: return($ownername,$ownerdomain,$ownerhome);
9025: }
9026: # No business here
9027: return '';
9028: }
9029:
1.1282 raeburn 9030: # ----------------------------------------------------------- Content Blocking
9031:
9032: {
9033: # Caches for faster Course Contents display where content blocking
9034: # is in operation (i.e., interval param set) for timed quiz.
9035: #
9036: # User for whom data are being temporarily cached.
9037: my $cacheduser='';
1.1424 raeburn 9038: # Course for which data are being temporarily cached.
9039: my $cachedcid='';
1.1282 raeburn 9040: # Cached blockers for this user (a hash of blocking items).
9041: my %cachedblockers=();
9042: # When the data were last cached.
9043: my $cachedlast='';
9044:
9045: sub load_all_blockers {
1.1427 raeburn 9046: my ($uname,$udom)=@_;
1.1282 raeburn 9047: if (($uname ne '') && ($udom ne '')) {
9048: if (($cacheduser eq $uname.':'.$udom) &&
1.1424 raeburn 9049: ($cachedcid eq $env{'request.course.id'}) &&
1.1427 raeburn 9050: (abs($cachedlast-time)<5)) {
1.1282 raeburn 9051: return;
9052: }
9053: }
9054: $cachedlast=time;
9055: $cacheduser=$uname.':'.$udom;
1.1424 raeburn 9056: $cachedcid=$env{'request.course.id'};
1.1427 raeburn 9057: %cachedblockers = &get_commblock_resources();
1.1424 raeburn 9058: return;
1.1282 raeburn 9059: }
9060:
1.1162 raeburn 9061: sub get_comm_blocks {
9062: my ($cdom,$cnum) = @_;
9063: if ($cdom eq '' || $cnum eq '') {
9064: return unless ($env{'request.course.id'});
9065: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9066: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9067: }
9068: my %commblocks;
9069: my $hashid=$cdom.'_'.$cnum;
9070: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
9071: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
9072: %commblocks = %{$blocksref};
9073: } else {
1.1494 raeburn 9074: %commblocks = &dump('comm_block',$cdom,$cnum);
1.1162 raeburn 9075: my $cachetime = 600;
9076: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
9077: }
9078: return %commblocks;
9079: }
9080:
1.1282 raeburn 9081: sub get_commblock_resources {
9082: my ($blocks) = @_;
9083: my %blockers = ();
9084: return %blockers unless ($env{'request.course.id'});
1.1470 raeburn 9085: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9086: if ($env{'request.course.sec'}) {
9087: $courseurl .= '/'.$env{'request.course.sec'};
9088: }
9089: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162 raeburn 9090: my %commblocks;
9091: if (ref($blocks) eq 'HASH') {
9092: %commblocks = %{$blocks};
9093: } else {
9094: %commblocks = &get_comm_blocks();
9095: }
1.1282 raeburn 9096: return %blockers unless (keys(%commblocks) > 0);
9097: my $navmap = Apache::lonnavmaps::navmap->new();
9098: return %blockers unless (ref($navmap));
1.1162 raeburn 9099: my $now = time;
9100: foreach my $block (keys(%commblocks)) {
9101: if ($block =~ /^(\d+)____(\d+)$/) {
9102: my ($start,$end) = ($1,$2);
9103: if ($start <= $now && $end >= $now) {
9104: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
9105: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
9106: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 9107: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9108: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 9109: }
9110: }
9111: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 9112: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9113: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 9114: }
9115: }
9116: }
9117: }
9118: }
9119: } elsif ($block =~ /^firstaccess____(.+)$/) {
9120: my $item = $1;
9121: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
9122: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1471 raeburn 9123: my (@interval,$mapname);
1.1282 raeburn 9124: my $type = 'map';
9125: if ($item eq 'course') {
9126: $type = 'course';
9127: @interval=&EXT("resource.0.interval");
9128: } else {
9129: if ($item =~ /___\d+___/) {
9130: $type = 'resource';
9131: @interval=&EXT("resource.0.interval",$item);
1.1162 raeburn 9132: } else {
1.1471 raeburn 9133: $mapname = &deversion($item);
9134: if (ref($navmap)) {
9135: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
9136: @interval = ($timelimit,'map');
1.1162 raeburn 9137: }
9138: }
1.1282 raeburn 9139: }
1.1310 raeburn 9140: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 9141: my $timelimit = $1;
1.1282 raeburn 9142: my $first_access;
9143: if ($type eq 'resource') {
9144: $first_access=&get_first_access($interval[1],$item);
9145: } elsif ($type eq 'map') {
9146: $first_access=&get_first_access($interval[1],undef,$item);
9147: } else {
9148: $first_access=&get_first_access($interval[1]);
9149: }
9150: if ($first_access) {
1.1292 raeburn 9151: my $timesup = $first_access+$timelimit;
1.1282 raeburn 9152: if ($timesup > $now) {
9153: my $activeblock;
1.1471 raeburn 9154: if ($type eq 'resource') {
9155: if (ref($navmap)) {
9156: my $res = $navmap->getBySymb($item);
9157: if ($res->answerable()) {
9158: $activeblock = 1;
9159: }
9160: }
9161: } elsif ($type eq 'map') {
9162: my $mapsymb = &symbread($mapname,1);
9163: if (($mapsymb) && (ref($navmap))) {
9164: my $mapres = $navmap->getBySymb($mapsymb);
9165: if (ref($mapres)) {
9166: my $first = $mapres->map_start();
9167: my $finish = $mapres->map_finish();
9168: my $it = $navmap->getIterator($first,$finish,undef,0,0);
9169: if (ref($it)) {
9170: my $res;
9171: while ($res = $it->next(undef,1)) {
9172: next unless (ref($res));
9173: my $symb = $res->symb();
9174: next if (($symb eq $mapsymb) || ($symb eq ''));
9175: @interval=&EXT("resource.0.interval",$symb);
9176: if ($interval[1] eq 'map') {
9177: if ($res->answerable()) {
9178: $activeblock = 1;
9179: last;
9180: }
9181: }
9182: }
9183: }
9184: }
1.1282 raeburn 9185: }
9186: }
9187: if ($activeblock) {
9188: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
9189: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9190: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
9191: }
9192: }
9193: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
9194: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9195: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 9196: }
1.1162 raeburn 9197: }
9198: }
9199: }
9200: }
9201: }
9202: }
9203: }
9204: }
9205: }
1.1282 raeburn 9206: return %blockers;
1.1162 raeburn 9207: }
9208:
1.1282 raeburn 9209: sub has_comm_blocking {
1.1427 raeburn 9210: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282 raeburn 9211: my @blockers;
9212: return unless ($env{'request.course.id'});
9213: return unless ($priv eq 'bre');
9214: return if ($env{'request.state'} eq 'construct');
1.1470 raeburn 9215: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9216: if ($env{'request.course.sec'}) {
9217: $courseurl .= '/'.$env{'request.course.sec'};
9218: }
9219: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1427 raeburn 9220: my %blockinfo;
9221: if (ref($blocks) eq 'HASH') {
9222: %blockinfo = &get_commblock_resources($blocks);
9223: } else {
9224: &load_all_blockers($env{'user.name'},$env{'user.domain'});
9225: %blockinfo = %cachedblockers;
9226: }
9227: return unless (keys(%blockinfo) > 0);
1.1282 raeburn 9228: my (%possibles,@symbs);
9229: if (!$symb) {
1.1427 raeburn 9230: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 9231: }
1.1282 raeburn 9232: if ($symb) {
9233: @symbs = ($symb);
9234: } elsif (keys(%possibles)) {
9235: @symbs = keys(%possibles);
9236: }
9237: my $noblock;
9238: foreach my $symb (@symbs) {
9239: last if ($noblock);
9240: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427 raeburn 9241: foreach my $block (keys(%blockinfo)) {
1.1282 raeburn 9242: if ($block =~ /^firstaccess____(.+)$/) {
9243: my $item = $1;
1.1424 raeburn 9244: unless ($blocked) {
9245: if (($item eq $map) || ($item eq $symb)) {
9246: $noblock = 1;
9247: last;
9248: }
1.1282 raeburn 9249: }
9250: }
1.1427 raeburn 9251: if (ref($blockinfo{$block}) eq 'HASH') {
9252: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
9253: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282 raeburn 9254: unless (grep(/^\Q$block\E$/,@blockers)) {
9255: push(@blockers,$block);
9256: }
9257: }
9258: }
1.1427 raeburn 9259: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
9260: if ($blockinfo{$block}{'maps'}{$map}) {
1.1424 raeburn 9261: unless (grep(/^\Q$block\E$/,@blockers)) {
9262: push(@blockers,$block);
9263: }
1.1282 raeburn 9264: }
9265: }
1.1162 raeburn 9266: }
9267: }
9268: }
1.1424 raeburn 9269: unless ($noblock) {
9270: return @blockers;
9271: }
9272: return;
1.1282 raeburn 9273: }
1.1162 raeburn 9274: }
9275:
1.1402 raeburn 9276: sub deeplink_check {
9277: my ($priv,$symb,$uri) = @_;
9278: return unless ($env{'request.course.id'});
9279: return unless ($priv eq 'bre');
9280: return if ($env{'request.state'} eq 'construct');
9281: return if ($env{'request.role.adv'});
9282: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9283: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9284: my (%possibles,@symbs);
9285: if (!$symb) {
9286: $symb = &symbread($uri,1,1,1,\%possibles);
9287: }
9288: if ($symb) {
9289: @symbs = ($symb);
9290: } elsif (keys(%possibles)) {
9291: @symbs = keys(%possibles);
9292: }
9293:
1.1461 raeburn 9294: my ($deeplink_symb,$allow);
9295: if ($env{'request.deeplink.login'}) {
9296: $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1.1402 raeburn 9297: }
9298: foreach my $symb (@symbs) {
9299: last if ($allow);
9300: my $deeplink = &EXT("resource.0.deeplink",$symb);
9301: if ($deeplink eq '') {
9302: $allow = 1;
9303: } else {
1.1463 raeburn 9304: my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
9305: if ($state ne 'only') {
1.1402 raeburn 9306: $allow = 1;
1.1463 raeburn 9307: } else {
9308: my $check_deeplink_entry;
9309: if ($protect ne 'none') {
9310: my ($acctype,$item) = split(/:/,$protect);
9311: if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
9312: if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
9313: $check_deeplink_entry = 1
9314: }
9315: } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
9316: if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
9317: $check_deeplink_entry = 1;
9318: }
9319: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
9320: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
9321: $check_deeplink_entry = 1;
9322: }
9323: }
9324: }
9325: if (($protect eq 'none') || ($check_deeplink_entry)) {
1.1402 raeburn 9326: if ($scope eq 'res') {
1.1461 raeburn 9327: if ($symb eq $deeplink_symb) {
1.1402 raeburn 9328: $allow = 1;
9329: }
1.1459 raeburn 9330: } elsif (($scope eq 'map') || ($scope eq 'rec')) {
1.1463 raeburn 9331: my ($map_from_symb,$map_from_login);
1.1461 raeburn 9332: $map_from_symb = &deversion((&decode_symb($symb))[0]);
9333: if ($deeplink_symb =~ /\.(page|sequence)$/) {
9334: $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
9335: } else {
9336: $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
9337: }
1.1459 raeburn 9338: if (($map_from_symb) && ($map_from_login)) {
9339: if ($map_from_symb eq $map_from_login) {
9340: $allow = 1;
9341: } elsif ($scope eq 'rec') {
9342: my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
9343: if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
9344: $allow = 1;
9345: }
9346: }
9347: }
1.1402 raeburn 9348: }
9349: }
9350: }
9351: }
9352: }
9353: return if ($allow);
9354: return 1;
9355: }
9356:
1.1282 raeburn 9357: # -------------------------------- Deversion and split uri into path an filename
9358:
1.1133 foxr 9359: #
1.1282 raeburn 9360: # Removes the version from a URI and
1.1133 foxr 9361: # splits it in to its filename and path to the filename.
9362: # Seems like File::Basename could have done this more clearly.
9363: # Parameters:
9364: # $uri - input URI
9365: # Returns:
9366: # Two element list consisting of
9367: # $pathname - the URI up to and excluding the trailing /
9368: # $filename - The part of the URI following the last /
9369: # NOTE:
9370: # Another realization of this is simply:
9371: # use File::Basename;
9372: # ...
9373: # $uri = shift;
9374: # $filename = basename($uri);
9375: # $path = dirname($uri);
9376: # return ($filename, $path);
9377: #
9378: # The implementation below is probably faster however.
9379: #
1.710 albertel 9380: sub split_uri_for_cond {
9381: my $uri=&deversion(&declutter(shift));
9382: my @uriparts=split(/\//,$uri);
9383: my $filename=pop(@uriparts);
9384: my $pathname=join('/',@uriparts);
9385: return ($pathname,$filename);
9386: }
1.232 www 9387: # --------------------------------------------------- Is a resource on the map?
9388:
9389: sub is_on_map {
1.710 albertel 9390: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 9391: #Trying to find the conditional for the file
1.620 albertel 9392: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 9393: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 9394: if ($match) {
1.289 bowersj2 9395: return (1,$1);
9396: } else {
1.434 www 9397: return (0,0);
1.289 bowersj2 9398: }
1.12 www 9399: }
9400:
1.427 www 9401: # --------------------------------------------------------- Get symb from alias
9402:
9403: sub get_symb_from_alias {
9404: my $symb=shift;
9405: my ($map,$resid,$url)=&decode_symb($symb);
9406: # Already is a symb
9407: if ($url) { return $symb; }
9408: # Must be an alias
9409: my $aliassymb='';
9410: my %bighash;
1.620 albertel 9411: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 9412: &GDBM_READER(),0640)) {
9413: my $rid=$bighash{'mapalias_'.$symb};
9414: if ($rid) {
9415: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 9416: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9417: $resid,$bighash{'src_'.$rid});
1.427 www 9418: }
9419: untie %bighash;
9420: }
9421: return $aliassymb;
9422: }
9423:
1.12 www 9424: # ----------------------------------------------------------------- Define Role
9425:
9426: sub definerole {
9427: if (allowed('mcr','/')) {
1.1326 raeburn 9428: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 9429: foreach my $role (split(':',$sysrole)) {
9430: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9431: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9432: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9433: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9434: return "refused:s:$crole&$cqual";
9435: }
9436: }
1.191 harris41 9437: }
1.800 albertel 9438: foreach my $role (split(':',$domrole)) {
9439: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9440: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9441: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9442: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 9443: return "refused:d:$crole&$cqual";
9444: }
9445: }
1.191 harris41 9446: }
1.800 albertel 9447: foreach my $role (split(':',$courole)) {
9448: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9449: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9450: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9451: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9452: return "refused:c:$crole&$cqual";
9453: }
9454: }
1.191 harris41 9455: }
1.1326 raeburn 9456: my $uhome;
9457: if (($uname ne '') && ($udom ne '')) {
9458: $uhome = &homeserver($uname,$udom);
9459: return $uhome if ($uhome eq 'no_host');
9460: } else {
9461: $uname = $env{'user.name'};
9462: $udom = $env{'user.domain'};
9463: $uhome = $env{'user.home'};
9464: }
1.620 albertel 9465: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 9466: "$udom:$uname:rolesdef_$rolename=".
1.21 www 9467: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 9468: return reply($command,$uhome);
1.12 www 9469: } else {
9470: return 'refused';
9471: }
1.105 harris41 9472: }
9473:
9474: # ---------------- Make a metadata query against the network of library servers
9475:
9476: sub metadata_query {
1.1237 raeburn 9477: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 9478: my %rhash;
1.845 albertel 9479: my %libserv = &all_library();
1.244 matthew 9480: my @server_list = (defined($server_array) ? @$server_array
9481: : keys(%libserv) );
9482: for my $server (@server_list) {
1.1237 raeburn 9483: my $domains = '';
9484: if (ref($domains_hash) eq 'HASH') {
9485: $domains = $domains_hash->{$server};
9486: }
1.118 harris41 9487: unless ($custom or $customshow) {
1.1237 raeburn 9488: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 9489: $rhash{$server}=$reply;
9490: }
9491: else {
9492: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 9493: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 9494: $server);
9495: $rhash{$server}=$reply;
9496: }
1.112 harris41 9497: }
1.118 harris41 9498: return \%rhash;
1.240 www 9499: }
9500:
9501: # ----------------------------------------- Send log queries and wait for reply
9502:
9503: sub log_query {
9504: my ($uname,$udom,$query,%filters)=@_;
9505: my $uhome=&homeserver($uname,$udom);
9506: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 9507: my $uhost=&hostname($uhome);
1.800 albertel 9508: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 9509: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9510: $uhome);
1.479 albertel 9511: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 9512: return get_query_reply($queryid);
9513: }
9514:
1.818 raeburn 9515: # -------------------------- Update MySQL table for portfolio file
9516:
9517: sub update_portfolio_table {
1.821 raeburn 9518: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 9519: if ($group ne '') {
9520: $file_name =~s /^\Q$group\E//;
9521: }
1.818 raeburn 9522: my $homeserver = &homeserver($uname,$udom);
9523: my $queryid=
1.821 raeburn 9524: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9525: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 9526: my $reply = &get_query_reply($queryid);
9527: return $reply;
9528: }
9529:
1.899 raeburn 9530: # -------------------------- Update MySQL allusers table
9531:
9532: sub update_allusers_table {
9533: my ($uname,$udom,$names) = @_;
9534: my $homeserver = &homeserver($uname,$udom);
9535: my $queryid=
9536: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9537: 'lastname='.&escape($names->{'lastname'}).'%%'.
9538: 'firstname='.&escape($names->{'firstname'}).'%%'.
9539: 'middlename='.&escape($names->{'middlename'}).'%%'.
9540: 'generation='.&escape($names->{'generation'}).'%%'.
9541: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9542: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 9543: return;
1.899 raeburn 9544: }
9545:
1.508 raeburn 9546: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 9547:
9548: sub fetch_enrollment_query {
1.511 raeburn 9549: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 9550: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 9551: my $maxtries = 1;
1.508 raeburn 9552: if ($context eq 'automated') {
9553: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 9554: $sleep = 2;
9555: $loopmax = 100;
1.547 raeburn 9556: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 9557: } else {
9558: $homeserver = &homeserver($cnum,$dom);
9559: }
1.838 albertel 9560: my $host=&hostname($homeserver);
1.506 raeburn 9561: my $cmd = '';
1.1000 raeburn 9562: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9563: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9564: }
9565: $cmd =~ s/%%$//;
9566: $cmd = &escape($cmd);
9567: my $query = 'fetchenrollment';
1.620 albertel 9568: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9569: unless ($queryid=~/^\Q$host\E\_/) {
9570: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9571: return 'error: '.$queryid;
9572: }
1.1317 raeburn 9573: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9574: my $tries = 1;
9575: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 9576: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9577: $tries ++;
9578: }
1.526 raeburn 9579: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9580: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9581: } else {
1.901 albertel 9582: my @responses = split(/:/,$reply);
1.1322 raeburn 9583: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9584: foreach my $line (@responses) {
9585: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9586: $$replyref{$key} = $value;
9587: }
9588: } else {
1.1117 foxr 9589: my $pathname = LONCAPA::tempdir();
1.800 albertel 9590: foreach my $line (@responses) {
9591: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9592: $$replyref{$key} = $value;
9593: if ($value > 0) {
1.800 albertel 9594: foreach my $item (@{$$affiliatesref{$key}}) {
9595: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9596: my $destname = $pathname.'/'.$filename;
9597: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9598: if ($xml_classlist =~ /^error/) {
9599: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9600: } else {
1.1359 raeburn 9601: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9602: print FILE &unescape($xml_classlist);
9603: close(FILE);
1.526 raeburn 9604: } else {
9605: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9606: }
9607: }
9608: }
9609: }
9610: }
9611: }
9612: return 'ok';
9613: }
9614: return 'error';
9615: }
9616:
1.242 www 9617: sub get_query_reply {
1.1471 raeburn 9618: my ($queryid,$sleep,$loopmax) = @_;
1.1317 raeburn 9619: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9620: $sleep = 0.2;
9621: }
9622: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9623: $loopmax = 100;
9624: }
1.1117 foxr 9625: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9626: my $reply='';
1.1317 raeburn 9627: for (1..$loopmax) {
9628: sleep($sleep);
1.240 www 9629: if (-e $replyfile.'.end') {
1.1359 raeburn 9630: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9631: $reply = join('',<$fh>);
9632: close($fh);
1.240 www 9633: } else { return 'error: reply_file_error'; }
1.242 www 9634: return &unescape($reply);
9635: }
1.240 www 9636: }
1.242 www 9637: return 'timeout:'.$queryid;
1.240 www 9638: }
9639:
9640: sub courselog_query {
1.241 www 9641: #
9642: # possible filters:
9643: # url: url or symb
9644: # username
9645: # domain
9646: # action: view, submit, grade
9647: # start: timestamp
9648: # end: timestamp
9649: #
1.240 www 9650: my (%filters)=@_;
1.620 albertel 9651: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9652: if ($filters{'url'}) {
9653: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9654: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9655: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9656: }
1.620 albertel 9657: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9658: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9659: return &log_query($cname,$cdom,'courselog',%filters);
9660: }
9661:
9662: sub userlog_query {
1.858 raeburn 9663: #
9664: # possible filters:
9665: # action: log check role
9666: # start: timestamp
9667: # end: timestamp
9668: #
1.240 www 9669: my ($uname,$udom,%filters)=@_;
9670: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9671: }
9672:
1.506 raeburn 9673: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9674:
9675: sub auto_run {
1.508 raeburn 9676: my ($cnum,$cdom) = @_;
1.876 raeburn 9677: my $response = 0;
9678: my $settings;
9679: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9680: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9681: $settings = $domconfig{'autoenroll'};
9682: if ($settings->{'run'} eq '1') {
9683: $response = 1;
9684: }
9685: } else {
1.934 raeburn 9686: my $homeserver;
9687: if (&is_course($cdom,$cnum)) {
9688: $homeserver = &homeserver($cnum,$cdom);
9689: } else {
9690: $homeserver = &domain($cdom,'primary');
9691: }
9692: if ($homeserver ne 'no_host') {
9693: $response = &reply('autorun:'.$cdom,$homeserver);
9694: }
1.876 raeburn 9695: }
1.506 raeburn 9696: return $response;
9697: }
1.776 albertel 9698:
1.506 raeburn 9699: sub auto_get_sections {
1.508 raeburn 9700: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9701: my $homeserver;
9702: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9703: $homeserver = &homeserver($cnum,$cdom);
9704: }
9705: if (!defined($homeserver)) {
9706: if ($cdom =~ /^$match_domain$/) {
9707: $homeserver = &domain($cdom,'primary');
9708: }
9709: }
9710: my @secs;
9711: if (defined($homeserver)) {
9712: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9713: unless ($response eq 'refused') {
9714: @secs = split(/:/,$response);
9715: }
1.506 raeburn 9716: }
9717: return @secs;
9718: }
1.776 albertel 9719:
1.506 raeburn 9720: sub auto_new_course {
1.1099 raeburn 9721: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9722: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9723: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9724: return $response;
9725: }
1.776 albertel 9726:
1.506 raeburn 9727: sub auto_validate_courseID {
1.508 raeburn 9728: my ($cnum,$cdom,$inst_course_id) = @_;
9729: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9730: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9731: return $response;
9732: }
1.776 albertel 9733:
1.1007 raeburn 9734: sub auto_validate_instcode {
1.1020 raeburn 9735: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9736: my ($homeserver,$response);
9737: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9738: $homeserver = &homeserver($cnum,$cdom);
9739: }
9740: if (!defined($homeserver)) {
9741: if ($cdom =~ /^$match_domain$/) {
9742: $homeserver = &domain($cdom,'primary');
9743: }
9744: }
1.1065 raeburn 9745: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9746: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 9747: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9748: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9749: }
9750:
1.1444 raeburn 9751: sub auto_validate_inst_crosslist {
9752: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9753: my ($homeserver,$response);
9754: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9755: $homeserver = &homeserver($cnum,$cdom);
9756: }
9757: if (!defined($homeserver)) {
9758: if ($cdom =~ /^$match_domain$/) {
9759: $homeserver = &domain($cdom,'primary');
9760: }
9761: }
9762: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9763: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9764: &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445 raeburn 9765: &escape($coowner),$homeserver);
1.1444 raeburn 9766: }
9767: return $response;
9768: }
9769:
1.506 raeburn 9770: sub auto_create_password {
1.873 raeburn 9771: my ($cnum,$cdom,$authparam,$udom) = @_;
9772: my ($homeserver,$response);
1.506 raeburn 9773: my $create_passwd = 0;
9774: my $authchk = '';
1.873 raeburn 9775: if ($udom =~ /^$match_domain$/) {
9776: $homeserver = &domain($udom,'primary');
9777: }
9778: if ($homeserver eq '') {
9779: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9780: $homeserver = &homeserver($cnum,$cdom);
9781: }
9782: }
9783: if ($homeserver eq '') {
9784: $authchk = 'nodomain';
1.506 raeburn 9785: } else {
1.873 raeburn 9786: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9787: if ($response eq 'refused') {
9788: $authchk = 'refused';
9789: } else {
1.901 albertel 9790: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9791: }
1.506 raeburn 9792: }
9793: return ($authparam,$create_passwd,$authchk);
9794: }
9795:
1.706 raeburn 9796: sub auto_photo_permission {
9797: my ($cnum,$cdom,$students) = @_;
9798: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9799: my ($outcome,$perm_reqd,$conditions) =
9800: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9801: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9802: return (undef,undef);
9803: }
1.706 raeburn 9804: return ($outcome,$perm_reqd,$conditions);
9805: }
9806:
9807: sub auto_checkphotos {
9808: my ($uname,$udom,$pid) = @_;
9809: my $homeserver = &homeserver($uname,$udom);
9810: my ($result,$resulttype);
9811: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9812: &escape($uname).':'.&escape($pid),
9813: $homeserver));
1.709 albertel 9814: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9815: return (undef,undef);
9816: }
1.706 raeburn 9817: if ($outcome) {
9818: ($result,$resulttype) = split(/:/,$outcome);
9819: }
9820: return ($result,$resulttype);
9821: }
9822:
9823: sub auto_photochoice {
9824: my ($cnum,$cdom) = @_;
9825: my $homeserver = &homeserver($cnum,$cdom);
9826: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9827: &escape($cdom),
9828: $homeserver)));
1.709 albertel 9829: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9830: return (undef,undef);
9831: }
1.706 raeburn 9832: return ($update,$comment);
9833: }
9834:
9835: sub auto_photoupdate {
9836: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9837: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9838: my $host=&hostname($homeserver);
1.706 raeburn 9839: my $cmd = '';
9840: my $maxtries = 1;
1.800 albertel 9841: foreach my $affiliate (keys(%{$affiliatesref})) {
9842: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9843: }
9844: $cmd =~ s/%%$//;
9845: $cmd = &escape($cmd);
9846: my $query = 'institutionalphotos';
9847: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9848: unless ($queryid=~/^\Q$host\E\_/) {
9849: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9850: return 'error: '.$queryid;
9851: }
9852: my $reply = &get_query_reply($queryid);
9853: my $tries = 1;
9854: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9855: $reply = &get_query_reply($queryid);
9856: $tries ++;
9857: }
9858: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9859: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9860: } else {
9861: my @responses = split(/:/,$reply);
9862: my $outcome = shift(@responses);
9863: foreach my $item (@responses) {
9864: my ($key,$value) = split(/=/,$item);
9865: $$photo{$key} = $value;
9866: }
9867: return $outcome;
9868: }
9869: return 'error';
9870: }
9871:
1.521 raeburn 9872: sub auto_instcode_format {
1.793 albertel 9873: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9874: $cat_order) = @_;
1.521 raeburn 9875: my $courses = '';
1.772 raeburn 9876: my @homeservers;
1.521 raeburn 9877: if ($caller eq 'global') {
1.841 albertel 9878: my %servers = &get_servers($codedom,'library');
9879: foreach my $tryserver (keys(%servers)) {
9880: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9881: push(@homeservers,$tryserver);
9882: }
1.584 raeburn 9883: }
1.1022 raeburn 9884: } elsif ($caller eq 'requests') {
9885: if ($codedom =~ /^$match_domain$/) {
9886: my $chome = &domain($codedom,'primary');
9887: unless ($chome eq 'no_host') {
9888: push(@homeservers,$chome);
9889: }
9890: }
1.521 raeburn 9891: } else {
1.772 raeburn 9892: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9893: }
1.793 albertel 9894: foreach my $code (keys(%{$instcodes})) {
9895: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9896: }
9897: chop($courses);
1.772 raeburn 9898: my $ok_response = 0;
9899: my $response;
9900: while (@homeservers > 0 && $ok_response == 0) {
9901: my $server = shift(@homeservers);
9902: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9903: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9904: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9905: split(/:/,$response);
1.772 raeburn 9906: %{$codes} = (%{$codes},&str2hash($codes_str));
9907: push(@{$codetitles},&str2array($codetitles_str));
9908: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9909: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9910: $ok_response = 1;
9911: }
9912: }
9913: if ($ok_response) {
1.521 raeburn 9914: return 'ok';
1.772 raeburn 9915: } else {
9916: return $response;
1.521 raeburn 9917: }
9918: }
9919:
1.792 raeburn 9920: sub auto_instcode_defaults {
9921: my ($domain,$returnhash,$code_order) = @_;
9922: my @homeservers;
1.841 albertel 9923:
9924: my %servers = &get_servers($domain,'library');
9925: foreach my $tryserver (keys(%servers)) {
9926: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9927: push(@homeservers,$tryserver);
9928: }
1.792 raeburn 9929: }
1.841 albertel 9930:
1.792 raeburn 9931: my $response;
1.841 albertel 9932: foreach my $server (@homeservers) {
1.792 raeburn 9933: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9934: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9935:
9936: foreach my $pair (split(/\&/,$response)) {
9937: my ($name,$value)=split(/\=/,$pair);
9938: if ($name eq 'code_order') {
9939: @{$code_order} = split(/\&/,&unescape($value));
9940: } else {
9941: $returnhash->{&unescape($name)}=&unescape($value);
9942: }
9943: }
9944: return 'ok';
1.792 raeburn 9945: }
1.841 albertel 9946:
9947: return $response;
1.1003 raeburn 9948: }
9949:
9950: sub auto_possible_instcodes {
1.1007 raeburn 9951: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9952: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9953: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9954: return;
9955: }
1.1003 raeburn 9956: my (@homeservers,$uhome);
9957: if (defined(&domain($domain,'primary'))) {
9958: $uhome=&domain($domain,'primary');
9959: push(@homeservers,&domain($domain,'primary'));
9960: } else {
9961: my %servers = &get_servers($domain,'library');
9962: foreach my $tryserver (keys(%servers)) {
9963: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9964: push(@homeservers,$tryserver);
9965: }
9966: }
9967: }
9968: my $response;
9969: foreach my $server (@homeservers) {
9970: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9971: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9972: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9973: split(':',$response);
9974: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9975: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9976: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9977: my ($name,$value)=split('=',$item);
9978: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9979: }
9980: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9981: my ($name,$value)=split('=',$item);
9982: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9983: }
9984: return 'ok';
9985: }
9986: return $response;
9987: }
1.792 raeburn 9988:
1.1010 raeburn 9989: sub auto_courserequest_checks {
9990: my ($dom) = @_;
1.1020 raeburn 9991: my ($homeserver,%validations);
9992: if ($dom =~ /^$match_domain$/) {
9993: $homeserver = &domain($dom,'primary');
9994: }
9995: unless ($homeserver eq 'no_host') {
9996: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9997: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9998: my @items = split(/&/,$response);
9999: foreach my $item (@items) {
10000: my ($key,$value) = split('=',$item);
10001: $validations{&unescape($key)} = &thaw_unescape($value);
10002: }
10003: }
10004: }
1.1010 raeburn 10005: return %validations;
10006: }
10007:
1.1020 raeburn 10008: sub auto_courserequest_validation {
1.1255 raeburn 10009: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 10010: my ($homeserver,$response);
10011: if ($dom =~ /^$match_domain$/) {
10012: $homeserver = &domain($dom,'primary');
10013: }
1.1255 raeburn 10014: unless ($homeserver eq 'no_host') {
10015: my $customdata;
10016: if (ref($custominfo) eq 'HASH') {
10017: $customdata = &freeze_escape($custominfo);
10018: }
1.1020 raeburn 10019: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 10020: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 10021: ':'.&escape($instcode).':'.&escape($instseclist).':'.
10022: $customdata,$homeserver));
1.1020 raeburn 10023: }
10024: return $response;
10025: }
10026:
1.777 albertel 10027: sub auto_validate_class_sec {
1.918 raeburn 10028: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 10029: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 10030: my $ownerlist;
10031: if (ref($owners) eq 'ARRAY') {
10032: $ownerlist = join(',',@{$owners});
10033: } else {
10034: $ownerlist = $owners;
10035: }
1.773 raeburn 10036: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 10037: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 10038: return $response;
10039: }
10040:
1.1460 raeburn 10041: sub auto_instsec_reformat {
10042: my ($cdom,$action,$instsecref) = @_;
10043: return unless(($action eq 'clutter') || ($action eq 'declutter'));
10044: my @homeservers;
10045: if (defined(&domain($cdom,'primary'))) {
10046: push(@homeservers,&domain($cdom,'primary'));
10047: } else {
10048: my %servers = &get_servers($cdom,'library');
10049: foreach my $tryserver (keys(%servers)) {
10050: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10051: push(@homeservers,$tryserver);
10052: }
10053: }
10054: }
10055: my $response;
10056: my %reformatted = %{$instsecref};
10057: foreach my $server (@homeservers) {
10058: if (ref($instsecref) eq 'HASH') {
10059: my $info = &freeze_escape($instsecref);
10060: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10061: $action.':'.$info,$server);
10062: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
10063: my @items = split(/&/,$response);
10064: foreach my $item (@items) {
10065: my ($key,$value) = split(/=/,$item);
10066: $reformatted{&unescape($key)} = &thaw_unescape($value);
10067: }
10068: }
10069: }
10070: return %reformatted;
10071: }
10072:
1.1367 raeburn 10073: sub auto_validate_instclasses {
10074: my ($cdom,$cnum,$owners,$classesref) = @_;
10075: my ($homeserver,%validations);
10076: $homeserver = &homeserver($cnum,$cdom);
10077: unless ($homeserver eq 'no_host') {
10078: my $ownerlist;
10079: if (ref($owners) eq 'ARRAY') {
10080: $ownerlist = join(',',@{$owners});
10081: } else {
10082: $ownerlist = $owners;
10083: }
10084: if (ref($classesref) eq 'HASH') {
10085: my $classes = &freeze_escape($classesref);
10086: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10087: ':'.$cdom.':'.$classes,$homeserver);
10088: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10089: my @items = split(/&/,$response);
10090: foreach my $item (@items) {
10091: my ($key,$value) = split('=',$item);
10092: $validations{&unescape($key)} = &thaw_unescape($value);
10093: }
10094: }
10095: }
10096: }
10097: return %validations;
10098: }
10099:
1.1248 raeburn 10100: sub auto_crsreq_update {
10101: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 10102: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 10103: my ($homeserver,%crsreqresponse);
10104: if ($cdom =~ /^$match_domain$/) {
10105: $homeserver = &domain($cdom,'primary');
10106: }
10107: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10108: my $info;
10109: if (ref($inbound) eq 'HASH') {
10110: $info = &freeze_escape($inbound);
10111: }
10112: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10113: ':'.&escape($action).':'.&escape($ownername).':'.
10114: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 10115: &escape($title).':'.&escape($code).':'.
10116: &escape($accessstart).':'.&escape($accessend).':'.$info,
10117: $homeserver);
1.1248 raeburn 10118: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10119: my @items = split(/&/,$response);
10120: foreach my $item (@items) {
10121: my ($key,$value) = split('=',$item);
10122: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10123: }
10124: }
10125: }
10126: return \%crsreqresponse;
10127: }
10128:
1.1305 raeburn 10129: sub auto_export_grades {
1.1309 raeburn 10130: my ($cdom,$cnum,$inforef,$gradesref) = @_;
10131: my ($homeserver,%exportresponse);
10132: if ($cdom =~ /^$match_domain$/) {
10133: $homeserver = &domain($cdom,'primary');
10134: }
10135: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10136: my $info;
10137: if (ref($inforef) eq 'HASH') {
10138: $info = &freeze_escape($inforef);
10139: }
10140: if (ref($gradesref) eq 'HASH') {
10141: my $grades = &freeze_escape($gradesref);
10142: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10143: $info.':'.$grades,$homeserver);
10144: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10145: my @items = split(/&/,$response);
10146: foreach my $item (@items) {
10147: my ($key,$value) = split('=',$item);
10148: $exportresponse{&unescape($key)} = &thaw_unescape($value);
10149: }
10150: }
10151: }
10152: }
10153: return \%exportresponse;
1.1305 raeburn 10154: }
10155:
1.1287 raeburn 10156: sub check_instcode_cloning {
10157: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10158: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10159: return;
10160: }
10161: my $canclone;
10162: if (@{$code_order} > 0) {
10163: my $instcoderegexp ='^';
10164: my @clonecodes = split(/\&/,$cloner);
10165: foreach my $item (@{$code_order}) {
10166: if (grep(/^\Q$item\E=/,@clonecodes)) {
10167: foreach my $pair (@clonecodes) {
10168: my ($key,$val) = split(/\=/,$pair,2);
10169: $val = &unescape($val);
10170: if ($key eq $item) {
10171: $instcoderegexp .= '('.$val.')';
10172: last;
10173: }
10174: }
10175: } else {
10176: $instcoderegexp .= $codedefaults->{$item};
10177: }
10178: }
10179: $instcoderegexp .= '$';
10180: my (@from,@to);
10181: eval {
10182: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10183: (@to) = ($clonetocode =~ /$instcoderegexp/);
10184: };
10185: if ((@from > 0) && (@to > 0)) {
10186: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10187: if (!@diffs) {
10188: $canclone = 1;
10189: }
10190: }
10191: }
10192: return $canclone;
10193: }
10194:
10195: sub default_instcode_cloning {
10196: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10197: my (%codedefaults,@code_order,$canclone);
10198: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10199: %codedefaults = %{$codedefaultsref};
10200: @code_order = @{$codeorderref};
10201: } elsif ($clonedom) {
10202: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10203: }
10204: if (($domdefclone) && (@code_order)) {
10205: my @clonecodes = split(/\+/,$domdefclone);
10206: my $instcoderegexp ='^';
10207: foreach my $item (@code_order) {
10208: if (grep(/^\Q$item\E$/,@clonecodes)) {
10209: $instcoderegexp .= '('.$codedefaults{$item}.')';
10210: } else {
10211: $instcoderegexp .= $codedefaults{$item};
10212: }
10213: }
10214: $instcoderegexp .= '$';
10215: my (@from,@to);
10216: eval {
10217: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10218: (@to) = ($clonetocode =~ /$instcoderegexp/);
10219: };
10220: if ((@from > 0) && (@to > 0)) {
10221: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10222: if (!@diffs) {
10223: $canclone = 1;
10224: }
10225: }
10226: }
10227: return $canclone;
10228: }
10229:
1.679 raeburn 10230: # ------------------------------------------------------- Course Group routines
10231:
10232: sub get_coursegroups {
1.809 raeburn 10233: my ($cdom,$cnum,$group,$namespace) = @_;
10234: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 10235: }
10236:
1.679 raeburn 10237: sub modify_coursegroup {
10238: my ($cdom,$cnum,$groupsettings) = @_;
10239: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10240: }
10241:
1.809 raeburn 10242: sub toggle_coursegroup_status {
10243: my ($cdom,$cnum,$group,$action) = @_;
10244: my ($from_namespace,$to_namespace);
10245: if ($action eq 'delete') {
10246: $from_namespace = 'coursegroups';
10247: $to_namespace = 'deleted_groups';
10248: } else {
10249: $from_namespace = 'deleted_groups';
10250: $to_namespace = 'coursegroups';
10251: }
10252: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 10253: if (my $tmp = &error(%curr_group)) {
10254: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10255: return ('read error',$tmp);
10256: } else {
10257: my %savedsettings = %curr_group;
1.809 raeburn 10258: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 10259: my $deloutcome;
10260: if ($result eq 'ok') {
1.809 raeburn 10261: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 10262: } else {
10263: return ('write error',$result);
10264: }
10265: if ($deloutcome eq 'ok') {
10266: return 'ok';
10267: } else {
10268: return ('delete error',$deloutcome);
10269: }
10270: }
10271: }
10272:
1.679 raeburn 10273: sub modify_group_roles {
1.957 raeburn 10274: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 10275: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10276: my $role = 'gr/'.&escape($userprivs);
10277: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 10278: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 10279: if ($result eq 'ok') {
10280: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10281: }
1.679 raeburn 10282: return $result;
10283: }
10284:
10285: sub modify_coursegroup_membership {
10286: my ($cdom,$cnum,$membership) = @_;
10287: my $result = &put('groupmembership',$membership,$cdom,$cnum);
10288: return $result;
10289: }
10290:
1.682 raeburn 10291: sub get_active_groups {
10292: my ($udom,$uname,$cdom,$cnum) = @_;
10293: my $now = time;
10294: my %groups = ();
10295: foreach my $key (keys(%env)) {
1.811 albertel 10296: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 10297: my ($start,$end) = split(/\./,$env{$key});
10298: if (($end!=0) && ($end<$now)) { next; }
10299: if (($start!=0) && ($start>$now)) { next; }
10300: if ($1 eq $cdom && $2 eq $cnum) {
10301: $groups{$3} = $env{$key} ;
10302: }
10303: }
10304: }
10305: return %groups;
10306: }
10307:
1.683 raeburn 10308: sub get_group_membership {
10309: my ($cdom,$cnum,$group) = @_;
10310: return(&dump('groupmembership',$cdom,$cnum,$group));
10311: }
10312:
10313: sub get_users_groups {
10314: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 10315: my @usersgroups;
1.683 raeburn 10316: my $cachetime=1800;
10317:
10318: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 10319: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10320: if (defined($cached)) {
1.734 albertel 10321: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 10322: } else {
10323: $grouplist = '';
1.816 raeburn 10324: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 10325: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 10326: my $access_end = $env{'course.'.$courseid.
10327: '.default_enrollment_end_date'};
10328: my $now = time;
10329: foreach my $key (keys(%roleshash)) {
10330: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10331: my $group = $1;
10332: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10333: my $start = $2;
10334: my $end = $1;
10335: if ($start == -1) { next; } # deleted from group
10336: if (($start!=0) && ($start>$now)) { next; }
10337: if (($end!=0) && ($end<$now)) {
10338: if ($access_end && $access_end < $now) {
10339: if ($access_end - $end < 86400) {
10340: push(@usersgroups,$group);
1.733 raeburn 10341: }
10342: }
1.817 raeburn 10343: next;
1.733 raeburn 10344: }
1.817 raeburn 10345: push(@usersgroups,$group);
1.683 raeburn 10346: }
10347: }
10348: }
1.817 raeburn 10349: @usersgroups = &sort_course_groups($courseid,@usersgroups);
10350: $grouplist = join(':',@usersgroups);
10351: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 10352: }
1.733 raeburn 10353: return @usersgroups;
1.683 raeburn 10354: }
10355:
10356: sub devalidate_getgroups_cache {
10357: my ($udom,$uname,$cdom,$cnum)=@_;
10358: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 10359:
1.683 raeburn 10360: my $hashid="$udom:$uname:$courseid";
10361: &devalidate_cache_new('getgroups',$hashid);
10362: }
10363:
1.12 www 10364: # ------------------------------------------------------------------ Plain Text
10365:
10366: sub plaintext {
1.988 raeburn 10367: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 10368: if ($short =~ m{^cr/}) {
1.758 albertel 10369: return (split('/',$short))[-1];
10370: }
1.742 raeburn 10371: if (!defined($cid)) {
10372: $cid = $env{'request.course.id'};
10373: }
10374: my %rolenames = (
1.1008 raeburn 10375: Course => 'std',
10376: Community => 'alt1',
1.1305 raeburn 10377: Placement => 'std',
1.742 raeburn 10378: );
1.1037 raeburn 10379: if ($cid ne '') {
10380: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10381: unless ($forcedefault) {
10382: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
10383: &Apache::lonlocal::mt_escape(\$roletext);
10384: return &Apache::lonlocal::mt($roletext);
10385: }
10386: }
10387: }
10388: if ((defined($type)) && (defined($rolenames{$type})) &&
10389: (defined($rolenames{$type})) &&
10390: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 10391: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 10392: } elsif ($cid ne '') {
10393: my $crstype = $env{'course.'.$cid.'.type'};
10394: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10395: (defined($prp{$short}{$rolenames{$crstype}}))) {
10396: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10397: }
1.742 raeburn 10398: }
1.1037 raeburn 10399: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 10400: }
10401:
10402: # ----------------------------------------------------------------- Assign Role
10403:
10404: sub assignrole {
1.957 raeburn 10405: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10406: $context)=@_;
1.21 www 10407: my $mrole;
10408: if ($role =~ /^cr\//) {
1.393 www 10409: my $cwosec=$url;
1.811 albertel 10410: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.1502 raeburn 10411: if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
1.1026 raeburn 10412: my $refused = 1;
10413: if ($context eq 'requestcourses') {
10414: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10415: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10416: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10417: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10418: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10419: if ($crsenv{'internal.courseowner'} eq
10420: $env{'user.name'}.':'.$env{'user.domain'}) {
10421: $refused = '';
10422: }
10423: }
10424: }
10425: }
10426: }
10427: if ($refused) {
10428: &logthis('Refused custom assignrole: '.
10429: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10430: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10431: return 'refused';
10432: }
1.104 www 10433: }
1.21 www 10434: $mrole='cr';
1.678 raeburn 10435: } elsif ($role =~ /^gr\//) {
10436: my $cwogrp=$url;
1.811 albertel 10437: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 10438: unless (&allowed('mdg',$cwogrp)) {
10439: &logthis('Refused group assignrole: '.
10440: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10441: $env{'user.name'}.' at '.$env{'user.domain'});
10442: return 'refused';
10443: }
10444: $mrole='gr';
1.21 www 10445: } else {
1.82 www 10446: my $cwosec=$url;
1.811 albertel 10447: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 10448: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10449: my $refused;
10450: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10451: if (!(&allowed('c'.$role,$url))) {
10452: $refused = 1;
10453: }
10454: } else {
10455: $refused = 1;
10456: }
1.947 raeburn 10457: if ($refused) {
1.1045 raeburn 10458: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377 raeburn 10459: if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045 raeburn 10460: my %crsenv;
10461: if ($role eq 'cc' || $role eq 'co') {
10462: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10463: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10464: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10465: if ($crsenv{'internal.courseowner'} eq
10466: $env{'user.name'}.':'.$env{'user.domain'}) {
10467: $refused = '';
10468: }
10469: }
10470: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10471: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10472: if ($crsenv{'internal.courseowner'} eq
10473: $env{'user.name'}.':'.$env{'user.domain'}) {
10474: $refused = '';
10475: }
10476: }
10477: }
10478: }
1.1368 raeburn 10479: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10480: if ($role eq 'st') {
10481: $refused = '';
1.1377 raeburn 10482: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368 raeburn 10483: $refused = '';
10484: }
1.1017 raeburn 10485: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 10486: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 10487: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 10488: my $wrongcc;
10489: if ($cnum =~ /^$match_community$/) {
10490: $wrongcc = 1 if ($role eq 'cc');
10491: } else {
10492: $wrongcc = 1 if ($role eq 'co');
10493: }
10494: unless ($wrongcc) {
10495: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10496: if ($crsenv{'internal.courseowner'} eq
10497: $env{'user.name'}.':'.$env{'user.domain'}) {
10498: $refused = '';
10499: }
1.1017 raeburn 10500: }
10501: }
1.1183 raeburn 10502: } elsif ($context eq 'requestauthor') {
10503: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10504: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10505: if ($env{'environment.requestauthor'} eq 'automatic') {
10506: $refused = '';
10507: } else {
10508: my %domdefaults = &get_domain_defaults($udom);
10509: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10510: my $checkbystatus;
10511: if ($env{'user.adv'}) {
10512: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10513: if ($disposition eq 'automatic') {
10514: $refused = '';
10515: } elsif ($disposition eq '') {
10516: $checkbystatus = 1;
10517: }
10518: } else {
10519: $checkbystatus = 1;
10520: }
10521: if ($checkbystatus) {
10522: if ($env{'environment.inststatus'}) {
10523: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10524: foreach my $type (@inststatuses) {
10525: if (($type ne '') &&
10526: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10527: $refused = '';
10528: }
10529: }
10530: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10531: $refused = '';
10532: }
10533: }
10534: }
10535: }
10536: }
1.1017 raeburn 10537: }
10538: if ($refused) {
1.947 raeburn 10539: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10540: ' '.$role.' '.$end.' '.$start.' by '.
10541: $env{'user.name'}.' at '.$env{'user.domain'});
10542: return 'refused';
10543: }
1.932 raeburn 10544: }
1.1131 raeburn 10545: } elsif ($role eq 'au') {
10546: if ($url ne '/'.$udom.'/') {
10547: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10548: ' to assign author role for '.$uname.':'.$udom.
10549: ' in domain: '.$url.' refused (wrong domain).');
10550: return 'refused';
10551: }
1.104 www 10552: }
1.21 www 10553: $mrole=$role;
10554: }
1.620 albertel 10555: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 10556: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 10557: if ($end) { $command.='_'.$end; }
1.21 www 10558: if ($start) {
10559: if ($end) {
1.81 www 10560: $command.='_'.$start;
1.21 www 10561: } else {
1.81 www 10562: $command.='_0_'.$start;
1.21 www 10563: }
10564: }
1.739 raeburn 10565: my $origstart = $start;
10566: my $origend = $end;
1.957 raeburn 10567: my $delflag;
1.357 www 10568: # actually delete
10569: if ($deleteflag) {
1.373 www 10570: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 10571: # modify command to delete the role
1.620 albertel 10572: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 10573: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 10574: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 10575: # set start and finish to negative values for userrolelog
10576: $start=-1;
10577: $end=-1;
1.957 raeburn 10578: $delflag = 1;
1.357 www 10579: }
10580: }
10581: # send command
1.349 www 10582: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 10583: # log new user role if status is ok
1.349 www 10584: if ($answer eq 'ok') {
1.663 raeburn 10585: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 10586: if (($role eq 'cc') || ($role eq 'in') ||
10587: ($role eq 'ep') || ($role eq 'ad') ||
10588: ($role eq 'ta') || ($role eq 'st') ||
10589: ($role=~/^cr/) || ($role eq 'gr') ||
10590: ($role eq 'co')) {
1.1200 raeburn 10591: # for course roles, perform group memberships changes triggered by role change.
10592: unless ($role =~ /^gr/) {
10593: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10594: $origstart,$selfenroll,$context);
10595: }
1.1184 raeburn 10596: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10597: $selfenroll,$context);
10598: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 10599: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10600: ($role eq 'da')) {
1.1184 raeburn 10601: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10602: $context);
10603: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10604: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10605: $context);
10606: }
1.1053 raeburn 10607: if ($role eq 'cc') {
10608: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10609: }
1.349 www 10610: }
10611: return $answer;
1.169 harris41 10612: }
10613:
1.1053 raeburn 10614: sub autoupdate_coowners {
10615: my ($url,$end,$start,$uname,$udom) = @_;
10616: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10617: if (($cdom ne '') && ($cnum ne '')) {
10618: my $now = time;
10619: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10620: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10621: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10622: my $instcode = $coursehash{'internal.coursecode'};
1.1444 raeburn 10623: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 10624: if ($instcode ne '') {
1.1056 raeburn 10625: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10626: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10627: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10628: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444 raeburn 10629: unless ($result eq 'valid') {
10630: if ($xlists ne '') {
10631: foreach my $xlist (split(',',$xlists)) {
10632: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10633: $result =
1.1446 raeburn 10634: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10635: $inst_crosslist,$uname.':'.$udom);
10636: last if ($result eq 'valid');
1.1444 raeburn 10637: }
10638: }
10639: }
1.1056 raeburn 10640: if ($result eq 'valid') {
10641: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10642: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10643: push(@newcoowners,$coowner);
10644: }
10645: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10646: push(@newcoowners,$uname.':'.$udom);
10647: }
10648: @newcoowners = sort(@newcoowners);
10649: } else {
10650: push(@newcoowners,$uname.':'.$udom);
10651: }
1.1444 raeburn 10652: } elsif ($coursehash{'internal.co-owners'}) {
10653: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10654: unless ($coowner eq $uname.':'.$udom) {
10655: push(@newcoowners,$coowner);
1.1053 raeburn 10656: }
1.1444 raeburn 10657: }
10658: unless (@newcoowners > 0) {
10659: $delcoowners = 1;
10660: $coowners = '';
1.1053 raeburn 10661: }
10662: }
10663: if (@newcoowners || $delcoowners) {
10664: &store_coowners($cdom,$cnum,$coursehash{'home'},
10665: $delcoowners,@newcoowners);
10666: }
10667: }
10668: }
10669: }
10670: }
10671: }
10672: }
10673:
10674: sub store_coowners {
10675: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10676: my $cid = $cdom.'_'.$cnum;
10677: my ($coowners,$delresult,$putresult);
10678: if (@newcoowners) {
10679: $coowners = join(',',@newcoowners);
10680: my %coownershash = (
10681: 'internal.co-owners' => $coowners,
10682: );
10683: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10684: if ($putresult eq 'ok') {
10685: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10686: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10687: }
10688: }
10689: }
10690: if ($delcoowners) {
10691: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10692: if ($delresult eq 'ok') {
10693: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10694: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10695: }
10696: }
10697: }
10698: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10699: my %crsinfo =
1.1494 raeburn 10700: &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
1.1053 raeburn 10701: if (ref($crsinfo{$cid}) eq 'HASH') {
10702: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
1.1494 raeburn 10703: my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
1.1053 raeburn 10704: }
10705: }
10706: }
10707:
1.169 harris41 10708: # -------------------------------------------------- Modify user authentication
1.197 www 10709: # Overrides without validation
10710:
1.169 harris41 10711: sub modifyuserauth {
10712: my ($udom,$uname,$umode,$upass)=@_;
10713: my $uhome=&homeserver($uname,$udom);
1.1409 raeburn 10714: my $allowed;
10715: if (&allowed('mau',$udom)) {
10716: $allowed = 1;
10717: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10718: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10719: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10720: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10721: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10722: if (($cdom ne '') && ($cnum ne '')) {
10723: my $is_owner = &is_course_owner($cdom,$cnum);
10724: if ($is_owner) {
10725: $allowed = 1;
10726: }
10727: }
10728: }
10729: unless ($allowed) { return 'refused'; }
1.197 www 10730: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10731: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10732: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10733: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10734: &escape($upass),$uhome);
1.1434 raeburn 10735: my $ip = &get_requestor_ip();
1.620 albertel 10736: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10737: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434 raeburn 10738: '(Remote '.$ip.'): '.$reply);
1.197 www 10739: &log($udom,,$uname,$uhome,
1.620 albertel 10740: 'Authentication changed by '.$env{'user.domain'}.', '.
10741: $env{'user.name'}.', '.$umode.
1.1435 raeburn 10742: '(Remote '.$ip.'): '.$reply);
1.169 harris41 10743: unless ($reply eq 'ok') {
1.197 www 10744: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10745: return 'error: '.$reply;
10746: }
1.170 harris41 10747: return 'ok';
1.80 www 10748: }
10749:
1.81 www 10750: # --------------------------------------------------------------- Modify a user
1.80 www 10751:
1.81 www 10752: sub modifyuser {
1.206 matthew 10753: my ($udom, $uname, $uid,
10754: $umode, $upass, $first,
10755: $middle, $last, $gene,
1.1058 raeburn 10756: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10757: $udom= &LONCAPA::clean_domain($udom);
10758: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10759: my $showcandelete = 'none';
10760: if (ref($candelete) eq 'ARRAY') {
10761: if (@{$candelete} > 0) {
10762: $showcandelete = join(', ',@{$candelete});
10763: }
10764: }
1.81 www 10765: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10766: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10767: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10768: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10769: ' desiredhome not specified').
1.620 albertel 10770: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10771: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10772: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10773: my $newuser;
10774: if ($uhome eq 'no_host') {
10775: $newuser = 1;
1.1368 raeburn 10776: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10777: ($umode eq 'lti')) {
10778: return 'error: more information needed to create new user';
10779: }
1.1075 raeburn 10780: }
1.80 www 10781: # ----------------------------------------------------------------- Create User
1.406 albertel 10782: if (($uhome eq 'no_host') &&
1.1368 raeburn 10783: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80 www 10784: my $unhome='';
1.844 albertel 10785: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10786: $unhome = $desiredhome;
1.620 albertel 10787: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10788: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10789: } else { # load balancing routine for determining $unhome
1.81 www 10790: my $loadm=10000000;
1.841 albertel 10791: my %servers = &get_servers($udom,'library');
10792: foreach my $tryserver (keys(%servers)) {
10793: my $answer=reply('load',$tryserver);
10794: if (($answer=~/\d+/) && ($answer<$loadm)) {
10795: $loadm=$answer;
10796: $unhome=$tryserver;
10797: }
1.80 www 10798: }
10799: }
10800: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10801: return 'error: unable to find a home server for '.$uname.
10802: ' in domain '.$udom;
1.80 www 10803: }
10804: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10805: &escape($upass),$unhome);
10806: unless ($reply eq 'ok') {
10807: return 'error: '.$reply;
10808: }
1.230 stredwic 10809: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10810: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10811: return 'error: unable verify users home machine.';
1.80 www 10812: }
1.209 matthew 10813: } # End of creation of new user
1.80 www 10814: # ---------------------------------------------------------------------- Add ID
10815: if ($uid) {
10816: $uid=~tr/A-Z/a-z/;
10817: my %uidhash=&idrget($udom,$uname);
1.196 www 10818: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10819: && (!$forceid)) {
1.80 www 10820: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10821: return 'error: user id "'.$uid.'" does not match '.
10822: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10823: }
10824: } else {
1.1300 raeburn 10825: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 10826: }
10827: }
10828: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10829: my @tmp=&get('environment',
1.899 raeburn 10830: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10831: 'permanentemail','inststatus'],
1.134 albertel 10832: $udom,$uname);
1.1075 raeburn 10833: my (%names,%oldnames);
1.313 matthew 10834: if ($tmp[0] =~ m/^error:.*/) {
10835: %names=();
10836: } else {
10837: %names = @tmp;
1.1075 raeburn 10838: %oldnames = %names;
1.313 matthew 10839: }
1.388 www 10840: #
1.1058 raeburn 10841: # If name, email and/or uid are blank (e.g., because an uploaded file
10842: # of users did not contain them), do not overwrite existing values
10843: # unless field is in $candelete array ref.
10844: #
10845:
10846: my @fields = ('firstname','middlename','lastname','generation',
10847: 'permanentemail','id');
10848: my %newvalues;
10849: if (ref($candelete) eq 'ARRAY') {
10850: foreach my $field (@fields) {
10851: if (grep(/^\Q$field\E$/,@{$candelete})) {
10852: if ($field eq 'firstname') {
10853: $names{$field} = $first;
10854: } elsif ($field eq 'middlename') {
10855: $names{$field} = $middle;
10856: } elsif ($field eq 'lastname') {
10857: $names{$field} = $last;
10858: } elsif ($field eq 'generation') {
10859: $names{$field} = $gene;
10860: } elsif ($field eq 'permanentemail') {
10861: $names{$field} = $email;
10862: } elsif ($field eq 'id') {
10863: $names{$field} = $uid;
10864: }
10865: }
10866: }
10867: }
1.388 www 10868: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10869: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10870: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10871: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10872: if ($email) {
10873: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10874: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10875: }
1.899 raeburn 10876: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10877: if (defined($inststatus)) {
10878: $names{'inststatus'} = '';
10879: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10880: if (ref($usertypes) eq 'HASH') {
10881: my @okstatuses;
10882: foreach my $item (split(/:/,$inststatus)) {
10883: if (defined($usertypes->{$item})) {
10884: push(@okstatuses,$item);
10885: }
10886: }
10887: if (@okstatuses) {
10888: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10889: }
10890: }
10891: }
1.1075 raeburn 10892: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10893: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10894: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10895: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10896: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10897: } else {
10898: $logmsg .= ' during self creation';
10899: }
1.1075 raeburn 10900: my $changed;
10901: if ($newuser) {
10902: $changed = 1;
10903: } else {
10904: foreach my $field (@fields) {
10905: if ($names{$field} ne $oldnames{$field}) {
10906: $changed = 1;
10907: last;
10908: }
10909: }
10910: }
10911: unless ($changed) {
10912: $logmsg = 'No changes in user information needed for: '.$logmsg;
10913: &logthis($logmsg);
10914: return 'ok';
10915: }
10916: my $reply = &put('environment', \%names, $udom,$uname);
10917: if ($reply ne 'ok') {
10918: return 'error: '.$reply;
10919: }
1.1087 raeburn 10920: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
1.1494 raeburn 10921: &devalidate_cache_new('emailscache',$uname.':'.$udom);
1.1087 raeburn 10922: }
1.1075 raeburn 10923: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10924: &devalidate_cache_new('namescache',$uname.':'.$udom);
10925: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10926: &logthis($logmsg);
1.134 albertel 10927: return 'ok';
1.80 www 10928: }
10929:
1.81 www 10930: # -------------------------------------------------------------- Modify student
1.80 www 10931:
1.81 www 10932: sub modifystudent {
10933: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10934: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 10935: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10936: if (!$cid) {
1.620 albertel 10937: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10938: return 'not_in_class';
10939: }
1.80 www 10940: }
10941: # --------------------------------------------------------------- Make the user
1.81 www 10942: my $reply=&modifyuser
1.209 matthew 10943: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10944: $desiredhome,$email,$inststatus);
1.80 www 10945: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10946: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 10947: # student's environment
1.297 matthew 10948: $uid = undef if (!$forceid);
1.455 albertel 10949: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 10950: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 10951: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10952: return $reply;
10953: }
10954:
10955: sub modify_student_enrollment {
1.1216 raeburn 10956: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 10957: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10958: my ($cdom,$cnum,$chome);
10959: if (!$cid) {
1.620 albertel 10960: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10961: return 'not_in_class';
10962: }
1.620 albertel 10963: $cdom=$env{'course.'.$cid.'.domain'};
10964: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10965: } else {
10966: ($cdom,$cnum)=split(/_/,$cid);
10967: }
1.620 albertel 10968: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10969: if (!$chome) {
1.457 raeburn 10970: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10971: }
1.455 albertel 10972: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10973: # Make sure the user exists
1.81 www 10974: my $uhome=&homeserver($uname,$udom);
10975: if (($uhome eq '') || ($uhome eq 'no_host')) {
10976: return 'error: no such user';
10977: }
1.297 matthew 10978: # Get student data if we were not given enough information
10979: if (!defined($first) || $first eq '' ||
10980: !defined($last) || $last eq '' ||
10981: !defined($uid) || $uid eq '' ||
10982: !defined($middle) || $middle eq '' ||
10983: !defined($gene) || $gene eq '') {
1.294 matthew 10984: # They did not supply us with enough data to enroll the student, so
10985: # we need to pick up more information.
1.297 matthew 10986: my %tmp = &get('environment',
1.294 matthew 10987: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10988: ,$udom,$uname);
10989:
1.800 albertel 10990: #foreach my $key (keys(%tmp)) {
10991: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10992: #}
1.294 matthew 10993: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10994: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10995: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10996: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10997: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10998: }
1.556 albertel 10999: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 11000: my $user = "$uname:$udom";
1.1494 raeburn 11001: my %old_entry = &get('classlist',[$user],$cdom,$cnum);
1.487 albertel 11002: my $reply=cput('classlist',
1.1148 raeburn 11003: {$user =>
1.1314 raeburn 11004: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 11005: $cdom,$cnum);
1.1148 raeburn 11006: if (($reply eq 'ok') || ($reply eq 'delayed')) {
11007: &devalidate_getsection_cache($udom,$uname,$cid);
11008: } else {
1.81 www 11009: return 'error: '.$reply;
11010: }
1.297 matthew 11011: # Add student role to user
1.83 www 11012: my $uurl='/'.$cid;
1.81 www 11013: $uurl=~s/\_/\//g;
11014: if ($usec) {
11015: $uurl.='/'.$usec;
11016: }
1.1148 raeburn 11017: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
11018: $selfenroll,$context);
11019: if ($result ne 'ok') {
11020: if ($old_entry{$user} ne '') {
11021: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11022: } else {
11023: $reply = &del('classlist',[$user],$cdom,$cnum);
11024: }
11025: }
11026: return $result;
1.21 www 11027: }
11028:
1.556 albertel 11029: sub format_name {
11030: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11031: my $name;
11032: if ($first ne 'lastname') {
11033: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11034: } else {
11035: if ($lastname=~/\S/) {
11036: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11037: $name=~s/\s+,/,/;
11038: } else {
11039: $name.= $firstname.' '.$middlename.' '.$generation;
11040: }
11041: }
11042: $name=~s/^\s+//;
11043: $name=~s/\s+$//;
11044: $name=~s/\s+/ /g;
11045: return $name;
11046: }
11047:
1.84 www 11048: # ------------------------------------------------- Write to course preferences
11049:
11050: sub writecoursepref {
11051: my ($courseid,%prefs)=@_;
11052: $courseid=~s/^\///;
11053: $courseid=~s/\_/\//g;
11054: my ($cdomain,$cnum)=split(/\//,$courseid);
11055: my $chome=homeserver($cnum,$cdomain);
11056: if (($chome eq '') || ($chome eq 'no_host')) {
11057: return 'error: no such course';
11058: }
11059: my $cstring='';
1.800 albertel 11060: foreach my $pref (keys(%prefs)) {
11061: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 11062: }
1.84 www 11063: $cstring=~s/\&$//;
11064: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11065: }
11066:
11067: # ---------------------------------------------------------- Make/modify course
11068:
11069: sub createcourse {
1.741 raeburn 11070: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423 raeburn 11071: $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84 www 11072: $url=&declutter($url);
11073: my $cid='';
1.1028 raeburn 11074: if ($context eq 'requestcourses') {
11075: my $can_create = 0;
11076: my ($ownername,$ownerdom) = split(':',$course_owner);
11077: if ($udom eq $ownerdom) {
1.1423 raeburn 11078: my $reload;
11079: if (($callercontext eq 'auto') &&
11080: ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11081: $reload = 'reload';
11082: }
11083: if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028 raeburn 11084: $context)) {
11085: $can_create = 1;
11086: }
11087: } else {
11088: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11089: $category);
11090: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11091: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11092: if (@curr > 0) {
11093: my @options = qw(approval validate autolimit);
11094: my $optregex = join('|',@options);
11095: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11096: $can_create = 1;
11097: }
11098: }
11099: }
11100: }
11101: if ($can_create) {
11102: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11103: unless (&allowed('ccc',$udom)) {
11104: return 'refused';
11105: }
1.1017 raeburn 11106: }
11107: } else {
11108: return 'refused';
11109: }
1.1028 raeburn 11110: } elsif (!&allowed('ccc',$udom)) {
11111: return 'refused';
1.84 www 11112: }
1.1011 raeburn 11113: # --------------------------------------------------------------- Get Unique ID
11114: my $uname;
11115: if ($cnum =~ /^$match_courseid$/) {
11116: my $chome=&homeserver($cnum,$udom,'true');
11117: if (($chome eq '') || ($chome eq 'no_host')) {
11118: $uname = $cnum;
11119: } else {
1.1038 raeburn 11120: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 11121: }
11122: } else {
1.1038 raeburn 11123: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 11124: }
11125: return $uname if ($uname =~ /^error/);
11126: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 11127: if (!defined($course_server)) {
11128: if (defined(&domain($udom,'primary'))) {
11129: $course_server = &domain($udom,'primary');
11130: } else {
11131: $course_server = $env{'user.home'};
11132: }
11133: }
11134: my %host_servers =
1.1494 raeburn 11135: &get_servers($udom,'library');
1.1052 raeburn 11136: unless ($host_servers{$course_server}) {
11137: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 11138: }
1.84 www 11139: # ------------------------------------------------------------- Make the course
11140: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 11141: $course_server);
1.84 www 11142: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 11143: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 11144: if (($uhome eq '') || ($uhome eq 'no_host')) {
11145: return 'error: no such course';
11146: }
1.271 www 11147: # ----------------------------------------------------------------- Course made
1.516 raeburn 11148: # log existence
1.1029 raeburn 11149: my $now = time;
1.918 raeburn 11150: my $newcourse = {
11151: $udom.'_'.$uname => {
1.921 raeburn 11152: description => $description,
11153: inst_code => $inst_code,
11154: owner => $course_owner,
11155: type => $crstype,
1.1029 raeburn 11156: creator => $env{'user.name'}.':'.
11157: $env{'user.domain'},
11158: created => $now,
11159: context => $context,
1.918 raeburn 11160: },
11161: };
1.921 raeburn 11162: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 11163: # set toplevel url
1.271 www 11164: my $topurl=$url;
11165: unless ($nonstandard) {
11166: # ------------------------------------------ For standard courses, make top url
11167: my $mapurl=&clutter($url);
1.278 www 11168: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 11169: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 11170: <map>
11171: <resource id="1" type="start"></resource>
11172: <resource id="2" src="$mapurl"></resource>
11173: <resource id="3" type="finish"></resource>
11174: <link index="1" from="1" to="2"></link>
11175: <link index="2" from="2" to="3"></link>
11176: </map>
11177: ENDINITMAP
11178: $topurl=&declutter(
1.638 albertel 11179: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 11180: );
11181: }
11182: # ----------------------------------------------------------- Write preferences
1.84 www 11183: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 11184: ('description' => $description,
11185: 'url' => $topurl,
11186: 'internal.creator' => $env{'user.name'}.':'.
11187: $env{'user.domain'},
11188: 'internal.created' => $now,
11189: 'internal.creationcontext' => $context)
11190: );
1.84 www 11191: return '/'.$udom.'/'.$uname;
11192: }
11193:
1.1011 raeburn 11194: # ------------------------------------------------------------------- Create ID
11195: sub generate_coursenum {
1.1038 raeburn 11196: my ($udom,$crstype) = @_;
1.1011 raeburn 11197: my $domdesc = &domain($udom);
11198: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 11199: my $first;
11200: if ($crstype eq 'Community') {
11201: $first = '0';
11202: } else {
11203: $first = int(1+rand(9));
11204: }
11205: my $uname=$first.
1.1011 raeburn 11206: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11207: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11208: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11209: # ----------------------------------------------- Make sure that does not exist
11210: my $uhome=&homeserver($uname,$udom,'true');
11211: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 11212: if ($crstype eq 'Community') {
11213: $first = '0';
11214: } else {
11215: $first = int(1+rand(9));
11216: }
11217: $uname=$first.
1.1011 raeburn 11218: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11219: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11220: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11221: $uhome=&homeserver($uname,$udom,'true');
11222: unless (($uhome eq '') || ($uhome eq 'no_host')) {
11223: return 'error: unable to generate unique course-ID';
11224: }
11225: }
11226: return $uname;
11227: }
11228:
1.813 albertel 11229: sub is_course {
1.1167 droeschl 11230: my ($cdom, $cnum) = scalar(@_) == 1 ?
11231: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
11232:
1.1381 raeburn 11233: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11234: my $uhome=&homeserver($cnum,$cdom);
11235: my $iscourse;
11236: if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382 raeburn 11237: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381 raeburn 11238: } else {
11239: my $hashid = $cdom.':'.$cnum;
11240: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11241: unless (defined($cached)) {
11242: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11243: $cnum,undef,undef,'.');
11244: $iscourse = 0;
11245: if (exists($courses{$cdom.'_'.$cnum})) {
11246: $iscourse = 1;
11247: }
11248: &do_cache_new('iscourse',$hashid,$iscourse,3600);
11249: }
11250: }
11251: return unless ($iscourse);
1.1167 droeschl 11252: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 11253: }
11254:
1.1015 raeburn 11255: sub store_userdata {
11256: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 11257: my $result;
1.1016 raeburn 11258: if ($datakey ne '') {
1.1013 raeburn 11259: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 11260: if ($udom eq '' || $uname eq '') {
11261: $udom = $env{'user.domain'};
11262: $uname = $env{'user.name'};
11263: }
11264: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 11265: if (($uhome eq '') || ($uhome eq 'no_host')) {
11266: $result = 'error: no_host';
11267: } else {
1.1434 raeburn 11268: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 11269: $storehash->{'host'} = $perlvar{'lonHostID'};
11270:
11271: my $namevalue='';
11272: foreach my $key (keys(%{$storehash})) {
11273: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11274: }
11275: $namevalue=~s/\&$//;
1.1224 raeburn 11276: unless ($namespace eq 'courserequests') {
11277: $datakey = &escape($datakey);
11278: }
1.1105 raeburn 11279: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
11280: $namevalue,$uhome);
1.1013 raeburn 11281: }
11282: } else {
11283: $result = 'error: data to store was not a hash reference';
11284: }
11285: } else {
11286: $result= 'error: invalid requestkey';
11287: }
11288: return $result;
11289: }
11290:
1.21 www 11291: # ---------------------------------------------------------- Assign Custom Role
11292:
11293: sub assigncustomrole {
1.957 raeburn 11294: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11295: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 11296: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 11297: }
11298:
11299: # ----------------------------------------------------------------- Revoke Role
11300:
11301: sub revokerole {
1.957 raeburn 11302: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11303: my $now=time;
1.965 raeburn 11304: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 11305: }
11306:
11307: # ---------------------------------------------------------- Revoke Custom Role
11308:
11309: sub revokecustomrole {
1.957 raeburn 11310: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11311: my $now=time;
1.357 www 11312: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 11313: $deleteflag,$selfenroll,$context);
1.17 www 11314: }
11315:
1.533 banghart 11316: # ------------------------------------------------------------ Disk usage
1.535 albertel 11317: sub diskusage {
1.955 raeburn 11318: my ($udom,$uname,$directorypath,$getpropath)=@_;
11319: $directorypath =~ s/\/$//;
11320: my $listing=&reply('du2:'.&escape($directorypath).':'
11321: .&escape($getpropath).':'.&escape($uname).':'
11322: .&escape($udom),homeserver($uname,$udom));
11323: if ($listing eq 'unknown_cmd') {
11324: if ($getpropath) {
11325: $directorypath = &propath($udom,$uname).'/'.$directorypath;
11326: }
11327: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11328: }
1.514 albertel 11329: return $listing;
1.512 banghart 11330: }
11331:
1.566 banghart 11332: sub is_locked {
1.1096 raeburn 11333: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 11334: my @check;
11335: my $is_locked;
1.1093 raeburn 11336: push (@check,$file_name);
1.613 albertel 11337: my %locked = &get('file_permissions',\@check,
1.620 albertel 11338: $env{'user.domain'},$env{'user.name'});
1.615 albertel 11339: my ($tmp)=keys(%locked);
11340: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 11341:
1.566 banghart 11342: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 11343: $is_locked = 'false';
11344: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 11345: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 11346: $is_locked = 'true';
1.1096 raeburn 11347: if (ref($which) eq 'ARRAY') {
11348: push(@{$which},$entry);
11349: } else {
11350: last;
11351: }
1.745 raeburn 11352: }
11353: }
1.566 banghart 11354: } else {
11355: $is_locked = 'false';
11356: }
1.1093 raeburn 11357: return $is_locked;
1.566 banghart 11358: }
11359:
1.759 albertel 11360: sub declutter_portfile {
11361: my ($file) = @_;
1.833 albertel 11362: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 11363: return $file;
11364: }
11365:
1.559 banghart 11366: # ------------------------------------------------------------- Mark as Read Only
11367:
11368: sub mark_as_readonly {
11369: my ($domain,$user,$files,$what) = @_;
1.613 albertel 11370: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11371: my ($tmp)=keys(%current_permissions);
11372: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 11373: foreach my $file (@{$files}) {
1.759 albertel 11374: $file = &declutter_portfile($file);
1.561 banghart 11375: push(@{$current_permissions{$file}},$what);
1.559 banghart 11376: }
1.613 albertel 11377: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11378: return;
11379: }
11380:
1.572 banghart 11381: # ------------------------------------------------------------Save Selected Files
11382:
11383: sub save_selected_files {
11384: my ($user, $path, @files) = @_;
11385: my $filename = $user."savedfiles";
1.573 banghart 11386: my @other_files = &files_not_in_path($user, $path);
1.1359 raeburn 11387: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 11388: foreach my $file (@files) {
1.620 albertel 11389: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 11390: }
11391: foreach my $file (@other_files) {
1.574 banghart 11392: print (OUT $file."\n");
1.572 banghart 11393: }
1.574 banghart 11394: close (OUT);
1.572 banghart 11395: return 'ok';
11396: }
11397:
1.574 banghart 11398: sub clear_selected_files {
11399: my ($user) = @_;
11400: my $filename = $user."savedfiles";
1.1359 raeburn 11401: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 11402: print (OUT undef);
11403: close (OUT);
11404: return ("ok");
11405: }
11406:
1.572 banghart 11407: sub files_in_path {
11408: my ($user, $path) = @_;
11409: my $filename = $user."savedfiles";
11410: my %return_files;
1.1359 raeburn 11411: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 11412: while (my $line_in = <IN>) {
1.574 banghart 11413: chomp ($line_in);
11414: my @paths_and_file = split (m!/!, $line_in);
11415: my $file_part = pop (@paths_and_file);
11416: my $path_part = join ('/', @paths_and_file);
1.573 banghart 11417: $path_part.='/';
11418: my $path_and_file = $path_part.$file_part;
11419: if ($path_part eq $path) {
11420: $return_files{$file_part}= 'selected';
11421: }
11422: }
1.574 banghart 11423: close (IN);
11424: return (\%return_files);
1.572 banghart 11425: }
11426:
11427: # called in portfolio select mode, to show files selected NOT in current directory
11428: sub files_not_in_path {
11429: my ($user, $path) = @_;
11430: my $filename = $user."savedfiles";
11431: my @return_files;
11432: my $path_part;
1.1359 raeburn 11433: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 11434: while (my $line = <IN>) {
1.572 banghart 11435: #ok, I know it's clunky, but I want it to work
1.800 albertel 11436: my @paths_and_file = split(m|/|, $line);
11437: my $file_part = pop(@paths_and_file);
11438: chomp($file_part);
11439: my $path_part = join('/', @paths_and_file);
1.572 banghart 11440: $path_part .= '/';
11441: my $path_and_file = $path_part.$file_part;
11442: if ($path_part ne $path) {
1.800 albertel 11443: push(@return_files, ($path_and_file));
1.572 banghart 11444: }
11445: }
1.800 albertel 11446: close(OUT);
1.574 banghart 11447: return (@return_files);
1.572 banghart 11448: }
11449:
1.1273 raeburn 11450: #------------------------------Submitted/Handedback Portfolio Files Versioning
11451:
11452: sub portfiles_versioning {
11453: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11454: my $portfolio_root = '/userfiles/portfolio';
11455: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11456: foreach my $file (@{$portfiles}) {
11457: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11458: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11459: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11460: my $getpropath = 1;
11461: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11462: $stu_name,$getpropath);
11463: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11464: my $new_answer =
11465: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11466: if ($new_answer ne 'problem getting file') {
11467: push(@{$versioned_portfiles}, $directory.$new_answer);
11468: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11469: [$symb,$env{'request.course.id'},'graded']);
11470: }
11471: }
11472: }
11473:
11474: sub get_next_version {
11475: my ($answer_name, $answer_ext, $dir_list) = @_;
11476: my $version;
11477: if (ref($dir_list) eq 'ARRAY') {
11478: foreach my $row (@{$dir_list}) {
11479: my ($file) = split(/\&/,$row,2);
11480: my ($file_name,$file_version,$file_ext) =
11481: &file_name_version_ext($file);
11482: if (($file_name eq $answer_name) &&
11483: ($file_ext eq $answer_ext)) {
11484: # gets here if filename and extension match,
11485: # regardless of version
11486: if ($file_version ne '') {
11487: # a versioned file is found so save it for later
11488: if ($file_version > $version) {
11489: $version = $file_version;
11490: }
11491: }
11492: }
11493: }
11494: }
11495: $version ++;
11496: return($version);
11497: }
11498:
11499: sub version_selected_portfile {
11500: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11501: my ($answer_name,$answer_ver,$answer_ext) =
11502: &file_name_version_ext($file_name);
11503: my $new_answer;
11504: $env{'form.copy'} =
11505: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11506: if($env{'form.copy'} eq '-1') {
11507: $new_answer = 'problem getting file';
11508: } else {
11509: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11510: my $copy_result =
11511: &finishuserfileupload($stu_name,$domain,'copy',
11512: '/portfolio'.$directory.$new_answer);
11513: }
11514: undef($env{'form.copy'});
11515: return ($new_answer);
11516: }
11517:
11518: sub file_name_version_ext {
11519: my ($file)=@_;
11520: my @file_parts = split(/\./, $file);
11521: my ($name,$version,$ext);
11522: if (@file_parts > 1) {
11523: $ext=pop(@file_parts);
11524: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11525: $version=pop(@file_parts);
11526: }
11527: $name=join('.',@file_parts);
11528: } else {
11529: $name=join('.',@file_parts);
11530: }
11531: return($name,$version,$ext);
11532: }
11533:
1.745 raeburn 11534: #----------------------------------------------Get portfolio file permissions
1.629 banghart 11535:
1.745 raeburn 11536: sub get_portfile_permissions {
11537: my ($domain,$user) = @_;
1.613 albertel 11538: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11539: my ($tmp)=keys(%current_permissions);
11540: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11541: return \%current_permissions;
11542: }
11543:
11544: #---------------------------------------------Get portfolio file access controls
11545:
1.749 raeburn 11546: sub get_access_controls {
1.745 raeburn 11547: my ($current_permissions,$group,$file) = @_;
1.769 albertel 11548: my %access;
11549: my $real_file = $file;
11550: $file =~ s/\.meta$//;
1.745 raeburn 11551: if (defined($file)) {
1.749 raeburn 11552: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11553: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 11554: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 11555: }
11556: }
1.745 raeburn 11557: } else {
1.749 raeburn 11558: foreach my $key (keys(%{$current_permissions})) {
11559: if ($key =~ /\0accesscontrol$/) {
11560: if (defined($group)) {
11561: if ($key !~ m-^\Q$group\E/-) {
11562: next;
11563: }
11564: }
11565: my ($fullpath) = split(/\0/,$key);
11566: if (ref($$current_permissions{$key}) eq 'HASH') {
11567: foreach my $control (keys(%{$$current_permissions{$key}})) {
11568: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11569: }
11570: }
11571: }
11572: }
11573: }
11574: return %access;
11575: }
11576:
11577: sub modify_access_controls {
11578: my ($file_name,$changes,$domain,$user)=@_;
11579: my ($outcome,$deloutcome);
11580: my %store_permissions;
11581: my %new_values;
11582: my %new_control;
11583: my %translation;
11584: my @deletions = ();
11585: my $now = time;
11586: if (exists($$changes{'activate'})) {
11587: if (ref($$changes{'activate'}) eq 'HASH') {
11588: my @newitems = sort(keys(%{$$changes{'activate'}}));
11589: my $numnew = scalar(@newitems);
11590: for (my $i=0; $i<$numnew; $i++) {
11591: my $newkey = $newitems[$i];
11592: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 11593: if ($newkey =~ /^\d+:/) {
11594: $newkey =~ s/^(\d+)/$newid/;
11595: $translation{$1} = $newid;
11596: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11597: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11598: $translation{$1} = $newid;
11599: }
1.749 raeburn 11600: $new_values{$file_name."\0".$newkey} =
11601: $$changes{'activate'}{$newitems[$i]};
11602: $new_control{$newkey} = $now;
11603: }
11604: }
11605: }
11606: my %todelete;
11607: my %changed_items;
11608: foreach my $action ('delete','update') {
11609: if (exists($$changes{$action})) {
11610: if (ref($$changes{$action}) eq 'HASH') {
11611: foreach my $key (keys(%{$$changes{$action}})) {
11612: my ($itemnum) = ($key =~ /^([^:]+):/);
11613: if ($action eq 'delete') {
11614: $todelete{$itemnum} = 1;
11615: } else {
11616: $changed_items{$itemnum} = $key;
11617: }
11618: }
1.745 raeburn 11619: }
11620: }
1.749 raeburn 11621: }
11622: # get lock on access controls for file.
11623: my $lockhash = {
11624: $file_name."\0".'locked_access_records' => $env{'user.name'}.
11625: ':'.$env{'user.domain'},
11626: };
11627: my $tries = 0;
11628: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11629:
1.1288 damieng 11630: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 11631: $tries ++;
1.1289 damieng 11632: sleep(0.1);
1.749 raeburn 11633: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11634: }
11635: if ($gotlock eq 'ok') {
11636: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11637: my ($tmp)=keys(%curr_permissions);
11638: if ($tmp=~/^error:/) { undef(%curr_permissions); }
11639: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11640: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11641: if (ref($curr_controls) eq 'HASH') {
11642: foreach my $control_item (keys(%{$curr_controls})) {
11643: my ($itemnum) = ($control_item =~ /^([^:]+):/);
11644: if (defined($todelete{$itemnum})) {
11645: push(@deletions,$file_name."\0".$control_item);
11646: } else {
11647: if (defined($changed_items{$itemnum})) {
11648: $new_control{$changed_items{$itemnum}} = $now;
11649: push(@deletions,$file_name."\0".$control_item);
11650: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11651: } else {
11652: $new_control{$control_item} = $$curr_controls{$control_item};
11653: }
11654: }
1.745 raeburn 11655: }
11656: }
11657: }
1.970 raeburn 11658: my ($group);
11659: if (&is_course($domain,$user)) {
11660: ($group,my $file) = split(/\//,$file_name,2);
11661: }
1.749 raeburn 11662: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11663: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11664: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11665: # remove lock
11666: my @del_lock = ($file_name."\0".'locked_access_records');
11667: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11668: my $sqlresult =
1.970 raeburn 11669: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11670: $group);
1.749 raeburn 11671: } else {
11672: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11673: }
1.749 raeburn 11674: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11675: }
11676:
1.827 raeburn 11677: sub make_public_indefinitely {
1.1271 raeburn 11678: my (@requrl) = @_;
11679: return &automated_portfile_access('public',\@requrl);
11680: }
11681:
11682: sub automated_portfile_access {
11683: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 11684: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11685: return 'invalid';
11686: }
1.1271 raeburn 11687: my %urls;
11688: if (ref($addsref) eq 'ARRAY') {
11689: foreach my $requrl (@{$addsref}) {
11690: if (&is_portfolio_url($requrl)) {
11691: unless (exists($urls{$requrl})) {
11692: $urls{$requrl} = 'add';
11693: }
11694: }
11695: }
11696: }
11697: if (ref($delsref) eq 'ARRAY') {
11698: foreach my $requrl (@{$delsref}) {
11699: if (&is_portfolio_url($requrl)) {
11700: unless (exists($urls{$requrl})) {
11701: $urls{$requrl} = 'delete';
11702: }
11703: }
11704: }
11705: }
11706: unless (keys(%urls)) {
11707: return 'invalid';
11708: }
11709: my $ip;
11710: if ($accesstype eq 'ip') {
11711: if (ref($info) eq 'HASH') {
11712: if ($info->{'ip'} ne '') {
11713: $ip = $info->{'ip'};
11714: }
11715: }
11716: if ($ip eq '') {
11717: return 'invalid';
11718: }
11719: }
11720: my $errors;
1.827 raeburn 11721: my $now = time;
1.1271 raeburn 11722: my %current_perms;
11723: foreach my $requrl (sort(keys(%urls))) {
11724: my $action;
11725: if ($urls{$requrl} eq 'add') {
11726: $action = 'activate';
11727: } else {
11728: $action = 'none';
11729: }
11730: my $aclnum = 0;
1.827 raeburn 11731: my (undef,$udom,$unum,$file_name,$group) =
11732: &parse_portfolio_url($requrl);
1.1271 raeburn 11733: unless (exists($current_perms{$unum.':'.$udom})) {
11734: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11735: }
11736: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 11737: $group,$file_name);
11738: foreach my $key (keys(%{$access_controls{$file_name}})) {
11739: my ($num,$scope,$end,$start) =
11740: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 11741: if ($scope eq $accesstype) {
11742: if (($start <= $now) && ($end == 0)) {
11743: if ($accesstype eq 'ip') {
11744: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11745: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11746: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11747: if ($urls{$requrl} eq 'add') {
11748: $action = 'none';
11749: last;
11750: } else {
11751: $action = 'delete';
11752: $aclnum = $num;
11753: last;
11754: }
11755: }
11756: }
11757: }
11758: } elsif ($accesstype eq 'public') {
11759: if ($urls{$requrl} eq 'add') {
11760: $action = 'none';
11761: last;
11762: } else {
11763: $action = 'delete';
11764: $aclnum = $num;
11765: last;
11766: }
11767: }
11768: } elsif ($accesstype eq 'public') {
1.827 raeburn 11769: $action = 'update';
11770: $aclnum = $num;
1.1271 raeburn 11771: last;
1.827 raeburn 11772: }
11773: }
11774: }
11775: if ($action eq 'none') {
1.1271 raeburn 11776: next;
1.827 raeburn 11777: } else {
11778: my %changes;
11779: my $newend = 0;
11780: my $newstart = $now;
1.1271 raeburn 11781: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 11782: $changes{$action}{$newkey} = {
1.1271 raeburn 11783: type => $accesstype,
1.827 raeburn 11784: time => {
11785: start => $newstart,
11786: end => $newend,
11787: },
11788: };
1.1271 raeburn 11789: if ($accesstype eq 'ip') {
11790: $changes{$action}{$newkey}{'ip'} = [$ip];
11791: }
1.827 raeburn 11792: my ($outcome,$deloutcome,$new_values,$translation) =
11793: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 11794: unless ($outcome eq 'ok') {
11795: $errors .= $outcome.' ';
11796: }
1.827 raeburn 11797: }
1.1271 raeburn 11798: }
11799: if ($errors) {
11800: $errors =~ s/\s$//;
11801: return $errors;
1.827 raeburn 11802: } else {
1.1271 raeburn 11803: return 'ok';
1.827 raeburn 11804: }
11805: }
11806:
1.745 raeburn 11807: #------------------------------------------------------Get Marked as Read Only
11808:
11809: sub get_marked_as_readonly {
11810: my ($domain,$user,$what,$group) = @_;
11811: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11812: my @readonly_files;
1.629 banghart 11813: my $cmp1=$what;
11814: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11815: while (my ($file_name,$value) = each(%{$current_permissions})) {
11816: if (defined($group)) {
11817: if ($file_name !~ m-^\Q$group\E/-) {
11818: next;
11819: }
11820: }
1.561 banghart 11821: if (ref($value) eq "ARRAY"){
11822: foreach my $stored_what (@{$value}) {
1.629 banghart 11823: my $cmp2=$stored_what;
1.759 albertel 11824: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11825: $cmp2=join('',@{$stored_what});
1.745 raeburn 11826: }
1.629 banghart 11827: if ($cmp1 eq $cmp2) {
1.561 banghart 11828: push(@readonly_files, $file_name);
1.745 raeburn 11829: last;
1.563 banghart 11830: } elsif (!defined($what)) {
11831: push(@readonly_files, $file_name);
1.745 raeburn 11832: last;
1.561 banghart 11833: }
11834: }
1.745 raeburn 11835: }
1.561 banghart 11836: }
11837: return @readonly_files;
11838: }
1.577 banghart 11839: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11840:
1.577 banghart 11841: sub get_marked_as_readonly_hash {
1.745 raeburn 11842: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11843: my %readonly_files;
1.745 raeburn 11844: while (my ($file_name,$value) = each(%{$current_permissions})) {
11845: if (defined($group)) {
11846: if ($file_name !~ m-^\Q$group\E/-) {
11847: next;
11848: }
11849: }
1.577 banghart 11850: if (ref($value) eq "ARRAY"){
11851: foreach my $stored_what (@{$value}) {
1.745 raeburn 11852: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11853: foreach my $lock_descriptor(@{$stored_what}) {
11854: if ($lock_descriptor eq 'graded') {
11855: $readonly_files{$file_name} = 'graded';
11856: } elsif ($lock_descriptor eq 'handback') {
11857: $readonly_files{$file_name} = 'handback';
11858: } else {
11859: if (!exists($readonly_files{$file_name})) {
11860: $readonly_files{$file_name} = 'locked';
11861: }
11862: }
1.745 raeburn 11863: }
1.750 banghart 11864: }
1.577 banghart 11865: }
11866: }
11867: }
11868: return %readonly_files;
11869: }
1.559 banghart 11870: # ------------------------------------------------------------ Unmark as Read Only
11871:
11872: sub unmark_as_readonly {
1.629 banghart 11873: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11874: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11875: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11876: $file_name = &declutter_portfile($file_name);
1.634 albertel 11877: my $symb_crs = $what;
11878: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11879: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11880: my ($tmp)=keys(%current_permissions);
11881: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11882: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11883: foreach my $file (@readonly_files) {
1.759 albertel 11884: my $clean_file = &declutter_portfile($file);
11885: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11886: my $current_locks = $current_permissions{$file};
1.563 banghart 11887: my @new_locks;
11888: my @del_keys;
11889: if (ref($current_locks) eq "ARRAY"){
11890: foreach my $locker (@{$current_locks}) {
1.632 albertel 11891: my $compare=$locker;
1.749 raeburn 11892: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11893: $compare=join('',@{$locker});
1.746 raeburn 11894: if ($compare ne $symb_crs) {
11895: push(@new_locks, $locker);
11896: }
1.563 banghart 11897: }
11898: }
1.650 albertel 11899: if (scalar(@new_locks) > 0) {
1.563 banghart 11900: $current_permissions{$file} = \@new_locks;
11901: } else {
11902: push(@del_keys, $file);
1.613 albertel 11903: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11904: delete($current_permissions{$file});
1.563 banghart 11905: }
11906: }
1.561 banghart 11907: }
1.613 albertel 11908: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11909: return;
11910: }
1.512 banghart 11911:
1.17 www 11912: # ------------------------------------------------------------ Directory lister
11913:
11914: sub dirlist {
1.955 raeburn 11915: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11916: $uri=~s/^\///;
11917: $uri=~s/\/$//;
1.253 stredwic 11918: my ($udom, $uname);
1.955 raeburn 11919: if ($getuserdir) {
1.253 stredwic 11920: $udom = $userdomain;
11921: $uname = $username;
1.955 raeburn 11922: } else {
11923: (undef,$udom,$uname)=split(/\//,$uri);
11924: if(defined($userdomain)) {
11925: $udom = $userdomain;
11926: }
11927: if(defined($username)) {
11928: $uname = $username;
11929: }
1.253 stredwic 11930: }
1.955 raeburn 11931: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11932:
1.955 raeburn 11933: $dirRoot = $perlvar{'lonDocRoot'};
11934: if (defined($getpropath)) {
11935: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11936: $dirRoot =~ s/\/$//;
1.955 raeburn 11937: } elsif (defined($getuserdir)) {
11938: my $subdir=$uname.'__';
11939: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11940: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11941: ."/$udom/$subdir/$uname";
11942: } elsif (defined($alternateRoot)) {
11943: $dirRoot = $alternateRoot;
1.751 banghart 11944: }
1.253 stredwic 11945:
11946: if($udom) {
11947: if($uname) {
1.1135 raeburn 11948: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11949: if ($uhome eq 'no_host') {
11950: return ([],'no_host');
11951: }
1.955 raeburn 11952: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11953: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11954: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11955: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11956: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11957: } else {
11958: @listing_results = map { &unescape($_); } split(/:/,$listing);
11959: }
1.605 matthew 11960: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11961: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11962: @listing_results = split(/:/,$listing);
11963: } else {
11964: @listing_results = map { &unescape($_); } split(/:/,$listing);
11965: }
1.1135 raeburn 11966: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11967: ($listing eq 'rejected') || ($listing eq 'refused') ||
11968: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11969: return ([],$listing);
11970: } else {
11971: return (\@listing_results);
1.1135 raeburn 11972: }
1.955 raeburn 11973: } elsif(!$alternateRoot) {
1.1136 raeburn 11974: my (%allusers,%listerror);
1.841 albertel 11975: my %servers = &get_servers($udom,'library');
1.955 raeburn 11976: foreach my $tryserver (keys(%servers)) {
11977: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11978: &escape($udom),$tryserver);
11979: if ($listing eq 'unknown_cmd') {
11980: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11981: $udom, $tryserver);
11982: } else {
11983: @listing_results = map { &unescape($_); } split(/:/,$listing);
11984: }
1.841 albertel 11985: if ($listing eq 'unknown_cmd') {
11986: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11987: $udom, $tryserver);
11988: @listing_results = split(/:/,$listing);
11989: } else {
11990: @listing_results =
11991: map { &unescape($_); } split(/:/,$listing);
11992: }
1.1136 raeburn 11993: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11994: ($listing eq 'rejected') || ($listing eq 'refused') ||
11995: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11996: $listerror{$tryserver} = $listing;
11997: } else {
1.841 albertel 11998: foreach my $line (@listing_results) {
11999: my ($entry) = split(/&/,$line,2);
12000: $allusers{$entry} = 1;
12001: }
12002: }
1.253 stredwic 12003: }
1.1136 raeburn 12004: my @alluserslist=();
1.800 albertel 12005: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 12006: push(@alluserslist,$user.'&user');
1.253 stredwic 12007: }
1.1318 droeschl 12008:
12009: if (!%listerror) {
12010: # no errors
12011: return (\@alluserslist);
12012: } elsif (scalar(keys(%servers)) == 1) {
12013: # one library server, one error
12014: my ($key) = keys(%listerror);
12015: return (\@alluserslist, $listerror{$key});
12016: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
12017: # con_lost indicates that we might miss data from at least one
12018: # library server
12019: return (\@alluserslist, 'con_lost');
12020: } else {
12021: # multiple library servers and no con_lost -> data should be
12022: # complete.
12023: return (\@alluserslist);
12024: }
12025:
1.253 stredwic 12026: } else {
1.1136 raeburn 12027: return ([],'missing username');
1.253 stredwic 12028: }
1.955 raeburn 12029: } elsif(!defined($getpropath)) {
1.1136 raeburn 12030: my $path = $perlvar{'lonDocRoot'}.'/res/';
12031: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
12032: return (\@all_domains);
1.955 raeburn 12033: } else {
1.1136 raeburn 12034: return ([],'missing domain');
1.275 stredwic 12035: }
12036: }
12037:
12038: # --------------------------------------------- GetFileTimestamp
12039: # This function utilizes dirlist and returns the date stamp for
12040: # when it was last modified. It will also return an error of -1
12041: # if an error occurs
12042:
12043: sub GetFileTimestamp {
1.955 raeburn 12044: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 12045: $studentDomain = &LONCAPA::clean_domain($studentDomain);
12046: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 12047: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
12048: undef,$getuserdir);
12049: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12050: return -1;
12051: }
12052: if (ref($fileref) eq 'ARRAY') {
12053: my @stats = split('&',$fileref->[0]);
1.375 matthew 12054: # @stats contains first the filename, then the stat output
12055: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 12056: } else {
12057: return -1;
1.253 stredwic 12058: }
1.26 www 12059: }
12060:
1.712 albertel 12061: sub stat_file {
12062: my ($uri) = @_;
1.787 albertel 12063: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 12064:
1.955 raeburn 12065: my ($udom,$uname,$file);
1.712 albertel 12066: if ($uri =~ m-^/(uploaded|editupload)/-) {
12067: ($udom,$uname,$file) =
1.811 albertel 12068: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 12069: $file = 'userfiles/'.$file;
12070: }
12071: if ($uri =~ m-^/res/-) {
12072: ($udom,$uname) =
1.807 albertel 12073: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 12074: $file = $uri;
12075: }
12076:
12077: if (!$udom || !$uname || !$file) {
12078: # unable to handle the uri
12079: return ();
12080: }
1.956 raeburn 12081: my $getpropath;
12082: if ($file =~ /^userfiles\//) {
12083: $getpropath = 1;
12084: }
1.1136 raeburn 12085: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12086: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12087: return ();
12088: } else {
12089: if (ref($listref) eq 'ARRAY') {
12090: my @stats = split('&',$listref->[0]);
12091: shift(@stats); #filename is first
12092: return @stats;
12093: }
1.712 albertel 12094: }
12095: return ();
12096: }
12097:
1.1313 raeburn 12098: # --------------------------------------------------------- recursedirs
12099: # Recursive function to traverse either a specific user's Authoring Space
12100: # or corresponding Published Resource Space, and populate the hash ref:
12101: # $dirhashref with URLs of all directories, and if $filehashref hash
12102: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
1.1503 raeburn 12103: # or .rights files in resource space, and .meta, .save, .log, .bak and
12104: # .rights files in Authoring Space.
1.1313 raeburn 12105: #
12106: # Inputs:
12107: #
12108: # $is_home - true if current server is home server for user's space
1.1503 raeburn 12109: # $recurse - if true will also traverse subdirectories recursively
12110: # $include - reference to hash containing allowed file extensions. If provided,
12111: # files which do not have a matching extension will be ignored.
12112: # $exclude - reference to hash containing excluded file extensions. If provided,
12113: # files which have a matching extension will be ignored.
12114: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
12115: # directory with first file found (with acceptable extension).
1.1505 raeburn 12116: # $addtopdir - if true, set $dirhashref->{'/'} = 1
1.1313 raeburn 12117: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12118: # $relpath - Current path (relative to top level).
12119: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12120: # $filehashref - reference to hash to populate with URLs of files (Optional)
12121: #
12122: # Returns: nothing
12123: #
12124: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12125: #
12126: # Currently used by interface/londocs.pm to create linked select boxes for
12127: # directory and filename to import a Course "Author" resource into a course, and
12128: # also to create linked select boxes for Authoring Space and Directory to choose
12129: # save location for creation of a new "standard" problem from the Course Editor.
12130: #
12131:
12132: sub recursedirs {
1.1505 raeburn 12133: my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
1.1313 raeburn 12134: return unless (ref($dirhashref) eq 'HASH');
1.1503 raeburn 12135: my $docroot = $perlvar{'lonDocRoot'};
1.1313 raeburn 12136: my $currpath = $docroot.$toppath;
1.1503 raeburn 12137: if ($relpath ne '') {
1.1313 raeburn 12138: $currpath .= "/$relpath";
12139: }
1.1503 raeburn 12140: my ($savefile,$checkinc,$checkexc);
1.1313 raeburn 12141: if (ref($filehashref)) {
12142: $savefile = 1;
12143: }
1.1503 raeburn 12144: if (ref($include) eq 'HASH') {
12145: $checkinc = 1;
12146: }
12147: if (ref($exclude) eq 'HASH') {
12148: $checkexc = 1;
12149: }
1.1313 raeburn 12150: if ($is_home) {
1.1505 raeburn 12151: if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
1.1503 raeburn 12152: my $filecount = 0;
1.1313 raeburn 12153: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12154: next if ($item eq '');
12155: if (-d "$currpath/$item") {
12156: my $newpath;
1.1503 raeburn 12157: if ($relpath ne '') {
1.1313 raeburn 12158: $newpath = "$relpath/$item";
12159: } else {
12160: $newpath = $item;
12161: }
12162: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
1.1503 raeburn 12163: if ($recurse) {
1.1505 raeburn 12164: &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
1.1503 raeburn 12165: }
12166: } elsif (($savefile) || ($relpath eq '')) {
12167: next if ($nonemptydir && $filecount);
12168: if ($checkinc || $checkexc) {
12169: my ($extension) = ($item =~ /\.(\w+)$/);
12170: if ($checkinc) {
12171: next unless ($extension && $include->{$extension});
12172: }
12173: if ($checkexc) {
12174: next if ($extension && $exclude->{$extension});
12175: }
12176: }
1.1505 raeburn 12177: if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
1.1503 raeburn 12178: $dirhashref->{'/'} = 1;
12179: }
12180: if ($savefile) {
12181: if ($relpath eq '') {
12182: $filehashref->{'/'}{$item} = 1;
12183: } else {
1.1313 raeburn 12184: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12185: }
12186: }
1.1503 raeburn 12187: $filecount ++;
1.1313 raeburn 12188: }
12189: }
12190: closedir($dirh);
12191: }
12192: } else {
12193: my ($dirlistref,$listerror) =
12194: &dirlist($toppath.$relpath);
12195: my @dir_lines;
12196: my $dirptr=16384;
12197: if (ref($dirlistref) eq 'ARRAY') {
1.1503 raeburn 12198: my $filecount = 0;
1.1313 raeburn 12199: foreach my $dir_line (sort
12200: {
12201: my ($afile)=split('&',$a,2);
12202: my ($bfile)=split('&',$b,2);
12203: return (lc($afile) cmp lc($bfile));
12204: } (@{$dirlistref})) {
12205: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12206: split(/\&/,$dir_line,16);
12207: $item =~ s/\s+$//;
12208: next if (($item =~ /^\.\.?$/) || ($obs));
12209: if ($dirptr&$testdir) {
12210: my $newpath;
12211: if ($relpath) {
12212: $newpath = "$relpath/$item";
12213: } else {
12214: $newpath = $item;
12215: }
12216: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
1.1503 raeburn 12217: if ($recurse) {
1.1505 raeburn 12218: &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
1.1503 raeburn 12219: }
12220: } elsif (($savefile) || ($relpath eq '')) {
12221: next if ($nonemptydir && $filecount);
12222: if ($checkinc || $checkexc) {
12223: my $extension;
12224: if ($checkinc) {
12225: next unless ($extension && $include->{$extension});
12226: }
12227: if ($checkexc) {
12228: next if ($extension && $exclude->{$extension});
12229: }
12230: }
12231: if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12232: $dirhashref->{'/'} = 1;
12233: }
12234: if ($savefile) {
12235: if ($relpath eq '') {
12236: $filehashref->{'/'}{$item} = 1;
12237: } else {
12238: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
1.1313 raeburn 12239: }
12240: }
1.1503 raeburn 12241: $filecount ++;
1.1313 raeburn 12242: }
12243: }
12244: }
12245: }
1.1505 raeburn 12246: if ($addtopdir) {
12247: if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12248: $dirhashref->{'/'} = 1;
12249: }
12250: }
1.1313 raeburn 12251: return;
12252: }
12253:
1.1503 raeburn 12254: sub priv_exclude {
12255: return {
12256: meta => 1,
12257: save => 1,
12258: log => 1,
12259: bak => 1,
12260: rights => 1,
12261: DS_Store => 1,
12262: };
12263: }
12264:
1.26 www 12265: # -------------------------------------------------------- Value of a Condition
12266:
1.713 albertel 12267: # gets the value of a specific preevaluated condition
12268: # stored in the string $env{user.state.<cid>}
12269: # or looks up a condition reference in the bighash and if if hasn't
12270: # already been evaluated recurses into docondval to get the value of
12271: # the condition, then memoizing it to
12272: # $env{user.state.<cid>.<condition>}
1.40 www 12273: sub directcondval {
12274: my $number=shift;
1.620 albertel 12275: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 12276: &Apache::lonuserstate::evalstate();
12277: }
1.713 albertel 12278: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12279: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12280: } elsif ($number =~ /^_/) {
12281: my $sub_condition;
12282: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12283: &GDBM_READER(),0640)) {
12284: $sub_condition=$bighash{'conditions'.$number};
12285: untie(%bighash);
12286: }
12287: my $value = &docondval($sub_condition);
1.949 raeburn 12288: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 12289: return $value;
12290: }
1.620 albertel 12291: if ($env{'user.state.'.$env{'request.course.id'}}) {
12292: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 12293: } else {
12294: return 2;
12295: }
12296: }
12297:
1.713 albertel 12298: # get the collection of conditions for this resource
1.26 www 12299: sub condval {
12300: my $condidx=shift;
1.54 www 12301: my $allpathcond='';
1.713 albertel 12302: foreach my $cond (split(/\|/,$condidx)) {
12303: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12304: $allpathcond.=
12305: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12306: }
1.191 harris41 12307: }
1.54 www 12308: $allpathcond=~s/\|$//;
1.713 albertel 12309: return &docondval($allpathcond);
12310: }
12311:
12312: #evaluates an expression of conditions
12313: sub docondval {
12314: my ($allpathcond) = @_;
12315: my $result=0;
12316: if ($env{'request.course.id'}
12317: && defined($allpathcond)) {
12318: my $operand='|';
12319: my @stack;
12320: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12321: if ($chunk eq '(') {
12322: push @stack,($operand,$result);
12323: } elsif ($chunk eq ')') {
12324: my $before=pop @stack;
12325: if (pop @stack eq '&') {
12326: $result=$result>$before?$before:$result;
12327: } else {
12328: $result=$result>$before?$result:$before;
12329: }
12330: } elsif (($chunk eq '&') || ($chunk eq '|')) {
12331: $operand=$chunk;
12332: } else {
12333: my $new=directcondval($chunk);
12334: if ($operand eq '&') {
12335: $result=$result>$new?$new:$result;
12336: } else {
12337: $result=$result>$new?$result:$new;
12338: }
12339: }
12340: }
1.26 www 12341: }
12342: return $result;
1.421 albertel 12343: }
12344:
12345: # ---------------------------------------------------- Devalidate courseresdata
12346:
12347: sub devalidatecourseresdata {
12348: my ($coursenum,$coursedomain)=@_;
12349: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12350: &devalidate_cache_new('courseres',$hashid);
1.28 www 12351: }
12352:
1.763 www 12353:
1.200 www 12354: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 12355: #
12356: # Parameters:
12357: # $coursenum - Number of the course.
12358: # $coursedomain - Domain at which the course was created.
12359: # Returns:
12360: # A hash of the course parameters along (I think) with timestamps
12361: # and version info.
1.877 foxr 12362:
1.624 albertel 12363: sub get_courseresdata {
12364: my ($coursenum,$coursedomain)=@_;
1.200 www 12365: my $coursehom=&homeserver($coursenum,$coursedomain);
12366: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12367: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 12368: my %dumpreply;
1.417 albertel 12369: unless (defined($cached)) {
1.624 albertel 12370: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 12371: $result=\%dumpreply;
1.251 albertel 12372: my ($tmp) = keys(%dumpreply);
12373: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 12374: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 12375: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12376: return $tmp;
1.416 albertel 12377: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 12378: $result=undef;
1.599 albertel 12379: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 12380: }
12381: }
1.624 albertel 12382: return $result;
12383: }
12384:
1.633 albertel 12385: sub devalidateuserresdata {
12386: my ($uname,$udom)=@_;
12387: my $hashid="$udom:$uname";
12388: &devalidate_cache_new('userres',$hashid);
12389: }
12390:
1.624 albertel 12391: sub get_userresdata {
12392: my ($uname,$udom)=@_;
12393: #most student don\'t have any data set, check if there is some data
12394: if (&EXT_cache_status($udom,$uname)) { return undef; }
12395:
12396: my $hashid="$udom:$uname";
12397: my ($result,$cached)=&is_cached_new('userres',$hashid);
12398: if (!defined($cached)) {
12399: my %resourcedata=&dump('resourcedata',$udom,$uname);
12400: $result=\%resourcedata;
12401: &do_cache_new('userres',$hashid,$result,600);
12402: }
12403: my ($tmp)=keys(%$result);
12404: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12405: return $result;
12406: }
12407: #error 2 occurs when the .db doesn't exist
12408: if ($tmp!~/error: 2 /) {
1.1294 raeburn 12409: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12410: &logthis("<font color=\"blue\">WARNING:".
12411: " Trying to get resource data for ".
12412: $uname." at ".$udom.": ".
12413: $tmp."</font>");
12414: }
1.624 albertel 12415: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 12416: #&EXT_cache_set($udom,$uname);
12417: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 12418: undef($tmp); # not really an error so don't send it back
1.624 albertel 12419: }
12420: return $tmp;
12421: }
1.879 foxr 12422: #----------------------------------------------- resdata - return resource data
12423: # Purpose:
12424: # Return resource data for either users or for a course.
12425: # Parameters:
12426: # $name - Course/user name.
12427: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 12428: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 12429: # $mapp - decluttered URL of enclosing map
12430: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
12431: # $recurseup - Ref to array of map URLs, starting with map containing
12432: # $mapp up through hierarchy of nested maps to top level map.
12433: # $courseid - CourseID (first part of param identifier).
12434: # $modifier - Middle part of param identifier.
12435: # $what - Last part of param identifier.
1.879 foxr 12436: # @which - Array of names of resources desired.
12437: # Returns:
12438: # The value of the first reasource in @which that is found in the
12439: # resource hash.
12440: # Exceptional Conditions:
12441: # If the $type passed in is not valid (not the string 'course' or
12442: # 'user', an undefined reference is returned.
12443: # If none of the resources are found, an undef is returned
1.624 albertel 12444: sub resdata {
1.1301 raeburn 12445: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12446: $modifier,$what,@which)=@_;
1.624 albertel 12447: my $result;
12448: if ($type eq 'course') {
12449: $result=&get_courseresdata($name,$domain);
12450: } elsif ($type eq 'user') {
12451: $result=&get_userresdata($name,$domain);
12452: }
12453: if (!ref($result)) { return $result; }
1.251 albertel 12454: foreach my $item (@which) {
1.1301 raeburn 12455: if ($item->[1] eq 'course') {
12456: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12457: unless ($$recursed) {
1.1302 raeburn 12458: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 12459: $$recursed = 1;
12460: }
12461: foreach my $item (@${recurseup}) {
12462: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12463: last if (defined($result->{$norecursechk}));
12464: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12465: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12466: }
12467: }
12468: }
12469: if (defined($result->{$item->[0]})) {
1.927 albertel 12470: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 12471: }
1.250 albertel 12472: }
1.291 albertel 12473: return undef;
1.200 www 12474: }
12475:
1.1360 raeburn 12476: sub get_domain_lti {
12477: my ($cdom,$context) = @_;
1.1483 raeburn 12478: my ($name,$cachename,%lti);
1.1360 raeburn 12479: if ($context eq 'consumer') {
12480: $name = 'ltitools';
12481: } elsif ($context eq 'provider') {
12482: $name = 'lti';
1.1483 raeburn 12483: } elsif ($context eq 'linkprot') {
12484: $name = 'ltisec';
1.1360 raeburn 12485: } else {
12486: return %lti;
12487: }
1.1483 raeburn 12488:
12489: if ($context eq 'linkprot') {
12490: $cachename = $context;
12491: } else {
12492: $cachename = $name;
12493: }
12494:
12495: my ($result,$cached)=&is_cached_new($cachename,$cdom);
1.1298 raeburn 12496: if (defined($cached)) {
12497: if (ref($result) eq 'HASH') {
1.1360 raeburn 12498: %lti = %{$result};
1.1298 raeburn 12499: }
12500: } else {
1.1360 raeburn 12501: my %domconfig = &get_dom('configuration',[$name],$cdom);
12502: if (ref($domconfig{$name}) eq 'HASH') {
1.1483 raeburn 12503: if ($context eq 'linkprot') {
12504: if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12505: %lti = %{$domconfig{$name}{'linkprot'}};
12506: }
12507: } else {
12508: %lti = %{$domconfig{$name}};
12509: }
12510: if (($context eq 'consumer') && (keys(%lti))) {
12511: my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
12512: if (ref($encdomconfig{$name}) eq 'HASH') {
12513: foreach my $id (keys(%lti)) {
12514: if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12515: foreach my $item ('key','secret') {
12516: $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12517: }
1.1344 raeburn 12518: }
12519: }
12520: }
12521: }
1.1298 raeburn 12522: }
12523: my $cachetime = 24*60*60;
1.1483 raeburn 12524: &do_cache_new($cachename,$cdom,\%lti,$cachetime);
1.1298 raeburn 12525: }
1.1360 raeburn 12526: return %lti;
1.1298 raeburn 12527: }
12528:
1.1463 raeburn 12529: sub get_course_lti {
12530: my ($cnum,$cdom) = @_;
12531: my $hashid=$cdom.'_'.$cnum;
12532: my %courselti;
12533: my ($result,$cached)=&is_cached_new('courselti',$hashid);
12534: if (defined($cached)) {
12535: if (ref($result) eq 'HASH') {
12536: %courselti = %{$result};
12537: }
12538: } else {
12539: %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
12540: my $cachetime = 24*60*60;
12541: &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
12542: }
12543: return %courselti;
12544: }
12545:
1.1479 raeburn 12546: sub courselti_itemid {
12547: my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12548: my ($chome,$itemid);
12549: $chome = &homeserver($cnum,$cdom);
12550: return if ($chome eq 'no_host');
12551: if (ref($params) eq 'HASH') {
12552: my $rep;
12553: if (grep { $_ eq $chome } current_machine_ids()) {
12554: $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12555: } else {
12556: my $escurl = &escape($url);
12557: my $escmethod = &escape($method);
12558: my $items = &freeze_escape($params);
12559: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12560: }
12561: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12562: ($rep eq 'unknown_cmd')) {
12563: $itemid = $rep;
12564: }
12565: }
12566: return $itemid;
12567: }
12568:
12569: sub domainlti_itemid {
12570: my ($cdom,$url,$method,$params,$context) = @_;
12571: my ($primary_id,$itemid);
12572: $primary_id = &domain($cdom,'primary');
12573: return if ($primary_id eq '');
12574: if (ref($params) eq 'HASH') {
12575: my $rep;
12576: if (grep { $_ eq $primary_id } current_machine_ids()) {
12577: $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12578: } else {
12579: my $cnum = '';
12580: my $escurl = &escape($url);
12581: my $escmethod = &escape($method);
12582: my $items = &freeze_escape($params);
12583: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12584: }
12585: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12586: ($rep eq 'unknown_cmd')) {
12587: $itemid = $rep;
12588: }
12589: }
12590: return $itemid;
12591: }
12592:
1.1496 raeburn 12593: sub count_supptools {
12594: my ($cnum,$cdom,$ignorecache,$reload)=@_;
12595: my $hashid=$cnum.':'.$cdom;
12596: my ($numexttools,$cached);
12597: unless ($ignorecache) {
12598: ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
12599: }
12600: unless (defined($cached)) {
12601: my $chome=&homeserver($cnum,$cdom);
12602: $numexttools = 0;
12603: unless ($chome eq 'no_host') {
1.1500 raeburn 12604: my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
1.1496 raeburn 12605: if (ref($supplemental) eq 'HASH') {
12606: if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12607: foreach my $key (keys(%{$supplemental->{'ids'}})) {
12608: if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
12609: $numexttools ++;
12610: }
12611: }
12612: }
12613: }
12614: }
12615: &do_cache_new('supptools',$hashid,$numexttools,600);
12616: }
12617: return $numexttools;
12618: }
12619:
12620: sub has_unhidden_suppfiles {
1.1498 raeburn 12621: my ($cnum,$cdom,$ignorecache,$possdel)=@_;
1.1236 raeburn 12622: my $hashid=$cnum.':'.$cdom;
1.1496 raeburn 12623: my ($showsupp,$cached);
1.1236 raeburn 12624: unless ($ignorecache) {
1.1496 raeburn 12625: ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
1.1236 raeburn 12626: }
12627: unless (defined($cached)) {
12628: my $chome=&homeserver($cnum,$cdom);
12629: unless ($chome eq 'no_host') {
1.1500 raeburn 12630: my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
1.1496 raeburn 12631: if (ref($supplemental) eq 'HASH') {
12632: if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12633: foreach my $key (keys(%{$supplemental->{'ids'}})) {
12634: next if ($key =~ /\.sequence$/);
12635: if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
12636: foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
12637: unless ($supplemental->{'hidden'}->{$id}) {
12638: $showsupp = 1;
12639: last;
12640: }
12641: }
12642: }
12643: last if ($showsupp);
12644: }
12645: }
12646: }
1.1236 raeburn 12647: }
1.1496 raeburn 12648: &do_cache_new('showsupp',$hashid,$showsupp,600);
1.1236 raeburn 12649: }
1.1496 raeburn 12650: return $showsupp;
12651: }
12652:
1.379 matthew 12653: #
12654: # EXT resource caching routines
12655: #
12656:
1.1302 raeburn 12657: {
12658: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12659: #
12660: # The course for which we cache
12661: my $cachedmapkey='';
12662: # The cached recursive maps for this course
12663: my %cachedmaps=();
12664: # When this was last done
12665: my $cachedmaptime='';
12666:
1.379 matthew 12667: sub clear_EXT_cache_status {
1.383 albertel 12668: &delenv('cache.EXT.');
1.379 matthew 12669: }
12670:
12671: sub EXT_cache_status {
12672: my ($target_domain,$target_user) = @_;
1.383 albertel 12673: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 12674: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 12675: # We know already the user has no data
12676: return 1;
12677: } else {
12678: return 0;
12679: }
12680: }
12681:
12682: sub EXT_cache_set {
12683: my ($target_domain,$target_user) = @_;
1.383 albertel 12684: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 12685: #&appenv({$cachename => time});
1.379 matthew 12686: }
12687:
1.28 www 12688: # --------------------------------------------------------- Value of a Variable
1.58 www 12689: sub EXT {
1.715 albertel 12690:
1.1461 raeburn 12691: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
1.68 www 12692: unless ($varname) { return ''; }
1.218 albertel 12693: #get real user name/domain, courseid and symb
12694: my $courseid;
1.359 albertel 12695: my $publicuser;
1.427 www 12696: if ($symbparm) {
12697: $symbparm=&get_symb_from_alias($symbparm);
12698: }
1.218 albertel 12699: if (!($uname && $udom)) {
1.790 albertel 12700: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 12701: if (!$symbparm) { $symbparm=$cursymb; }
12702: } else {
1.620 albertel 12703: $courseid=$env{'request.course.id'};
1.218 albertel 12704: }
1.48 www 12705: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12706: my $rest;
1.320 albertel 12707: if (defined($therest[0])) {
1.48 www 12708: $rest=join('.',@therest);
12709: } else {
12710: $rest='';
12711: }
1.320 albertel 12712:
1.57 www 12713: my $qualifierrest=$qualifier;
12714: if ($rest) { $qualifierrest.='.'.$rest; }
12715: my $spacequalifierrest=$space;
12716: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 12717: if ($realm eq 'user') {
1.48 www 12718: # --------------------------------------------------------------- user.resource
12719: if ($space eq 'resource') {
1.651 albertel 12720: if ( (defined($Apache::lonhomework::parsing_a_problem)
12721: || defined($Apache::lonhomework::parsing_a_task))
12722: &&
1.1469 raeburn 12723: ($symbparm eq &symbread()) ) {
1.744 albertel 12724: # if we are in the middle of processing the resource the
12725: # get the value we are planning on committing
12726: if (defined($Apache::lonhomework::results{$qualifierrest})) {
12727: return $Apache::lonhomework::results{$qualifierrest};
12728: } else {
12729: return $Apache::lonhomework::history{$qualifierrest};
12730: }
1.335 albertel 12731: } else {
1.359 albertel 12732: my %restored;
1.620 albertel 12733: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 12734: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12735: } else {
12736: %restored=&restore($symbparm,$courseid,$udom,$uname);
12737: }
1.335 albertel 12738: return $restored{$qualifierrest};
12739: }
1.48 www 12740: # ----------------------------------------------------------------- user.access
12741: } elsif ($space eq 'access') {
1.218 albertel 12742: # FIXME - not supporting calls for a specific user
1.48 www 12743: return &allowed($qualifier,$rest);
12744: # ------------------------------------------ user.preferences, user.environment
12745: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 12746: if (($uname eq $env{'user.name'}) &&
12747: ($udom eq $env{'user.domain'})) {
12748: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 12749: } else {
1.359 albertel 12750: my %returnhash;
12751: if (!$publicuser) {
12752: %returnhash=&userenvironment($udom,$uname,
12753: $qualifierrest);
12754: }
1.218 albertel 12755: return $returnhash{$qualifierrest};
12756: }
1.48 www 12757: # ----------------------------------------------------------------- user.course
12758: } elsif ($space eq 'course') {
1.218 albertel 12759: # FIXME - not supporting calls for a specific user
1.620 albertel 12760: return $env{join('.',('request.course',$qualifier))};
1.48 www 12761: # ------------------------------------------------------------------- user.role
12762: } elsif ($space eq 'role') {
1.218 albertel 12763: # FIXME - not supporting calls for a specific user
1.620 albertel 12764: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 12765: if ($qualifier eq 'value') {
12766: return $role;
12767: } elsif ($qualifier eq 'extent') {
12768: return $where;
12769: }
12770: # ----------------------------------------------------------------- user.domain
12771: } elsif ($space eq 'domain') {
1.218 albertel 12772: return $udom;
1.48 www 12773: # ------------------------------------------------------------------- user.name
12774: } elsif ($space eq 'name') {
1.218 albertel 12775: return $uname;
1.48 www 12776: # ---------------------------------------------------- Any other user namespace
1.29 www 12777: } else {
1.359 albertel 12778: my %reply;
12779: if (!$publicuser) {
12780: %reply=&get($space,[$qualifierrest],$udom,$uname);
12781: }
12782: return $reply{$qualifierrest};
1.48 www 12783: }
1.236 www 12784: } elsif ($realm eq 'query') {
12785: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 12786: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12787: [$spacequalifierrest]);
1.620 albertel 12788: return $env{'form.'.$spacequalifierrest};
1.236 www 12789: } elsif ($realm eq 'request') {
1.48 www 12790: # ------------------------------------------------------------- request.browser
12791: if ($space eq 'browser') {
1.1145 bisitz 12792: return $env{'browser.'.$qualifier};
1.57 www 12793: # ------------------------------------------------------------ request.filename
12794: } else {
1.620 albertel 12795: return $env{'request.'.$spacequalifierrest};
1.29 www 12796: }
1.28 www 12797: } elsif ($realm eq 'course') {
1.48 www 12798: # ---------------------------------------------------------- course.description
1.620 albertel 12799: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 12800: } elsif ($realm eq 'resource') {
1.165 www 12801:
1.620 albertel 12802: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 12803: if (!$symbparm) { $symbparm=&symbread(); }
12804: }
1.693 albertel 12805:
1.1232 raeburn 12806: if ($qualifier eq '') {
12807: if ($space eq 'title') {
12808: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12809: return &gettitle($symbparm);
12810: }
1.693 albertel 12811:
1.1232 raeburn 12812: if ($space eq 'map') {
12813: my ($map) = &decode_symb($symbparm);
12814: return &symbread($map);
12815: }
12816: if ($space eq 'maptitle') {
12817: my ($map) = &decode_symb($symbparm);
12818: return &gettitle($map);
12819: }
12820: if ($space eq 'filename') {
12821: if ($symbparm) {
12822: return &clutter((&decode_symb($symbparm))[2]);
12823: }
12824: return &hreflocation('',$env{'request.filename'});
1.905 albertel 12825: }
1.1232 raeburn 12826:
1.1233 raeburn 12827: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12828: if ($space eq 'visibleparts') {
12829: my $navmap = Apache::lonnavmaps::navmap->new();
12830: my $item;
12831: if (ref($navmap)) {
12832: my $res = $navmap->getBySymb($symbparm);
12833: my $parts = $res->parts();
12834: if (ref($parts) eq 'ARRAY') {
12835: $item = join(',',@{$parts});
12836: }
12837: undef($navmap);
1.1232 raeburn 12838: }
1.1233 raeburn 12839: return $item;
1.1232 raeburn 12840: }
12841: }
12842: }
1.693 albertel 12843:
1.1301 raeburn 12844: my ($section, $group, @groups, @recurseup, $recursed);
1.1461 raeburn 12845: if (ref($recurseupref) eq 'ARRAY') {
12846: @recurseup = @{$recurseupref};
12847: $recursed = 1;
12848: }
1.1301 raeburn 12849: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 12850: if (($courseid eq '') && ($cid)) {
12851: $courseid = $cid;
12852: }
12853: if (($symbparm && $courseid) &&
12854: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 12855:
1.218 albertel 12856: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 12857:
1.60 www 12858: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 12859: my $symbp=$symbparm;
1.1301 raeburn 12860: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 12861: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 12862: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 12863: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 12864: if (($env{'user.name'} eq $uname) &&
12865: ($env{'user.domain'} eq $udom)) {
12866: $section=$env{'request.course.sec'};
1.733 raeburn 12867: @groups = split(/:/,$env{'request.course.groups'});
12868: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 12869: } else {
1.539 albertel 12870: if (! defined($usection)) {
1.551 albertel 12871: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 12872: } else {
12873: $section = $usection;
12874: }
1.733 raeburn 12875: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 12876: }
12877:
12878: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12879: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 12880: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 12881: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12882:
1.593 albertel 12883: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 12884: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 12885: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 12886: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 12887:
1.60 www 12888: # ----------------------------------------------------------- first, check user
1.624 albertel 12889:
1.1301 raeburn 12890: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12891: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 12892: ([$courselevelr,'resource'],
12893: [$courselevelm,'map' ],
1.1301 raeburn 12894: [$courseleveli,'map' ],
1.927 albertel 12895: [$courselevel, 'course' ]));
1.931 albertel 12896: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 12897:
1.594 albertel 12898: # ------------------------------------------------ second, check some of course
1.684 raeburn 12899: my $coursereply;
1.691 raeburn 12900: if (@groups > 0) {
12901: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 12902: $recurseparm,$mapparm,$spacequalifierrest,
12903: $mapp,\$recursed,\@recurseup);
12904: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 12905: }
1.96 www 12906:
1.684 raeburn 12907: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 12908: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12909: 'course',$mapp,\$recursed,\@recurseup,
12910: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 12911: ([$seclevelr, 'resource'],
12912: [$seclevelm, 'map' ],
1.1301 raeburn 12913: [$secleveli, 'map' ],
1.927 albertel 12914: [$seclevel, 'course' ],
12915: [$courselevelr,'resource']));
12916: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 12917:
1.60 www 12918: # ------------------------------------------------------ third, check map parms
1.218 albertel 12919: my %parmhash=();
12920: my $thisparm='';
12921: if (tie(%parmhash,'GDBM_File',
1.620 albertel 12922: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 12923: &GDBM_READER(),0640)) {
1.218 albertel 12924: $thisparm=$parmhash{$symbparm};
12925: untie(%parmhash);
12926: }
1.927 albertel 12927: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 12928: }
1.594 albertel 12929: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 12930:
12931: my $what = $spacequalifierrest;
12932: $what=~s/\./\_/;
1.282 albertel 12933: my $filename;
12934: if (!$symbparm) { $symbparm=&symbread(); }
12935: if ($symbparm) {
1.409 www 12936: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 12937: } else {
1.620 albertel 12938: $filename=$env{'request.filename'};
1.282 albertel 12939: }
1.1362 raeburn 12940: my $toolsymb;
12941: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12942: $toolsymb = $symbparm;
12943: }
12944: my $metadata=&metadata($filename,$what,$toolsymb);
1.927 albertel 12945: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362 raeburn 12946: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927 albertel 12947: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 12948:
1.1301 raeburn 12949: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 12950: if ($symbparm && defined($courseid) &&
1.620 albertel 12951: $courseid eq $env{'request.course.id'}) {
1.624 albertel 12952: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12953: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12954: 'course',$mapp,\$recursed,\@recurseup,
12955: $courseid,'.',$spacequalifierrest,
1.927 albertel 12956: ([$courselevelm,'map' ],
1.1301 raeburn 12957: [$courseleveli,'map' ],
1.927 albertel 12958: [$courselevel, 'course']));
12959: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 12960: }
1.145 www 12961: # ------------------------------------------------------------------ Cascade up
1.218 albertel 12962: unless ($space eq '0') {
1.336 albertel 12963: my @parts=split(/_/,$space);
12964: my $id=pop(@parts);
12965: my $part=join('_',@parts);
12966: if ($part eq '') { $part='0'; }
1.927 albertel 12967: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 12968: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 12969: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 12970: }
1.395 albertel 12971: if ($recurse) { return undef; }
1.1362 raeburn 12972: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927 albertel 12973: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 12974: # ---------------------------------------------------- Any other user namespace
12975: } elsif ($realm eq 'environment') {
12976: # ----------------------------------------------------------------- environment
1.620 albertel 12977: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12978: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 12979: } else {
1.770 albertel 12980: if ($uname eq 'anonymous' && $udom eq '') {
12981: return '';
12982: }
1.219 albertel 12983: my %returnhash=&userenvironment($udom,$uname,
12984: $spacequalifierrest);
12985: return $returnhash{$spacequalifierrest};
12986: }
1.28 www 12987: } elsif ($realm eq 'system') {
1.48 www 12988: # ----------------------------------------------------------------- system.time
12989: if ($space eq 'time') {
12990: return time;
12991: }
1.696 albertel 12992: } elsif ($realm eq 'server') {
12993: # ----------------------------------------------------------------- system.time
12994: if ($space eq 'name') {
12995: return $ENV{'SERVER_NAME'};
12996: }
1.1415 raeburn 12997: } elsif ($realm eq 'client') {
12998: if ($space eq 'remote_addr') {
1.1441 raeburn 12999: return &get_requestor_ip();
1.1415 raeburn 13000: }
1.28 www 13001: }
1.48 www 13002: return '';
1.61 www 13003: }
13004:
1.927 albertel 13005: sub get_reply {
13006: my ($reply_value) = @_;
1.940 raeburn 13007: if (ref($reply_value) eq 'ARRAY') {
13008: if (wantarray) {
13009: return @$reply_value;
13010: }
13011: return $reply_value->[0];
13012: } else {
13013: return $reply_value;
1.927 albertel 13014: }
13015: }
13016:
1.691 raeburn 13017: sub check_group_parms {
1.1301 raeburn 13018: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
13019: $recursed,$recurseupref) = @_;
13020: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
13021: [$what,'course']);
13022: my $coursereply;
1.691 raeburn 13023: foreach my $group (@{$groups}) {
1.1301 raeburn 13024: my @groupitems = ();
1.691 raeburn 13025: foreach my $level (@levels) {
1.927 albertel 13026: my $item = $courseid.'.['.$group.'].'.$level->[0];
13027: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 13028: }
1.1301 raeburn 13029: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
13030: $env{'course.'.$courseid.'.domain'},
13031: 'course',$mapp,$recursed,$recurseupref,
13032: $courseid,'.['.$group.'].',$what,
13033: @groupitems);
13034: last if (defined($coursereply));
1.691 raeburn 13035: }
13036: return $coursereply;
13037: }
13038:
1.1301 raeburn 13039: sub get_map_hierarchy {
1.1302 raeburn 13040: my ($mapname,$courseid) = @_;
13041: my @recurseup = ();
1.1301 raeburn 13042: if ($mapname) {
1.1302 raeburn 13043: if (($cachedmapkey eq $courseid) &&
13044: (abs($cachedmaptime-time)<5)) {
13045: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
13046: return @{$cachedmaps{$mapname}};
13047: }
13048: }
1.1301 raeburn 13049: my $navmap = Apache::lonnavmaps::navmap->new();
13050: if (ref($navmap)) {
13051: @recurseup = $navmap->recurseup_maps($mapname);
13052: undef($navmap);
1.1302 raeburn 13053: $cachedmaps{$mapname} = \@recurseup;
13054: $cachedmaptime=time;
13055: $cachedmapkey=$courseid;
1.1301 raeburn 13056: }
13057: }
13058: return @recurseup;
13059: }
13060:
1.1302 raeburn 13061: }
13062:
1.691 raeburn 13063: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 13064: my ($courseid,@groups) = @_;
13065: @groups = sort(@groups);
1.691 raeburn 13066: return @groups;
13067: }
13068:
1.395 albertel 13069: sub packages_tab_default {
1.1362 raeburn 13070: my ($uri,$varname,$toolsymb)=@_;
1.395 albertel 13071: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 13072:
13073: my (@extension,@specifics,$do_default);
1.1362 raeburn 13074: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395 albertel 13075: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 13076: if ($pack_type eq 'default') {
13077: $do_default=1;
13078: } elsif ($pack_type eq 'extension') {
13079: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 13080: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 13081: # only look at packages defaults for packages that this id is
1.738 albertel 13082: push(@specifics,[$package,$pack_type,$pack_part]);
13083: }
13084: }
13085: # first look for a package that matches the requested part id
13086: foreach my $package (@specifics) {
13087: my (undef,$pack_type,$pack_part)=@{$package};
13088: next if ($pack_part ne $part);
13089: if (defined($packagetab{"$pack_type&$name&default"})) {
13090: return $packagetab{"$pack_type&$name&default"};
13091: }
13092: }
13093: # look for any possible matching non extension_ package
13094: foreach my $package (@specifics) {
13095: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 13096: if (defined($packagetab{"$pack_type&$name&default"})) {
13097: return $packagetab{"$pack_type&$name&default"};
13098: }
1.585 albertel 13099: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 13100: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13101: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 13102: }
13103: }
1.738 albertel 13104: # look for any posible extension_ match
13105: foreach my $package (@extension) {
13106: my ($package,$pack_type)=@{$package};
13107: if (defined($packagetab{"$pack_type&$name&default"})) {
13108: return $packagetab{"$pack_type&$name&default"};
13109: }
13110: if (defined($packagetab{$package."&$name&default"})) {
13111: return $packagetab{$package."&$name&default"};
13112: }
13113: }
13114: # look for a global default setting
13115: if ($do_default && defined($packagetab{"default&$name&default"})) {
13116: return $packagetab{"default&$name&default"};
13117: }
1.395 albertel 13118: return undef;
13119: }
13120:
1.334 albertel 13121: sub add_prefix_and_part {
13122: my ($prefix,$part)=@_;
13123: my $keyroot;
13124: if (defined($prefix) && $prefix !~ /^__/) {
13125: # prefix that has a part already
13126: $keyroot=$prefix;
13127: } elsif (defined($prefix)) {
13128: # prefix that is missing a part
13129: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13130: } else {
13131: # no prefix at all
13132: if (defined($part)) { $keyroot='_'.$part; }
13133: }
13134: return $keyroot;
13135: }
13136:
1.71 www 13137: # ---------------------------------------------------------------- Get metadata
13138:
1.599 albertel 13139: my %metaentry;
1.1070 www 13140: my %importedpartids;
1.1369 raeburn 13141: my %importedrespids;
1.71 www 13142: sub metadata {
1.1362 raeburn 13143: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71 www 13144: $uri=&declutter($uri);
1.288 albertel 13145: # if it is a non metadata possible uri return quickly
1.529 albertel 13146: if (($uri eq '') ||
13147: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 13148: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 13149: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 13150: return undef;
13151: }
1.1261 raeburn 13152: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 13153: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 13154: return undef;
1.288 albertel 13155: }
1.73 www 13156: my $filename=$uri;
13157: $uri=~s/\.meta$//;
1.172 www 13158: #
13159: # Is the metadata already cached?
1.177 www 13160: # Look at timestamp of caching
1.172 www 13161: # Everything is cached by the main uri, libraries are never directly cached
13162: #
1.428 albertel 13163: if (!defined($liburi)) {
1.599 albertel 13164: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 13165: if (defined($cached)) { return $result->{':'.$what}; }
13166: }
1.1362 raeburn 13167:
13168: #
13169: # If the uri is for an external tool the file from
13170: # which metadata should be retrieved depends on whether
13171: # the tool had been configured to be gradable (set in the Course
13172: # Editor or Resource Editor).
13173: #
13174: # If a valid symb has been included as the third arg in the call
13175: # to &metadata() that can be used to retrieve the value of
13176: # parameter_0_gradable set for the resource, and included in the
13177: # uploaded map containing the tool. The value is retrieved via
13178: # &EXT(), if a valid symb is available. Otherwise the value of
13179: # gradable in the exttool_$marker.db file for the tool instance
1.1364 raeburn 13180: # is retrieved via &get().
13181: #
13182: # When lonuserstate::traceroute() calls lonnet::EXT() for
13183: # hiddenresource and encrypturl (during course initialization)
13184: # the map-level parameter for resource.0.gradable included in the
13185: # uploaded map containing the tool will not yet have been stored
13186: # in the user_course_parms.db file for the user's session, so in
13187: # this case fall back to retrieving gradable status from the
13188: # exttool_$marker.db file.
1.1362 raeburn 13189: #
13190: # In order to avoid an infinite loop, &metadata() will return
13191: # before a call to &EXT(), if the uri is for an external tool
13192: # and the $what for which metadata is being requested is
13193: # parameter_0_gradable or 0_gradable.
13194: #
13195:
13196: if ($uri =~ /ext\.tool$/) {
13197: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13198: return;
13199: } else {
13200: my ($checked,$use_passback);
13201: if ($toolsymb ne '') {
13202: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364 raeburn 13203: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362 raeburn 13204: $checked = 1;
13205: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13206: $use_passback = 1;
13207: }
13208: }
13209: }
13210: unless ($checked) {
13211: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13212: $marker=~s/\D//g;
1.1363 raeburn 13213: if ($marker) {
1.1362 raeburn 13214: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13215: $use_passback = $toolsettings{'gradable'};
13216: }
13217: }
13218: if ($use_passback) {
13219: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13220: } else {
13221: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13222: }
13223: }
13224: }
13225:
1.428 albertel 13226: {
1.1069 www 13227: # Imported parts would go here
1.1369 raeburn 13228: my @origfiletagids=();
1.1069 www 13229: my $importedparts=0;
1.1369 raeburn 13230:
13231: # Imported responseids would go here
13232: my $importedresponses=0;
1.172 www 13233: #
13234: # Is this a recursive call for a library?
13235: #
1.599 albertel 13236: # if (! exists($metacache{$uri})) {
13237: # $metacache{$uri}={};
13238: # }
1.924 albertel 13239: my $cachetime = 60*60;
1.171 www 13240: if ($liburi) {
13241: $liburi=&declutter($liburi);
13242: $filename=$liburi;
1.401 bowersj2 13243: } else {
1.599 albertel 13244: &devalidate_cache_new('meta',$uri);
13245: undef(%metaentry);
1.401 bowersj2 13246: }
1.140 www 13247: my %metathesekeys=();
1.73 www 13248: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 13249: my $metastring;
1.1140 www 13250: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 13251: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 13252: $metastring =
1.929 albertel 13253: &Apache::lonnet::ssi_body($which,
1.924 albertel 13254: ('grade_target' => 'meta'));
13255: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 13256: } elsif (($uri !~ m -^(editupload)/-) &&
13257: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 13258: my $file=&filelocation('',&clutter($filename));
1.599 albertel 13259: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 13260: $metastring=&getfile($file);
1.489 albertel 13261: }
1.208 albertel 13262: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 13263: my $token;
1.140 www 13264: undef %metathesekeys;
1.71 www 13265: while ($token=$parser->get_token) {
1.339 albertel 13266: if ($token->[0] eq 'S') {
13267: if (defined($token->[2]->{'package'})) {
1.172 www 13268: #
13269: # This is a package - get package info
13270: #
1.339 albertel 13271: my $package=$token->[2]->{'package'};
13272: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13273: if (defined($token->[2]->{'id'})) {
13274: $keyroot.='_'.$token->[2]->{'id'};
13275: }
1.599 albertel 13276: if ($metaentry{':packages'}) {
13277: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 13278: } else {
1.599 albertel 13279: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 13280: }
1.736 albertel 13281: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 13282: my $part=$keyroot;
13283: $part=~s/^\_//;
1.736 albertel 13284: if ($pack_entry=~/^\Q$package\E\&/ ||
13285: $pack_entry=~/^\Q$package\E_0\&/) {
13286: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 13287: # ignore package.tab specified default values
13288: # here &package_tab_default() will fetch those
13289: if ($subp eq 'default') { next; }
1.736 albertel 13290: my $value=$packagetab{$pack_entry};
1.432 albertel 13291: my $unikey;
13292: if ($pack =~ /_0$/) {
13293: $unikey='parameter_0_'.$name;
13294: $part=0;
13295: } else {
13296: $unikey='parameter'.$keyroot.'_'.$name;
13297: }
1.339 albertel 13298: if ($subp eq 'display') {
13299: $value.=' [Part: '.$part.']';
13300: }
1.599 albertel 13301: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 13302: $metathesekeys{$unikey}=1;
1.599 albertel 13303: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13304: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 13305: }
1.599 albertel 13306: if (defined($metaentry{':'.$unikey.'.default'})) {
13307: $metaentry{':'.$unikey}=
13308: $metaentry{':'.$unikey.'.default'};
1.356 albertel 13309: }
1.339 albertel 13310: }
13311: }
13312: } else {
1.172 www 13313: #
13314: # This is not a package - some other kind of start tag
1.339 albertel 13315: #
13316: my $entry=$token->[1];
1.1068 www 13317: my $unikey='';
1.175 www 13318:
1.339 albertel 13319: if ($entry eq 'import') {
1.175 www 13320: #
13321: # Importing a library here
1.339 albertel 13322: #
1.1067 www 13323: my $location=$parser->get_text('/import');
13324: my $dir=$filename;
13325: $dir=~s|[^/]*$||;
13326: $location=&filelocation($dir,$location);
1.1369 raeburn 13327:
13328: my $importid=$token->[2]->{'id'};
1.1068 www 13329: my $importmode=$token->[2]->{'importmode'};
1.1369 raeburn 13330: #
13331: # Check metadata for imported file to
13332: # see if it contained response items
13333: #
1.1372 raeburn 13334: my ($origfile,@libfilekeys);
1.1370 raeburn 13335: my %currmetaentry = %metaentry;
1.1372 raeburn 13336: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13337: $depthcount+1));
13338: if (grep(/^responseorder$/,@libfilekeys)) {
13339: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13340: undef,$depthcount+1);
13341: if ($libresponseorder ne '') {
13342: if ($#origfiletagids<0) {
13343: undef(%importedrespids);
13344: undef(%importedpartids);
13345: }
1.1373 raeburn 13346: my @respids = split(/\s*,\s*/,$libresponseorder);
13347: if (@respids) {
13348: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13349: }
13350: if ($importedrespids{$importid} ne '') {
1.1372 raeburn 13351: $importedresponses = 1;
1.1369 raeburn 13352: # We need to get the original file and the imported file to get the response order correct
13353: # Load and inspect original file
1.1372 raeburn 13354: if ($#origfiletagids<0) {
13355: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13356: $origfile=&getfile($origfilelocation);
13357: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13358: }
1.1369 raeburn 13359: }
13360: }
13361: }
1.1370 raeburn 13362: # Do not overwrite contents of %metaentry hash for resource itself with
13363: # hash populated for imported library file
13364: %metaentry = %currmetaentry;
13365: undef(%currmetaentry);
1.1374 raeburn 13366: if ($importmode eq 'part') {
1.1068 www 13367: # Import as part(s)
1.1069 www 13368: $importedparts=1;
13369: # We need to get the original file and the imported file to get the part order correct
13370: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369 raeburn 13371: # Load and inspect original file if we didn't do that already
13372: if ($#origfiletagids<0) {
13373: undef(%importedrespids);
13374: undef(%importedpartids);
13375: if ($origfile eq '') {
13376: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13377: $origfile=&getfile($origfilelocation);
13378: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13379: }
1.1070 www 13380: }
1.1372 raeburn 13381: my @impfilepartids;
13382: # If <partorder> tag is included in metadata for the imported file
13383: # get the parts in the imported file from that.
13384: if (grep(/^partorder$/,@libfilekeys)) {
13385: %currmetaentry = %metaentry;
13386: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13387: $depthcount+1);
13388: %metaentry = %currmetaentry;
13389: undef(%currmetaentry);
13390: if ($libpartorder ne '') {
13391: @impfilepartids=split(/\s*,\s*/,$libpartorder);
13392: }
13393: } else {
13394: # If no <partorder> tag available, load and inspect imported file
13395: my $impfile=&getfile($location);
13396: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13397: }
1.1069 www 13398: if ($#impfilepartids>=0) {
13399: # This problem had parts
1.1070 www 13400: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 13401: } else {
13402: # Importing by turning a single problem into a problem part
13403: # It gets the import-tags ID as part-ID
13404: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 13405: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 13406: }
1.1068 www 13407: } else {
1.1374 raeburn 13408: # Import as problem or as normal import
13409: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13410: unless ($importmode eq 'problem') {
1.1068 www 13411: # Normal import
1.1374 raeburn 13412: if (defined($token->[2]->{'id'})) {
13413: $unikey.='_'.$token->[2]->{'id'};
13414: }
13415: }
13416: # Check metadata for imported file to
13417: # see if it contained parts
13418: if (grep(/^partorder$/,@libfilekeys)) {
13419: %currmetaentry = %metaentry;
13420: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13421: $depthcount+1);
13422: %metaentry = %currmetaentry;
13423: undef(%currmetaentry);
13424: if ($libpartorder ne '') {
13425: $importedparts = 1;
13426: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13427: }
13428: }
1.1067 www 13429: }
1.339 albertel 13430: if ($depthcount<20) {
1.736 albertel 13431: my $metadata =
1.1362 raeburn 13432: &metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736 albertel 13433: $depthcount+1);
13434: foreach my $meta (split(',',$metadata)) {
13435: $metaentry{':'.$meta}=$metaentry{':'.$meta};
13436: $metathesekeys{$meta}=1;
1.339 albertel 13437: }
1.1068 www 13438: }
1.1067 www 13439: } else {
13440: #
13441: # Not importing, some other kind of non-package, non-library start tag
13442: #
13443: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13444: if (defined($token->[2]->{'id'})) {
13445: $unikey.='_'.$token->[2]->{'id'};
13446: }
1.339 albertel 13447: if (defined($token->[2]->{'name'})) {
13448: $unikey.='_'.$token->[2]->{'name'};
13449: }
13450: $metathesekeys{$unikey}=1;
1.736 albertel 13451: foreach my $param (@{$token->[3]}) {
13452: $metaentry{':'.$unikey.'.'.$param} =
13453: $token->[2]->{$param};
1.339 albertel 13454: }
13455: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 13456: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 13457: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13458: # only ws inside the tag, and not in default, so use default
13459: # as value
1.599 albertel 13460: $metaentry{':'.$unikey}=$default;
1.908 albertel 13461: } elsif ( $internaltext =~ /\S/ ) {
13462: # something interesting inside the tag
13463: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 13464: } else {
1.908 albertel 13465: # no interesting values, don't set a default
1.339 albertel 13466: }
1.172 www 13467: # end of not-a-package not-a-library import
1.339 albertel 13468: }
1.172 www 13469: # end of not-a-package start tag
1.339 albertel 13470: }
1.172 www 13471: # the next is the end of "start tag"
1.339 albertel 13472: }
13473: }
1.483 albertel 13474: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 13475: $extension = lc($extension);
13476: if ($extension eq 'htm') { $extension='html'; }
13477:
1.737 albertel 13478: foreach my $key (keys(%packagetab)) {
1.483 albertel 13479: #no specific packages #how's our extension
13480: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 13481: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 13482: \%metathesekeys);
13483: }
1.883 albertel 13484:
13485: if (!exists($metaentry{':packages'})
13486: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 13487: foreach my $key (keys(%packagetab)) {
1.483 albertel 13488: #no specific packages well let's get default then
13489: if ($key!~/^default&/) { next; }
1.488 albertel 13490: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 13491: \%metathesekeys);
13492: }
13493: }
1.338 www 13494: # are there custom rights to evaluate
1.599 albertel 13495: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 13496:
1.338 www 13497: #
13498: # Importing a rights file here
1.339 albertel 13499: #
13500: unless ($depthcount) {
1.599 albertel 13501: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 13502: my $dir=$filename;
13503: $dir=~s|[^/]*$||;
13504: $location=&filelocation($dir,$location);
1.736 albertel 13505: my $rights_metadata =
1.1362 raeburn 13506: &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736 albertel 13507: $depthcount+1);
13508: foreach my $rights (split(',',$rights_metadata)) {
13509: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13510: $metathesekeys{$rights}=1;
1.339 albertel 13511: }
13512: }
13513: }
1.737 albertel 13514: # uniqifiy package listing
13515: my %seen;
13516: my @uniq_packages =
13517: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13518: $metaentry{':packages'} = join(',',@uniq_packages);
13519:
1.1369 raeburn 13520: if (($importedresponses) || ($importedparts)) {
13521: if ($importedparts) {
1.1070 www 13522: # We had imported parts and need to rebuild partorder
1.1369 raeburn 13523: $metaentry{':partorder'}='';
13524: $metathesekeys{'partorder'}=1;
13525: }
13526: if ($importedresponses) {
13527: # We had imported responses and need to rebuil responseorder
13528: $metaentry{':responseorder'}='';
13529: $metathesekeys{'responseorder'}=1;
13530: }
13531: for (my $index=0;$index<$#origfiletagids;$index+=2) {
13532: my $origid = $origfiletagids[$index+1];
13533: if ($origfiletagids[$index] eq 'part') {
13534: # Original part, part of the problem
13535: if ($importedparts) {
13536: $metaentry{':partorder'}.=','.$origid;
13537: }
13538: } elsif ($origfiletagids[$index] eq 'import') {
13539: if ($importedparts) {
13540: # We have imported parts at this position
1.1373 raeburn 13541: if ($importedpartids{$origid} ne '') {
13542: $metaentry{':partorder'}.=','.$importedpartids{$origid};
13543: }
1.1369 raeburn 13544: }
13545: if ($importedresponses) {
13546: # We have imported responses at this position
1.1373 raeburn 13547: if ($importedrespids{$origid} ne '') {
13548: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369 raeburn 13549: }
13550: }
13551: } else {
13552: # Original response item, part of the problem
13553: if ($importedresponses) {
13554: $metaentry{':responseorder'}.=','.$origid;
13555: }
13556: }
13557: }
13558: if ($importedparts) {
13559: $metaentry{':partorder'}=~s/^\,//;
13560: }
13561: if ($importedresponses) {
13562: $metaentry{':responseorder'}=~s/^\,//;
13563: }
1.1070 www 13564: }
1.737 albertel 13565: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 13566: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 13567: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371 raeburn 13568: unless ($liburi) {
13569: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13570: }
1.177 www 13571: # this is the end of "was not already recently cached
1.71 www 13572: }
1.599 albertel 13573: return $metaentry{':'.$what};
1.261 albertel 13574: }
13575:
1.488 albertel 13576: sub metadata_create_package_def {
1.483 albertel 13577: my ($uri,$key,$package,$metathesekeys)=@_;
13578: my ($pack,$name,$subp)=split(/\&/,$key);
13579: if ($subp eq 'default') { next; }
13580:
1.599 albertel 13581: if (defined($metaentry{':packages'})) {
13582: $metaentry{':packages'}.=','.$package;
1.483 albertel 13583: } else {
1.599 albertel 13584: $metaentry{':packages'}=$package;
1.483 albertel 13585: }
13586: my $value=$packagetab{$key};
13587: my $unikey;
13588: $unikey='parameter_0_'.$name;
1.599 albertel 13589: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 13590: $$metathesekeys{$unikey}=1;
1.599 albertel 13591: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13592: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 13593: }
1.599 albertel 13594: if (defined($metaentry{':'.$unikey.'.default'})) {
13595: $metaentry{':'.$unikey}=
13596: $metaentry{':'.$unikey.'.default'};
1.483 albertel 13597: }
13598: }
13599:
1.261 albertel 13600: sub metadata_generate_part0 {
13601: my ($metadata,$metacache,$uri) = @_;
13602: my %allnames;
1.737 albertel 13603: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 13604: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 13605: my $part=$$metacache{':'.$metakey.'.part'};
13606: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 13607: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 13608: $allnames{$name}=$part;
13609: }
13610: }
13611: }
13612: foreach my $name (keys(%allnames)) {
13613: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 13614: my $key=":parameter_0_$name";
1.261 albertel 13615: $$metacache{"$key.part"}='0';
13616: $$metacache{"$key.name"}=$name;
1.428 albertel 13617: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 13618: $allnames{$name}.'_'.$name.
13619: '.type'};
1.428 albertel 13620: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 13621: '.display'};
1.644 www 13622: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 13623: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 13624: $$metacache{"$key.display"}=$olddis;
13625: }
1.71 www 13626: }
13627:
1.764 albertel 13628: # ------------------------------------------------------ Devalidate title cache
13629:
13630: sub devalidate_title_cache {
13631: my ($url)=@_;
13632: if (!$env{'request.course.id'}) { return; }
13633: my $symb=&symbread($url);
13634: if (!$symb) { return; }
13635: my $key=$env{'request.course.id'}."\0".$symb;
13636: &devalidate_cache_new('title',$key);
13637: }
13638:
1.1014 droeschl 13639: # ------------------------------------------------- Get the title of a course
13640:
13641: sub current_course_title {
13642: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13643: }
1.301 www 13644: # ------------------------------------------------- Get the title of a resource
13645:
13646: sub gettitle {
13647: my $urlsymb=shift;
13648: my $symb=&symbread($urlsymb);
1.534 albertel 13649: if ($symb) {
1.620 albertel 13650: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 13651: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 13652: if (defined($cached)) {
13653: return $result;
13654: }
1.534 albertel 13655: my ($map,$resid,$url)=&decode_symb($symb);
13656: my $title='';
1.907 albertel 13657: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13658: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13659: } else {
13660: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13661: &GDBM_READER(),0640)) {
13662: my $mapid=$bighash{'map_pc_'.&clutter($map)};
13663: $title=$bighash{'title_'.$mapid.'.'.$resid};
13664: untie(%bighash);
13665: }
1.534 albertel 13666: }
13667: $title=~s/\&colon\;/\:/gs;
13668: if ($title) {
1.1159 www 13669: # Remember both $symb and $title for dynamic metadata
13670: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 13671: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 13672: # Cache this title and then return it
1.599 albertel 13673: return &do_cache_new('title',$key,$title,600);
1.534 albertel 13674: }
13675: $urlsymb=$url;
13676: }
13677: my $title=&metadata($urlsymb,'title');
13678: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
13679: return $title;
1.301 www 13680: }
1.613 albertel 13681:
1.614 albertel 13682: sub get_slot {
13683: my ($which,$cnum,$cdom)=@_;
13684: if (!$cnum || !$cdom) {
1.790 albertel 13685: (undef,my $courseid)=&whichuser();
1.620 albertel 13686: $cdom=$env{'course.'.$courseid.'.domain'};
13687: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 13688: }
1.703 albertel 13689: my $key=join("\0",'slots',$cdom,$cnum,$which);
13690: my %slotinfo;
13691: if (exists($remembered{$key})) {
13692: $slotinfo{$which} = $remembered{$key};
13693: } else {
13694: %slotinfo=&get('slots',[$which],$cdom,$cnum);
13695: &Apache::lonhomework::showhash(%slotinfo);
13696: my ($tmp)=keys(%slotinfo);
13697: if ($tmp=~/^error:/) { return (); }
13698: $remembered{$key} = $slotinfo{$which};
13699: }
1.616 albertel 13700: if (ref($slotinfo{$which}) eq 'HASH') {
13701: return %{$slotinfo{$which}};
13702: }
13703: return $slotinfo{$which};
1.614 albertel 13704: }
1.1150 raeburn 13705:
13706: sub get_reservable_slots {
13707: my ($cnum,$cdom,$uname,$udom) = @_;
13708: my $now = time;
13709: my $reservable_info;
13710: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13711: if (exists($remembered{$key})) {
13712: $reservable_info = $remembered{$key};
13713: } else {
13714: my %resv;
13715: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13716: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13717: $reservable_info = \%resv;
13718: $remembered{$key} = $reservable_info;
13719: }
13720: return $reservable_info;
13721: }
13722:
13723: sub get_course_slots {
13724: my ($cnum,$cdom) = @_;
13725: my $hashid=$cnum.':'.$cdom;
1.1494 raeburn 13726: my ($result,$cached) = &is_cached_new('allslots',$hashid);
1.1150 raeburn 13727: if (defined($cached)) {
13728: if (ref($result) eq 'HASH') {
13729: return %{$result};
13730: }
13731: } else {
1.1494 raeburn 13732: my %slots=&dump('slots',$cdom,$cnum);
1.1150 raeburn 13733: my ($tmp) = keys(%slots);
13734: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 13735: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 13736: return %slots;
13737: }
13738: }
13739: return;
13740: }
13741:
13742: sub devalidate_slots_cache {
13743: my ($cnum,$cdom)=@_;
13744: my $hashid=$cnum.':'.$cdom;
13745: &devalidate_cache_new('allslots',$hashid);
13746: }
13747:
1.1181 raeburn 13748: sub get_coursechange {
13749: my ($cdom,$cnum) = @_;
13750: if ($cdom eq '' || $cnum eq '') {
13751: return unless ($env{'request.course.id'});
13752: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13753: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13754: }
13755: my $hashid=$cdom.'_'.$cnum;
13756: my ($change,$cached)=&is_cached_new('crschange',$hashid);
13757: if ((defined($cached)) && ($change ne '')) {
13758: return $change;
13759: } else {
13760: my %crshash;
13761: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13762: if ($crshash{'internal.contentchange'} eq '') {
13763: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13764: if ($change eq '') {
13765: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13766: $change = $crshash{'internal.created'};
13767: }
13768: } else {
13769: $change = $crshash{'internal.contentchange'};
13770: }
13771: my $cachetime = 600;
13772: &do_cache_new('crschange',$hashid,$change,$cachetime);
13773: }
13774: return $change;
13775: }
13776:
13777: sub devalidate_coursechange_cache {
1.1496 raeburn 13778: my ($cdom,$cnum)=@_;
13779: my $hashid=$cdom.'_'.$cnum;
1.1181 raeburn 13780: &devalidate_cache_new('crschange',$hashid);
13781: }
13782:
1.1496 raeburn 13783: sub get_suppchange {
13784: my ($cdom,$cnum) = @_;
13785: if ($cdom eq '' || $cnum eq '') {
13786: return unless ($env{'request.course.id'});
13787: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13788: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13789: }
13790: my $hashid=$cdom.'_'.$cnum;
13791: my ($change,$cached)=&is_cached_new('suppchange',$hashid);
13792: if ((defined($cached)) && ($change ne '')) {
13793: return $change;
13794: } else {
13795: my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
13796: if ($crshash{'internal.supplementalchange'} eq '') {
13797: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13798: if ($change eq '') {
13799: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13800: $change = $crshash{'internal.created'};
13801: }
13802: } else {
13803: $change = $crshash{'internal.supplementalchange'};
13804: }
13805: my $cachetime = 600;
13806: &do_cache_new('suppchange',$hashid,$change,$cachetime);
13807: }
13808: return $change;
13809: }
13810:
13811: sub devalidate_suppchange_cache {
13812: my ($cdom,$cnum)=@_;
13813: my $hashid=$cdom.'_'.$cnum;
13814: &devalidate_cache_new('suppchange',$hashid);
13815: }
13816:
1.1497 raeburn 13817: sub update_supp_caches {
13818: my ($cdom,$cnum) = @_;
13819: my %servers = &internet_dom_servers($cdom);
13820: my @ids=¤t_machine_ids();
13821: foreach my $server (keys(%servers)) {
13822: next if (grep(/^\Q$server\E$/,@ids));
13823: my $hashid=$cnum.':'.$cdom;
13824: my $cachekey = &escape('showsupp').':'.&escape($hashid);
13825: &remote_devalidate_cache($server,[$cachekey]);
13826: }
13827: &has_unhidden_suppfiles($cnum,$cdom,1,1);
13828: &count_supptools($cnum,$cdom,1);
13829: my $now = time;
13830: if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
13831: &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
13832: }
13833: &put('environment',{'internal.supplementalchange' => $now},
13834: $cdom,$cnum);
13835: &Apache::lonnet::appenv(
13836: {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
13837: &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
13838: }
13839:
1.31 www 13840: # ------------------------------------------------- Update symbolic store links
13841:
13842: sub symblist {
13843: my ($mapname,%newhash)=@_;
1.438 www 13844: $mapname=&deversion(&declutter($mapname));
1.31 www 13845: my %hash;
1.620 albertel 13846: if (($env{'request.course.fn'}) && (%newhash)) {
13847: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 13848: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 13849: foreach my $url (keys(%newhash)) {
1.711 albertel 13850: next if ($url eq 'last_known'
13851: && $env{'form.no_update_last_known'});
13852: $hash{declutter($url)}=&encode_symb($mapname,
13853: $newhash{$url}->[1],
13854: $newhash{$url}->[0]);
1.191 harris41 13855: }
1.31 www 13856: if (untie(%hash)) {
13857: return 'ok';
13858: }
13859: }
13860: }
13861: return 'error';
1.212 www 13862: }
13863:
13864: # --------------------------------------------------------------- Verify a symb
13865:
13866: sub symbverify {
1.1190 raeburn 13867: my ($symb,$thisurl,$encstate)=@_;
1.510 www 13868: my $thisfn=$thisurl;
1.439 www 13869: $thisfn=&declutter($thisfn);
1.215 www 13870: # direct jump to resource in page or to a sequence - will construct own symbs
13871: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13872: # check URL part
1.409 www 13873: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 13874:
1.431 www 13875: unless ($url eq $thisfn) { return 0; }
1.213 www 13876:
1.216 www 13877: $symb=&symbclean($symb);
1.510 www 13878: $thisurl=&deversion($thisurl);
1.439 www 13879: $thisfn=&deversion($thisfn);
1.213 www 13880:
13881: my %bighash;
13882: my $okay=0;
1.431 www 13883:
1.620 albertel 13884: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13885: &GDBM_READER(),0640)) {
1.1032 raeburn 13886: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13887: $thisurl =~ s/\?.+$//;
1.1204 raeburn 13888: if ($map =~ m{^uploaded/.+\.page$}) {
13889: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13890: $thisurl =~ s{^\Qhttp://https://\E}{https://};
13891: }
13892: }
13893: my $ids;
1.1419 raeburn 13894: if ($map =~ m{^uploaded/.+\.page$}) {
13895: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204 raeburn 13896: } else {
13897: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 13898: }
1.1102 raeburn 13899: unless ($ids) {
13900: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
13901: $ids=$bighash{$idkey};
1.216 www 13902: }
13903: if ($ids) {
13904: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 13905: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 13906: $symb =~ s/\?.+$//;
1.1202 raeburn 13907: }
1.800 albertel 13908: foreach my $id (split(/\,/,$ids)) {
13909: my ($mapid,$resid)=split(/\./,$id);
1.216 www 13910: if (
13911: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 13912: eq $symb) {
13913: if (ref($encstate)) {
13914: $$encstate = $bighash{'encrypted_'.$id};
13915: }
1.620 albertel 13916: if (($env{'request.role.adv'}) ||
1.1101 raeburn 13917: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13918: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 13919: $okay=1;
1.1202 raeburn 13920: last;
1.582 albertel 13921: }
13922: }
1.216 www 13923: }
13924: }
1.213 www 13925: untie(%bighash);
13926: }
13927: return $okay;
1.31 www 13928: }
13929:
1.210 www 13930: # --------------------------------------------------------------- Clean-up symb
13931:
13932: sub symbclean {
13933: my $symb=shift;
1.568 albertel 13934: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 13935: # remove version from map
13936: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 13937:
1.210 www 13938: # remove version from URL
13939: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 13940:
1.507 www 13941: # remove wrapper
13942:
1.510 www 13943: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 13944: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 13945: return $symb;
1.409 www 13946: }
13947:
13948: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 13949:
13950: sub encode_symb {
13951: my ($map,$resid,$url)=@_;
13952: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13953: }
1.409 www 13954:
13955: sub decode_symb {
1.568 albertel 13956: my $symb=shift;
13957: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13958: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 13959: return (&fixversion($map),$resid,&fixversion($url));
13960: }
13961:
13962: sub fixversion {
13963: my $fn=shift;
1.609 banghart 13964: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 13965: my %bighash;
13966: my $uri=&clutter($fn);
1.620 albertel 13967: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 13968: # is this cached?
1.599 albertel 13969: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 13970: if (defined($cached)) { return $result; }
13971: # unfortunately not cached, or expired
1.620 albertel 13972: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 13973: &GDBM_READER(),0640)) {
13974: if ($bighash{'version_'.$uri}) {
13975: my $version=$bighash{'version_'.$uri};
1.444 www 13976: unless (($version eq 'mostrecent') ||
13977: ($version==&getversion($uri))) {
1.440 www 13978: $uri=~s/\.(\w+)$/\.$version\.$1/;
13979: }
13980: }
13981: untie %bighash;
1.413 www 13982: }
1.599 albertel 13983: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 13984: }
13985:
13986: sub deversion {
13987: my $url=shift;
13988: $url=~s/\.\d+\.(\w+)$/\.$1/;
13989: return $url;
1.210 www 13990: }
13991:
1.31 www 13992: # ------------------------------------------------------ Return symb list entry
13993:
13994: sub symbread {
1.1424 raeburn 13995: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427 raeburn 13996: $ignoresymbdb,$noenccheck)=@_;
1.1265 raeburn 13997: my $cache_str='request.symbread.cached.'.$thisfn;
1.1427 raeburn 13998: if (defined($env{$cache_str})) {
1.1424 raeburn 13999: unless (ref($possibles) eq 'HASH') {
14000: if ($ignorecachednull) {
14001: return $env{$cache_str} unless ($env{$cache_str} eq '');
14002: } else {
14003: return $env{$cache_str};
14004: }
1.1282 raeburn 14005: }
14006: }
1.242 www 14007: # no filename provided? try from environment
1.1265 raeburn 14008: unless ($thisfn) {
1.620 albertel 14009: if ($env{'request.symb'}) {
1.1427 raeburn 14010: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 14011: }
1.620 albertel 14012: $thisfn=$env{'request.filename'};
1.44 www 14013: }
1.569 albertel 14014: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 14015: # is that filename actually a symb? Verify, clean, and return
14016: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 14017: if (&symbverify($thisfn,$1)) {
1.1427 raeburn 14018: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 14019: }
1.242 www 14020: }
1.44 www 14021: $thisfn=declutter($thisfn);
1.31 www 14022: my %hash;
1.37 www 14023: my %bighash;
14024: my $syval='';
1.620 albertel 14025: if (($env{'request.course.fn'}) && ($thisfn)) {
1.1427 raeburn 14026: unless ($ignoresymbdb) {
1.1424 raeburn 14027: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14028: &GDBM_READER(),0640)) {
1.1487 raeburn 14029: $syval=$hash{$thisfn};
1.1424 raeburn 14030: untie(%hash);
14031: }
1.1427 raeburn 14032: if ($syval && $checkforblock) {
14033: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424 raeburn 14034: if (@blockers) {
14035: $syval='';
14036: }
14037: }
1.37 www 14038: }
14039: # ---------------------------------------------------------- There was an entry
14040: if ($syval) {
1.601 albertel 14041: #unless ($syval=~/\_\d+$/) {
1.620 albertel 14042: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 14043: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 14044: #return $env{$cache_str}='';
1.601 albertel 14045: #}
14046: #$syval.=$1;
14047: #}
1.37 www 14048: } else {
14049: # ------------------------------------------------------- Was not in symb table
1.620 albertel 14050: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 14051: &GDBM_READER(),0640)) {
1.37 www 14052: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 14053: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 14054: unless ($ids) {
14055: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 14056: }
14057: unless ($ids) {
14058: # alias?
14059: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 14060: }
1.37 www 14061: if ($ids) {
14062: # ------------------------------------------------------------------- Has ID(s)
14063: my @possibilities=split(/\,/,$ids);
1.39 www 14064: if ($#possibilities==0) {
14065: # ----------------------------------------------- There is only one possibility
1.37 www 14066: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 14067: $syval=&encode_symb($bighash{'map_id_'.$mapid},
14068: $resid,$thisfn);
1.1282 raeburn 14069: if (ref($possibles) eq 'HASH') {
1.1424 raeburn 14070: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14071: $possibles->{$syval} = 1;
14072: }
1.1282 raeburn 14073: }
14074: if ($checkforblock) {
1.1424 raeburn 14075: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426 raeburn 14076: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424 raeburn 14077: if (@blockers) {
14078: $syval = '';
1.1425 raeburn 14079: untie(%bighash);
14080: return $env{$cache_str}='';
1.1424 raeburn 14081: }
1.1282 raeburn 14082: }
14083: }
14084: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 14085: # ------------------------------------------ There is more than one possibility
14086: my $realpossible=0;
1.800 albertel 14087: foreach my $id (@possibilities) {
14088: my $file=$bighash{'src_'.$id};
1.1282 raeburn 14089: my $canaccess;
14090: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14091: $canaccess = 1;
14092: } else {
14093: $canaccess = &allowed('bre',$file);
14094: }
14095: if ($canaccess) {
14096: my ($mapid,$resid)=split(/\./,$id);
14097: if ($bighash{'map_type_'.$mapid} ne 'page') {
14098: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14099: $resid,$thisfn);
1.1424 raeburn 14100: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426 raeburn 14101: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282 raeburn 14102: if ($checkforblock) {
1.1426 raeburn 14103: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424 raeburn 14104: if (@blockers > 0) {
14105: $syval = '';
14106: } else {
1.1282 raeburn 14107: $syval = $poss_syval;
14108: $realpossible++;
14109: }
14110: } else {
14111: $syval = $poss_syval;
14112: $realpossible++;
14113: }
1.1424 raeburn 14114: if ($syval) {
14115: if (ref($possibles) eq 'HASH') {
14116: $possibles->{$syval} = 1;
14117: }
14118: }
1.1282 raeburn 14119: }
1.39 www 14120: }
1.191 harris41 14121: }
1.39 www 14122: if ($realpossible!=1) { $syval=''; }
1.249 www 14123: } else {
14124: $syval='';
1.37 www 14125: }
14126: }
1.1282 raeburn 14127: untie(%bighash);
1.481 raeburn 14128: }
1.31 www 14129: }
1.62 www 14130: if ($syval) {
1.1427 raeburn 14131: return $env{$cache_str}=$syval;
1.62 www 14132: }
1.31 www 14133: }
1.949 raeburn 14134: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 14135: return $env{$cache_str}='';
1.31 www 14136: }
14137:
14138: # ---------------------------------------------------------- Return random seed
14139:
1.32 www 14140: sub numval {
14141: my $txt=shift;
14142: $txt=~tr/A-J/0-9/;
14143: $txt=~tr/a-j/0-9/;
14144: $txt=~tr/K-T/0-9/;
14145: $txt=~tr/k-t/0-9/;
14146: $txt=~tr/U-Z/0-5/;
14147: $txt=~tr/u-z/0-5/;
14148: $txt=~s/\D//g;
1.564 albertel 14149: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 14150: return int($txt);
1.368 albertel 14151: }
14152:
1.484 albertel 14153: sub numval2 {
14154: my $txt=shift;
14155: $txt=~tr/A-J/0-9/;
14156: $txt=~tr/a-j/0-9/;
14157: $txt=~tr/K-T/0-9/;
14158: $txt=~tr/k-t/0-9/;
14159: $txt=~tr/U-Z/0-5/;
14160: $txt=~tr/u-z/0-5/;
14161: $txt=~s/\D//g;
14162: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14163: my $total;
14164: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 14165: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 14166: return int($total);
14167: }
14168:
1.575 albertel 14169: sub numval3 {
14170: use integer;
14171: my $txt=shift;
14172: $txt=~tr/A-J/0-9/;
14173: $txt=~tr/a-j/0-9/;
14174: $txt=~tr/K-T/0-9/;
14175: $txt=~tr/k-t/0-9/;
14176: $txt=~tr/U-Z/0-5/;
14177: $txt=~tr/u-z/0-5/;
14178: $txt=~s/\D//g;
14179: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14180: my $total;
14181: foreach my $val (@txts) { $total+=$val; }
14182: if ($_64bit) { $total=(($total<<32)>>32); }
14183: return $total;
14184: }
14185:
1.675 albertel 14186: sub digest {
14187: my ($data)=@_;
14188: my $digest=&Digest::MD5::md5($data);
14189: my ($a,$b,$c,$d)=unpack("iiii",$digest);
14190: my ($e,$f);
14191: {
14192: use integer;
14193: $e=($a+$b);
14194: $f=($c+$d);
14195: if ($_64bit) {
14196: $e=(($e<<32)>>32);
14197: $f=(($f<<32)>>32);
14198: }
14199: }
14200: if (wantarray) {
14201: return ($e,$f);
14202: } else {
14203: my $g;
14204: {
14205: use integer;
14206: $g=($e+$f);
14207: if ($_64bit) {
14208: $g=(($g<<32)>>32);
14209: }
14210: }
14211: return $g;
14212: }
14213: }
14214:
1.368 albertel 14215: sub latest_rnd_algorithm_id {
1.675 albertel 14216: return '64bit5';
1.366 albertel 14217: }
1.32 www 14218:
1.503 albertel 14219: sub get_rand_alg {
14220: my ($courseid)=@_;
1.790 albertel 14221: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 14222: if ($courseid) {
1.620 albertel 14223: return $env{"course.$courseid.rndseed"};
1.503 albertel 14224: }
14225: return &latest_rnd_algorithm_id();
14226: }
14227:
1.562 albertel 14228: sub validCODE {
14229: my ($CODE)=@_;
14230: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14231: return 0;
14232: }
14233:
1.491 albertel 14234: sub getCODE {
1.620 albertel 14235: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 14236: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14237: defined($Apache::lonhomework::parsing_a_task) ) &&
14238: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 14239: return $Apache::lonhomework::history{'resource.CODE'};
14240: }
14241: return undef;
14242: }
1.1133 foxr 14243: #
14244: # Determines the random seed for a specific context:
14245: #
14246: # parameters:
14247: # symb - in course context the symb for the seed.
14248: # course_id - The course id of the form domain_coursenum.
14249: # domain - Domain for the user.
14250: # course - Course for the user.
14251: # cenv - environment of the course.
14252: #
14253: # NOTE:
14254: # All parameters are picked out of the environment if missing
14255: # or not defined.
14256: # If a symb cannot be determined the current time is used instead.
14257: #
14258: # For a given well defined symb, courside, domain, username,
14259: # and course environment, the seed is reproducible.
14260: #
1.31 www 14261: sub rndseed {
1.1133 foxr 14262: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 14263: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 14264: if (!defined($symb)) {
1.366 albertel 14265: unless ($symb=$wsymb) { return time; }
14266: }
1.1146 foxr 14267: if (!defined $courseid) {
14268: $courseid=$wcourseid;
14269: }
14270: if (!defined $domain) { $domain=$wdomain; }
14271: if (!defined $username) { $username=$wusername }
1.1133 foxr 14272:
14273: my $which;
14274: if (defined($cenv->{'rndseed'})) {
14275: $which = $cenv->{'rndseed'};
14276: } else {
14277: $which =&get_rand_alg($courseid);
14278: }
1.491 albertel 14279: if (defined(&getCODE())) {
1.1133 foxr 14280:
1.675 albertel 14281: if ($which eq '64bit5') {
14282: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14283: } elsif ($which eq '64bit4') {
1.575 albertel 14284: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14285: } else {
14286: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14287: }
1.675 albertel 14288: } elsif ($which eq '64bit5') {
14289: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 14290: } elsif ($which eq '64bit4') {
14291: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 14292: } elsif ($which eq '64bit3') {
14293: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 14294: } elsif ($which eq '64bit2') {
14295: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 14296: } elsif ($which eq '64bit') {
14297: return &rndseed_64bit($symb,$courseid,$domain,$username);
14298: }
14299: return &rndseed_32bit($symb,$courseid,$domain,$username);
14300: }
14301:
14302: sub rndseed_32bit {
14303: my ($symb,$courseid,$domain,$username)=@_;
14304: {
14305: use integer;
14306: my $symbchck=unpack("%32C*",$symb) << 27;
14307: my $symbseed=numval($symb) << 22;
14308: my $namechck=unpack("%32C*",$username) << 17;
14309: my $nameseed=numval($username) << 12;
14310: my $domainseed=unpack("%32C*",$domain) << 7;
14311: my $courseseed=unpack("%32C*",$courseid);
14312: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 14313: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14314: #&logthis("rndseed :$num:$symb");
1.564 albertel 14315: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 14316: return $num;
14317: }
14318: }
14319:
14320: sub rndseed_64bit {
14321: my ($symb,$courseid,$domain,$username)=@_;
14322: {
14323: use integer;
14324: my $symbchck=unpack("%32S*",$symb) << 21;
14325: my $symbseed=numval($symb) << 10;
14326: my $namechck=unpack("%32S*",$username);
14327:
14328: my $nameseed=numval($username) << 21;
14329: my $domainseed=unpack("%32S*",$domain) << 10;
14330: my $courseseed=unpack("%32S*",$courseid);
14331:
14332: my $num1=$symbchck+$symbseed+$namechck;
14333: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14334: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14335: #&logthis("rndseed :$num:$symb");
1.564 albertel 14336: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 14337: return "$num1,$num2";
1.155 albertel 14338: }
1.366 albertel 14339: }
14340:
1.443 albertel 14341: sub rndseed_64bit2 {
14342: my ($symb,$courseid,$domain,$username)=@_;
14343: {
14344: use integer;
14345: # strings need to be an even # of cahracters long, it it is odd the
14346: # last characters gets thrown away
14347: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14348: my $symbseed=numval($symb) << 10;
14349: my $namechck=unpack("%32S*",$username.' ');
14350:
14351: my $nameseed=numval($username) << 21;
1.501 albertel 14352: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14353: my $courseseed=unpack("%32S*",$courseid.' ');
14354:
14355: my $num1=$symbchck+$symbseed+$namechck;
14356: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14357: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14358: #&logthis("rndseed :$num:$symb");
1.803 albertel 14359: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 14360: return "$num1,$num2";
14361: }
14362: }
14363:
14364: sub rndseed_64bit3 {
14365: my ($symb,$courseid,$domain,$username)=@_;
14366: {
14367: use integer;
14368: # strings need to be an even # of cahracters long, it it is odd the
14369: # last characters gets thrown away
14370: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14371: my $symbseed=numval2($symb) << 10;
14372: my $namechck=unpack("%32S*",$username.' ');
14373:
14374: my $nameseed=numval2($username) << 21;
1.443 albertel 14375: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14376: my $courseseed=unpack("%32S*",$courseid.' ');
14377:
14378: my $num1=$symbchck+$symbseed+$namechck;
14379: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14380: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14381: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 14382: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14383:
1.503 albertel 14384: return "$num1:$num2";
1.443 albertel 14385: }
14386: }
14387:
1.575 albertel 14388: sub rndseed_64bit4 {
14389: my ($symb,$courseid,$domain,$username)=@_;
14390: {
14391: use integer;
14392: # strings need to be an even # of cahracters long, it it is odd the
14393: # last characters gets thrown away
14394: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14395: my $symbseed=numval3($symb) << 10;
14396: my $namechck=unpack("%32S*",$username.' ');
14397:
14398: my $nameseed=numval3($username) << 21;
14399: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14400: my $courseseed=unpack("%32S*",$courseid.' ');
14401:
14402: my $num1=$symbchck+$symbseed+$namechck;
14403: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14404: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14405: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 14406: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14407:
1.575 albertel 14408: return "$num1:$num2";
14409: }
14410: }
14411:
1.675 albertel 14412: sub rndseed_64bit5 {
14413: my ($symb,$courseid,$domain,$username)=@_;
14414: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14415: return "$num1:$num2";
14416: }
14417:
1.366 albertel 14418: sub rndseed_CODE_64bit {
14419: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 14420: {
1.366 albertel 14421: use integer;
1.443 albertel 14422: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 14423: my $symbseed=numval2($symb);
1.491 albertel 14424: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14425: my $CODEseed=numval(&getCODE());
1.443 albertel 14426: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 14427: my $num1=$symbseed+$CODEchck;
14428: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14429: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14430: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 14431: if ($_64bit) { $num1=(($num1<<32)>>32); }
14432: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 14433: return "$num1:$num2";
1.366 albertel 14434: }
14435: }
14436:
1.575 albertel 14437: sub rndseed_CODE_64bit4 {
14438: my ($symb,$courseid,$domain,$username)=@_;
14439: {
14440: use integer;
14441: my $symbchck=unpack("%32S*",$symb.' ') << 16;
14442: my $symbseed=numval3($symb);
14443: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14444: my $CODEseed=numval3(&getCODE());
14445: my $courseseed=unpack("%32S*",$courseid.' ');
14446: my $num1=$symbseed+$CODEchck;
14447: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14448: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14449: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 14450: if ($_64bit) { $num1=(($num1<<32)>>32); }
14451: if ($_64bit) { $num2=(($num2<<32)>>32); }
14452: return "$num1:$num2";
14453: }
14454: }
14455:
1.675 albertel 14456: sub rndseed_CODE_64bit5 {
14457: my ($symb,$courseid,$domain,$username)=@_;
14458: my $code = &getCODE();
14459: my ($num1,$num2)=&digest("$symb,$courseid,$code");
14460: return "$num1:$num2";
14461: }
14462:
1.366 albertel 14463: sub setup_random_from_rndseed {
14464: my ($rndseed)=@_;
1.503 albertel 14465: if ($rndseed =~/([,:])/) {
1.1262 raeburn 14466: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14467: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14468: &Math::Random::random_set_seed_from_phrase($rndseed);
14469: } else {
14470: &Math::Random::random_set_seed($num1,$num2);
14471: }
1.366 albertel 14472: } else {
14473: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 14474: }
1.36 albertel 14475: }
14476:
1.474 albertel 14477: sub latest_receipt_algorithm_id {
1.835 albertel 14478: return 'receipt3';
1.474 albertel 14479: }
14480:
1.480 www 14481: sub recunique {
14482: my $fucourseid=shift;
14483: my $unique;
1.835 albertel 14484: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14485: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14486: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 14487: } else {
14488: $unique=$perlvar{'lonReceipt'};
14489: }
14490: return unpack("%32C*",$unique);
14491: }
14492:
14493: sub recprefix {
14494: my $fucourseid=shift;
14495: my $prefix;
1.835 albertel 14496: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14497: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14498: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 14499: } else {
14500: $prefix=$perlvar{'lonHostID'};
14501: }
14502: return unpack("%32C*",$prefix);
14503: }
14504:
1.76 www 14505: sub ireceipt {
1.474 albertel 14506: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 14507:
14508: my $return =&recprefix($fucourseid).'-';
14509:
14510: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14511: $env{'request.state'} eq 'construct') {
14512: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14513: return $return;
14514: }
14515:
1.76 www 14516: my $cuname=unpack("%32C*",$funame);
14517: my $cudom=unpack("%32C*",$fudom);
14518: my $cucourseid=unpack("%32C*",$fucourseid);
14519: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 14520: my $cunique=&recunique($fucourseid);
1.474 albertel 14521: my $cpart=unpack("%32S*",$part);
1.835 albertel 14522: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14523:
1.790 albertel 14524: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 14525:
14526: $return.= ($cunique%$cuname+
14527: $cunique%$cudom+
14528: $cusymb%$cuname+
14529: $cusymb%$cudom+
14530: $cucourseid%$cuname+
14531: $cucourseid%$cudom+
14532: $cpart%$cuname+
14533: $cpart%$cudom);
14534: } else {
14535: $return.= ($cunique%$cuname+
14536: $cunique%$cudom+
14537: $cusymb%$cuname+
14538: $cusymb%$cudom+
14539: $cucourseid%$cuname+
14540: $cucourseid%$cudom);
14541: }
14542: return $return;
1.76 www 14543: }
14544:
14545: sub receipt {
1.474 albertel 14546: my ($part)=@_;
1.790 albertel 14547: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 14548: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 14549: }
1.260 ng 14550:
1.790 albertel 14551: sub whichuser {
14552: my ($passedsymb)=@_;
14553: my ($symb,$courseid,$domain,$name,$publicuser);
14554: if (defined($env{'form.grade_symb'})) {
14555: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14556: my $allowed=&allowed('vgr',$tmp_courseid);
14557: if (!$allowed &&
14558: exists($env{'request.course.sec'}) &&
14559: $env{'request.course.sec'} !~ /^\s*$/) {
14560: $allowed=&allowed('vgr',$tmp_courseid.
14561: '/'.$env{'request.course.sec'});
14562: }
14563: if ($allowed) {
14564: ($symb)=&get_env_multiple('form.grade_symb');
14565: $courseid=$tmp_courseid;
14566: ($domain)=&get_env_multiple('form.grade_domain');
14567: ($name)=&get_env_multiple('form.grade_username');
14568: return ($symb,$courseid,$domain,$name,$publicuser);
14569: }
14570: }
14571: if (!$passedsymb) {
14572: $symb=&symbread();
14573: } else {
14574: $symb=$passedsymb;
14575: }
14576: $courseid=$env{'request.course.id'};
14577: $domain=$env{'user.domain'};
14578: $name=$env{'user.name'};
14579: if ($name eq 'public' && $domain eq 'public') {
14580: if (!defined($env{'form.username'})) {
14581: $env{'form.username'}.=time.rand(10000000);
14582: }
14583: $name.=$env{'form.username'};
14584: }
14585: return ($symb,$courseid,$domain,$name,$publicuser);
14586:
14587: }
14588:
1.36 albertel 14589: # ------------------------------------------------------------ Serves up a file
1.472 albertel 14590: # returns either the contents of the file or
14591: # -1 if the file doesn't exist
1.481 raeburn 14592: #
14593: # if the target is a file that was uploaded via DOCS,
14594: # a check will be made to see if a current copy exists on the local server,
14595: # if it does this will be served, otherwise a copy will be retrieved from
14596: # the home server for the course and stored in /home/httpd/html/userfiles on
14597: # the local server.
1.472 albertel 14598:
1.36 albertel 14599: sub getfile {
1.538 albertel 14600: my ($file) = @_;
1.609 banghart 14601: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 14602: &repcopy($file);
14603: return &readfile($file);
14604: }
14605:
14606: sub repcopy_userfile {
14607: my ($file)=@_;
1.1142 raeburn 14608: my $londocroot = $perlvar{'lonDocRoot'};
14609: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 14610: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 14611: my ($cdom,$cnum,$filename) =
1.811 albertel 14612: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 14613: my $uri="/uploaded/$cdom/$cnum/$filename";
14614: if (-e "$file") {
1.828 www 14615: # we already have a local copy, check it out
1.538 albertel 14616: my @fileinfo = stat($file);
1.828 www 14617: my $rtncode;
14618: my $info;
1.538 albertel 14619: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 14620: if ($lwpresp ne 'ok') {
1.828 www 14621: # there is no such file anymore, even though we had a local copy
1.482 albertel 14622: if ($rtncode eq '404') {
1.538 albertel 14623: unlink($file);
1.482 albertel 14624: }
14625: return -1;
14626: }
14627: if ($info < $fileinfo[9]) {
1.828 www 14628: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 14629: return 'ok';
1.828 www 14630: } else {
14631: # the file is outdated, get rid of it
14632: unlink($file);
1.482 albertel 14633: }
1.828 www 14634: }
14635: # one way or the other, at this point, we don't have the file
14636: # construct the correct path for the file
14637: my @parts = ($cdom,$cnum);
14638: if ($filename =~ m|^(.+)/[^/]+$|) {
14639: push @parts, split(/\//,$1);
14640: }
14641: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14642: foreach my $part (@parts) {
14643: $path .= '/'.$part;
14644: if (!-e $path) {
14645: mkdir($path,0770);
1.482 albertel 14646: }
14647: }
1.828 www 14648: # now the path exists for sure
14649: # get a user agent
14650: my $transferfile=$file.'.in.transfer';
14651: # FIXME: this should flock
14652: if (-e $transferfile) { return 'ok'; }
14653: my $request;
14654: $uri=~s/^\///;
1.980 raeburn 14655: my $homeserver = &homeserver($cnum,$cdom);
1.1398 raeburn 14656: my $hostname = &hostname($homeserver);
1.980 raeburn 14657: my $protocol = $protocol{$homeserver};
14658: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14659: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345 raeburn 14660: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828 www 14661: # did it work?
14662: if ($response->is_error()) {
14663: unlink($transferfile);
14664: &logthis("Userfile repcopy failed for $uri");
14665: return -1;
14666: }
14667: # worked, rename the transfer file
14668: rename($transferfile,$file);
1.607 raeburn 14669: return 'ok';
1.481 raeburn 14670: }
14671:
1.517 albertel 14672: sub tokenwrapper {
14673: my $uri=shift;
1.980 raeburn 14674: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 14675: $uri=~s|^/||;
1.620 albertel 14676: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 14677: my $token=$1;
1.552 albertel 14678: my (undef,$udom,$uname,$file)=split('/',$uri,4);
14679: if ($udom && $uname && $file) {
14680: $file=~s|(\?\.*)*$||;
1.949 raeburn 14681: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 14682: my $homeserver = &homeserver($uname,$udom);
1.1397 raeburn 14683: my $hostname = &hostname($homeserver);
1.980 raeburn 14684: my $protocol = $protocol{$homeserver};
14685: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14686: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 14687: (($uri=~/\?/)?'&':'?').'token='.$token.
14688: '&tokenissued='.$perlvar{'lonHostID'};
14689: } else {
14690: return '/adm/notfound.html';
14691: }
14692: }
14693:
1.828 www 14694: # call with reqtype HEAD: get last modification time
14695: # call with reqtype GET: get the file contents
14696: # Do not call this with reqtype GET for large files! It loads everything into memory
14697: #
1.481 raeburn 14698: sub getuploaded {
14699: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14700: $uri=~s/^\///;
1.980 raeburn 14701: my $homeserver = &homeserver($cnum,$cdom);
1.1397 raeburn 14702: my $hostname = &hostname($homeserver);
1.980 raeburn 14703: my $protocol = $protocol{$homeserver};
14704: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14705: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 14706: my $request=new HTTP::Request($reqtype,$uri);
1.1345 raeburn 14707: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481 raeburn 14708: $$rtncode = $response->code;
1.482 albertel 14709: if (! $response->is_success()) {
14710: return 'failed';
14711: }
14712: if ($reqtype eq 'HEAD') {
1.486 www 14713: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 14714: } elsif ($reqtype eq 'GET') {
14715: $$info = $response->content;
1.472 albertel 14716: }
1.482 albertel 14717: return 'ok';
1.36 albertel 14718: }
14719:
1.481 raeburn 14720: sub readfile {
14721: my $file = shift;
14722: if ( (! -e $file ) || ($file eq '') ) { return -1; };
14723: my $fh;
1.1359 raeburn 14724: open($fh,"<",$file);
1.481 raeburn 14725: my $a='';
1.800 albertel 14726: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 14727: return $a;
14728: }
14729:
1.36 albertel 14730: sub filelocation {
1.590 banghart 14731: my ($dir,$file) = @_;
14732: my $location;
14733: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 14734:
14735: if ($file =~ m-^/adm/-) {
14736: $file=~s-^/adm/wrapper/-/-;
14737: $file=~s-^/adm/coursedocs/showdoc/-/-;
14738: }
1.882 albertel 14739:
1.1139 www 14740: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 14741: $location = $file;
1.609 banghart 14742: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 14743: my ($udom,$uname,$filename)=
1.811 albertel 14744: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 14745: my $home=&homeserver($uname,$udom);
14746: my $is_me=0;
14747: my @ids=¤t_machine_ids();
14748: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14749: if ($is_me) {
1.1117 foxr 14750: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 14751: } else {
14752: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14753: $udom.'/'.$uname.'/'.$filename;
14754: }
1.882 albertel 14755: } elsif ($file =~ m-^/adm/-) {
14756: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 14757: } else {
14758: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 14759: $file=~s:^/(res|priv)/:/:;
14760: my $space=$1;
1.590 banghart 14761: if ( !( $file =~ m:^/:) ) {
14762: $location = $dir. '/'.$file;
14763: } else {
1.1142 raeburn 14764: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 14765: }
1.59 albertel 14766: }
1.590 banghart 14767: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 14768: while ($location=~m{/\.\./}) {
14769: if ($location =~ m{/[^/]+/\.\./}) {
14770: $location=~ s{/[^/]+/\.\./}{/}g;
14771: } else {
14772: $location=~ s{/\.\./}{/}g;
14773: }
14774: } #remove dir/..
1.590 banghart 14775: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14776: return $location;
1.46 www 14777: }
1.36 albertel 14778:
1.46 www 14779: sub hreflocation {
14780: my ($dir,$file)=@_;
1.980 raeburn 14781: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 14782: $file=filelocation($dir,$file);
1.700 albertel 14783: } elsif ($file=~m-^/adm/-) {
14784: $file=~s-^/adm/wrapper/-/-;
14785: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 14786: }
14787: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14788: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14789: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 14790: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14791: {/uploaded/$1/$2/}x;
1.46 www 14792: }
1.913 albertel 14793: if ($file=~ m{^/userfiles/}) {
14794: $file =~ s{^/userfiles/}{/uploaded/};
14795: }
1.462 albertel 14796: return $file;
1.465 albertel 14797: }
14798:
1.1139 www 14799:
14800:
14801:
14802:
1.465 albertel 14803: sub current_machine_domains {
1.853 albertel 14804: return &machine_domains(&hostname($perlvar{'lonHostID'}));
14805: }
14806:
14807: sub machine_domains {
14808: my ($hostname) = @_;
1.465 albertel 14809: my @domains;
1.838 albertel 14810: my %hostname = &all_hostnames();
1.465 albertel 14811: while( my($id, $name) = each(%hostname)) {
1.467 matthew 14812: # &logthis("-$id-$name-$hostname-");
1.465 albertel 14813: if ($hostname eq $name) {
1.844 albertel 14814: push(@domains,&host_domain($id));
1.465 albertel 14815: }
14816: }
14817: return @domains;
14818: }
14819:
14820: sub current_machine_ids {
1.853 albertel 14821: return &machine_ids(&hostname($perlvar{'lonHostID'}));
14822: }
14823:
14824: sub machine_ids {
14825: my ($hostname) = @_;
14826: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 14827: my @ids;
1.888 albertel 14828: my %name_to_host = &all_names();
1.889 albertel 14829: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14830: return @{ $name_to_host{$hostname} };
14831: }
14832: return;
1.31 www 14833: }
14834:
1.824 raeburn 14835: sub additional_machine_domains {
14836: my @domains;
1.1466 raeburn 14837: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14838: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14839: while (my $line = <$fh>) {
14840: chomp($line);
14841: $line =~ s/\s//g;
14842: push(@domains,$line);
14843: }
14844: close($fh);
14845: }
1.824 raeburn 14846: }
14847: return @domains;
14848: }
14849:
14850: sub default_login_domain {
14851: my $domain = $perlvar{'lonDefDomain'};
14852: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14853: foreach my $posdom (¤t_machine_domains(),
14854: &additional_machine_domains()) {
14855: if (lc($posdom) eq lc($testdomain)) {
14856: $domain=$posdom;
14857: last;
14858: }
14859: }
14860: return $domain;
14861: }
14862:
1.1414 raeburn 14863: sub shared_institution {
1.1439 raeburn 14864: my ($dom,$lonhost) = @_;
14865: if ($lonhost eq '') {
14866: $lonhost = $perlvar{'lonHostID'};
14867: }
1.1414 raeburn 14868: my $same_intdom;
1.1439 raeburn 14869: my $hostintdom = &internet_dom($lonhost);
1.1414 raeburn 14870: if ($hostintdom ne '') {
14871: my %iphost = &get_iphost();
14872: my $primary_id = &domain($dom,'primary');
14873: my $primary_ip = &get_host_ip($primary_id);
14874: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14875: foreach my $id (@{$iphost{$primary_ip}}) {
14876: my $intdom = &internet_dom($id);
14877: if ($intdom eq $hostintdom) {
14878: $same_intdom = 1;
14879: last;
14880: }
14881: }
14882: }
14883: }
14884: return $same_intdom;
14885: }
14886:
1.1398 raeburn 14887: sub uses_sts {
14888: my ($ignore_cache) = @_;
14889: my $lonhost = $perlvar{'lonHostID'};
14890: my $hostname = &hostname($lonhost);
14891: my $sts_on;
14892: if ($protocol{$lonhost} eq 'https') {
14893: my $cachetime = 12*3600;
14894: if (!$ignore_cache) {
14895: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14896: if (defined($cached)) {
14897: return $sts_on;
14898: }
14899: }
14900: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14901: my $request=new HTTP::Request('HEAD',$url);
14902: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14903: if ($response->is_success) {
14904: my $has_sts = $response->header('Strict-Transport-Security');
14905: if ($has_sts eq '') {
14906: $sts_on = 0;
14907: } else {
14908: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14909: my $maxage = $1;
14910: if ($maxage) {
14911: $sts_on = 1;
14912: } else {
14913: $sts_on = 0;
14914: }
14915: } else {
14916: $sts_on = 0;
14917: }
14918: }
14919: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14920: }
14921: }
14922: return;
14923: }
14924:
1.1449 raeburn 14925: sub waf_allssl {
14926: my ($host_name) = @_;
14927: my $alias = &get_proxy_alias();
14928: if ($host_name eq '') {
14929: $host_name = $ENV{'SERVER_NAME'};
14930: }
14931: if (($host_name ne '') && ($alias eq $host_name)) {
14932: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14933: my %defdomdefaults = &get_domain_defaults($serverhomedom);
14934: if ($defdomdefaults{'waf_sslopt'}) {
14935: return $defdomdefaults{'waf_sslopt'};
14936: }
14937: }
14938: return;
14939: }
14940:
1.1434 raeburn 14941: sub get_requestor_ip {
14942: my ($r,$nolookup,$noproxy) = @_;
14943: my $from_ip;
14944: if (ref($r)) {
1.1447 raeburn 14945: if ($r->can('useragent_ip')) {
14946: if ($noproxy && $r->can('client_ip')) {
14947: $from_ip = $r->client_ip();
14948: } else {
14949: $from_ip = $r->useragent_ip();
14950: }
14951: } elsif ($r->connection->can('remote_ip')) {
14952: $from_ip = $r->connection->remote_ip();
14953: } else {
14954: $from_ip = $r->get_remote_host($nolookup);
14955: }
1.1434 raeburn 14956: } else {
14957: $from_ip = $ENV{'REMOTE_ADDR'};
14958: }
14959: return $from_ip if ($noproxy);
14960: # Who controls proxy settings for server
14961: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14962: my $proxyinfo = &get_proxy_settings($dom_in_use);
14963: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437 raeburn 14964: if ($proxyinfo->{'vpnint'}) {
14965: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434 raeburn 14966: return $from_ip;
14967: }
14968: }
14969: if ($proxyinfo->{'trusted'}) {
14970: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14971: my $ipheader = $proxyinfo->{'ipheader'};
14972: my ($ip,$xfor);
14973: if (ref($r)) {
14974: if ($ipheader) {
14975: $ip = $r->headers_in->{$ipheader};
14976: }
14977: $xfor = $r->headers_in->{'X-Forwarded-For'};
14978: } else {
14979: if ($ipheader) {
14980: $ip = $ENV{'HTTP_'.uc($ipheader)};
14981: }
14982: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14983: }
14984: if (($ip eq '') && ($xfor ne '')) {
14985: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14986: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14987: $ip = $poss_ip;
1.1435 raeburn 14988: last;
1.1434 raeburn 14989: }
14990: }
14991: }
14992: if ($ip ne '') {
14993: return $ip;
14994: }
14995: }
14996: }
14997: }
14998: return $from_ip;
14999: }
15000:
15001: sub get_proxy_settings {
15002: my ($dom_in_use) = @_;
1.1494 raeburn 15003: my %domdefaults = &get_domain_defaults($dom_in_use);
1.1434 raeburn 15004: my $proxyinfo = {
15005: ipheader => $domdefaults{'waf_ipheader'},
15006: trusted => $domdefaults{'waf_trusted'},
1.1437 raeburn 15007: vpnint => $domdefaults{'waf_vpnint'},
1.1438 raeburn 15008: vpnext => $domdefaults{'waf_vpnext'},
1.1449 raeburn 15009: sslopt => $domdefaults{'waf_sslopt'},
1.1434 raeburn 15010: };
15011: return $proxyinfo;
15012: }
15013:
15014: sub ip_match {
15015: my ($ip,$pattern_str) = @_;
15016: $ip=Net::CIDR::cidrvalidate($ip);
15017: if ($ip) {
15018: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
15019: }
15020: return;
15021: }
15022:
15023: sub get_proxy_alias {
1.1450 raeburn 15024: my ($lonid) = @_;
15025: if ($lonid eq '') {
15026: $lonid = $perlvar{'lonHostID'};
15027: }
15028: if (!defined(&hostname($lonid))) {
15029: return;
15030: }
15031: if ($lonid ne '') {
15032: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434 raeburn 15033: if ($cached) {
15034: return $alias;
15035: }
1.1494 raeburn 15036: my $dom = &host_domain($lonid);
1.1434 raeburn 15037: if ($dom ne '') {
15038: my $cachetime = 60*60*24;
15039: my %domconfig =
1.1494 raeburn 15040: &get_dom('configuration',['wafproxy'],$dom);
1.1437 raeburn 15041: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15042: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450 raeburn 15043: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
15044: }
15045: }
15046: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
15047: }
15048: }
15049: return;
15050: }
15051:
15052: sub use_proxy_alias {
15053: my ($r,$lonid) = @_;
15054: my $alias = &get_proxy_alias($lonid);
15055: if ($alias) {
15056: my $dom = &host_domain($lonid);
15057: if ($dom ne '') {
1.1467 raeburn 15058: my $proxyinfo = &get_proxy_settings($dom);
1.1450 raeburn 15059: my ($vpnint,$remote_ip);
15060: if (ref($proxyinfo) eq 'HASH') {
15061: $vpnint = $proxyinfo->{'vpnint'};
15062: if ($vpnint) {
15063: $remote_ip = &get_requestor_ip($r,1,1);
1.1434 raeburn 15064: }
15065: }
1.1450 raeburn 15066: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
15067: return $alias;
15068: }
1.1434 raeburn 15069: }
15070: }
15071: return;
15072: }
15073:
1.1474 raeburn 15074: sub alias_sso {
1.1467 raeburn 15075: my ($lonid) = @_;
15076: if ($lonid eq '') {
15077: $lonid = $perlvar{'lonHostID'};
15078: }
15079: if (!defined(&hostname($lonid))) {
15080: return;
15081: }
15082: if ($lonid ne '') {
15083: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15084: if ($cached) {
15085: return $use_alias;
15086: }
1.1494 raeburn 15087: my $dom = &host_domain($lonid);
1.1467 raeburn 15088: if ($dom ne '') {
15089: my $cachetime = 60*60*24;
15090: my %domconfig =
1.1494 raeburn 15091: &get_dom('configuration',['wafproxy'],$dom);
1.1467 raeburn 15092: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15093: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15094: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15095: }
15096: }
15097: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15098: }
15099: }
15100: return;
15101: }
15102:
1.1465 raeburn 15103: sub get_saml_landing {
15104: my ($lonid) = @_;
15105: if ($lonid eq '') {
15106: my $defdom = &default_login_domain();
15107: my @hosts = ¤t_machine_ids();
15108: if (@hosts > 1) {
15109: foreach my $hostid (@hosts) {
15110: if (&host_domain($hostid) eq $defdom) {
15111: $lonid = $hostid;
15112: last;
15113: }
15114: }
15115: } else {
15116: $lonid = $perlvar{'lonHostID'};
15117: }
15118: if ($lonid) {
1.1494 raeburn 15119: unless (&host_domain($lonid) eq $defdom) {
1.1465 raeburn 15120: return;
15121: }
15122: } else {
15123: return;
15124: }
15125: } elsif (!defined(&hostname($lonid))) {
15126: return;
15127: }
15128: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15129: if ($cached) {
15130: return $landing;
15131: }
1.1494 raeburn 15132: my $dom = &host_domain($lonid);
1.1465 raeburn 15133: if ($dom ne '') {
15134: my $cachetime = 60*60*24;
15135: my %domconfig =
1.1494 raeburn 15136: &get_dom('configuration',['login'],$dom);
1.1465 raeburn 15137: if (ref($domconfig{'login'}) eq 'HASH') {
15138: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15139: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15140: $landing = 1;
15141: }
15142: }
15143: }
15144: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15145: }
15146: return;
15147: }
15148:
1.31 www 15149: # ------------------------------------------------------------- Declutters URLs
15150:
15151: sub declutter {
15152: my $thisfn=shift;
1.569 albertel 15153: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 15154: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15155: $thisfn=~s{^/home/httpd/html}{};
15156: }
1.31 www 15157: $thisfn=~s/^\///;
1.697 albertel 15158: $thisfn=~s|^adm/wrapper/||;
15159: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 15160: $thisfn=~s/^res\///;
1.1172 bisitz 15161: $thisfn=~s/^priv\///;
1.1032 raeburn 15162: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15163: $thisfn=~s/\?.+$//;
15164: }
1.268 www 15165: return $thisfn;
15166: }
15167:
15168: # ------------------------------------------------------------- Clutter up URLs
15169:
15170: sub clutter {
15171: my $thisfn='/'.&declutter(shift);
1.887 albertel 15172: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 15173: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 15174: $thisfn='/res'.$thisfn;
15175: }
1.1031 raeburn 15176: if ($thisfn !~m|^/adm|) {
15177: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 15178: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 15179: } else {
15180: my ($ext) = ($thisfn =~ /\.(\w+)$/);
15181: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 15182: if ($embstyle eq 'ssi'
15183: || ($embstyle eq 'hdn')
15184: || ($embstyle eq 'rat')
15185: || ($embstyle eq 'prv')
15186: || ($embstyle eq 'ign')) {
15187: #do nothing with these
15188: } elsif (($embstyle eq 'img')
1.695 albertel 15189: || ($embstyle eq 'emb')
15190: || ($embstyle eq 'wrp')) {
15191: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 15192: } elsif ($embstyle eq 'unk'
15193: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 15194: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 15195: } else {
1.718 www 15196: # &logthis("Got a blank emb style");
1.695 albertel 15197: }
1.694 albertel 15198: }
1.1343 raeburn 15199: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 15200: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 15201: }
1.31 www 15202: return $thisfn;
1.12 www 15203: }
15204:
1.787 albertel 15205: sub clutter_with_no_wrapper {
15206: my $uri = &clutter(shift);
15207: if ($uri =~ m-^/adm/-) {
15208: $uri =~ s-^/adm/wrapper/-/-;
15209: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
15210: }
15211: return $uri;
15212: }
15213:
1.557 albertel 15214: sub freeze_escape {
15215: my ($value)=@_;
15216: if (ref($value)) {
15217: $value=&nfreeze($value);
15218: return '__FROZEN__'.&escape($value);
15219: }
15220: return &escape($value);
15221: }
15222:
1.11 www 15223:
1.557 albertel 15224: sub thaw_unescape {
15225: my ($value)=@_;
15226: if ($value =~ /^__FROZEN__/) {
15227: substr($value,0,10,undef);
15228: $value=&unescape($value);
15229: return &thaw($value);
15230: }
15231: return &unescape($value);
15232: }
15233:
1.436 albertel 15234: sub correct_line_ends {
15235: my ($result)=@_;
15236: $$result =~s/\r\n/\n/mg;
15237: $$result =~s/\r/\n/mg;
1.415 albertel 15238: }
1.1 albertel 15239: # ================================================================ Main Program
15240:
1.184 www 15241: sub goodbye {
1.204 albertel 15242: &logthis("Starting Shut down");
1.443 albertel 15243: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 15244: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 15245: #converted
1.599 albertel 15246: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 15247: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15248: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15249: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 15250: #1.1 only
1.870 albertel 15251: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15252: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15253: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15254: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15255: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 15256: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15257: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 15258: &flushcourselogs();
15259: &logthis("Shutting down");
15260: }
15261:
1.852 albertel 15262: sub get_dns {
1.1210 raeburn 15263: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 15264: if (!$ignore_cache) {
15265: my ($content,$cached)=
1.1494 raeburn 15266: &is_cached_new('dns',$url);
1.869 albertel 15267: if ($cached) {
1.1210 raeburn 15268: &$func($content,$hashref);
1.869 albertel 15269: return;
15270: }
15271: }
15272:
15273: my %alldns;
1.1379 raeburn 15274: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15275: foreach my $dns (<$config>) {
15276: next if ($dns !~ /^\^(\S*)/x);
15277: my $line = $1;
15278: my ($host,$protocol) = split(/:/,$line);
15279: if ($protocol ne 'https') {
15280: $protocol = 'http';
15281: }
15282: $alldns{$host} = $protocol;
1.979 raeburn 15283: }
1.1379 raeburn 15284: close($config);
1.869 albertel 15285: }
15286: while (%alldns) {
1.1263 raeburn 15287: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456 raeburn 15288: my ($contents,@content);
15289: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15290: my $command = (split('/',$url))[3];
15291: my ($dir,$file) = &parse_getdns_url($command,$url);
15292: delete($alldns{$dns});
15293: next if (($dir eq '') || ($file eq ''));
15294: if (open(my $config,'<',"$dir/$file")) {
1.1457 raeburn 15295: @content = <$config>;
1.1456 raeburn 15296: close($config);
15297: }
15298: if ($url eq '/adm/dns/loncapaCRL') {
15299: $contents = join('',@content);
15300: }
15301: } else {
15302: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15303: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15304: delete($alldns{$dns});
15305: next if ($response->is_error());
15306: if ($url eq '/adm/dns/loncapaCRL') {
15307: $contents = $response->content;
15308: } else {
15309: @content = split("\n",$response->content);
15310: }
15311: }
1.1379 raeburn 15312: if ($url eq '/adm/dns/loncapaCRL') {
1.1456 raeburn 15313: return &$func($contents);
1.1379 raeburn 15314: } else {
15315: unless ($nocache) {
15316: &do_cache_new('dns',$url,\@content,30*24*60*60);
15317: }
15318: &$func(\@content,$hashref);
15319: return;
15320: }
15321: }
15322: my $which = (split('/',$url,4))[3];
15323: if ($which eq 'loncapaCRL') {
15324: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15325: if (-e $diskfile) {
15326: &logthis("unable to contact DNS, on disk file $diskfile not updated");
15327: } else {
15328: &logthis("unable to contact DNS, no on disk file $diskfile available");
15329: }
15330: } else {
15331: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15332: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15333: my @content = <$config>;
15334: close($config);
15335: &$func(\@content,$hashref);
15336: }
1.852 albertel 15337: }
1.1210 raeburn 15338: return;
15339: }
15340:
15341: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 15342: sub parse_dns_checksums_tab {
1.1210 raeburn 15343: my ($lines,$hashref) = @_;
1.1264 raeburn 15344: my $lonhost = $perlvar{'lonHostID'};
1.1494 raeburn 15345: my $machine_dom = &host_domain($lonhost);
1.1210 raeburn 15346: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 15347: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15348: my $webconfdir = '/etc/httpd/conf';
15349: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15350: $webconfdir = '/etc/apache2';
15351: } elsif ($distro =~ /^sles(\d+)$/) {
15352: if ($1 >= 10) {
15353: $webconfdir = '/etc/apache2';
15354: }
15355: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15356: if ($1 >= 10.0) {
15357: $webconfdir = '/etc/apache2';
15358: }
15359: }
1.1210 raeburn 15360: my ($release,$timestamp) = split(/\-/,$loncaparev);
15361: my (%chksum,%revnum);
15362: if (ref($lines) eq 'ARRAY') {
15363: chomp(@{$lines});
1.1238 raeburn 15364: my $version = shift(@{$lines});
15365: if ($version eq $release) {
1.1210 raeburn 15366: foreach my $line (@{$lines}) {
1.1238 raeburn 15367: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 15368: if ($file =~ m{^/etc/httpd/conf}) {
15369: if ($webconfdir eq '/etc/apache2') {
15370: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15371: }
15372: }
1.1238 raeburn 15373: $chksum{$file} = $shasum;
15374: $revnum{$file} = $version;
1.1210 raeburn 15375: }
15376: if (ref($hashref) eq 'HASH') {
15377: %{$hashref} = (
15378: sums => \%chksum,
15379: versions => \%revnum,
15380: );
15381: }
15382: }
15383: }
1.869 albertel 15384: return;
1.852 albertel 15385: }
1.1210 raeburn 15386:
15387: sub fetch_dns_checksums {
1.1238 raeburn 15388: my %checksums;
1.1494 raeburn 15389: my $machine_dom = &host_domain($perlvar{'lonHostID'});
1.1260 raeburn 15390: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 15391: my ($release,$timestamp) = split(/\-/,$loncaparev);
15392: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 15393: \%checksums);
1.1210 raeburn 15394: return \%checksums;
15395: }
15396:
1.1379 raeburn 15397: sub fetch_crl_pemfile {
15398: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15399: }
15400:
15401: sub save_crl_pem {
1.1456 raeburn 15402: my ($content) = @_;
1.1380 raeburn 15403: my ($msg,$hadchanges);
1.1456 raeburn 15404: if ($content ne '') {
1.1379 raeburn 15405: my $now = time;
15406: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15407: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15408: if (open(my $fh,'>',"$tmpcrl")) {
1.1456 raeburn 15409: print $fh $content;
1.1379 raeburn 15410: close($fh);
15411: if (-e $lonca) {
15412: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15413: my $check = <PIPE>;
15414: close(PIPE);
15415: chomp($check);
15416: if ($check eq 'verify OK') {
15417: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380 raeburn 15418: my $backup;
1.1379 raeburn 15419: if (-e $dest) {
1.1380 raeburn 15420: if (&File::Copy::move($dest,"$dest.bak")) {
15421: $backup = 'ok';
15422: }
1.1379 raeburn 15423: }
15424: if (&File::Copy::move($tmpcrl,$dest)) {
15425: $msg = 'ok';
1.1380 raeburn 15426: if ($backup) {
15427: my (%oldnums,%newnums);
15428: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15429: while (<PIPE>) {
15430: $oldnums{(split(/:/))[1]} = 1;
15431: }
15432: close(PIPE);
15433: }
15434: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15435: while(<PIPE>) {
15436: $newnums{(split(/:/))[1]} = 1;
15437: }
15438: close(PIPE);
15439: }
15440: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15441: unless (exists($oldnums{$key})) {
15442: $hadchanges = 1;
15443: last;
15444: }
15445: }
15446: unless ($hadchanges) {
15447: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15448: unless (exists($newnums{$key})) {
15449: $hadchanges = 1;
15450: last;
15451: }
15452: }
15453: }
15454: }
1.1379 raeburn 15455: }
15456: } else {
15457: unlink($tmpcrl);
15458: }
15459: } else {
15460: unlink($tmpcrl);
15461: }
15462: } else {
15463: unlink($tmpcrl);
15464: }
15465: }
15466: }
1.1380 raeburn 15467: return ($msg,$hadchanges);
1.1379 raeburn 15468: }
15469:
1.1456 raeburn 15470: sub parse_getdns_url {
15471: my ($command,$url) = @_;
15472: my $dir = $perlvar{'lonTabDir'};
15473: my $file;
15474: if ($command eq 'hosts') {
15475: $file = 'dns_hosts.tab';
15476: } elsif ($command eq 'domain') {
15477: $file = 'dns_domain.tab';
15478: } elsif ($command eq 'checksums') {
15479: my $version = (split('/',$url))[4];
15480: $file = "dns_checksums/$version.tab",
15481: } elsif ($command eq 'loncapaCRL') {
15482: $dir = $perlvar{'lonCertificateDirectory'};
15483: $file = $perlvar{'lonnetCertRevocationList'};
15484: }
15485: return ($dir,$file);
15486: }
15487:
1.327 albertel 15488: # ------------------------------------------------------------ Read domain file
15489: {
1.852 albertel 15490: my $loaded;
1.846 albertel 15491: my %domain;
15492:
1.852 albertel 15493: sub parse_domain_tab {
15494: my ($lines) = @_;
15495: foreach my $line (@$lines) {
15496: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 15497:
1.846 albertel 15498: chomp($line);
1.852 albertel 15499: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 15500: my %this_domain;
15501: foreach my $field ('description', 'auth_def', 'auth_arg_def',
15502: 'lang_def', 'city', 'longi', 'lati',
15503: 'primary') {
15504: $this_domain{$field} = shift(@elements);
15505: }
15506: $domain{$name} = \%this_domain;
1.852 albertel 15507: }
15508: }
1.864 albertel 15509:
15510: sub reset_domain_info {
15511: undef($loaded);
15512: undef(%domain);
15513: }
15514:
1.852 albertel 15515: sub load_domain_tab {
1.1293 raeburn 15516: my ($ignore_cache,$nocache) = @_;
15517: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 15518: my $fh;
1.1359 raeburn 15519: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 15520: my @lines = <$fh>;
15521: &parse_domain_tab(\@lines);
1.448 albertel 15522: }
1.852 albertel 15523: close($fh);
15524: $loaded = 1;
1.327 albertel 15525: }
1.846 albertel 15526:
15527: sub domain {
1.852 albertel 15528: &load_domain_tab() if (!$loaded);
15529:
1.846 albertel 15530: my ($name,$what) = @_;
15531: return if ( !exists($domain{$name}) );
15532:
15533: if (!$what) {
15534: return $domain{$name}{'description'};
15535: }
15536: return $domain{$name}{$what};
15537: }
1.974 raeburn 15538:
15539: sub domain_info {
15540: &load_domain_tab() if (!$loaded);
15541: return %domain;
15542: }
15543:
1.327 albertel 15544: }
15545:
15546:
1.1 albertel 15547: # ------------------------------------------------------------- Read hosts file
15548: {
1.838 albertel 15549: my %hostname;
1.844 albertel 15550: my %hostdom;
1.845 albertel 15551: my %libserv;
1.852 albertel 15552: my $loaded;
1.888 albertel 15553: my %name_to_host;
1.1074 raeburn 15554: my %internetdom;
1.1107 raeburn 15555: my %LC_dns_serv;
1.852 albertel 15556:
15557: sub parse_hosts_tab {
15558: my ($file) = @_;
15559: foreach my $configline (@$file) {
15560: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 15561: chomp($configline);
15562: if ($configline =~ /^\^/) {
15563: if ($configline =~ /^\^([\w.\-]+)/) {
15564: $LC_dns_serv{$1} = 1;
15565: }
15566: next;
15567: }
1.1074 raeburn 15568: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 15569: $name=~s/\s//g;
15570: if ($id && $domain && $role && $name) {
1.1351 raeburn 15571: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15572: my $curr = $hostname{$id};
15573: my $skip;
15574: if (ref($name_to_host{$curr}) eq 'ARRAY') {
15575: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15576: $skip = 1;
15577: } else {
15578: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15579: }
15580: }
15581: unless ($skip) {
15582: push(@{$name_to_host{$name}},$id);
15583: }
15584: } else {
15585: push(@{$name_to_host{$name}},$id);
15586: }
1.852 albertel 15587: $hostname{$id}=$name;
15588: $hostdom{$id}=$domain;
15589: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 15590: if (defined($protocol)) {
15591: if ($protocol eq 'https') {
15592: $protocol{$id} = $protocol;
15593: } else {
15594: $protocol{$id} = 'http';
15595: }
1.968 raeburn 15596: } else {
1.969 raeburn 15597: $protocol{$id} = 'http';
1.968 raeburn 15598: }
1.1074 raeburn 15599: if (defined($intdom)) {
15600: $internetdom{$id} = $intdom;
15601: }
1.852 albertel 15602: }
15603: }
15604: }
1.864 albertel 15605:
15606: sub reset_hosts_info {
1.897 albertel 15607: &purge_remembered();
1.864 albertel 15608: &reset_domain_info();
15609: &reset_hosts_ip_info();
1.1339 raeburn 15610: undef(%internetdom);
1.892 albertel 15611: undef(%name_to_host);
1.864 albertel 15612: undef(%hostname);
15613: undef(%hostdom);
15614: undef(%libserv);
15615: undef($loaded);
15616: }
1.1 albertel 15617:
1.852 albertel 15618: sub load_hosts_tab {
1.1293 raeburn 15619: my ($ignore_cache,$nocache) = @_;
15620: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359 raeburn 15621: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 15622: my @config = <$config>;
15623: &parse_hosts_tab(\@config);
15624: close($config);
15625: $loaded=1;
1.1 albertel 15626: }
1.852 albertel 15627:
1.838 albertel 15628: sub hostname {
1.852 albertel 15629: &load_hosts_tab() if (!$loaded);
15630:
1.838 albertel 15631: my ($lonid) = @_;
15632: return $hostname{$lonid};
15633: }
1.845 albertel 15634:
1.838 albertel 15635: sub all_hostnames {
1.852 albertel 15636: &load_hosts_tab() if (!$loaded);
15637:
1.838 albertel 15638: return %hostname;
15639: }
1.845 albertel 15640:
1.888 albertel 15641: sub all_names {
1.1293 raeburn 15642: my ($ignore_cache,$nocache) = @_;
15643: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 15644:
15645: return %name_to_host;
15646: }
15647:
1.974 raeburn 15648: sub all_host_domain {
15649: &load_hosts_tab() if (!$loaded);
15650: return %hostdom;
15651: }
15652:
1.1339 raeburn 15653: sub all_host_intdom {
15654: &load_hosts_tab() if (!$loaded);
15655: return %internetdom;
15656: }
15657:
1.845 albertel 15658: sub is_library {
1.852 albertel 15659: &load_hosts_tab() if (!$loaded);
15660:
1.845 albertel 15661: return exists($libserv{$_[0]});
15662: }
15663:
15664: sub all_library {
1.852 albertel 15665: &load_hosts_tab() if (!$loaded);
15666:
1.845 albertel 15667: return %libserv;
15668: }
15669:
1.1062 droeschl 15670: sub unique_library {
15671: #2x reverse removes all hostnames that appear more than once
15672: my %unique = reverse &all_library();
15673: return reverse %unique;
15674: }
15675:
1.841 albertel 15676: sub get_servers {
1.852 albertel 15677: &load_hosts_tab() if (!$loaded);
15678:
1.841 albertel 15679: my ($domain,$type) = @_;
15680: my %possible_hosts = ($type eq 'library') ? %libserv
15681: : %hostname;
15682: my %result;
1.842 albertel 15683: if (ref($domain) eq 'ARRAY') {
15684: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 15685: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 15686: $result{$host} = $hostname;
15687: }
15688: }
15689: } else {
15690: while ( my ($host,$hostname) = each(%possible_hosts)) {
15691: if ($hostdom{$host} eq $domain) {
15692: $result{$host} = $hostname;
15693: }
1.841 albertel 15694: }
15695: }
15696: return %result;
15697: }
1.845 albertel 15698:
1.1062 droeschl 15699: sub get_unique_servers {
15700: my %unique = reverse &get_servers(@_);
15701: return reverse %unique;
15702: }
15703:
1.844 albertel 15704: sub host_domain {
1.852 albertel 15705: &load_hosts_tab() if (!$loaded);
15706:
1.844 albertel 15707: my ($lonid) = @_;
15708: return $hostdom{$lonid};
15709: }
15710:
1.841 albertel 15711: sub all_domains {
1.852 albertel 15712: &load_hosts_tab() if (!$loaded);
15713:
1.841 albertel 15714: my %seen;
15715: my @uniq = grep(!$seen{$_}++, values(%hostdom));
15716: return @uniq;
15717: }
1.1074 raeburn 15718:
15719: sub internet_dom {
15720: &load_hosts_tab() if (!$loaded);
15721:
15722: my ($lonid) = @_;
15723: return $internetdom{$lonid};
15724: }
1.1107 raeburn 15725:
15726: sub is_LC_dns {
15727: &load_hosts_tab() if (!$loaded);
15728:
15729: my ($hostname) = @_;
15730: return exists($LC_dns_serv{$hostname});
15731: }
15732:
1.1 albertel 15733: }
15734:
1.847 albertel 15735: {
15736: my %iphost;
1.856 albertel 15737: my %name_to_ip;
15738: my %lonid_to_ip;
1.869 albertel 15739:
1.847 albertel 15740: sub get_hosts_from_ip {
15741: my ($ip) = @_;
15742: my %iphosts = &get_iphost();
15743: if (ref($iphosts{$ip})) {
15744: return @{$iphosts{$ip}};
15745: }
15746: return;
1.839 albertel 15747: }
1.864 albertel 15748:
15749: sub reset_hosts_ip_info {
15750: undef(%iphost);
15751: undef(%name_to_ip);
15752: undef(%lonid_to_ip);
15753: }
1.856 albertel 15754:
15755: sub get_host_ip {
15756: my ($lonid) = @_;
15757: if (exists($lonid_to_ip{$lonid})) {
15758: return $lonid_to_ip{$lonid};
15759: }
15760: my $name=&hostname($lonid);
15761: my $ip = gethostbyname($name);
15762: return if (!$ip || length($ip) ne 4);
15763: $ip=inet_ntoa($ip);
15764: $name_to_ip{$name} = $ip;
15765: $lonid_to_ip{$lonid} = $ip;
15766: return $ip;
15767: }
1.847 albertel 15768:
15769: sub get_iphost {
1.1293 raeburn 15770: my ($ignore_cache,$nocache) = @_;
1.894 albertel 15771:
1.869 albertel 15772: if (!$ignore_cache) {
15773: if (%iphost) {
15774: return %iphost;
15775: }
15776: my ($ip_info,$cached)=
1.1494 raeburn 15777: &is_cached_new('iphost','iphost');
1.869 albertel 15778: if ($cached) {
15779: %iphost = %{$ip_info->[0]};
15780: %name_to_ip = %{$ip_info->[1]};
15781: %lonid_to_ip = %{$ip_info->[2]};
15782: return %iphost;
15783: }
15784: }
1.894 albertel 15785:
15786: # get yesterday's info for fallback
15787: my %old_name_to_ip;
15788: my ($ip_info,$cached)=
1.1495 raeburn 15789: &is_cached_new('iphost','iphost');
1.894 albertel 15790: if ($cached) {
15791: %old_name_to_ip = %{$ip_info->[1]};
15792: }
15793:
1.1293 raeburn 15794: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 15795: foreach my $name (keys(%name_to_host)) {
1.847 albertel 15796: my $ip;
15797: if (!exists($name_to_ip{$name})) {
15798: $ip = gethostbyname($name);
15799: if (!$ip || length($ip) ne 4) {
1.894 albertel 15800: if (defined($old_name_to_ip{$name})) {
15801: $ip = $old_name_to_ip{$name};
15802: &logthis("Can't find $name defaulting to old $ip");
15803: } else {
15804: &logthis("Name $name no IP found");
15805: next;
15806: }
15807: } else {
15808: $ip=inet_ntoa($ip);
1.847 albertel 15809: }
15810: $name_to_ip{$name} = $ip;
15811: } else {
15812: $ip = $name_to_ip{$name};
1.653 albertel 15813: }
1.888 albertel 15814: foreach my $id (@{ $name_to_host{$name} }) {
15815: $lonid_to_ip{$id} = $ip;
15816: }
15817: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 15818: }
1.1293 raeburn 15819: unless ($nocache) {
15820: &do_cache_new('iphost','iphost',
15821: [\%iphost,\%name_to_ip,\%lonid_to_ip],
15822: 48*60*60);
15823: }
1.869 albertel 15824:
1.847 albertel 15825: return %iphost;
1.598 albertel 15826: }
15827:
1.992 raeburn 15828: #
15829: # Given a DNS returns the loncapa host name for that DNS
15830: #
15831: sub host_from_dns {
15832: my ($dns) = @_;
15833: my @hosts;
15834: my $ip;
15835:
1.993 raeburn 15836: if (exists($name_to_ip{$dns})) {
1.992 raeburn 15837: $ip = $name_to_ip{$dns};
15838: }
15839: if (!$ip) {
15840: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15841: if (length($ip) == 4) {
15842: $ip = &IO::Socket::inet_ntoa($ip);
15843: }
15844: }
15845: if ($ip) {
15846: @hosts = get_hosts_from_ip($ip);
15847: return $hosts[0];
15848: }
15849: return undef;
1.986 foxr 15850: }
1.992 raeburn 15851:
1.1074 raeburn 15852: sub get_internet_names {
15853: my ($lonid) = @_;
15854: return if ($lonid eq '');
15855: my ($idnref,$cached)=
1.1494 raeburn 15856: &is_cached_new('internetnames',$lonid);
1.1074 raeburn 15857: if ($cached) {
15858: return $idnref;
15859: }
15860: my $ip = &get_host_ip($lonid);
15861: my @hosts = &get_hosts_from_ip($ip);
15862: my %iphost = &get_iphost();
15863: my (@idns,%seen);
15864: foreach my $id (@hosts) {
15865: my $dom = &host_domain($id);
15866: my $prim_id = &domain($dom,'primary');
15867: my $prim_ip = &get_host_ip($prim_id);
15868: next if ($seen{$prim_ip});
15869: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15870: foreach my $id (@{$iphost{$prim_ip}}) {
15871: my $intdom = &internet_dom($id);
15872: unless (grep(/^\Q$intdom\E$/,@idns)) {
15873: push(@idns,$intdom);
15874: }
15875: }
15876: }
15877: $seen{$prim_ip} = 1;
15878: }
1.1219 raeburn 15879: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 15880: }
15881:
1.986 foxr 15882: }
15883:
1.1079 raeburn 15884: sub all_loncaparevs {
1.1249 raeburn 15885: 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 15886: }
15887:
1.1227 raeburn 15888: # ---------------------------------------------------------- Read loncaparev table
15889: {
15890: sub load_loncaparevs {
15891: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359 raeburn 15892: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227 raeburn 15893: while (my $configline=<$config>) {
15894: chomp($configline);
15895: my ($hostid,$loncaparev)=split(/:/,$configline);
15896: $loncaparevs{$hostid}=$loncaparev;
15897: }
15898: close($config);
15899: }
15900: }
15901: }
15902: }
15903:
15904: # ---------------------------------------------------------- Read serverhostID table
15905: {
15906: sub load_serverhomeIDs {
15907: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359 raeburn 15908: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227 raeburn 15909: while (my $configline=<$config>) {
15910: chomp($configline);
15911: my ($name,$id)=split(/:/,$configline);
15912: $serverhomeIDs{$name}=$id;
15913: }
15914: close($config);
15915: }
15916: }
15917: }
15918: }
15919:
15920:
1.862 albertel 15921: BEGIN {
15922:
15923: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15924: unless ($readit) {
15925: {
15926: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15927: %perlvar = (%perlvar,%{$configvars});
15928: }
15929:
15930:
1.1 albertel 15931: # ------------------------------------------------------ Read spare server file
15932: {
1.1359 raeburn 15933: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 15934:
15935: while (my $configline=<$config>) {
15936: chomp($configline);
1.284 matthew 15937: if ($configline) {
1.784 albertel 15938: my ($host,$type) = split(':',$configline,2);
1.785 albertel 15939: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 15940: push(@{ $spareid{$type} }, $host);
1.1 albertel 15941: }
15942: }
1.448 albertel 15943: close($config);
1.1 albertel 15944: }
1.11 www 15945: # ------------------------------------------------------------ Read permissions
15946: {
1.1359 raeburn 15947: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 15948:
15949: while (my $configline=<$config>) {
1.448 albertel 15950: chomp($configline);
15951: if ($configline) {
15952: my ($role,$perm)=split(/ /,$configline);
15953: if ($perm ne '') { $pr{$role}=$perm; }
15954: }
1.11 www 15955: }
1.448 albertel 15956: close($config);
1.11 www 15957: }
15958:
15959: # -------------------------------------------- Read plain texts for permissions
15960: {
1.1359 raeburn 15961: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 15962:
15963: while (my $configline=<$config>) {
1.448 albertel 15964: chomp($configline);
15965: if ($configline) {
1.742 raeburn 15966: my ($short,@plain)=split(/:/,$configline);
15967: %{$prp{$short}} = ();
15968: if (@plain > 0) {
15969: $prp{$short}{'std'} = $plain[0];
15970: for (my $i=1; $i<@plain; $i++) {
15971: $prp{$short}{'alt'.$i} = $plain[$i];
15972: }
15973: }
1.448 albertel 15974: }
1.135 www 15975: }
1.448 albertel 15976: close($config);
1.135 www 15977: }
15978:
15979: # ---------------------------------------------------------- Read package table
15980: {
1.1359 raeburn 15981: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 15982:
15983: while (my $configline=<$config>) {
1.483 albertel 15984: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 15985: chomp($configline);
15986: my ($short,$plain)=split(/:/,$configline);
15987: my ($pack,$name)=split(/\&/,$short);
15988: if ($plain ne '') {
15989: $packagetab{$pack.'&'.$name.'&name'}=$name;
15990: $packagetab{$short}=$plain;
15991: }
1.11 www 15992: }
1.448 albertel 15993: close($config);
1.329 matthew 15994: }
15995:
1.1073 raeburn 15996: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 15997:
15998: &load_loncaparevs();
1.1073 raeburn 15999:
1.1074 raeburn 16000: # ---------------------------------------------------------- Read serverhostID table
16001:
1.1227 raeburn 16002: &load_serverhomeIDs();
16003:
16004: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 16005: {
16006: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
16007: if (-e $file) {
16008: my $parser = HTML::LCParser->new($file);
16009: while (my $token = $parser->get_token()) {
16010: if ($token->[0] eq 'S') {
16011: my $item = $token->[1];
16012: my $name = $token->[2]{'name'};
16013: my $value = $token->[2]{'value'};
1.1285 raeburn 16014: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 16015: my $namematch = $token->[2]{'namematch'};
16016: if ($item eq 'parameter') {
16017: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
16018: my $release = $parser->get_text();
16019: $release =~ s/(^\s*|\s*$ )//gx;
16020: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
16021: }
16022: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 16023: my $release = $parser->get_text();
16024: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 16025: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 16026: }
16027: }
16028: }
16029: }
1.1073 raeburn 16030: }
16031:
1.1138 raeburn 16032: # ---------------------------------------------------------- Read managers table
16033: {
16034: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359 raeburn 16035: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 16036: while (my $configline=<$config>) {
16037: chomp($configline);
16038: next if ($configline =~ /^\#/);
16039: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
16040: $managerstab{$configline} = 1;
16041: }
16042: }
16043: close($config);
16044: }
16045: }
16046: }
16047:
1.329 matthew 16048: # ------------- set up temporary directory
16049: {
1.1117 foxr 16050: $tmpdir = LONCAPA::tempdir();
1.329 matthew 16051:
1.11 www 16052: }
16053:
1.1405 raeburn 16054: # ------------- set default texengine (domain default overrides this)
16055: {
16056: $deftex = LONCAPA::texengine();
16057: }
16058:
1.1416 raeburn 16059: # ------------- set default minimum length for passwords for internal auth users
16060: {
16061: $passwdmin = LONCAPA::passwd_min();
16062: }
16063:
1.794 albertel 16064: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
16065: 'compress_threshold'=> 20_000,
16066: });
1.185 www 16067:
1.281 www 16068: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 16069: $dumpcount=0;
1.958 www 16070: $locknum=0;
1.22 www 16071:
1.163 harris41 16072: &logtouch();
1.672 albertel 16073: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 16074: $readit=1;
1.564 albertel 16075: {
16076: use integer;
16077: my $test=(2**32)+1;
1.568 albertel 16078: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 16079: &logthis(" Detected 64bit platform ($_64bit)");
16080: }
1.195 www 16081: }
1.1 albertel 16082: }
1.179 www 16083:
1.1 albertel 16084: 1;
1.191 harris41 16085: __END__
16086:
1.243 albertel 16087: =pod
16088:
1.191 harris41 16089: =head1 NAME
16090:
1.243 albertel 16091: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 16092:
16093: =head1 SYNOPSIS
16094:
1.243 albertel 16095: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 16096:
16097: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16098:
1.243 albertel 16099: Common parameters:
16100:
16101: =over 4
16102:
16103: =item *
16104:
16105: $uname : an internal username (if $cname expecting a course Id specifically)
16106:
16107: =item *
16108:
16109: $udom : a domain (if $cdom expecting a course's domain specifically)
16110:
16111: =item *
16112:
16113: $symb : a resource instance identifier
16114:
16115: =item *
16116:
16117: $namespace : the name of a .db file that contains the data needed or
16118: being set.
16119:
16120: =back
16121:
1.394 bowersj2 16122: =head1 OVERVIEW
1.191 harris41 16123:
1.394 bowersj2 16124: lonnet provides subroutines which interact with the
16125: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16126: about classes, users, and resources.
1.243 albertel 16127:
16128: For many of these objects you can also use this to store data about
16129: them or modify them in various ways.
1.191 harris41 16130:
1.394 bowersj2 16131: =head2 Symbs
1.191 harris41 16132:
1.394 bowersj2 16133: To identify a specific instance of a resource, LON-CAPA uses symbols
16134: or "symbs"X<symb>. These identifiers are built from the URL of the
16135: map, the resource number of the resource in the map, and the URL of
16136: the resource itself. The latter is somewhat redundant, but might help
16137: if maps change.
16138:
16139: An example is
16140:
16141: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16142:
16143: The respective map entry is
16144:
16145: <resource id="19" src="/res/msu/korte/tests/part12.problem"
16146: title="Problem 2">
16147: </resource>
16148:
16149: Symbs are used by the random number generator, as well as to store and
16150: restore data specific to a certain instance of for example a problem.
16151:
16152: =head2 Storing And Retrieving Data
16153:
16154: X<store()>X<cstore()>X<restore()>Three of the most important functions
16155: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16156: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16157: is is the non-critical message twin of cstore. These functions are for
16158: handlers to store a perl hash to a user's permanent data space in an
16159: easy manner, and to retrieve it again on another call. It is expected
16160: that a handler would use this once at the beginning to retrieve data,
16161: and then again once at the end to send only the new data back.
16162:
16163: The data is stored in the user's data directory on the user's
16164: homeserver under the ID of the course.
16165:
16166: The hash that is returned by restore will have all of the previous
16167: value for all of the elements of the hash.
16168:
16169: Example:
16170:
16171: #creating a hash
16172: my %hash;
16173: $hash{'foo'}='bar';
16174:
16175: #storing it
16176: &Apache::lonnet::cstore(\%hash);
16177:
16178: #changing a value
16179: $hash{'foo'}='notbar';
16180:
16181: #adding a new value
16182: $hash{'bar'}='foo';
16183: &Apache::lonnet::cstore(\%hash);
16184:
16185: #retrieving the hash
16186: my %history=&Apache::lonnet::restore();
16187:
16188: #print the hash
16189: foreach my $key (sort(keys(%history))) {
16190: print("\%history{$key} = $history{$key}");
16191: }
16192:
16193: Will print out:
1.191 harris41 16194:
1.394 bowersj2 16195: %history{1:foo} = bar
16196: %history{1:keys} = foo:timestamp
16197: %history{1:timestamp} = 990455579
16198: %history{2:bar} = foo
16199: %history{2:foo} = notbar
16200: %history{2:keys} = foo:bar:timestamp
16201: %history{2:timestamp} = 990455580
16202: %history{bar} = foo
16203: %history{foo} = notbar
16204: %history{timestamp} = 990455580
16205: %history{version} = 2
16206:
16207: Note that the special hash entries C<keys>, C<version> and
16208: C<timestamp> were added to the hash. C<version> will be equal to the
16209: total number of versions of the data that have been stored. The
16210: C<timestamp> attribute will be the UNIX time the hash was
16211: stored. C<keys> is available in every historical section to list which
16212: keys were added or changed at a specific historical revision of a
16213: hash.
16214:
16215: B<Warning>: do not store the hash that restore returns directly. This
16216: will cause a mess since it will restore the historical keys as if the
16217: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 16218:
1.394 bowersj2 16219: Calling convention:
1.191 harris41 16220:
1.1225 raeburn 16221: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 16222: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 16223:
1.394 bowersj2 16224: For more detailed information, see lonnet specific documentation.
1.191 harris41 16225:
1.394 bowersj2 16226: =head1 RETURN MESSAGES
1.191 harris41 16227:
1.394 bowersj2 16228: =over 4
1.191 harris41 16229:
1.394 bowersj2 16230: =item * B<con_lost>: unable to contact remote host
1.191 harris41 16231:
1.394 bowersj2 16232: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16233: when the connection is brought back up
1.191 harris41 16234:
1.394 bowersj2 16235: =item * B<con_failed>: unable to contact remote host and unable to save message
16236: for later delivery
1.191 harris41 16237:
1.967 bisitz 16238: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 16239:
1.394 bowersj2 16240: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 16241: that was requested
1.191 harris41 16242:
1.243 albertel 16243: =back
1.191 harris41 16244:
1.243 albertel 16245: =head1 PUBLIC SUBROUTINES
1.191 harris41 16246:
1.243 albertel 16247: =head2 Session Environment Functions
1.191 harris41 16248:
1.243 albertel 16249: =over 4
1.191 harris41 16250:
1.394 bowersj2 16251: =item *
16252: X<appenv()>
1.949 raeburn 16253: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 16254: the user envirnoment file, and will be restored for each access this
1.620 albertel 16255: user makes during this session, also modifies the %env for the current
1.949 raeburn 16256: process. Optional rolesarrayref - if defined contains a reference to an array
16257: of roles which are exempt from the restriction on modifying user.role entries
16258: in the user's environment.db and in %env.
1.191 harris41 16259:
16260: =item *
1.394 bowersj2 16261: X<delenv()>
1.987 raeburn 16262: B<delenv($delthis,$regexp)>: removes all items from the session
16263: environment file that begin with $delthis. If the
16264: optional second arg - $regexp - is true, $delthis is treated as a
16265: regular expression, otherwise \Q$delthis\E is used.
16266: The values are also deleted from the current processes %env.
1.191 harris41 16267:
1.795 albertel 16268: =item * get_env_multiple($name)
16269:
16270: gets $name from the %env hash, it seemlessly handles the cases where multiple
16271: values may be defined and end up as an array ref.
16272:
16273: returns an array of values
16274:
1.243 albertel 16275: =back
16276:
16277: =head2 User Information
1.191 harris41 16278:
1.243 albertel 16279: =over 4
1.191 harris41 16280:
16281: =item *
1.394 bowersj2 16282: X<queryauthenticate()>
16283: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 16284: authentication scheme
16285:
16286: =item *
1.394 bowersj2 16287: X<authenticate()>
1.1073 raeburn 16288: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 16289: authenticate user from domain's lib servers (first use the current
16290: one). C<$upass> should be the users password.
1.1073 raeburn 16291: $checkdefauth is optional (value is 1 if a check should be made to
16292: authenticate user using default authentication method, and allow
16293: account creation if username does not have account in the domain).
16294: $clientcancheckhost is optional (value is 1 if checking whether the
16295: server can host will occur on the client side in lonauth.pm).
1.191 harris41 16296:
16297: =item *
1.394 bowersj2 16298: X<homeserver()>
16299: B<homeserver($uname,$udom)>: find the server which has
16300: the user's directory and files (there must be only one), this caches
16301: the answer, and also caches if there is a borken connection.
1.191 harris41 16302:
16303: =item *
1.394 bowersj2 16304: X<idget()>
1.1300 raeburn 16305: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
16306: a list of student/employee IDs or clicker IDs
16307: (student/employee IDs are a unique resource in a domain, there must be
16308: only 1 ID per username, and only 1 username per ID in a specific domain).
16309: clickerIDs are not necessarily unique, as students might share clickers.
16310: (returns hash: id=>name,id=>name)
1.191 harris41 16311:
16312: =item *
1.394 bowersj2 16313: X<idrget()>
16314: B<idrget($udom,@unames)>: find the IDs behind a list of
16315: usernames (returns hash: name=>id,name=>id)
1.191 harris41 16316:
16317: =item *
1.394 bowersj2 16318: X<idput()>
1.1300 raeburn 16319: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
16320: names and associated student/employee IDs or clicker IDs.
16321:
16322: =item *
16323: X<iddel()>
16324: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
16325: student/employee ID or clicker ID username look-ups from domain.
16326: The homeserver ($uhome) and namespace ($namespace) are optional.
16327: If no $uhome is provided, it will be determined usig &homeserver()
16328: for each user. If no $namespace is provided, the default is ids.
16329:
16330: =item *
16331: X<updateclickers()>
16332: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
16333: clicker ID-to-username look-ups in clickers.db on library server.
16334: Permitted actions are add or del (i.e., add or delete). The
16335: clickers.db contains clickerID as keys (escaped), and each corresponding
16336: value is an escaped comma-separated list of usernames (for whom the
16337: library server is the homeserver), who registered that particular ID.
16338: If $critical is true, the update will be sent via &critical, otherwise
16339: &reply() will be used.
1.191 harris41 16340:
16341: =item *
1.394 bowersj2 16342: X<rolesinit()>
1.1169 droeschl 16343: B<rolesinit($udom,$username)>: get user privileges.
16344: returns user role, first access and timer interval hashes
1.243 albertel 16345:
16346: =item *
1.1171 droeschl 16347: X<privileged()>
16348: B<privileged($username,$domain)>: returns a true if user has a
16349: privileged and active role (i.e. su or dc), false otherwise.
16350:
16351: =item *
1.551 albertel 16352: X<getsection()>
16353: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 16354: course $cname, return section name/number or '' for "not in course"
16355: and '-1' for "no section"
16356:
16357: =item *
1.394 bowersj2 16358: X<userenvironment()>
16359: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 16360: passed in @what from the requested user's environment, returns a hash
16361:
1.858 raeburn 16362: =item *
16363: X<userlog_query()>
1.859 albertel 16364: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16365: activity.log file. %filters defines filters applied when parsing the
16366: log file. These can be start or end timestamps, or the type of action
16367: - log to look for Login or Logout events, check for Checkin or
16368: Checkout, role for role selection. The response is in the form
16369: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
16370: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 16371:
1.243 albertel 16372: =back
16373:
16374: =head2 User Roles
16375:
16376: =over 4
16377:
16378: =item *
16379:
1.1284 raeburn 16380: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
16381: returns codes for allowed actions.
16382:
16383: The first argument is required, all others are optional.
16384:
16385: $priv is the privilege being checked.
16386: $uri contains additional information about what is being checked for access (e.g.,
16387: URL, course ID etc.).
16388: $symb is the unique resource instance identifier in a course; if needed,
16389: but not provided, it will be retrieved via a call to &symbread().
16390: $role is the role for which a priv is being checked (only used if priv is evb).
16391: $clientip is the user's IP address (only used when checking for access to portfolio
16392: files).
16393: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
16394: prevents recursive calls to &allowed.
16395:
1.243 albertel 16396: F: full access
16397: U,I,K: authentication modes (cxx only)
16398: '': forbidden
16399: 1: user needs to choose course
16400: 2: browse allowed
1.766 albertel 16401: A: passphrase authentication needed
1.1284 raeburn 16402: B: access temporarily blocked because of a blocking event in a course.
1.1402 raeburn 16403: D: access blocked because access is required via session initiated via deep-link
1.243 albertel 16404:
16405: =item *
16406:
1.1192 raeburn 16407: constructaccess($url,$setpriv) : check for access to construction space URL
16408:
16409: See if the owner domain and name in the URL match those in the
16410: expected environment. If so, return three element list
16411: ($ownername,$ownerdomain,$ownerhome).
16412:
16413: Otherwise return the null string.
16414:
16415: If second argument 'setpriv' is true, it assigns the privileges,
16416: and returns the same three element list, unless the owner has
16417: blocked "ad hoc" Domain Coordinator access to the Author Space,
16418: in which case the null string is returned.
16419:
16420: =item *
16421:
1.1326 raeburn 16422: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16423: define a custom role rolename set privileges in format of lonTabs/roles.tab
16424: for system, domain, and course level. $uname and $udom are optional (current
16425: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 16426:
16427: =item *
16428:
1.988 raeburn 16429: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
16430: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 16431: $type is Course (default) or Community.
1.988 raeburn 16432: If $forcedefault evaluates to true, text returned will be default
16433: text for $type. Otherwise, if this is a course, the text returned
16434: will be a custom name for the role (if defined in the course's
16435: environment). If no custom name is defined the default is returned.
16436:
1.832 raeburn 16437: =item *
16438:
1.1219 raeburn 16439: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 16440: All arguments are optional. Returns a hash of a roles, either for
16441: co-author/assistant author roles for a user's Construction Space
1.906 albertel 16442: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 16443: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16444: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16445: For each key, value is set to colon-separated start and end times for
16446: the role. If no username and domain are specified, will default to
1.934 raeburn 16447: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 16448: of role statuses (active, future or previous), roles
16449: (e.g., cc,in, st etc.) and domains of the roles which can be used
16450: to restrict the list of roles reported. If no array ref is
16451: provided for types, will default to return only active roles.
1.834 albertel 16452:
1.1195 raeburn 16453: =item *
16454:
16455: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 16456: user: $uname:$udom has a role in the course: $cdom_$cnum.
16457:
16458: Additional optional arguments are: $type (if role checking is to be restricted
16459: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 16460: available roles) or future (roles available in the future), and
16461: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 16462: have active Domain Coordinator role in course's domain or in additional
16463: domains (specified in 'Domains to check for privileged users' in course
16464: environment -- set via: Course Settings -> Classlists and staff listing).
16465:
16466: =item *
16467:
16468: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16469: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16470: $possdomains and $possroles are optional array refs -- to domains to check and
16471: roles to check. If $possdomains is not specified, a dump will be done of the
16472: users' roles.db to check for a dc or su role in any domain. This can be
16473: time consuming if &privileged is called repeatedly (e.g., when displaying a
16474: classlist), so in such cases, supplying a $possdomains array is preferred, as
16475: this then allows &privileged_by_domain() to be used, which caches the identity
16476: of privileged users, eliminating the need for repeated calls to &dump().
16477:
16478: =item *
16479:
16480: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16481: where the outer hash keys are domains specified in the $possdomains array ref,
16482: next inner hash keys are privileged roles specified in the $roles array ref,
16483: and the innermost hash contains key = value pairs for username:domain = end:start
16484: for active or future "privileged" users with that role in that domain. To avoid
16485: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16486: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 16487:
1.243 albertel 16488: =back
16489:
16490: =head2 User Modification
16491:
16492: =over 4
16493:
16494: =item *
16495:
1.957 raeburn 16496: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 16497: user for the level given by URL. Optional start and end dates (leave empty
16498: string or zero for "no date")
1.191 harris41 16499:
16500: =item *
16501:
1.243 albertel 16502: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16503: change a users, password, possible return values are: ok,
16504: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16505: refused
1.191 harris41 16506:
16507: =item *
16508:
1.243 albertel 16509: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 16510:
16511: =item *
16512:
1.1058 raeburn 16513: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16514: $forceid,$desiredhome,$email,$inststatus,$candelete) :
16515:
16516: will update user information (firstname,middlename,lastname,generation,
16517: permanentemail), and if forceid is true, student/employee ID also.
16518: A user's institutional affiliation(s) can also be updated.
16519: User information fields will not be overwritten with empty entries
16520: unless the field is included in the $candelete array reference.
16521: This array is included when a single user is modified via "Manage Users",
16522: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 16523:
16524: =item *
16525:
1.286 matthew 16526: modifystudent
16527:
1.957 raeburn 16528: modify a student's enrollment and identification information.
1.1235 raeburn 16529: The course id is resolved based on the current user's environment.
16530: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 16531: associated with a course.
16532:
1.297 matthew 16533: This call is essentially a wrapper for lonnet::modifyuser and
16534: lonnet::modify_student_enrollment
1.286 matthew 16535:
16536: Inputs:
16537:
16538: =over 4
16539:
1.957 raeburn 16540: =item B<$udom> Student's loncapa domain
1.286 matthew 16541:
1.957 raeburn 16542: =item B<$uname> Student's loncapa login name
1.286 matthew 16543:
1.964 bisitz 16544: =item B<$uid> Student/Employee ID
1.286 matthew 16545:
1.957 raeburn 16546: =item B<$umode> Student's authentication mode
1.286 matthew 16547:
1.957 raeburn 16548: =item B<$upass> Student's password
1.286 matthew 16549:
1.957 raeburn 16550: =item B<$first> Student's first name
1.286 matthew 16551:
1.957 raeburn 16552: =item B<$middle> Student's middle name
1.286 matthew 16553:
1.957 raeburn 16554: =item B<$last> Student's last name
1.286 matthew 16555:
1.957 raeburn 16556: =item B<$gene> Student's generation
1.286 matthew 16557:
1.957 raeburn 16558: =item B<$usec> Student's section in course
1.286 matthew 16559:
16560: =item B<$end> Unix time of the roles expiration
16561:
16562: =item B<$start> Unix time of the roles start date
16563:
16564: =item B<$forceid> If defined, allow $uid to be changed
16565:
16566: =item B<$desiredhome> server to use as home server for student
16567:
1.957 raeburn 16568: =item B<$email> Student's permanent e-mail address
16569:
16570: =item B<$type> Type of enrollment (auto or manual)
16571:
1.963 raeburn 16572: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
16573:
16574: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 16575:
1.963 raeburn 16576: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 16577:
1.963 raeburn 16578: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 16579:
1.1216 raeburn 16580: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16581:
16582: =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 16583:
1.286 matthew 16584: =back
1.297 matthew 16585:
16586: =item *
16587:
16588: modify_student_enrollment
16589:
1.1235 raeburn 16590: Change a student's enrollment status in a class. The environment variable
1.297 matthew 16591: 'role.request.course' must be defined for this function to proceed.
16592:
16593: Inputs:
16594:
16595: =over 4
16596:
1.1235 raeburn 16597: =item $udom, student's domain
1.297 matthew 16598:
1.1235 raeburn 16599: =item $uname, student's name
1.297 matthew 16600:
1.1235 raeburn 16601: =item $uid, student's user id
1.297 matthew 16602:
1.1235 raeburn 16603: =item $first, student's first name
1.297 matthew 16604:
16605: =item $middle
16606:
16607: =item $last
16608:
16609: =item $gene
16610:
16611: =item $usec
16612:
16613: =item $end
16614:
16615: =item $start
16616:
1.957 raeburn 16617: =item $type
16618:
16619: =item $locktype
16620:
16621: =item $cid
16622:
16623: =item $selfenroll
16624:
16625: =item $context
16626:
1.1216 raeburn 16627: =item $credits, number of credits student will earn from this class
16628:
1.1314 raeburn 16629: =item $instsec, institutional course section code for student
16630:
1.297 matthew 16631: =back
16632:
1.191 harris41 16633:
16634: =item *
16635:
1.243 albertel 16636: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16637: custom role; give a custom role to a user for the level given by URL. Specify
16638: name and domain of role author, and role name
1.191 harris41 16639:
16640: =item *
16641:
1.243 albertel 16642: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 16643:
16644: =item *
16645:
1.243 albertel 16646: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16647:
16648: =back
16649:
16650: =head2 Course Infomation
16651:
16652: =over 4
1.191 harris41 16653:
16654: =item *
16655:
1.1118 foxr 16656: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 16657: specified course id, including all environment settings for the
16658: course, the description of the course will be in the hash under the
16659: key 'description'
1.191 harris41 16660:
1.1118 foxr 16661: $options is an optional parameter that if supplied is a hash reference that controls
16662: what how this function works. It has the following key/values:
16663:
16664: =over 4
16665:
16666: =item freshen_cache
16667:
16668: If defined, and the environment cache for the course is valid, it is
16669: returned in the returned hash.
16670:
16671: =item one_time
16672:
16673: If defined, the last cache time is set to _now_
16674:
16675: =item user
16676:
16677: If defined, the supplied username is used instead of the current user.
16678:
16679:
16680: =back
16681:
1.191 harris41 16682: =item *
16683:
1.624 albertel 16684: resdata($name,$domain,$type,@which) : request for current parameter
16685: setting for a specific $type, where $type is either 'course' or 'user',
16686: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 16687: answers for 10 minutes.
1.243 albertel 16688:
1.877 foxr 16689: =item *
16690:
16691: get_courseresdata($courseid, $domain) : dump the entire course resource
16692: data base, returning a hash that is keyed by the resource name and has
16693: values that are the resource value. I believe that the timestamps and
16694: versions are also returned.
16695:
1.243 albertel 16696: =back
16697:
16698: =head2 Course Modification
16699:
16700: =over 4
1.191 harris41 16701:
16702: =item *
16703:
1.243 albertel 16704: writecoursepref($courseid,%prefs) : write preferences (environment
16705: database) for a course
1.191 harris41 16706:
16707: =item *
16708:
1.1011 raeburn 16709: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16710:
16711: =item *
16712:
1.1038 raeburn 16713: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 16714:
1.1167 droeschl 16715: =item *
16716:
16717: is_course($courseid), is_course($cdom, $cnum)
16718:
16719: Accepts either a combined $courseid (in the form of domain_courseid) or the
16720: two component version $cdom, $cnum. It checks if the specified course exists.
16721:
16722: Returns:
16723: undef if the course doesn't exist, otherwise
16724: in scalar context the combined courseid.
16725: in list context the two components of the course identifier, domain and
16726: courseid.
16727:
1.243 albertel 16728: =back
16729:
1.1401 raeburn 16730: =head2 Bubblesheet Configuration
16731:
16732: =over 4
16733:
16734: =item *
16735:
16736: get_scantron_config($which)
16737:
16738: $which - the name of the configuration to parse from the file.
16739:
16740: Parses and returns the bubblesheet configuration line selected as a
16741: hash of configuration file fields.
16742:
16743:
16744: Returns:
16745: If the named configuration is not in the file, an empty
16746: hash is returned.
16747:
16748: a hash with the fields
16749: name - internal name for the this configuration setup
16750: description - text to display to operator that describes this config
16751: CODElocation - if 0 or the string 'none'
16752: - no CODE exists for this config
16753: if -1 || the string 'letter'
16754: - a CODE exists for this config and is
16755: a string of letters
16756: Unsupported value (but planned for future support)
16757: if a positive integer
16758: - The CODE exists as the first n items from
16759: the question section of the form
16760: if the string 'number'
16761: - The CODE exists for this config and is
16762: a string of numbers
16763: CODEstart - (only matter if a CODE exists) column in the line where
16764: the CODE starts
16765: CODElength - length of the CODE
16766: IDstart - column where the student/employee ID starts
16767: IDlength - length of the student/employee ID info
16768: Qstart - column where the information from the bubbled
16769: 'questions' start
16770: Qlength - number of columns comprising a single bubble line from
16771: the sheet. (usually either 1 or 10)
16772: Qon - either a single character representing the character used
16773: to signal a bubble was chosen in the positional setup, or
16774: the string 'letter' if the letter of the chosen bubble is
16775: in the final, or 'number' if a number representing the
16776: chosen bubble is in the file (1->A 0->J)
16777: Qoff - the character used to represent that a bubble was
16778: left blank
16779: PaperID - if the scanning process generates a unique number for each
16780: sheet scanned the column that this ID number starts in
16781: PaperIDlength - number of columns that comprise the unique ID number
16782: for the sheet of paper
16783: FirstName - column that the first name starts in
16784: FirstNameLength - number of columns that the first name spans
16785: LastName - column that the last name starts in
16786: LastNameLength - number of columns that the last name spans
16787: BubblesPerRow - number of bubbles available in each row used to
16788: bubble an answer. (If not specified, 10 assumed).
16789:
16790:
16791: =item *
16792:
16793: get_scantronformat_file($cdom)
16794:
16795: $cdom - the course's domain (optional); if not supplied, uses
16796: domain for current $env{'request.course.id'}.
16797:
16798: Returns an array containing lines from the scantron format file for
16799: the domain of the course.
16800:
16801: If a url for a custom.tab file is listed in domain's configuration.db,
16802: lines are from this file.
16803:
16804: Otherwise, if a default.tab has been published in RES space by the
16805: domainconfig user, lines are from this file.
16806:
16807: Otherwise, fall back to getting lines from the legacy file on the
16808: local server: /home/httpd/lonTabs/default_scantronformat.tab
16809:
16810: =back
16811:
1.243 albertel 16812: =head2 Resource Subroutines
16813:
16814: =over 4
1.191 harris41 16815:
16816: =item *
16817:
1.243 albertel 16818: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 16819:
16820: =item *
16821:
1.243 albertel 16822: repcopy($filename) : subscribes to the requested file, and attempts to
16823: replicate from the owning library server, Might return
1.607 raeburn 16824: 'unavailable', 'not_found', 'forbidden', 'ok', or
16825: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 16826: resource. Expects the local filesystem pathname
16827: (/home/httpd/html/res/....)
16828:
16829: =back
16830:
16831: =head2 Resource Information
16832:
16833: =over 4
1.191 harris41 16834:
16835: =item *
16836:
1.1228 raeburn 16837: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
16838: and returns the value of a variety of different possible values,
16839: $varname should be a request string, and the other parameters can be
16840: used to specify who and what one is asking about. Ordinarily, $cid
16841: does not need to be specified, as it is retrived from
16842: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16843: within lonuserstate::loadmap() when initializing a course, before
16844: $env{'request.course.id'} has been set, so it needs to be provided
16845: in that one case.
1.243 albertel 16846:
16847: Possible values for $varname are environment.lastname (or other item
16848: from the envirnment hash), user.name (or someother aspect about the
16849: user), resource.0.maxtries (or some other part and parameter of a
16850: resource)
1.204 albertel 16851:
16852: =item *
16853:
1.243 albertel 16854: directcondval($number) : get current value of a condition; reads from a state
16855: string
1.204 albertel 16856:
16857: =item *
16858:
1.243 albertel 16859: condval($condidx) : value of condition index based on state
1.204 albertel 16860:
16861: =item *
16862:
1.1362 raeburn 16863: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243 albertel 16864: resource's metadata, $what should be either a specific key, or either
16865: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362 raeburn 16866: packages that this resource currently uses, the last 3 arguments are
16867: only used internally for recursive metadata.
16868:
16869: the toolsymb is only used where the uri is for an external tool (for which
16870: the uri as well as the symb are guaranteed to be unique).
1.243 albertel 16871:
1.1371 raeburn 16872: this function automatically caches all requests except any made recursively
16873: to retrieve a list of metadata keys for an imported library file ($liburi is
16874: defined).
1.191 harris41 16875:
16876: =item *
16877:
1.243 albertel 16878: metadata_query($query,$custom,$customshow) : make a metadata query against the
16879: network of library servers; returns file handle of where SQL and regex results
16880: will be stored for query
1.191 harris41 16881:
16882: =item *
16883:
1.1282 raeburn 16884: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
16885: return symbolic list entry (all arguments optional).
16886:
16887: Args: filename is the filename (including path) for the file for which a symb
16888: is required; donotrecurse, if true will prevent calls to allowed() being made
16889: to check access status if more than one resource was found in the bighash
16890: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
16891: a randompick); ignorecachednull, if true will prevent a symb of '' being
16892: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16893: cause possible symbs to be checked to determine if they are subject to content
16894: blocking, if so they will not be included as possible symbs; possibles is a
16895: ref to a hash, which, as a side effect, will be populated with all possible
16896: symbs (content blocking not tested).
16897:
1.243 albertel 16898: returns the data handle
1.191 harris41 16899:
16900: =item *
16901:
1.1190 raeburn 16902: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16903: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 16904: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 16905: on failure, user must be in a course, as it assumes the existence of
16906: the course initial hash, and uses $env('request.course.id'}. The third
16907: arg is an optional reference to a scalar. If this arg is passed in the
16908: call to symbverify, it will be set to 1 if the symb has been set to be
16909: encrypted; otherwise it will be null.
1.191 harris41 16910:
16911: =item *
16912:
1.243 albertel 16913: symbclean($symb) : removes versions numbers from a symb, returns the
16914: cleaned symb
1.191 harris41 16915:
16916: =item *
16917:
1.243 albertel 16918: is_on_map($uri) : checks if the $uri is somewhere on the current
16919: course map, user must be in a course for it to work.
1.191 harris41 16920:
16921: =item *
16922:
1.243 albertel 16923: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 16924:
16925: =item *
16926:
1.243 albertel 16927: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16928: a random seed, all arguments are optional, if they aren't sent it uses the
16929: environment to derive them. Note: if symb isn't sent and it can't get one
16930: from &symbread it will use the current time as its return value
1.191 harris41 16931:
16932: =item *
16933:
1.243 albertel 16934: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16935: unfakeable, receipt
1.191 harris41 16936:
16937: =item *
16938:
1.620 albertel 16939: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 16940:
16941: =item *
16942:
1.243 albertel 16943: countacc($url) : count the number of accesses to a given URL
1.191 harris41 16944:
16945: =item *
16946:
1.243 albertel 16947: 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 16948:
16949: =item *
16950:
1.243 albertel 16951: 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 16952:
16953: =item *
16954:
1.243 albertel 16955: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 16956:
16957: =item *
16958:
1.243 albertel 16959: devalidate($symb) : devalidate temporary spreadsheet calculations,
16960: forcing spreadsheet to reevaluate the resource scores next time.
16961:
1.1195 raeburn 16962: =item *
16963:
1.1196 raeburn 16964: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16965: when viewing in course context.
1.1195 raeburn 16966:
1.1196 raeburn 16967: input: six args -- filename (decluttered), course number, course domain,
16968: url, symb (if registered) and group (if this is a
16969: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 16970:
1.1196 raeburn 16971: output: array of five scalars --
1.1195 raeburn 16972: $cfile -- url for file editing if editable on current server
16973: $home -- homeserver of resource (i.e., for author if published,
16974: or course if uploaded.).
16975: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 16976: $forceedit -- 1 if icon/link should be to go to edit mode
16977: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 16978:
16979: =item *
16980:
16981: is_course_upload($file,$cnum,$cdom)
16982:
16983: Used in course context to determine if current file was uploaded to
16984: the course (i.e., would be found in /userfiles/docs on the course's
16985: homeserver.
16986:
16987: input: 3 args -- filename (decluttered), course number and course domain.
16988: output: boolean -- 1 if file was uploaded.
16989:
1.243 albertel 16990: =back
16991:
16992: =head2 Storing/Retreiving Data
16993:
16994: =over 4
1.191 harris41 16995:
16996: =item *
16997:
1.1269 raeburn 16998: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16999: permanently for this url; hashref needs to be given and should be a \%hashname;
17000: the remaining args aren't required and if they aren't passed or are '' they will
17001: be derived from the env (with the exception of $laststore, which is an
17002: optional arg used when a user's submission is stored in grading).
17003: $laststore is $version=$timestamp, where $version is the most recent version
17004: number retrieved for the corresponding $symb in the $namespace db file, and
17005: $timestamp is the timestamp for that transaction (UNIX time).
17006: $laststore is currently only passed when cstore() is called by
17007: structuretags::finalize_storage().
1.191 harris41 17008:
17009: =item *
17010:
1.1269 raeburn 17011: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
17012: but uses critical subroutine
1.191 harris41 17013:
17014: =item *
17015:
1.243 albertel 17016: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
17017: all args are optional
1.191 harris41 17018:
17019: =item *
17020:
1.717 albertel 17021: dumpstore($namespace,$udom,$uname,$regexp,$range) :
17022: dumps the complete (or key matching regexp) namespace into a hash
17023: ($udom, $uname, $regexp, $range are optional) for a namespace that is
17024: normally &store()ed into
17025:
17026: $range should be either an integer '100' (give me the first 100
17027: matching records)
17028: or be two integers sperated by a - with no spaces
17029: '30-50' (give me the 30th through the 50th matching
17030: records)
17031:
17032:
17033: =item *
17034:
1.1269 raeburn 17035: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 17036: replaces a &store() version of data with a replacement set of data
17037: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 17038: reference. If $tolog is true, the transaction is logged in the courselog
17039: with an action=PUTSTORE.
1.717 albertel 17040:
17041: =item *
17042:
1.243 albertel 17043: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
17044: works very similar to store/cstore, but all data is stored in a
17045: temporary location and can be reset using tmpreset, $storehash should
17046: be a hash reference, returns nothing on success
1.191 harris41 17047:
17048: =item *
17049:
1.243 albertel 17050: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
17051: similar to restore, but all data is stored in a temporary location and
17052: can be reset using tmpreset. Returns a hash of values on success,
17053: error string otherwise.
1.191 harris41 17054:
17055: =item *
17056:
1.243 albertel 17057: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
17058: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 17059:
17060: =item *
17061:
1.243 albertel 17062: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17063: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 17064:
17065: =item *
17066:
1.243 albertel 17067: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
17068: namesp ($udom and $uname are optional)
1.191 harris41 17069:
17070: =item *
17071:
1.702 albertel 17072: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 17073: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 17074: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 17075:
1.702 albertel 17076: $range should be either an integer '100' (give me the first 100
17077: matching records)
17078: or be two integers sperated by a - with no spaces
17079: '30-50' (give me the 30th through the 50th matching
17080: records)
1.449 matthew 17081: =item *
17082:
17083: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17084: $store can be a scalar, an array reference, or if the amount to be
17085: incremented is > 1, a hash reference.
17086:
17087: ($udom and $uname are optional)
1.191 harris41 17088:
17089: =item *
17090:
1.243 albertel 17091: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17092: ($udom and $uname are optional)
1.191 harris41 17093:
17094: =item *
17095:
1.243 albertel 17096: cput($namespace,$storehash,$udom,$uname) : critical put
17097: ($udom and $uname are optional)
1.191 harris41 17098:
17099: =item *
17100:
1.748 albertel 17101: newput($namespace,$storehash,$udom,$uname) :
17102:
17103: Attempts to store the items in the $storehash, but only if they don't
17104: currently exist, if this succeeds you can be certain that you have
17105: successfully created a new key value pair in the $namespace db.
17106:
17107:
17108: Args:
17109: $namespace: name of database to store values to
17110: $storehash: hashref to store to the db
17111: $udom: (optional) domain of user containing the db
17112: $uname: (optional) name of user caontaining the db
17113:
17114: Returns:
17115: 'ok' -> succeeded in storing all keys of $storehash
17116: 'key_exists: <key>' -> failed to anything out of $storehash, as at
17117: least <key> already existed in the db (other
17118: requested keys may also already exist)
1.967 bisitz 17119: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 17120: 'con_lost' -> unable to contact request server
17121: 'refused' -> action was not allowed by remote machine
17122:
17123:
17124: =item *
17125:
1.243 albertel 17126: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17127: reference filled in from namesp (encrypts the return communication)
17128: ($udom and $uname are optional)
1.191 harris41 17129:
17130: =item *
17131:
1.243 albertel 17132: log($udom,$name,$home,$message) : write to permanent log for user; use
17133: critical subroutine
17134:
1.806 raeburn 17135: =item *
17136:
1.860 raeburn 17137: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17138: array reference filled in from namespace found in domain level on either
17139: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 17140:
17141: =item *
17142:
1.860 raeburn 17143: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
17144: domain level either on specified domain server ($uhome) or primary domain
17145: server ($udom and $uhome are optional)
1.806 raeburn 17146:
1.943 raeburn 17147: =item *
17148:
1.1240 raeburn 17149: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
17150: for: authentication, language, quotas, timezone, date locale, and portal URL in
17151: the target domain.
17152:
17153: May also include additional key => value pairs for the following groups:
17154:
17155: =over
17156:
17157: =item
17158: disk quotas (MB allocated by default to portfolios and authoring spaces).
17159:
17160: =over
17161:
17162: =item defaultquota, authorquota
17163:
17164: =back
17165:
17166: =item
17167: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17168: portfolio for users).
17169:
17170: =over
17171:
17172: =item
17173: aboutme, blog, webdav, portfolio
17174:
17175: =back
17176:
17177: =item
17178: requestcourses: ability to request courses, and how requests are processed.
17179:
17180: =over
17181:
17182: =item
1.1305 raeburn 17183: official, unofficial, community, textbook, placement
1.1240 raeburn 17184:
17185: =back
17186:
17187: =item
17188: inststatus: types of institutional affiliation, and order in which they are displayed.
17189:
17190: =over
17191:
17192: =item
1.1256 raeburn 17193: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 17194:
17195: =back
17196:
17197: =item
17198: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17199: for course's uploaded content.
17200:
17201: =over
17202:
17203: =item
1.1246 raeburn 17204: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 17205: communityquota, textbookquota, placementquota
1.1240 raeburn 17206:
17207: =back
17208:
17209: =item
17210: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17211: on your servers.
17212:
17213: =over
17214:
17215: =item
17216: remotesessions, hostedsessions
17217:
17218: =back
17219:
17220: =back
17221:
17222: In cases where a domain coordinator has never used the "Set Domain Configuration"
17223: utility to create a configuration.db file on a domain's primary library server
17224: only the following domain defaults: auth_def, auth_arg_def, lang_def
17225: -- corresponding values are authentication type (internal, krb4, krb5,
17226: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
17227: will be available. Values are retrieved from cache (if current), unless the
17228: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17229: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17230:
17231: Typical usage:
1.943 raeburn 17232:
1.1240 raeburn 17233: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 17234:
1.243 albertel 17235: =back
17236:
17237: =head2 Network Status Functions
17238:
17239: =over 4
1.191 harris41 17240:
17241: =item *
17242:
1.1137 raeburn 17243: dirlist() : return directory list based on URI (first arg).
17244:
17245: Inputs: 1 required, 5 optional.
17246:
17247: =over
17248:
17249: =item
17250: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17251:
17252: =item
17253: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
17254:
17255: =item
17256: $username - username of user/course to be listed. Extracted from $uri if absent.
17257:
17258: =item
17259: $getpropath - boolean: 1 if prepend path using &propath().
17260:
17261: =item
17262: $getuserdir - boolean: 1 if prepend path for "userfiles".
17263:
17264: =item
17265: $alternateRoot - path to prepend in place of path from $uri.
17266:
17267: =back
17268:
17269: Returns: Array of up to two items.
17270:
17271: =over
17272:
17273: a reference to an array of files/subdirectories
17274:
17275: =over
17276:
17277: Each element in the array of files/subdirectories is a & separated list of
17278: item name and the result of running stat on the item. If dirlist was requested
17279: for a file instead of a directory, the item name will be ''. For a directory
17280: listing, if the item is a metadata file, the element will end &N&M
17281: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17282: default copyright set (1).
17283:
17284: =back
17285:
17286: a scalar containing error condition (if encountered).
17287:
17288: =over
17289:
17290: =item
17291: no_host (no homeserver identified for $username:$domain).
17292:
17293: =item
17294: no_such_host (server contacted for listing not identified as valid host).
17295:
17296: =item
17297: con_lost (connection to remote server failed).
17298:
17299: =item
17300: refused (invalid $username:$domain received on lond side).
17301:
17302: =item
17303: no_such_dir (directory at specified path on lond side does not exist).
17304:
17305: =item
17306: empty (directory at specified path on lond side is empty).
17307:
17308: =over
17309:
17310: This is currently not encountered because the &ls3, &ls2,
17311: &ls (_handler) routines on the lond side do not filter out
17312: . and .. from a directory listing.
17313:
17314: =back
17315:
17316: =back
17317:
17318: =back
1.191 harris41 17319:
17320: =item *
17321:
1.243 albertel 17322: spareserver() : find server with least workload from spare.tab
17323:
1.986 foxr 17324:
17325: =item *
17326:
17327: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17328: if there is no corresponding loncapa host.
17329:
1.243 albertel 17330: =back
17331:
1.986 foxr 17332:
1.243 albertel 17333: =head2 Apache Request
17334:
17335: =over 4
1.191 harris41 17336:
17337: =item *
17338:
1.243 albertel 17339: ssi($url,%hash) : server side include, does a complete request cycle on url to
17340: localhost, posts hash
17341:
17342: =back
17343:
17344: =head2 Data to String to Data
17345:
17346: =over 4
1.191 harris41 17347:
17348: =item *
17349:
1.243 albertel 17350: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17351: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 17352:
17353: =item *
17354:
1.243 albertel 17355: hashref2str($hashref) : convert a hashref into a string complete with
17356: escaping and '=' and '&' separators, supports elements that are
17357: arrayrefs and hashrefs
1.191 harris41 17358:
17359: =item *
17360:
1.243 albertel 17361: arrayref2str($arrayref) : convert an arrayref into a string complete
17362: with escaping and '&' separators, supports elements that are arrayrefs
17363: and hashrefs
1.191 harris41 17364:
17365: =item *
17366:
1.243 albertel 17367: str2hash($string) : convert string to hash using unescaping and
17368: splitting on '=' and '&', supports elements that are arrayrefs and
17369: hashrefs
1.191 harris41 17370:
17371: =item *
17372:
1.243 albertel 17373: str2array($string) : convert string to hash using unescaping and
17374: splitting on '&', supports elements that are arrayrefs and hashrefs
17375:
17376: =back
17377:
17378: =head2 Logging Routines
17379:
17380:
17381: These routines allow one to make log messages in the lonnet.log and
17382: lonnet.perm logfiles.
1.191 harris41 17383:
1.1119 foxr 17384: =over 4
17385:
1.191 harris41 17386: =item *
17387:
1.243 albertel 17388: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 17389:
17390: =item *
17391:
1.243 albertel 17392: logthis() : append message to the normal lonnet.log file, it gets
17393: preiodically rolled over and deleted.
1.191 harris41 17394:
17395: =item *
17396:
1.243 albertel 17397: logperm() : append a permanent message to lonnet.perm.log, this log
17398: file never gets deleted by any automated portion of the system, only
17399: messages of critical importance should go in here.
17400:
1.1119 foxr 17401:
1.243 albertel 17402: =back
17403:
17404: =head2 General File Helper Routines
17405:
17406: =over 4
1.191 harris41 17407:
17408: =item *
17409:
1.481 raeburn 17410: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17411: (a) files in /uploaded
17412: (i) If a local copy of the file exists -
17413: compares modification date of local copy with last-modified date for
17414: definitive version stored on home server for course. If local copy is
17415: stale, requests a new version from the home server and stores it.
17416: If the original has been removed from the home server, then local copy
17417: is unlinked.
17418: (ii) If local copy does not exist -
17419: requests the file from the home server and stores it.
17420:
17421: If $caller is 'uploadrep':
17422: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17423: for request for files originally uploaded via DOCS.
17424: - returns 'ok' if fresh local copy now available, -1 otherwise.
17425:
17426: Otherwise:
17427: This indicates a call from the content generation phase of the request.
17428: - returns the entire contents of the file or -1.
17429:
17430: (b) files in /res
17431: - returns the entire contents of a file or -1;
17432: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 17433:
1.712 albertel 17434:
17435: =item *
17436:
17437: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17438: reference
17439:
17440: returns either a stat() list of data about the file or an empty list
17441: if the file doesn't exist or couldn't find out about it (connection
17442: problems or user unknown)
17443:
1.191 harris41 17444: =item *
17445:
1.243 albertel 17446: filelocation($dir,$file) : returns file system location of a file
17447: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17448: directory that relative $file lookups are to looked in ($dir of /a/dir
17449: and a file of ../bob will become /a/bob)
1.191 harris41 17450:
17451: =item *
17452:
17453: hreflocation($dir,$file) : returns file system location or a URL; same as
17454: filelocation except for hrefs
17455:
17456: =item *
17457:
1.1261 raeburn 17458: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17459: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 17460:
1.243 albertel 17461: =back
17462:
1.608 albertel 17463: =head2 Usererfile file routines (/uploaded*)
17464:
17465: =over 4
17466:
17467: =item *
17468:
17469: userfileupload(): main rotine for putting a file in a user or course's
17470: filespace, arguments are,
17471:
1.620 albertel 17472: formname - required - this is the name of the element in $env where the
1.608 albertel 17473: filename, and the contents of the file to create/modifed exist
1.620 albertel 17474: the filename is in $env{'form.'.$formname.'.filename'} and the
17475: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 17476: context - if coursedoc, store the file in the course of the active role
17477: of the current user;
17478: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17479: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 17480: subdir - required - subdirectory to put the file in under ../userfiles/
17481: if undefined, it will be placed in "unknown"
17482:
17483: (This routine calls clean_filename() to remove any dangerous
17484: characters from the filename, and then calls finuserfileupload() to
17485: complete the transaction)
17486:
17487: returns either the url of the uploaded file (/uploaded/....) if successful
17488: and /adm/notfound.html if unsuccessful
17489:
17490: =item *
17491:
17492: clean_filename(): routine for cleaing a filename up for storage in
17493: userfile space, argument is:
17494:
17495: filename - proposed filename
17496:
17497: returns: the new clean filename
17498:
17499: =item *
17500:
1.1090 raeburn 17501: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 17502: userspace, probably shouldn't be called directly
17503:
17504: docuname: username or courseid of destination for the file
17505: docudom: domain of user/course of destination for the file
17506: formname: same as for userfileupload()
1.1090 raeburn 17507: fname: filename (including subdirectories) for the file
17508: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401 raeburn 17509: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 17510: allfiles: reference to hash used to store objects found by parser
17511: codebase: reference to hash used for codebases of java objects found by parser
17512: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17513: thumbheight: height (pixels) of thumbnail to be created for uploaded image
17514: resizewidth: width to be used to resize image using resizeImage from ImageMagick
17515: resizeheight: height to be used to resize image using resizeImage from ImageMagick
17516: context: if 'overwrite', will move the uploaded file from its temporary location to
17517: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 17518: mimetype: reference to scalar to accommodate mime type determined
17519: from File::MMagic if $parser = parse.
1.608 albertel 17520:
17521: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 17522: and /adm/notfound.html if unsuccessful (or an error message if context
17523: was 'overwrite').
17524:
1.608 albertel 17525:
17526: =item *
17527:
17528: renameuserfile(): renames an existing userfile to a new name
17529:
17530: Args:
17531: docuname: username or courseid of destination for the file
17532: docudom: domain of user/course of destination for the file
17533: old: current file name (including any subdirs under userfiles)
17534: new: desired file name (including any subdirs under userfiles)
17535:
17536: =item *
17537:
17538: mkdiruserfile(): creates a directory is a userfiles dir
17539:
17540: Args:
17541: docuname: username or courseid of destination for the file
17542: docudom: domain of user/course of destination for the file
17543: dir: dir to create (including any subdirs under userfiles)
17544:
17545: =item *
17546:
17547: removeuserfile(): removes a file that exists in userfiles
17548:
17549: Args:
17550: docuname: username or courseid of destination for the file
17551: docudom: domain of user/course of destination for the file
17552: fname: filname to delete (including any subdirs under userfiles)
17553:
17554: =item *
17555:
17556: removeuploadedurl(): convience function for removeuserfile()
17557:
17558: Args:
17559: url: a full /uploaded/... url to delete
17560:
1.747 albertel 17561: =item *
17562:
17563: get_portfile_permissions():
17564: Args:
17565: domain: domain of user or course contain the portfolio files
17566: user: name of user or num of course contain the portfolio files
17567: Returns:
17568: hashref of a dump of the proper file_permissions.db
17569:
17570:
17571: =item *
17572:
17573: get_access_controls():
17574:
17575: Args:
17576: current_permissions: the hash ref returned from get_portfile_permissions()
17577: group: (optional) the group you want the files associated with
17578: file: (optional) the file you want access info on
17579:
17580: Returns:
1.749 raeburn 17581: a hash (keys are file names) of hashes containing
17582: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17583: values are XML containing access control settings (see below)
1.747 albertel 17584:
17585: Internal notes:
17586:
1.749 raeburn 17587: access controls are stored in file_permissions.db as key=value pairs.
17588: key -> path to file/file_name\0uniqueID:scope_end_start
17589: where scope -> public,guest,course,group,domains or users.
17590: end -> UNIX time for end of access (0 -> no end date)
17591: start -> UNIX time for start of access
17592:
17593: value -> XML description of access control
17594: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17595: <start></start>
17596: <end></end>
17597:
17598: <password></password> for scope type = guest
17599:
17600: <domain></domain> for scope type = course or group
17601: <number></number>
17602: <roles id="">
17603: <role></role>
17604: <access></access>
17605: <section></section>
17606: <group></group>
17607: </roles>
17608:
17609: <dom></dom> for scope type = domains
17610:
17611: <users> for scope type = users
17612: <user>
17613: <uname></uname>
17614: <udom></udom>
17615: </user>
17616: </users>
17617: </scope>
17618:
17619: Access data is also aggregated for each file in an additional key=value pair:
17620: key -> path to file/file_name\0accesscontrol
17621: value -> reference to hash
17622: hash contains key = value pairs
17623: where key = uniqueID:scope_end_start
17624: value = UNIX time record was last updated
17625:
17626: Used to improve speed of look-ups of access controls for each file.
17627:
17628: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17629:
1.1198 raeburn 17630: =item *
17631:
1.749 raeburn 17632: modify_access_controls():
17633:
17634: Modifies access controls for a portfolio file
17635: Args
17636: 1. file name
17637: 2. reference to hash of required changes,
17638: 3. domain
17639: 4. username
17640: where domain,username are the domain of the portfolio owner
17641: (either a user or a course)
17642:
17643: Returns:
17644: 1. result of additions or updates ('ok' or 'error', with error message).
17645: 2. result of deletions ('ok' or 'error', with error message).
17646: 3. reference to hash of any new or updated access controls.
17647: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17648: key = integer (inbound ID)
1.1198 raeburn 17649: value = uniqueID
17650:
17651: =item *
17652:
17653: get_timebased_id():
17654:
17655: Attempts to get a unique timestamp-based suffix for use with items added to a
17656: course via the Course Editor (e.g., folders, composite pages,
17657: group bulletin boards).
17658:
17659: Args: (first three required; six others optional)
17660:
17661: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17662: docssequence, or name of group
17663:
17664: 2. keyid (alphanumeric): name of temporary locking key in hash,
17665: e.g., num, boardids
17666:
17667: 3. namespace: name of gdbm file used to store suffixes already assigned;
17668: file will be named nohist_namespace.db
17669:
17670: 4. cdom: domain of course; default is current course domain from %env
17671:
17672: 5. cnum: course number; default is current course number from %env
17673:
17674: 6. idtype: set to concat if an additional digit is to be appended to the
17675: unix timestamp to form the suffix, if the plain timestamp is already
17676: in use. Default is to not do this, but simply increment the unix
17677: timestamp by 1 until a unique key is obtained.
17678:
17679: 7. who: holder of locking key; defaults to user:domain for user.
17680:
17681: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
17682: retrying); default is 3.
17683:
17684: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
17685:
17686: Returns:
17687:
17688: 1. suffix obtained (numeric)
17689:
17690: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17691:
17692: 3. error: contains (localized) error message if an error occurred.
17693:
1.747 albertel 17694:
1.608 albertel 17695: =back
17696:
1.243 albertel 17697: =head2 HTTP Helper Routines
17698:
17699: =over 4
17700:
1.191 harris41 17701: =item *
17702:
17703: escape() : unpack non-word characters into CGI-compatible hex codes
17704:
17705: =item *
17706:
17707: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17708:
1.243 albertel 17709: =back
17710:
17711: =head1 PRIVATE SUBROUTINES
17712:
17713: =head2 Underlying communication routines (Shouldn't call)
17714:
17715: =over 4
17716:
17717: =item *
17718:
17719: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17720:
17721: =item *
17722:
17723: reply() : uses subreply to send a message to remote machine, logs all failures
17724:
17725: =item *
17726:
17727: critical() : passes a critical message to another server; if cannot
17728: get through then place message in connection buffer directory and
17729: returns con_delayed, if incapable of saving message, returns
17730: con_failed
17731:
17732: =item *
17733:
17734: reconlonc() : tries to reconnect lonc client processes.
17735:
17736: =back
17737:
17738: =head2 Resource Access Logging
17739:
17740: =over 4
17741:
17742: =item *
17743:
17744: flushcourselogs() : flush (save) buffer logs and access logs
17745:
17746: =item *
17747:
17748: courselog($what) : save message for course in hash
17749:
17750: =item *
17751:
17752: courseacclog($what) : save message for course using &courselog(). Perform
17753: special processing for specific resource types (problems, exams, quizzes, etc).
17754:
1.191 harris41 17755: =item *
17756:
17757: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17758: as a PerlChildExitHandler
1.243 albertel 17759:
17760: =back
17761:
17762: =head2 Other
17763:
17764: =over 4
17765:
17766: =item *
17767:
17768: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 17769:
17770: =back
17771:
17772: =cut
1.877 foxr 17773:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>